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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ef40932ccd010162829ca518a0a54e535e393a1a | 12,966 | cpp | C++ | main/src/Objects/CObjectContactCircleCable2D.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2020-10-06T08:06:25.000Z | 2020-10-06T08:06:25.000Z | main/src/Objects/CObjectContactCircleCable2D.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | main/src/Objects/CObjectContactCircleCable2D.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /** ***********************************************************************************************
* @brief Implementation of CObjectContactCircleCable2D
*
* @author Gerstmayr Johannes
* @date 2018-05-06 (generated)
*
* @copyright This file is part of Exudyn. Exudyn is free software: you can redistribute it and/or modify it under the terms of the Exudyn license. See "LICENSE.txt" for more details.
* @note Bug reports, support and further information:
- email: johannes.gerstmayr@uibk.ac.at
- weblink: missing
************************************************************************************************ */
#include "Main/CSystemData.h"
#include "Linalg/Geometry.h"
#include "Autogenerated/CNodeGenericData.h"
//#include "Autogenerated/CObjectContactCoordinate.h"
//for consistency checks:
#include "Main/MainSystem.h"
#include "Pymodules/PybindUtilities.h"
#include "Autogenerated/MainObjectContactCircleCable2D.h"
bool MainObjectContactCircleCable2D::CheckPreAssembleConsistency(const MainSystem& mainSystem, STDstring& errorString) const
{
CObjectContactCircleCable2D* cObject = (CObjectContactCircleCable2D*)GetCObject();
Index node = cObject->GetNodeNumber(0);
if (cObject->GetParameters().numberOfContactSegments > cObject->maxNumberOfSegments)
{
errorString = "ObjectContactCircleCable2D: numberOfContactSegments must be <= " + EXUstd::ToString(cObject->maxNumberOfSegments);
return false;
}
//check for valid node number already done prior to this function
if (std::strcmp(mainSystem.GetMainSystemData().GetMainNode(node).GetTypeName(), "GenericData") != 0)
{
errorString = "ObjectContactCircleCable2D: node must be of type 'GenericData'";
return false;
}
Index nc = ((const CNodeGenericData&)(cObject->GetCSystemData()->GetCNode(node))).GetNumberOfDataCoordinates();
if (nc != cObject->GetParameters().numberOfContactSegments)
{
errorString = STDstring("ObjectContactCircleCable2D: NodeGenericData (Node ") + EXUstd::ToString(node) + ") must have " + EXUstd::ToString(cObject->GetParameters().numberOfContactSegments)
+ " coordinates (found: " + EXUstd::ToString(nc) + ")";
return false;
}
if (cObject->GetParameters().contactDamping != 0)
{
errorString = STDstring("ObjectContactCircleCable2D: contactDamping is not yet implemented; set parameter to zero");
return false;
}
const ArrayIndex& nMarkers = cObject->GetMarkerNumbers();
if (!(mainSystem.GetCSystem()->GetSystemData().GetCMarker(nMarkers[0]).GetType() & Marker::Position))
{
errorString = STDstring("ObjectContactCircleCable2D: Marker 0 must be of type = 'Position'");
return false;
}
if (STDstring(mainSystem.GetMainSystemData().GetMainMarkers()[nMarkers[1]]->GetTypeName()) != STDstring("BodyCable2DShape"))
{
errorString = STDstring("ObjectContactCircleCable2D: Marker 1 must be of type = 'BodyCable2DShape'");
return false;
}
return true;
}
//! compute gap for given configuration (current, start of step, ...); gap <= 0 means contact, gap > 0 is no contact
//! gapPerSegment returns the 'area' gap per segment, which is the distance/penetration * segment length (or real penetrating area)
//! referenceCoordinatePerSegment returns the reference coordinate at the segment (range: [0,1]) in case of contact ==> used to apply forces (either this is the nearest point or a vertex of the segment)
//! the x/yDirectionGap show the direction of the gap, in which the contact force should act
void CObjectContactCircleCable2D::ComputeGap(const MarkerDataStructure& markerData, ConstSizeVector<maxNumberOfSegments>& gapPerSegment,
ConstSizeVector<maxNumberOfSegments>& referenceCoordinatePerSegment,
ConstSizeVector<maxNumberOfSegments>& xDirectionGap, ConstSizeVector<maxNumberOfSegments>& yDirectionGap) const
{
//circular segment, which cuts a piece with height h off the circle with radius r:
// alpha = 2*arccos(1-h/r); //angle of the cut
// s = 2*r*sin(alpha/2); //length of the cut
// A = r^2/2*(alpha - sin(alpha)) //area of the cut
//markerData contains:
// vectorValue = [x0,y0, x1,y1, x2,y2, ... ] ... the x/y positions of the cable points defining the contact segments [x0,y0,x1,y1], [x1,y1,x2,y2],
const MarkerData& markerData0 = markerData.GetMarkerData(0); //position based marker
const MarkerData& markerData1 = markerData.GetMarkerData(1); //ANCFCable2DShape
//position and radius of circle:
Vector2D circleCenter({ markerData0.position[0], markerData0.position[1] }); //center of the circle
const Real& r = parameters.circleRadius;
const Real& offset = parameters.offset;
Vector2D contactVector; //vector from contact point to circle midpoint; the contact force acts in opposite direction
Index nSeg = parameters.numberOfContactSegments;
gapPerSegment.SetNumberOfItems(nSeg);
referenceCoordinatePerSegment.SetNumberOfItems(nSeg);
xDirectionGap.SetNumberOfItems(nSeg);
yDirectionGap.SetNumberOfItems(nSeg);
//iterate over all segments:
for (Index i = 0; i < nSeg; i++)
{
//take 2 points as one segment
Vector2D p0({ markerData1.vectorValue[i * 2], markerData1.vectorValue[i * 2 + 1] }); //markerdata.value stores the x/y positions of the contact points
Vector2D p1({ markerData1.vectorValue[i * 2+2], markerData1.vectorValue[i * 2 + 1+2] }); //markerdata.value stores the x/y positions of the contact points
//compute shortest distance:
//referenceCoordinatePerSegment is the relative position [0..1] of the shortest projected point at the line segment
Real distance = HGeometry::ShortestDistanceEndPointsRelativePosition(p0, p1, circleCenter, referenceCoordinatePerSegment[i], contactVector);
if (distance != 0.) { contactVector *= 1. / distance; } //computes normal vector
gapPerSegment[i] = distance - r - offset;
xDirectionGap[i] = -contactVector[0]; //x-component of direction of force
yDirectionGap[i] = -contactVector[1]; //y-component of direction of force
}
}
bool CObjectContactCircleCable2D::IsActive() const
{
if (!parameters.activeConnector) { return false; }
for (Index i = 0; i < parameters.numberOfContactSegments; i++)
{
if (GetCNode(0)->GetCurrentCoordinate(i) <= 0) { return true; }
}
return false;
}
//! Computational function: compute right-hand-side (RHS) of second order ordinary differential equations (ODE) to "ode2rhs"
// MODEL: f
void CObjectContactCircleCable2D::ComputeODE2RHS(Vector& ode2Rhs, const MarkerDataStructure& markerData) const
{
ode2Rhs.SetNumberOfItems(markerData.GetMarkerData(0).positionJacobian.NumberOfColumns() + markerData.GetMarkerData(1).jacobian.NumberOfColumns());
ode2Rhs.SetAll(0.);
if (parameters.activeConnector)
{
//gap>0: no contact, gap<0: contact
//Real gap = (markerData.GetMarkerData(1).value - markerData.GetMarkerData(0).value - parameters.offset);
ConstSizeVector<maxNumberOfSegments> gapPerSegment;
ConstSizeVector<maxNumberOfSegments> referenceCoordinatePerSegment;
ConstSizeVector<maxNumberOfSegments> xDirectionGap;
ConstSizeVector<maxNumberOfSegments> yDirectionGap;
ComputeGap(markerData, gapPerSegment, referenceCoordinatePerSegment, xDirectionGap, yDirectionGap);
const Index maxNumberOfPoints = maxNumberOfSegments + 1;
//xDirectionGap.SetAll(0.);
//yDirectionGap.SetAll(1.);
//referenceCoordinatePerSegment.SetAll(0.5);
ConstSizeVector<maxNumberOfPoints * 2> forcePerPoint; //force (x/y) per contact point ==> used to apply forces
forcePerPoint.SetNumberOfItems((parameters.numberOfContactSegments + 1) * 2);
forcePerPoint.SetAll(0.);
Vector3D forceSum({0.,0.,0.}); //sum of all forces acting on circle (without friction, all forces can be replaced at center of circle
for (Index i = 0; i < parameters.numberOfContactSegments; i++)
{
//Real hasContact = 0; //1 for contact, 0 else
if (GetCNode(0)->GetCurrentCoordinate(i) <= 0) //this is the contact state: 1=contact/use contact force, 0=no contact
{
////as gap is negative in case of contact, the force needs to act in opposite direction
forcePerPoint[i * 2] += xDirectionGap[i] * ((1. - referenceCoordinatePerSegment[i])*gapPerSegment[i] * parameters.contactStiffness); // +gap_t * parameters.contactDamping);
forcePerPoint[(i + 1) * 2] += xDirectionGap[i] * (referenceCoordinatePerSegment[i] * gapPerSegment[i] * parameters.contactStiffness); // +gap_t * parameters.contactDamping);
forcePerPoint[i * 2 + 1] += yDirectionGap[i] * ((1. - referenceCoordinatePerSegment[i])*gapPerSegment[i] * parameters.contactStiffness); // +gap_t * parameters.contactDamping);
forcePerPoint[(i + 1) * 2 + 1] += yDirectionGap[i] * (referenceCoordinatePerSegment[i] * gapPerSegment[i] * parameters.contactStiffness); // +gap_t * parameters.contactDamping);
forceSum[0] += forcePerPoint[i * 2];
forceSum[0] += forcePerPoint[(i + 1) * 2];
forceSum[1] += forcePerPoint[i * 2 + 1];
forceSum[1] += forcePerPoint[(i + 1) * 2 + 1];
}
}
//if (!cSystemData->isODE2RHSjacobianComputation && forcePerPoint.GetL2Norm() != 0) {
// pout << "forcePerPoint=" << forcePerPoint << "\n";
// pout << "gapPerSegment=" << gapPerSegment << "\n";
// pout << "referenceCoordinatePerSegment=" << referenceCoordinatePerSegment << "\n";
// pout << "xDirectionGap=" << xDirectionGap << "\n";
// pout << "yDirectionGap=" << yDirectionGap << "\n";
//}
//if (forceSum.GetL2Norm() != 0) pout << "forceSum=" << forceSum << "\n";
//now link ode2Rhs Vector to partial result using the two jacobians
if (markerData.GetMarkerData(1).jacobian.NumberOfColumns()) //special case: COGround has (0,0) Jacobian
{
LinkedDataVector ldv1(ode2Rhs, markerData.GetMarkerData(0).positionJacobian.NumberOfColumns(), markerData.GetMarkerData(1).jacobian.NumberOfColumns());
//positive force on marker1
EXUmath::MultMatrixTransposedVector(markerData.GetMarkerData(1).jacobian, forcePerPoint, ldv1);
}
if (markerData.GetMarkerData(0).positionJacobian.NumberOfColumns()) //special case: COGround has (0,0) Jacobian
{
LinkedDataVector ldv0(ode2Rhs, 0, markerData.GetMarkerData(0).positionJacobian.NumberOfColumns());
forceSum *= -1; //negative force on marker0
EXUmath::MultMatrixTransposedVector(markerData.GetMarkerData(0).positionJacobian, forceSum, ldv0);
}
}
}
void CObjectContactCircleCable2D::ComputeJacobianODE2_ODE2(ResizableMatrix& jacobian, ResizableMatrix& jacobian_ODE2_t, const MarkerDataStructure& markerData) const
{
CHECKandTHROWstring("ERROR: illegal call to ObjectContactCircleCable2D::ComputeODE2RHSJacobian");
}
//! Flags to determine, which output variables are available (displacment, velocity, stress, ...)
OutputVariableType CObjectContactCircleCable2D::GetOutputVariableTypes() const
{
return OutputVariableType::Distance;
}
//! provide according output variable in "value"
void CObjectContactCircleCable2D::GetOutputVariableConnector(OutputVariableType variableType, const MarkerDataStructure& markerData, Vector& value) const
{
SysError("ObjectContactCircleCable2D::GetOutputVariableConnector not implemented");
}
//! function called after Newton method; returns a residual error (force);
//! done for two different computation states in order to estimate the correct time of contact
Real CObjectContactCircleCable2D::PostNewtonStep(const MarkerDataStructure& markerDataCurrent, PostNewtonFlags::Type& flags)
{
//return force-type error in case of contact: in case that the assumed contact state has been wrong,
// the contact force (also negative) is returned as measure of the error
Real discontinuousError = 0;
flags = PostNewtonFlags::_None;
if (parameters.activeConnector)
{
LinkedDataVector currentState = ((CNodeData*)GetCNode(0))->GetCoordinateVector(ConfigurationType::Current); //copy, but might change values ...
ConstSizeVector<maxNumberOfSegments> currentGapPerSegment;
ConstSizeVector<maxNumberOfSegments> referenceCoordinatePerSegment;
ConstSizeVector<maxNumberOfSegments> xDirectionGap;
ConstSizeVector<maxNumberOfSegments> yDirectionGap;
ComputeGap(markerDataCurrent, currentGapPerSegment, referenceCoordinatePerSegment, xDirectionGap, yDirectionGap);
for (Index i = 0; i < parameters.numberOfContactSegments; i++)
{
//if (currentGapPerSegment[i] > 0 && currentState[i] <= 0 || currentGapPerSegment[i] <= 0 && currentState[i] > 0) //OLD: brackets missing!
if ((currentGapPerSegment[i] > 0 && currentState[i] <= 0) || (currentGapPerSegment[i] <= 0 && currentState[i] > 0))
{//action: state1=currentGapState, error = |currentGap*k|
discontinuousError += fabs((currentGapPerSegment[i] - currentState[i])* parameters.contactStiffness);
currentState[i] = currentGapPerSegment[i];
}
}
}
return discontinuousError;
}
//! function called after discontinuous iterations have been completed for one step (e.g. to finalize history variables and set initial values for next step)
void CObjectContactCircleCable2D::PostDiscontinuousIterationStep()
{
}
| 48.928302 | 202 | 0.737776 | [
"geometry",
"vector",
"model"
] |
ef45605f4dee6b6a3b2fe3ff2d2b955d69bc5d73 | 714 | cc | C++ | src/binary_index_tree.cc | nryotaro/tamaki | cf75fa1754114c1fd0aae1bbc3f1cf1f47d181e6 | [
"MIT"
] | null | null | null | src/binary_index_tree.cc | nryotaro/tamaki | cf75fa1754114c1fd0aae1bbc3f1cf1f47d181e6 | [
"MIT"
] | 4 | 2017-01-15T06:47:15.000Z | 2017-01-15T06:50:46.000Z | src/binary_index_tree.cc | nryotaro/tamaki | cf75fa1754114c1fd0aae1bbc3f1cf1f47d181e6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class BinaryIndexTree final {
public:
vector<int> bit;
BinaryIndexTree(int max_value) : bit(max_value + 1){};
int sum(int i) {
int res = 0;
while (i > 0) {
res += bit[i];
i -= i & -i;
}
return res;
}
void add(int i, int v) {
int max_value = get_max_value();
while (i <= max_value) {
bit[i] += v;
i += i & -i;
}
}
int get_max_value() { return bit.size() - 1; }
};
int count_inversion_number(vector<int> &v, int max_value) {
BinaryIndexTree bit(max_value);
int n = v.size();
int res = 0;
for (int i = 0ll; i < n; i++) {
res += i - bit.sum(v[i]);
bit.add(v[i], 1);
}
return res;
}
| 18.789474 | 59 | 0.539216 | [
"vector"
] |
ef48c405489ee2bb5e44722844494379aa5500de | 956 | cpp | C++ | array/merge-intervals.cpp | Nilesh-Das/mustdogfg | bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f | [
"MIT"
] | null | null | null | array/merge-intervals.cpp | Nilesh-Das/mustdogfg | bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f | [
"MIT"
] | null | null | null | array/merge-intervals.cpp | Nilesh-Das/mustdogfg | bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
using namespace std;
vector<vector<int>> merge(vector<vector<int>> &intervals) {
vector<vector<int>> res;
auto comp = [&](const vector<int> &a, const vector<int> &b)
{ return a[0] < b[0]; };
sort(intervals.begin(), intervals.end(), comp);
int n = intervals.size();
res.push_back(intervals[0]);
vector<int> v;
for(int i=1; i<n; i++) {
if(res.back()[1] >= intervals[i][0]) {
v.resize(0);
v.push_back(res.back()[0]);
v.push_back(max(res.back()[1], intervals[i][1]));
res.pop_back();
res.push_back(v);
} else {
res.push_back(intervals[i]);
}
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};
vector<vector<int>> res = merge(intervals);
for(auto x : res) {
for(auto y : x) {
cout << y << ' ';
}
cout << '\n';
}
return 0;
} | 22.232558 | 63 | 0.557531 | [
"vector"
] |
ef493bd32fa4caaed05dd83d8f04b142bf219e83 | 3,968 | cc | C++ | tensorstore/driver/downsample/downsample_benchmark_test.cc | google/tensorstore | 8df16a67553debaec098698ceaa5404eaf79634a | [
"BSD-2-Clause"
] | 106 | 2020-04-02T20:00:18.000Z | 2022-03-23T20:27:31.000Z | tensorstore/driver/downsample/downsample_benchmark_test.cc | 0xgpapad/tensorstore | dfc2972e54588a7b745afea8b9322b57b26b657a | [
"BSD-2-Clause"
] | 28 | 2020-04-12T02:04:47.000Z | 2022-03-23T20:27:03.000Z | tensorstore/driver/downsample/downsample_benchmark_test.cc | 0xgpapad/tensorstore | dfc2972e54588a7b745afea8b9322b57b26b657a | [
"BSD-2-Clause"
] | 18 | 2020-04-08T06:41:30.000Z | 2022-02-18T03:05:49.000Z | // Copyright 2020 The TensorStore Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "absl/random/random.h"
#include <benchmark/benchmark.h>
#include "tensorstore/array.h"
#include "tensorstore/box.h"
#include "tensorstore/data_type.h"
#include "tensorstore/driver/downsample/downsample_array.h"
#include "tensorstore/driver/downsample/downsample_nditerable.h"
#include "tensorstore/driver/downsample/downsample_util.h"
#include "tensorstore/index.h"
#include "tensorstore/internal/data_type_random_generator.h"
#include "tensorstore/internal/global_initializer.h"
#include "tensorstore/util/str_cat.h"
namespace {
using tensorstore::Box;
using tensorstore::BoxView;
using tensorstore::DataType;
using tensorstore::DimensionIndex;
using tensorstore::DownsampleMethod;
using tensorstore::Index;
using tensorstore::internal_downsample::DownsampleArray;
using tensorstore::internal_downsample::DownsampleBounds;
void BenchmarkDownsample(::benchmark::State& state, DataType dtype,
DownsampleMethod downsample_method,
DimensionIndex rank, Index downsample_factor,
Index block_size) {
std::vector<Index> downsample_factors(rank, downsample_factor);
std::vector<Index> block_shape(rank, block_size);
absl::BitGen gen;
BoxView<> base_domain(block_shape);
auto base_array =
tensorstore::internal::MakeRandomArray(gen, base_domain, dtype);
Box<> downsampled_domain(rank);
DownsampleBounds(base_domain, downsampled_domain, downsample_factors,
downsample_method);
auto downsampled_array =
tensorstore::AllocateArray(downsampled_domain, tensorstore::c_order,
tensorstore::default_init, dtype);
const Index num_elements = base_domain.num_elements();
Index total_elements = 0;
while (state.KeepRunningBatch(num_elements)) {
TENSORSTORE_CHECK(DownsampleArray(base_array, downsampled_array,
downsample_factors, downsample_method)
.ok());
total_elements += num_elements;
}
state.SetItemsProcessed(total_elements);
}
TENSORSTORE_GLOBAL_INITIALIZER {
for (const DataType dtype : tensorstore::kDataTypes) {
for (const DownsampleMethod downsample_method :
{DownsampleMethod::kStride, DownsampleMethod::kMean,
DownsampleMethod::kMedian, DownsampleMethod::kMode,
DownsampleMethod::kMin,
// Skip `kMax` because it is redundant with `kMin`.
/*DownsampleMethod::kMax*/}) {
if (!tensorstore::internal_downsample::IsDownsampleMethodSupported(
dtype, downsample_method)) {
continue;
}
for (const DimensionIndex rank : {1, 2, 3}) {
for (const Index downsample_factor : {2, 3}) {
for (const Index block_size : {16, 32, 64, 128, 256}) {
::benchmark::RegisterBenchmark(
tensorstore::StrCat("DownsampleArray_", dtype, "_",
downsample_method, "_Rank", rank, "_Factor",
downsample_factor, "_BlockSize", block_size)
.c_str(),
[=](auto& state) {
BenchmarkDownsample(state, dtype, downsample_method, rank,
downsample_factor, block_size);
});
}
}
}
}
}
}
} // namespace
| 39.68 | 80 | 0.673135 | [
"vector"
] |
ef541f943c72a85b01b1bbd7ce605e22ece26740 | 9,173 | hpp | C++ | franka_gripper/include/franka_gripper/gripper_action_server.hpp | FarisHamdi/franka_ros2 | 32a936045e0029cbd0b380014a51cbe44f934f86 | [
"Apache-2.0"
] | 10 | 2021-12-14T21:48:41.000Z | 2022-03-21T20:50:44.000Z | franka_gripper/include/franka_gripper/gripper_action_server.hpp | FarisHamdi/franka_ros2 | 32a936045e0029cbd0b380014a51cbe44f934f86 | [
"Apache-2.0"
] | 2 | 2022-02-14T14:08:59.000Z | 2022-03-23T07:57:22.000Z | franka_gripper/include/franka_gripper/gripper_action_server.hpp | FarisHamdi/franka_ros2 | 32a936045e0029cbd0b380014a51cbe44f934f86 | [
"Apache-2.0"
] | 2 | 2022-02-14T08:39:59.000Z | 2022-03-22T19:09:20.000Z | // Copyright (c) 2021 Franka Emika GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <chrono>
#include <functional>
#include <future>
#include <memory>
#include <string>
#include <thread>
#include <franka/exception.h>
#include <franka/gripper.h>
#include <franka/gripper_state.h>
#include <control_msgs/action/gripper_command.hpp>
#include <franka_msgs/action/grasp.hpp>
#include <franka_msgs/action/homing.hpp>
#include <franka_msgs/action/move.hpp>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp_action/rclcpp_action.hpp>
#include <sensor_msgs/msg/joint_state.hpp>
#include <std_srvs/srv/trigger.hpp>
namespace franka_gripper {
/// checks whether an asynchronous command has finished
/// @tparam T the expected return type of the future
/// @param t the future which should be checked
/// @param future_wait_timeout how long to wait for the result before returning false
/// @return whether the asynchronous function has already finished
template <typename T>
bool resultIsReady(std::future<T>& t, std::chrono::nanoseconds future_wait_timeout) {
return t.wait_for(future_wait_timeout) == std::future_status::ready;
}
/// ROS node that offers multiple actions to use the gripper.
class GripperActionServer : public rclcpp::Node {
public:
using Homing = franka_msgs::action::Homing;
using GoalHandleHoming = rclcpp_action::ServerGoalHandle<Homing>;
using Move = franka_msgs::action::Move;
using GoalHandleMove = rclcpp_action::ServerGoalHandle<Move>;
using Grasp = franka_msgs::action::Grasp;
using GoalHandleGrasp = rclcpp_action::ServerGoalHandle<Grasp>;
using GripperCommand = control_msgs::action::GripperCommand;
using GoalHandleGripperCommand = rclcpp_action::ServerGoalHandle<GripperCommand>;
using Trigger = std_srvs::srv::Trigger;
/// creates an instance of a GripperActionServer
/// @param options options for node initialization
explicit GripperActionServer(const rclcpp::NodeOptions& options = rclcpp::NodeOptions());
private:
/// describes the different tasks. Each task corresponds to one action server
enum class Task { kHoming, kMove, kGrasp, kGripperCommand };
/// returns a string version of the Task enum
static std::string getTaskName(Task task) {
switch (task) {
case Task::kHoming:
return {"Homing"};
case Task::kMove:
return {"Moving"};
case Task::kGrasp:
return {"Grasping"};
case Task::kGripperCommand:
return {"GripperCommand"};
default:
throw std::invalid_argument("getTaskName is not implemented for this case");
}
};
const double k_default_grasp_epsilon = 0.005; // default inner and outer grasp epsilon in meter
const double k_default_speed = 0.1; // default gripper speed in m/s
const int k_default_state_publish_rate = 30; // default gripper state publish rate
const int k_default_feedback_publish_rate = 10; // default action feedback publish rate
std::unique_ptr<franka::Gripper> gripper_;
rclcpp_action::Server<Homing>::SharedPtr homing_server_;
rclcpp_action::Server<Move>::SharedPtr move_server_;
rclcpp_action::Server<Grasp>::SharedPtr grasp_server_;
rclcpp_action::Server<GripperCommand>::SharedPtr gripper_command_server_;
rclcpp::Service<Trigger>::SharedPtr stop_service_;
std::mutex gripper_state_mutex_;
franka::GripperState current_gripper_state_;
rclcpp::Publisher<sensor_msgs::msg::JointState>::SharedPtr joint_states_publisher_;
rclcpp::TimerBase::SharedPtr timer_;
double default_speed_; // default gripper speed parameter value in m/s
double default_epsilon_inner_; // default gripper inner epsilon parameter value in m
double default_epsilon_outer_; // default gripper outer epsilon parameter value in m
std::vector<std::string> joint_names_;
std::chrono::nanoseconds future_wait_timeout_{0};
void publishGripperState();
/// stops the gripper and writes the result into the response
/// @param[out] response will be updated with the success status and error message
void stopServiceCallback(const std::shared_ptr<Trigger::Response>& response);
/// accepts any cancel request
rclcpp_action::CancelResponse handleCancel(Task task);
/// accepts any goal request
rclcpp_action::GoalResponse handleGoal(Task task);
/// performs homing
void executeHoming(const std::shared_ptr<GoalHandleHoming>& goal_handle);
/// performs move
void executeMove(const std::shared_ptr<GoalHandleMove>& goal_handle);
/// performs grasp
void executeGrasp(const std::shared_ptr<GoalHandleGrasp>& goal_handle);
/// Performs the moveit grasp command
/// @param goal_handle
/// @param command_handler eiter a grasp or move command defined by the onExecuteGripperCommand
/// method
void executeGripperCommand(const std::shared_ptr<GoalHandleGripperCommand>& goal_handle,
const std::function<bool()>& command_handler);
/// Defines a function for either grasping or moving the gripper, depending on the current gripper
/// state and the commanded goal. Then it calls executeGripperCommand to execute that function
void onExecuteGripperCommand(const std::shared_ptr<GoalHandleGripperCommand>& goal_handle);
/// Executes a gripper command
/// @tparam T A gripper action message type (Move, Grasp, Homing)
/// @param[in] goal_handle The goal handle from the action server
/// @param[in] task The type of the Task
/// @param[in] command_handler a function that performs the the task. Returns true on success.
/// This function is allowed to throw a franka::Exception
template <typename T>
void executeCommand(const std::shared_ptr<rclcpp_action::ServerGoalHandle<T>>& goal_handle,
Task task,
const std::function<bool()>& command_handler) {
const auto kTaskName = getTaskName(task);
RCLCPP_INFO(this->get_logger(), "Gripper %s...", kTaskName.c_str());
auto command_execution_thread = withResultGenerator<T>(command_handler);
std::future<std::shared_ptr<typename T::Result>> result_future =
std::async(std::launch::async, command_execution_thread);
while (not resultIsReady(result_future, future_wait_timeout_) and rclcpp::ok()) {
if (goal_handle->is_canceling()) {
gripper_->stop();
auto result = result_future.get();
RCLCPP_INFO(get_logger(), "Gripper %s canceled", kTaskName.c_str());
goal_handle->canceled(result);
return;
}
publishGripperWidthFeedback(goal_handle);
}
if (rclcpp::ok()) {
const auto kResult = result_future.get();
if (kResult->success) {
RCLCPP_INFO(get_logger(), "Gripper %s succeeded", kTaskName.c_str());
goal_handle->succeed(kResult);
} else {
RCLCPP_INFO(get_logger(), "Gripper %s failed", kTaskName.c_str());
goal_handle->abort(kResult);
}
}
}
/// Creates a function that catches exceptions for the gripper command function and returns a
/// result
/// @tparam T A gripper action message type (Move, Grasp, Homing)
/// @param[in] command_handler a function that performs the the task. Returns true on success.
/// This function is allowed to throw a franka::Exception
/// @return[in] enhanced command_handler that now returns a result an does not throw a
/// franka::exception anymore
template <typename T>
auto withResultGenerator(const std::function<bool()>& command_handler)
-> std::function<std::shared_ptr<typename T::Result>()> {
return [command_handler]() {
auto result = std::make_shared<typename T::Result>();
try {
result->success = command_handler();
} catch (const franka::Exception& e) {
result->success = false;
result->error = e.what();
}
return result;
};
}
/// Publishes the gripper width as feedback for actions
/// @tparam T A gripper action message type (Move, Grasp, Homing)
/// @param[in] goal_handle The goal handle from the action server
template <typename T>
void publishGripperWidthFeedback(
const std::shared_ptr<rclcpp_action::ServerGoalHandle<T>>& goal_handle) {
auto gripper_feedback = std::make_shared<typename T::Feedback>();
std::lock_guard<std::mutex> guard(gripper_state_mutex_);
gripper_feedback->current_width = current_gripper_state_.width;
goal_handle->publish_feedback(gripper_feedback);
}
/// Publishes the gripper width as feedback for the GripperCommand action
void publishGripperCommandFeedback(
const std::shared_ptr<rclcpp_action::ServerGoalHandle<GripperCommand>>& goal_handle);
};
} // namespace franka_gripper
| 41.31982 | 100 | 0.72757 | [
"vector"
] |
ef57e5cf307f29801b0136f9ced180c2547df4d1 | 12,705 | cpp | C++ | source/renderer/passes/VolumePass.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | 6 | 2017-06-26T11:42:26.000Z | 2018-09-10T17:53:53.000Z | source/renderer/passes/VolumePass.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | 8 | 2017-06-24T20:25:42.000Z | 2017-08-09T10:50:40.000Z | source/renderer/passes/VolumePass.cpp | DaSutt/VolumetricParticles | 6ec9bac4bec4a8757343bb770b23110ef2364dfd | [
"Apache-2.0"
] | null | null | null | /*
MIT License
Copyright(c) 2017 Daniel Suttor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "VolumePass.h"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm\gtx\transform.hpp>
#include <glm\gtx\euler_angles.hpp>
#include <random>
#include <functional>
#include "..\passResources\ShaderBindingManager.h"
#include "..\passResources\ShaderManager.h"
#include "..\resources\ImageManager.h"
#include "..\resources\QueueManager.h"
#include "..\resources\BufferManager.h"
#include "..\wrapper\Surface.h"
#include "..\wrapper\Synchronization.h"
#include "..\wrapper\Instance.h"
#include "..\wrapper\Barrier.h"
#include "..\ShadowMap.h"
#include "..\scene\adaptiveGrid\AdaptiveGrid.h"
#include "GuiPass.h"
#include "..\..\scene\Scene.h"
namespace Renderer
{
VolumePass::VolumePass(ShaderBindingManager* bindingManager, RenderPassManager* renderPassManager) :
Pass::Pass(bindingManager, renderPassManager)
{}
void VolumePass::SetShadowMap(ShadowMap* shadowMap, ImageManager* imageManager)
{
shadowMap_ = shadowMap;
imageManager_ = imageManager;
}
void VolumePass::SetAdaptiveGrid(AdaptiveGrid* adaptiveGrid)
{
adaptiveGrid_ = adaptiveGrid;
}
void VolumePass::SetImageIndices(int raymarchingImage, int depthImage, int noiseArray)
{
raymarchingImage_ = raymarchingImage;
depthImage_ = depthImage;
noiseImageIndex_ = noiseArray;
}
void VolumePass::RequestResources(ImageManager* imageManager, BufferManager* bufferManager, int frameCount)
{
computePipelines_.resize(COMPUTE_MAX);
auto subpass = COMPUTE_GLOBAL;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_GLOBAL);
}
subpass = COMPUTE_GROUND_FOG;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_GROUND_FOG);
}
subpass = COMPUTE_PARTICLES;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_PARTICLES);
}
subpass = COMPUTE_DEBUG_FILLING;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_DEBUG_FILLING);
}
subpass = COMPUTE_NEIGHBOR_UPDATE;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_NEIGHBOR_UPDATE);
}
subpass = COMPUTE_MIPMAPPING;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_MIPMAPPING);
}
subpass = COMPUTE_MIPMAPPING_MERGING;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_MIPMAPPING_MERGING);
}
subpass = COMPUTE_RAYMARCHING;
{
computePipelines_[subpass].shaderBinding = adaptiveGrid_->GetShaderBinding(bindingManager_, AdaptiveGrid::GRID_PASS_RAYMARCHING);
}
}
bool VolumePass::Create(VkDevice device, ShaderManager* shaderManager, FrameBufferManager* frameBufferManager,
Surface* surface, ImageManager* imageManager)
{
if (!CreateComputePipelines(device, shaderManager)) { return false; }
const int imageCount = surface->GetImageCount();
if (!CreateCommandBuffers(device, QueueManager::QUEUE_COMPUTE, imageCount)) { return false; }
for (int i = 0; i < COMPUTE_MAX; ++i)
{
if (!Wrapper::CreateVulkanSemaphore(device, &computePipelines_[i].passFinishedSemaphore))
{
return false;
}
}
return true;
}
void VolumePass::UpdateBufferData(Surface* surface, Scene* scene)
{
const auto& volumeState = GuiPass::GetVolumeState();
const float fogHeight = volumeState.groundFogHeight;
const int centerCell = static_cast<int>((-scene->GetGrid()->GetMin().y) / scene->GetGrid()->GetCellSize().y);
mediaData_.fogHeight = (1.0f - fogHeight) * scene->GetGrid()->GetResolution().y;
const auto toWorld = glm::inverse(scene->GetCamera().GetProj() * scene->GetCamera().GetView());
//raymarchingData_.toLight = shadowMap_->GetViewProj();
const auto screenSize = surface->GetSurfaceSize();
raymarchingData_.toWorld = toWorld;
static std::default_random_engine generator;
static std::uniform_real_distribution<float> distribution(0.0f, 1.0f);
static auto RandPos = std::bind(distribution, generator);
raymarchingData_.randomness_ = { RandPos(), RandPos(), RandPos(), RandPos() };
}
void VolumePass::Update(float dt)
{
adaptiveGrid_->UpdateParticles(dt);
}
void VolumePass::Render(Surface* surface, FrameBufferManager* frameBufferManager,
QueueManager* queueManager, BufferManager* bufferManager,
std::vector<VkImageMemoryBarrier>& memoryBarrier, VkSemaphore* startSemaphore, int frameIndex)
{
auto& commandBuffer = commandBuffers_[frameIndex];
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
auto result = vkBeginCommandBuffer(commandBuffer, &beginInfo);
assert(result == VK_SUCCESS);
//imageManager_->Ref_ClearImage(commandBuffer, raymarchingImage_, { 0.0f, 0.0f, 0.0f, 1.0f });
int parentGridLevel = adaptiveGrid_->GetMaxParentLevel() + 1;
for (int pass = 0; pass < COMPUTE_MAX; ++pass)
{
RecordCommands(queueManager, bufferManager, imageManager_, surface, commandBuffer,
static_cast<ComputeSubpasses>(pass), frameIndex, parentGridLevel);
//Mip mapping has to be performed for each level seperately starting with the most detailed level
if (pass == COMPUTE_MIPMAPPING_MERGING && parentGridLevel > 0)
{
pass = COMPUTE_NEIGHBOR_UPDATE - 1;
}
if (pass == COMPUTE_NEIGHBOR_UPDATE)
{
parentGridLevel--;
}
}
result = vkEndCommandBuffer(commandBuffer);
assert(result == VK_SUCCESS);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &computePipelines_[COMPUTE_RAYMARCHING].passFinishedSemaphore;
std::vector<VkSemaphore> waitSemaphores;
waitSemaphores = { *startSemaphore };
submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
submitInfo.pWaitSemaphores = waitSemaphores.data();
std::vector<VkPipelineStageFlags> stageMasks = {
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT };
submitInfo.pWaitDstStageMask = stageMasks.data();
const auto& computeQueue = queueManager->GetQueue(QueueManager::QUEUE_COMPUTE);
vkQueueSubmit(computeQueue, 1, &submitInfo, VK_NULL_HANDLE);
adaptiveGrid_->UpdateDebugTraversal(queueManager, bufferManager, imageManager_);
}
void VolumePass::OnLoadScene(Scene* scene)
{
adaptiveGrid_->OnLoadScene(scene);
sceneLoaded_ = true;
}
void VolumePass::OnReloadShaders(VkDevice device, ShaderManager* shaderManager)
{
Pass::OnReloadShaders(device, shaderManager);
CreateComputePipelines(device, shaderManager);
}
void VolumePass::Release(VkDevice device)
{
Pass::Release(device);
}
VkSemaphore* VolumePass::GetFinishedSemaphore()
{
return &computePipelines_[COMPUTE_RAYMARCHING].passFinishedSemaphore;
}
bool VolumePass::CreateComputePipelines(VkDevice device, ShaderManager* shaderManager)
{
std::vector<VkComputePipelineCreateInfo> createInfos;
for(int subpass = SUBPASS_VOLUME_ADAPTIVE_GLOBAL; subpass <= SUBPASS_VOLUME_ADAPTIVE_RAYMARCHING; ++subpass)
{
VkComputePipelineCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
auto& shaderStage = shaderManager->GetShaderStageInfo(static_cast<SubPassType>(subpass));
createInfo.stage = shaderStage[0];
auto& pipelineLayout = bindingManager_->GetPipelineLayout(static_cast<SubPassType>(subpass));
createInfo.layout = pipelineLayout;
createInfos.push_back(createInfo);
}
std::vector<VkPipeline> pipelines(createInfos.size(), VK_NULL_HANDLE);
const auto result = vkCreateComputePipelines(device, VK_NULL_HANDLE,
static_cast<uint32_t>(createInfos.size()), createInfos.data(), nullptr, pipelines.data());
if (result != VK_SUCCESS)
{
printf("Create volume compute passes failed, %d\n", result);
return false;
}
for (size_t pass = 0; pass < pipelines.size(); ++pass)
{
computePipelines_[pass].pipeline = pipelines[pass];
}
return true;
}
bool VolumePass::RecordCommands(QueueManager* queueManager, BufferManager* bufferManager, ImageManager* imageManager, Surface* surface, VkCommandBuffer commandBuffer,
ComputeSubpasses subpass, uint32_t currFrameIndex, int gridLevel)
{
SubPassType passType;
AdaptiveGrid::Pass gridPass;
switch (subpass)
{
case COMPUTE_GLOBAL:
passType = SUBPASS_VOLUME_ADAPTIVE_GLOBAL;
gridPass = AdaptiveGrid::GRID_PASS_GLOBAL;
break;
case COMPUTE_GROUND_FOG:
passType = SUBPASS_VOLUME_ADAPTIVE_GROUND_FOG;
gridPass = AdaptiveGrid::GRID_PASS_GROUND_FOG;
break;
case COMPUTE_PARTICLES:
passType = SUBPASS_VOLUME_ADAPTIVE_PARTICLES;
gridPass = AdaptiveGrid::GRID_PASS_PARTICLES;
break;
case COMPUTE_DEBUG_FILLING:
passType = SUBPASS_VOLUME_ADAPTIVE_DEBUG_FILLING;
gridPass = AdaptiveGrid::GRID_PASS_DEBUG_FILLING;
break;
case COMPUTE_MIPMAPPING:
passType = SUBPASS_VOLUME_ADAPTIVE_MIPMAPPING;
gridPass = AdaptiveGrid::GRID_PASS_MIPMAPPING;
break;
case COMPUTE_MIPMAPPING_MERGING:
passType = SUBPASS_VOLUME_ADAPTIVE_MIPMAPPING_MERGING;
gridPass = AdaptiveGrid::GRID_PASS_MIPMAPPING_MERGING;
break;
case COMPUTE_NEIGHBOR_UPDATE:
passType = SUBPASS_VOLUME_ADAPTIVE_NEIGHBOR_UPDATE;
gridPass = AdaptiveGrid::GRID_PASS_NEIGHBOR_UPDATE;
break;
case COMPUTE_RAYMARCHING:
passType = SUBPASS_VOLUME_ADAPTIVE_RAYMARCHING;
gridPass = AdaptiveGrid::GRID_PASS_RAYMARCHING;
break;
default:
return true;
}
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE,
computePipelines_[subpass].pipeline);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE,
bindingManager_->GetPipelineLayout(passType), 0, 1,
&bindingManager_->GetDescriptorSet(computePipelines_[subpass].shaderBinding, currFrameIndex), 0, 0);
if (!sceneLoaded_)
{
if (subpass == COMPUTE_RAYMARCHING)
{
ImageManager::BarrierInfo shadowMapBarrier{};
shadowMapBarrier.imageIndex = shadowMap_->GetImageIndex();
shadowMapBarrier.type = ImageManager::BARRIER_READ_WRITE;
auto barriers = imageManager->Barrier({ shadowMapBarrier });
Wrapper::PipelineBarrierInfo pipelineBarrierInfo{};
pipelineBarrierInfo.src = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
pipelineBarrierInfo.dst = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
pipelineBarrierInfo.AddImageBarriers(barriers);
Wrapper::AddPipelineBarrier(commandBuffer, pipelineBarrierInfo);
}
return true;
}
switch (subpass)
{
case COMPUTE_PARTICLES:
case COMPUTE_GLOBAL:
case COMPUTE_DEBUG_FILLING:
case COMPUTE_GROUND_FOG:
case COMPUTE_MIPMAPPING:
case COMPUTE_MIPMAPPING_MERGING:
case COMPUTE_NEIGHBOR_UPDATE:
adaptiveGrid_->Dispatch(queueManager, imageManager, bufferManager, commandBuffer, gridPass, currFrameIndex, gridLevel);
break;
case COMPUTE_RAYMARCHING:
{
const auto& surfaceSize = surface->GetSurfaceSize();
adaptiveGrid_->Raymarch(imageManager, commandBuffer, surfaceSize.width, surfaceSize.height, currFrameIndex);
adaptiveGrid_->Dispatch(queueManager, imageManager, bufferManager, commandBuffer, gridPass, currFrameIndex, gridLevel);
} break;
}
return true;
}
} | 35.991501 | 168 | 0.761905 | [
"render",
"vector",
"transform"
] |
ef5c1e585d60bbfb92d9ebcf87e6c369e920373e | 6,701 | cpp | C++ | pyPBD/RigidBodyModule.cpp | mcx/PositionBasedDynamics | 136469f03f7869666d907ea8d27872b098715f4a | [
"MIT"
] | 1,169 | 2016-05-31T03:01:55.000Z | 2022-03-31T15:38:47.000Z | pyPBD/RigidBodyModule.cpp | Taiyuan-Zhang/PositionBasedDynamics | 136469f03f7869666d907ea8d27872b098715f4a | [
"MIT"
] | 88 | 2016-06-10T19:09:24.000Z | 2022-02-08T10:50:41.000Z | pyPBD/RigidBodyModule.cpp | Taiyuan-Zhang/PositionBasedDynamics | 136469f03f7869666d907ea8d27872b098715f4a | [
"MIT"
] | 267 | 2016-06-22T06:44:11.000Z | 2022-03-29T11:55:24.000Z | #include "common.h"
#include <Simulation/RigidBody.h>
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <pybind11/stl_bind.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
namespace py = pybind11;
template <typename... Args>
using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
#define GET_QUAT_FCT_CONVERT(name) .def(#name, [](PBD::RigidBody& obj) { return obj.name().coeffs(); })
#define SET_QUAT_FCT_CONVERT(name) \
.def(#name, [](PBD::RigidBody& obj, const Vector4r& qVec) \
{ \
Quaternionr q; \
q.coeffs() = qVec; \
obj.name(q); \
})
void RigidBodyModule(py::module m_sub)
{
py::class_<PBD::RigidBodyGeometry>(m_sub, "RigidBodyGeometry")
.def(py::init<>())
.def("getMesh", &PBD::RigidBodyGeometry::getMesh)
.def("getVertexData", (const PBD::VertexData & (PBD::RigidBodyGeometry::*)()const)(&PBD::RigidBodyGeometry::getVertexData))
.def("getVertexDataLocal", (const PBD::VertexData & (PBD::RigidBodyGeometry::*)()const)(&PBD::RigidBodyGeometry::getVertexDataLocal))
.def("initMesh", &PBD::RigidBodyGeometry::initMesh)
.def("updateMeshTransformation", &PBD::RigidBodyGeometry::updateMeshTransformation)
.def("updateMeshNormals", &PBD::RigidBodyGeometry::updateMeshNormals)
;
py::class_<PBD::RigidBody>(m_sub, "RigidBody")
.def(py::init<>())
.def("initBody", [](PBD::RigidBody& obj, const Real density,
const Vector3r& x, const Vector4r& qVec,
const PBD::VertexData& vertices, const Utilities::IndexedFaceMesh& mesh,
const Vector3r& scale)
{
Quaternionr q;
q.coeffs() = qVec;
obj.initBody(density, x, q, vertices, mesh, scale);
})
.def("initBody", [](PBD::RigidBody& obj, const Real mass,
const Vector3r& x, const Vector3r& inertiaTensor, const Vector4r& qVec,
const PBD::VertexData& vertices, const Utilities::IndexedFaceMesh& mesh,
const Vector3r& scale)
{
Quaternionr q;
q.coeffs() = qVec;
obj.initBody(mass, x, inertiaTensor, q, vertices, mesh, scale);
})
.def("reset", &PBD::RigidBody::reset)
.def("updateInverseTransformation", &PBD::RigidBody::updateInverseTransformation)
.def("rotationUpdated", &PBD::RigidBody::rotationUpdated)
.def("updateInertiaW", &PBD::RigidBody::updateInertiaW)
.def("determineMassProperties", &PBD::RigidBody::determineMassProperties)
.def("getTransformationR", &PBD::RigidBody::getTransformationR)
.def("getTransformationV1", &PBD::RigidBody::getTransformationV1)
.def("getTransformationV2", &PBD::RigidBody::getTransformationV2)
.def("getTransformationRXV1", &PBD::RigidBody::getTransformationRXV1)
.def("getMass", (const Real&(PBD::RigidBody::*)()const)(&PBD::RigidBody::getMass))
.def("setMass", &PBD::RigidBody::setMass)
.def("getInvMass", &PBD::RigidBody::getInvMass)
.def("getPosition", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getPosition))
.def("setPosition", &PBD::RigidBody::setPosition)
.def("getLastPosition", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getLastPosition))
.def("setLastPosition", &PBD::RigidBody::setLastPosition)
.def("getOldPosition", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getOldPosition))
.def("setOldPosition", &PBD::RigidBody::setOldPosition)
.def("getPosition0", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getPosition0))
.def("setPosition0", &PBD::RigidBody::setPosition0)
.def("getPositionInitial_MAT", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getPositionInitial_MAT))
.def("setPositionInitial_MAT", &PBD::RigidBody::setPositionInitial_MAT)
.def("getVelocity", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getVelocity))
.def("setVelocity", &PBD::RigidBody::setVelocity)
.def("getVelocity0", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getVelocity0))
.def("setVelocity0", &PBD::RigidBody::setVelocity0)
.def("getAcceleration", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getAcceleration))
.def("setAcceleration", &PBD::RigidBody::setAcceleration)
.def("getInertiaTensor", &PBD::RigidBody::getInertiaTensor)
.def("setInertiaTensor", &PBD::RigidBody::setInertiaTensor)
.def("getInertiaTensorW", (const Matrix3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getInertiaTensorW))
.def("getInertiaTensorInverse", &PBD::RigidBody::getInertiaTensorInverse)
.def("getInertiaTensorInverseW", (const Matrix3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getInertiaTensorInverseW))
.def("setInertiaTensorInverseW", &PBD::RigidBody::setInertiaTensorInverseW)
GET_QUAT_FCT_CONVERT(getRotation)
SET_QUAT_FCT_CONVERT(setRotation)
GET_QUAT_FCT_CONVERT(getLastRotation)
SET_QUAT_FCT_CONVERT(setLastRotation)
GET_QUAT_FCT_CONVERT(getOldRotation)
SET_QUAT_FCT_CONVERT(setOldRotation)
GET_QUAT_FCT_CONVERT(getRotation0)
SET_QUAT_FCT_CONVERT(setRotation0)
GET_QUAT_FCT_CONVERT(getRotationMAT)
SET_QUAT_FCT_CONVERT(setRotationMAT)
GET_QUAT_FCT_CONVERT(getRotationInitial)
SET_QUAT_FCT_CONVERT(setRotationInitial)
.def("getRotationMatrix", (const Matrix3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getRotationMatrix))
.def("setRotationMatrix", &PBD::RigidBody::setRotationMatrix)
.def("getAngularVelocity", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getAngularVelocity))
.def("setAngularVelocity", &PBD::RigidBody::setAngularVelocity)
.def("getAngularVelocity0", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getAngularVelocity0))
.def("setAngularVelocity0", &PBD::RigidBody::setAngularVelocity0)
.def("getTorque", (const Vector3r & (PBD::RigidBody::*)()const)(&PBD::RigidBody::getTorque))
.def("setTorque", &PBD::RigidBody::setTorque)
.def("getRestitutionCoeff", &PBD::RigidBody::getRestitutionCoeff)
.def("setRestitutionCoeff", &PBD::RigidBody::setRestitutionCoeff)
.def("getFrictionCoeff", &PBD::RigidBody::getFrictionCoeff)
.def("setFrictionCoeff", &PBD::RigidBody::setFrictionCoeff)
.def("getGeometry", &PBD::RigidBody::getGeometry)
;
} | 56.788136 | 141 | 0.662289 | [
"mesh"
] |
ef5e93b5632e36f2cf4d7a0d27e195383c73af9e | 3,056 | cpp | C++ | hiro/windows/widget/check-button.cpp | mp-lee/higan | c38a771f2272c3ee10fcb99f031e982989c08c60 | [
"Intel",
"ISC"
] | 38 | 2018-04-05T05:00:05.000Z | 2022-02-06T00:02:02.000Z | hiro/windows/widget/check-button.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 1 | 2018-04-29T19:45:14.000Z | 2018-04-29T19:45:14.000Z | hiro/windows/widget/check-button.cpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 8 | 2018-04-16T22:37:46.000Z | 2021-02-10T07:37:03.000Z | #if defined(Hiro_CheckButton)
namespace hiro {
static auto CALLBACK CheckButton_windowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) -> LRESULT {
if(auto object = (mObject*)GetWindowLongPtr(hwnd, GWLP_USERDATA)) {
if(auto button = dynamic_cast<mCheckButton*>(object)) {
if(auto self = button->self()) {
if(msg == WM_ERASEBKGND) return DefWindowProc(hwnd, msg, wparam, lparam);
if(msg == WM_PAINT) return Button_paintProc(hwnd, msg, wparam, lparam,
button->state.bordered, button->state.checked, button->enabled(true), button->font(true),
button->state.icon, button->state.orientation, button->state.text
);
return self->windowProc(hwnd, msg, wparam, lparam);
}
}
}
return DefWindowProc(hwnd, msg, wparam, lparam);
}
auto pCheckButton::construct() -> void {
hwnd = CreateWindow(L"BUTTON", L"",
WS_CHILD | WS_TABSTOP | BS_CHECKBOX | BS_PUSHLIKE,
0, 0, 0, 0, _parentHandle(), nullptr, GetModuleHandle(0), 0);
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)&reference);
windowProc = (WindowProc)GetWindowLongPtr(hwnd, GWLP_WNDPROC);
SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)CheckButton_windowProc);
pWidget::_setState();
_setState();
setChecked(state().checked);
}
auto pCheckButton::destruct() -> void {
DestroyWindow(hwnd);
}
auto pCheckButton::minimumSize() const -> Size {
Size icon = {(int)state().icon.width(), (int)state().icon.height()};
Size text = state().text ? pFont::size(self().font(true), state().text) : Size{};
Size size;
if(state().orientation == Orientation::Horizontal) {
size.setWidth(icon.width() + (icon && text ? 5 : 0) + text.width());
size.setHeight(max(icon.height(), text.height()));
}
if(state().orientation == Orientation::Vertical) {
size.setWidth(max(icon.width(), text.width()));
size.setHeight(icon.height() + (icon && text ? 5 : 0) + text.height());
}
size.setHeight(max(size.height(), pFont::size(self().font(true), " ").height()));
return {size.width() + (state().bordered && text ? 20 : 10), size.height() + 10};
}
auto pCheckButton::setBordered(bool bordered) -> void {
_setState();
}
auto pCheckButton::setChecked(bool checked) -> void {
SendMessage(hwnd, BM_SETCHECK, (WPARAM)checked, 0);
}
auto pCheckButton::setEnabled(bool enabled) -> void {
pWidget::setEnabled(enabled);
_setState();
}
auto pCheckButton::setFont(const Font& font) -> void {
pWidget::setFont(font);
_setState();
}
auto pCheckButton::setIcon(const image& icon) -> void {
_setState();
}
auto pCheckButton::setOrientation(Orientation orientation) -> void {
_setState();
}
auto pCheckButton::setText(const string& text) -> void {
_setState();
}
auto pCheckButton::setVisible(bool visible) -> void {
pWidget::setVisible(visible);
_setState();
}
auto pCheckButton::onToggle() -> void {
state().checked = !state().checked;
setChecked(state().checked);
self().doToggle();
}
auto pCheckButton::_setState() -> void {
InvalidateRect(hwnd, 0, false);
}
}
#endif
| 30.257426 | 107 | 0.674084 | [
"object"
] |
ef5f1fc8d5bd7380d07fcaccaa8f6cbe5a96c019 | 1,635 | cc | C++ | client/csrc/Service.cc | ao-song/May | eafe0e7b6a219db0e4b511274348bd6fac25eb01 | [
"Apache-2.0"
] | 1 | 2019-08-08T17:46:52.000Z | 2019-08-08T17:46:52.000Z | client/csrc/Service.cc | ao-song/May | eafe0e7b6a219db0e4b511274348bd6fac25eb01 | [
"Apache-2.0"
] | null | null | null | client/csrc/Service.cc | ao-song/May | eafe0e7b6a219db0e4b511274348bd6fac25eb01 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Ao Song <ao.song@outlook.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 "Service.h"
using namespace May;
Service::Service(
const string& id,
const string& name,
const string& address,
const int& port,
const vector<string>& tags)
: m_id(id),
m_name(name),
m_address(address),
m_port(port),
m_tags(tags)
{
m_json["id"] = id;
m_json["name"] = name;
m_json["address"] = address;
m_json["port"] = port;
json tmp_array;
for (auto i : tags)
{
tmp_array.push_back(i);
}
m_json["tags"] = tmp_array;
}
Service::Service(vector<uint8_t> bson)
{
m_json = json::from_bson(bson);
m_id = m_json["id"];
m_address = m_json["address"];
m_port = m_json["port"];
m_name = m_json["name"];
if (m_json["tags"].is_array())
{
m_tags.clear();
for (auto i : m_json["tags"])
{
m_tags.emplace_back(i);
}
}
}
string
Service::GetService()
{
return m_json.dump();
}
vector<uint8_t>
Service::GetServiceBson()
{
return json::to_bson(m_json);
}
| 22.094595 | 75 | 0.631804 | [
"vector"
] |
ef5f43220ea78dcc4f8aba9b0bf26f63d069160c | 177,933 | cpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/cisco_smart_license.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/cisco_smart_license.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/cisco_smart_license.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "cisco_smart_license.hpp"
using namespace ydk;
namespace cisco_ios_xe {
namespace cisco_smart_license {
RegisterIdToken::RegisterIdToken()
:
input(std::make_shared<RegisterIdToken::Input>())
, output(std::make_shared<RegisterIdToken::Output>())
{
input->parent = this;
output->parent = this;
yang_name = "register-id-token"; yang_parent_name = "cisco-smart-license"; is_top_level_class = true; has_list_ancestor = false;
}
RegisterIdToken::~RegisterIdToken()
{
}
bool RegisterIdToken::has_data() const
{
if (is_presence_container) return true;
return (input != nullptr && input->has_data())
|| (output != nullptr && output->has_data());
}
bool RegisterIdToken::has_operation() const
{
return is_set(yfilter)
|| (input != nullptr && input->has_operation())
|| (output != nullptr && output->has_operation());
}
std::string RegisterIdToken::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:register-id-token";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RegisterIdToken::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RegisterIdToken::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "input")
{
if(input == nullptr)
{
input = std::make_shared<RegisterIdToken::Input>();
}
return input;
}
if(child_yang_name == "output")
{
if(output == nullptr)
{
output = std::make_shared<RegisterIdToken::Output>();
}
return output;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RegisterIdToken::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(input != nullptr)
{
_children["input"] = input;
}
if(output != nullptr)
{
_children["output"] = output;
}
return _children;
}
void RegisterIdToken::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void RegisterIdToken::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> RegisterIdToken::clone_ptr() const
{
return std::make_shared<RegisterIdToken>();
}
std::string RegisterIdToken::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xe_models_path;
}
std::string RegisterIdToken::get_bundle_name() const
{
return "cisco_ios_xe";
}
augment_capabilities_function RegisterIdToken::get_augment_capabilities_function() const
{
return cisco_ios_xe_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> RegisterIdToken::get_namespace_identity_lookup() const
{
return cisco_ios_xe_namespace_identity_lookup;
}
bool RegisterIdToken::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "input" || name == "output")
return true;
return false;
}
RegisterIdToken::Input::Input()
:
id_token{YType::str, "id-token"},
force{YType::boolean, "force"}
{
yang_name = "input"; yang_parent_name = "register-id-token"; is_top_level_class = false; has_list_ancestor = false;
}
RegisterIdToken::Input::~Input()
{
}
bool RegisterIdToken::Input::has_data() const
{
if (is_presence_container) return true;
return id_token.is_set
|| force.is_set;
}
bool RegisterIdToken::Input::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(id_token.yfilter)
|| ydk::is_set(force.yfilter);
}
std::string RegisterIdToken::Input::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:register-id-token/" << get_segment_path();
return path_buffer.str();
}
std::string RegisterIdToken::Input::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "input";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RegisterIdToken::Input::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (id_token.is_set || is_set(id_token.yfilter)) leaf_name_data.push_back(id_token.get_name_leafdata());
if (force.is_set || is_set(force.yfilter)) leaf_name_data.push_back(force.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RegisterIdToken::Input::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RegisterIdToken::Input::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void RegisterIdToken::Input::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "id-token")
{
id_token = value;
id_token.value_namespace = name_space;
id_token.value_namespace_prefix = name_space_prefix;
}
if(value_path == "force")
{
force = value;
force.value_namespace = name_space;
force.value_namespace_prefix = name_space_prefix;
}
}
void RegisterIdToken::Input::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "id-token")
{
id_token.yfilter = yfilter;
}
if(value_path == "force")
{
force.yfilter = yfilter;
}
}
bool RegisterIdToken::Input::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "id-token" || name == "force")
return true;
return false;
}
RegisterIdToken::Output::Output()
:
return_code{YType::enumeration, "return-code"}
{
yang_name = "output"; yang_parent_name = "register-id-token"; is_top_level_class = false; has_list_ancestor = false;
}
RegisterIdToken::Output::~Output()
{
}
bool RegisterIdToken::Output::has_data() const
{
if (is_presence_container) return true;
return return_code.is_set;
}
bool RegisterIdToken::Output::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(return_code.yfilter);
}
std::string RegisterIdToken::Output::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:register-id-token/" << get_segment_path();
return path_buffer.str();
}
std::string RegisterIdToken::Output::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "output";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RegisterIdToken::Output::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (return_code.is_set || is_set(return_code.yfilter)) leaf_name_data.push_back(return_code.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RegisterIdToken::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RegisterIdToken::Output::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void RegisterIdToken::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "return-code")
{
return_code = value;
return_code.value_namespace = name_space;
return_code.value_namespace_prefix = name_space_prefix;
}
}
void RegisterIdToken::Output::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "return-code")
{
return_code.yfilter = yfilter;
}
}
bool RegisterIdToken::Output::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "return-code")
return true;
return false;
}
DeRegister::DeRegister()
:
output(std::make_shared<DeRegister::Output>())
{
output->parent = this;
yang_name = "de-register"; yang_parent_name = "cisco-smart-license"; is_top_level_class = true; has_list_ancestor = false;
}
DeRegister::~DeRegister()
{
}
bool DeRegister::has_data() const
{
if (is_presence_container) return true;
return (output != nullptr && output->has_data());
}
bool DeRegister::has_operation() const
{
return is_set(yfilter)
|| (output != nullptr && output->has_operation());
}
std::string DeRegister::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:de-register";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > DeRegister::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> DeRegister::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "output")
{
if(output == nullptr)
{
output = std::make_shared<DeRegister::Output>();
}
return output;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> DeRegister::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(output != nullptr)
{
_children["output"] = output;
}
return _children;
}
void DeRegister::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void DeRegister::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> DeRegister::clone_ptr() const
{
return std::make_shared<DeRegister>();
}
std::string DeRegister::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xe_models_path;
}
std::string DeRegister::get_bundle_name() const
{
return "cisco_ios_xe";
}
augment_capabilities_function DeRegister::get_augment_capabilities_function() const
{
return cisco_ios_xe_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> DeRegister::get_namespace_identity_lookup() const
{
return cisco_ios_xe_namespace_identity_lookup;
}
bool DeRegister::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "output")
return true;
return false;
}
DeRegister::Output::Output()
:
return_code{YType::enumeration, "return-code"}
{
yang_name = "output"; yang_parent_name = "de-register"; is_top_level_class = false; has_list_ancestor = false;
}
DeRegister::Output::~Output()
{
}
bool DeRegister::Output::has_data() const
{
if (is_presence_container) return true;
return return_code.is_set;
}
bool DeRegister::Output::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(return_code.yfilter);
}
std::string DeRegister::Output::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:de-register/" << get_segment_path();
return path_buffer.str();
}
std::string DeRegister::Output::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "output";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > DeRegister::Output::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (return_code.is_set || is_set(return_code.yfilter)) leaf_name_data.push_back(return_code.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> DeRegister::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> DeRegister::Output::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void DeRegister::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "return-code")
{
return_code = value;
return_code.value_namespace = name_space;
return_code.value_namespace_prefix = name_space_prefix;
}
}
void DeRegister::Output::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "return-code")
{
return_code.yfilter = yfilter;
}
}
bool DeRegister::Output::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "return-code")
return true;
return false;
}
RenewId::RenewId()
:
output(std::make_shared<RenewId::Output>())
{
output->parent = this;
yang_name = "renew-id"; yang_parent_name = "cisco-smart-license"; is_top_level_class = true; has_list_ancestor = false;
}
RenewId::~RenewId()
{
}
bool RenewId::has_data() const
{
if (is_presence_container) return true;
return (output != nullptr && output->has_data());
}
bool RenewId::has_operation() const
{
return is_set(yfilter)
|| (output != nullptr && output->has_operation());
}
std::string RenewId::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:renew-id";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RenewId::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RenewId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "output")
{
if(output == nullptr)
{
output = std::make_shared<RenewId::Output>();
}
return output;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RenewId::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(output != nullptr)
{
_children["output"] = output;
}
return _children;
}
void RenewId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void RenewId::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> RenewId::clone_ptr() const
{
return std::make_shared<RenewId>();
}
std::string RenewId::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xe_models_path;
}
std::string RenewId::get_bundle_name() const
{
return "cisco_ios_xe";
}
augment_capabilities_function RenewId::get_augment_capabilities_function() const
{
return cisco_ios_xe_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> RenewId::get_namespace_identity_lookup() const
{
return cisco_ios_xe_namespace_identity_lookup;
}
bool RenewId::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "output")
return true;
return false;
}
RenewId::Output::Output()
:
return_code{YType::enumeration, "return-code"}
{
yang_name = "output"; yang_parent_name = "renew-id"; is_top_level_class = false; has_list_ancestor = false;
}
RenewId::Output::~Output()
{
}
bool RenewId::Output::has_data() const
{
if (is_presence_container) return true;
return return_code.is_set;
}
bool RenewId::Output::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(return_code.yfilter);
}
std::string RenewId::Output::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:renew-id/" << get_segment_path();
return path_buffer.str();
}
std::string RenewId::Output::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "output";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RenewId::Output::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (return_code.is_set || is_set(return_code.yfilter)) leaf_name_data.push_back(return_code.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RenewId::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RenewId::Output::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void RenewId::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "return-code")
{
return_code = value;
return_code.value_namespace = name_space;
return_code.value_namespace_prefix = name_space_prefix;
}
}
void RenewId::Output::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "return-code")
{
return_code.yfilter = yfilter;
}
}
bool RenewId::Output::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "return-code")
return true;
return false;
}
RenewAuth::RenewAuth()
:
output(std::make_shared<RenewAuth::Output>())
{
output->parent = this;
yang_name = "renew-auth"; yang_parent_name = "cisco-smart-license"; is_top_level_class = true; has_list_ancestor = false;
}
RenewAuth::~RenewAuth()
{
}
bool RenewAuth::has_data() const
{
if (is_presence_container) return true;
return (output != nullptr && output->has_data());
}
bool RenewAuth::has_operation() const
{
return is_set(yfilter)
|| (output != nullptr && output->has_operation());
}
std::string RenewAuth::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:renew-auth";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RenewAuth::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RenewAuth::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "output")
{
if(output == nullptr)
{
output = std::make_shared<RenewAuth::Output>();
}
return output;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RenewAuth::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(output != nullptr)
{
_children["output"] = output;
}
return _children;
}
void RenewAuth::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void RenewAuth::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> RenewAuth::clone_ptr() const
{
return std::make_shared<RenewAuth>();
}
std::string RenewAuth::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xe_models_path;
}
std::string RenewAuth::get_bundle_name() const
{
return "cisco_ios_xe";
}
augment_capabilities_function RenewAuth::get_augment_capabilities_function() const
{
return cisco_ios_xe_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> RenewAuth::get_namespace_identity_lookup() const
{
return cisco_ios_xe_namespace_identity_lookup;
}
bool RenewAuth::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "output")
return true;
return false;
}
RenewAuth::Output::Output()
:
return_code{YType::enumeration, "return-code"}
{
yang_name = "output"; yang_parent_name = "renew-auth"; is_top_level_class = false; has_list_ancestor = false;
}
RenewAuth::Output::~Output()
{
}
bool RenewAuth::Output::has_data() const
{
if (is_presence_container) return true;
return return_code.is_set;
}
bool RenewAuth::Output::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(return_code.yfilter);
}
std::string RenewAuth::Output::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:renew-auth/" << get_segment_path();
return path_buffer.str();
}
std::string RenewAuth::Output::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "output";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > RenewAuth::Output::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (return_code.is_set || is_set(return_code.yfilter)) leaf_name_data.push_back(return_code.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> RenewAuth::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> RenewAuth::Output::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void RenewAuth::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "return-code")
{
return_code = value;
return_code.value_namespace = name_space;
return_code.value_namespace_prefix = name_space_prefix;
}
}
void RenewAuth::Output::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "return-code")
{
return_code.yfilter = yfilter;
}
}
bool RenewAuth::Output::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "return-code")
return true;
return false;
}
Licensing::Licensing()
:
config(std::make_shared<Licensing::Config>())
, state(std::make_shared<Licensing::State>())
{
config->parent = this;
state->parent = this;
yang_name = "licensing"; yang_parent_name = "cisco-smart-license"; is_top_level_class = true; has_list_ancestor = false;
}
Licensing::~Licensing()
{
}
bool Licensing::has_data() const
{
if (is_presence_container) return true;
return (config != nullptr && config->has_data())
|| (state != nullptr && state->has_data());
}
bool Licensing::has_operation() const
{
return is_set(yfilter)
|| (config != nullptr && config->has_operation())
|| (state != nullptr && state->has_operation());
}
std::string Licensing::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "config")
{
if(config == nullptr)
{
config = std::make_shared<Licensing::Config>();
}
return config;
}
if(child_yang_name == "state")
{
if(state == nullptr)
{
state = std::make_shared<Licensing::State>();
}
return state;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(config != nullptr)
{
_children["config"] = config;
}
if(state != nullptr)
{
_children["state"] = state;
}
return _children;
}
void Licensing::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Licensing::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Licensing::clone_ptr() const
{
return std::make_shared<Licensing>();
}
std::string Licensing::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xe_models_path;
}
std::string Licensing::get_bundle_name() const
{
return "cisco_ios_xe";
}
augment_capabilities_function Licensing::get_augment_capabilities_function() const
{
return cisco_ios_xe_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Licensing::get_namespace_identity_lookup() const
{
return cisco_ios_xe_namespace_identity_lookup;
}
bool Licensing::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "config" || name == "state")
return true;
return false;
}
Licensing::Config::Config()
:
enable{YType::boolean, "enable"},
custom_id{YType::str, "custom-id"}
,
privacy(std::make_shared<Licensing::Config::Privacy>())
, utility(std::make_shared<Licensing::Config::Utility>())
, transport(std::make_shared<Licensing::Config::Transport>())
{
privacy->parent = this;
utility->parent = this;
transport->parent = this;
yang_name = "config"; yang_parent_name = "licensing"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::~Config()
{
}
bool Licensing::Config::has_data() const
{
if (is_presence_container) return true;
return enable.is_set
|| custom_id.is_set
|| (privacy != nullptr && privacy->has_data())
|| (utility != nullptr && utility->has_data())
|| (transport != nullptr && transport->has_data());
}
bool Licensing::Config::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(enable.yfilter)
|| ydk::is_set(custom_id.yfilter)
|| (privacy != nullptr && privacy->has_operation())
|| (utility != nullptr && utility->has_operation())
|| (transport != nullptr && transport->has_operation());
}
std::string Licensing::Config::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "config";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata());
if (custom_id.is_set || is_set(custom_id.yfilter)) leaf_name_data.push_back(custom_id.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "privacy")
{
if(privacy == nullptr)
{
privacy = std::make_shared<Licensing::Config::Privacy>();
}
return privacy;
}
if(child_yang_name == "utility")
{
if(utility == nullptr)
{
utility = std::make_shared<Licensing::Config::Utility>();
}
return utility;
}
if(child_yang_name == "transport")
{
if(transport == nullptr)
{
transport = std::make_shared<Licensing::Config::Transport>();
}
return transport;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(privacy != nullptr)
{
_children["privacy"] = privacy;
}
if(utility != nullptr)
{
_children["utility"] = utility;
}
if(transport != nullptr)
{
_children["transport"] = transport;
}
return _children;
}
void Licensing::Config::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "enable")
{
enable = value;
enable.value_namespace = name_space;
enable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "custom-id")
{
custom_id = value;
custom_id.value_namespace = name_space;
custom_id.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "enable")
{
enable.yfilter = yfilter;
}
if(value_path == "custom-id")
{
custom_id.yfilter = yfilter;
}
}
bool Licensing::Config::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "privacy" || name == "utility" || name == "transport" || name == "enable" || name == "custom-id")
return true;
return false;
}
Licensing::Config::Privacy::Privacy()
:
hostname{YType::boolean, "hostname"},
version{YType::boolean, "version"}
{
yang_name = "privacy"; yang_parent_name = "config"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::Privacy::~Privacy()
{
}
bool Licensing::Config::Privacy::has_data() const
{
if (is_presence_container) return true;
return hostname.is_set
|| version.is_set;
}
bool Licensing::Config::Privacy::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(hostname.yfilter)
|| ydk::is_set(version.yfilter);
}
std::string Licensing::Config::Privacy::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/config/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::Privacy::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "privacy";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::Privacy::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (hostname.is_set || is_set(hostname.yfilter)) leaf_name_data.push_back(hostname.get_name_leafdata());
if (version.is_set || is_set(version.yfilter)) leaf_name_data.push_back(version.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::Privacy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::Privacy::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::Config::Privacy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "hostname")
{
hostname = value;
hostname.value_namespace = name_space;
hostname.value_namespace_prefix = name_space_prefix;
}
if(value_path == "version")
{
version = value;
version.value_namespace = name_space;
version.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::Privacy::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "hostname")
{
hostname.yfilter = yfilter;
}
if(value_path == "version")
{
version.yfilter = yfilter;
}
}
bool Licensing::Config::Privacy::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "hostname" || name == "version")
return true;
return false;
}
Licensing::Config::Utility::Utility()
:
utility_enable{YType::boolean, "utility-enable"}
,
customer_info(std::make_shared<Licensing::Config::Utility::CustomerInfo>())
{
customer_info->parent = this;
yang_name = "utility"; yang_parent_name = "config"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::Utility::~Utility()
{
}
bool Licensing::Config::Utility::has_data() const
{
if (is_presence_container) return true;
return utility_enable.is_set
|| (customer_info != nullptr && customer_info->has_data());
}
bool Licensing::Config::Utility::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(utility_enable.yfilter)
|| (customer_info != nullptr && customer_info->has_operation());
}
std::string Licensing::Config::Utility::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/config/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::Utility::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "utility";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::Utility::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (utility_enable.is_set || is_set(utility_enable.yfilter)) leaf_name_data.push_back(utility_enable.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::Utility::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "customer-info")
{
if(customer_info == nullptr)
{
customer_info = std::make_shared<Licensing::Config::Utility::CustomerInfo>();
}
return customer_info;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::Utility::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(customer_info != nullptr)
{
_children["customer-info"] = customer_info;
}
return _children;
}
void Licensing::Config::Utility::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "utility-enable")
{
utility_enable = value;
utility_enable.value_namespace = name_space;
utility_enable.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::Utility::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "utility-enable")
{
utility_enable.yfilter = yfilter;
}
}
bool Licensing::Config::Utility::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "customer-info" || name == "utility-enable")
return true;
return false;
}
Licensing::Config::Utility::CustomerInfo::CustomerInfo()
:
id{YType::str, "id"},
name{YType::str, "name"},
street{YType::str, "street"},
city{YType::str, "city"},
state{YType::str, "state"},
country{YType::str, "country"},
postal_code{YType::str, "postal-code"}
{
yang_name = "customer-info"; yang_parent_name = "utility"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::Utility::CustomerInfo::~CustomerInfo()
{
}
bool Licensing::Config::Utility::CustomerInfo::has_data() const
{
if (is_presence_container) return true;
return id.is_set
|| name.is_set
|| street.is_set
|| city.is_set
|| state.is_set
|| country.is_set
|| postal_code.is_set;
}
bool Licensing::Config::Utility::CustomerInfo::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(id.yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(street.yfilter)
|| ydk::is_set(city.yfilter)
|| ydk::is_set(state.yfilter)
|| ydk::is_set(country.yfilter)
|| ydk::is_set(postal_code.yfilter);
}
std::string Licensing::Config::Utility::CustomerInfo::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/config/utility/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::Utility::CustomerInfo::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "customer-info";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::Utility::CustomerInfo::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata());
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (street.is_set || is_set(street.yfilter)) leaf_name_data.push_back(street.get_name_leafdata());
if (city.is_set || is_set(city.yfilter)) leaf_name_data.push_back(city.get_name_leafdata());
if (state.is_set || is_set(state.yfilter)) leaf_name_data.push_back(state.get_name_leafdata());
if (country.is_set || is_set(country.yfilter)) leaf_name_data.push_back(country.get_name_leafdata());
if (postal_code.is_set || is_set(postal_code.yfilter)) leaf_name_data.push_back(postal_code.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::Utility::CustomerInfo::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::Utility::CustomerInfo::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::Config::Utility::CustomerInfo::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "id")
{
id = value;
id.value_namespace = name_space;
id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "street")
{
street = value;
street.value_namespace = name_space;
street.value_namespace_prefix = name_space_prefix;
}
if(value_path == "city")
{
city = value;
city.value_namespace = name_space;
city.value_namespace_prefix = name_space_prefix;
}
if(value_path == "state")
{
state = value;
state.value_namespace = name_space;
state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "country")
{
country = value;
country.value_namespace = name_space;
country.value_namespace_prefix = name_space_prefix;
}
if(value_path == "postal-code")
{
postal_code = value;
postal_code.value_namespace = name_space;
postal_code.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::Utility::CustomerInfo::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "id")
{
id.yfilter = yfilter;
}
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "street")
{
street.yfilter = yfilter;
}
if(value_path == "city")
{
city.yfilter = yfilter;
}
if(value_path == "state")
{
state.yfilter = yfilter;
}
if(value_path == "country")
{
country.yfilter = yfilter;
}
if(value_path == "postal-code")
{
postal_code.yfilter = yfilter;
}
}
bool Licensing::Config::Utility::CustomerInfo::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "id" || name == "name" || name == "street" || name == "city" || name == "state" || name == "country" || name == "postal-code")
return true;
return false;
}
Licensing::Config::Transport::Transport()
:
transport_type{YType::enumeration, "transport-type"}
,
transport_smart(std::make_shared<Licensing::Config::Transport::TransportSmart>())
{
transport_smart->parent = this;
yang_name = "transport"; yang_parent_name = "config"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::Transport::~Transport()
{
}
bool Licensing::Config::Transport::has_data() const
{
if (is_presence_container) return true;
return transport_type.is_set
|| (transport_smart != nullptr && transport_smart->has_data());
}
bool Licensing::Config::Transport::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(transport_type.yfilter)
|| (transport_smart != nullptr && transport_smart->has_operation());
}
std::string Licensing::Config::Transport::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/config/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::Transport::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "transport";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::Transport::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (transport_type.is_set || is_set(transport_type.yfilter)) leaf_name_data.push_back(transport_type.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::Transport::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "transport-smart")
{
if(transport_smart == nullptr)
{
transport_smart = std::make_shared<Licensing::Config::Transport::TransportSmart>();
}
return transport_smart;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::Transport::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(transport_smart != nullptr)
{
_children["transport-smart"] = transport_smart;
}
return _children;
}
void Licensing::Config::Transport::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "transport-type")
{
transport_type = value;
transport_type.value_namespace = name_space;
transport_type.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::Transport::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "transport-type")
{
transport_type.yfilter = yfilter;
}
}
bool Licensing::Config::Transport::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "transport-smart" || name == "transport-type")
return true;
return false;
}
Licensing::Config::Transport::TransportSmart::TransportSmart()
:
url_default{YType::boolean, "url-default"}
,
urls(std::make_shared<Licensing::Config::Transport::TransportSmart::Urls>())
{
urls->parent = this;
yang_name = "transport-smart"; yang_parent_name = "transport"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::Transport::TransportSmart::~TransportSmart()
{
}
bool Licensing::Config::Transport::TransportSmart::has_data() const
{
if (is_presence_container) return true;
return url_default.is_set
|| (urls != nullptr && urls->has_data());
}
bool Licensing::Config::Transport::TransportSmart::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(url_default.yfilter)
|| (urls != nullptr && urls->has_operation());
}
std::string Licensing::Config::Transport::TransportSmart::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/config/transport/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::Transport::TransportSmart::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "transport-smart";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::Transport::TransportSmart::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (url_default.is_set || is_set(url_default.yfilter)) leaf_name_data.push_back(url_default.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::Transport::TransportSmart::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "urls")
{
if(urls == nullptr)
{
urls = std::make_shared<Licensing::Config::Transport::TransportSmart::Urls>();
}
return urls;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::Transport::TransportSmart::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(urls != nullptr)
{
_children["urls"] = urls;
}
return _children;
}
void Licensing::Config::Transport::TransportSmart::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "url-default")
{
url_default = value;
url_default.value_namespace = name_space;
url_default.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::Transport::TransportSmart::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "url-default")
{
url_default.yfilter = yfilter;
}
}
bool Licensing::Config::Transport::TransportSmart::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "urls" || name == "url-default")
return true;
return false;
}
Licensing::Config::Transport::TransportSmart::Urls::Urls()
:
url_registration{YType::str, "url-registration"},
url_utility{YType::str, "url-utility"}
{
yang_name = "urls"; yang_parent_name = "transport-smart"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::Config::Transport::TransportSmart::Urls::~Urls()
{
}
bool Licensing::Config::Transport::TransportSmart::Urls::has_data() const
{
if (is_presence_container) return true;
return url_registration.is_set
|| url_utility.is_set;
}
bool Licensing::Config::Transport::TransportSmart::Urls::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(url_registration.yfilter)
|| ydk::is_set(url_utility.yfilter);
}
std::string Licensing::Config::Transport::TransportSmart::Urls::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/config/transport/transport-smart/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::Config::Transport::TransportSmart::Urls::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "urls";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::Config::Transport::TransportSmart::Urls::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (url_registration.is_set || is_set(url_registration.yfilter)) leaf_name_data.push_back(url_registration.get_name_leafdata());
if (url_utility.is_set || is_set(url_utility.yfilter)) leaf_name_data.push_back(url_utility.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::Config::Transport::TransportSmart::Urls::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::Config::Transport::TransportSmart::Urls::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::Config::Transport::TransportSmart::Urls::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "url-registration")
{
url_registration = value;
url_registration.value_namespace = name_space;
url_registration.value_namespace_prefix = name_space_prefix;
}
if(value_path == "url-utility")
{
url_utility = value;
url_utility.value_namespace = name_space;
url_utility.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::Config::Transport::TransportSmart::Urls::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "url-registration")
{
url_registration.yfilter = yfilter;
}
if(value_path == "url-utility")
{
url_utility.yfilter = yfilter;
}
}
bool Licensing::Config::Transport::TransportSmart::Urls::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "url-registration" || name == "url-utility")
return true;
return false;
}
Licensing::State::State()
:
always_enabled{YType::boolean, "always-enabled"},
smart_enabled{YType::boolean, "smart-enabled"},
version{YType::str, "version"}
,
state_info(std::make_shared<Licensing::State::StateInfo>())
{
state_info->parent = this;
yang_name = "state"; yang_parent_name = "licensing"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::~State()
{
}
bool Licensing::State::has_data() const
{
if (is_presence_container) return true;
return always_enabled.is_set
|| smart_enabled.is_set
|| version.is_set
|| (state_info != nullptr && state_info->has_data());
}
bool Licensing::State::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(always_enabled.yfilter)
|| ydk::is_set(smart_enabled.yfilter)
|| ydk::is_set(version.yfilter)
|| (state_info != nullptr && state_info->has_operation());
}
std::string Licensing::State::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "state";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (always_enabled.is_set || is_set(always_enabled.yfilter)) leaf_name_data.push_back(always_enabled.get_name_leafdata());
if (smart_enabled.is_set || is_set(smart_enabled.yfilter)) leaf_name_data.push_back(smart_enabled.get_name_leafdata());
if (version.is_set || is_set(version.yfilter)) leaf_name_data.push_back(version.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "state-info")
{
if(state_info == nullptr)
{
state_info = std::make_shared<Licensing::State::StateInfo>();
}
return state_info;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(state_info != nullptr)
{
_children["state-info"] = state_info;
}
return _children;
}
void Licensing::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "always-enabled")
{
always_enabled = value;
always_enabled.value_namespace = name_space;
always_enabled.value_namespace_prefix = name_space_prefix;
}
if(value_path == "smart-enabled")
{
smart_enabled = value;
smart_enabled.value_namespace = name_space;
smart_enabled.value_namespace_prefix = name_space_prefix;
}
if(value_path == "version")
{
version = value;
version.value_namespace = name_space;
version.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "always-enabled")
{
always_enabled.yfilter = yfilter;
}
if(value_path == "smart-enabled")
{
smart_enabled.yfilter = yfilter;
}
if(value_path == "version")
{
version.yfilter = yfilter;
}
}
bool Licensing::State::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "state-info" || name == "always-enabled" || name == "smart-enabled" || name == "version")
return true;
return false;
}
Licensing::State::StateInfo::StateInfo()
:
custom_id{YType::str, "custom-id"}
,
registration(std::make_shared<Licensing::State::StateInfo::Registration>())
, authorization(std::make_shared<Licensing::State::StateInfo::Authorization>())
, utility(std::make_shared<Licensing::State::StateInfo::Utility>())
, transport(std::make_shared<Licensing::State::StateInfo::Transport>())
, privacy(std::make_shared<Licensing::State::StateInfo::Privacy>())
, evaluation(std::make_shared<Licensing::State::StateInfo::Evaluation>())
, udi(std::make_shared<Licensing::State::StateInfo::Udi>())
, usage(this, {"entitlement_tag"})
{
registration->parent = this;
authorization->parent = this;
utility->parent = this;
transport->parent = this;
privacy->parent = this;
evaluation->parent = this;
udi->parent = this;
yang_name = "state-info"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::~StateInfo()
{
}
bool Licensing::State::StateInfo::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<usage.len(); index++)
{
if(usage[index]->has_data())
return true;
}
return custom_id.is_set
|| (registration != nullptr && registration->has_data())
|| (authorization != nullptr && authorization->has_data())
|| (utility != nullptr && utility->has_data())
|| (transport != nullptr && transport->has_data())
|| (privacy != nullptr && privacy->has_data())
|| (evaluation != nullptr && evaluation->has_data())
|| (udi != nullptr && udi->has_data());
}
bool Licensing::State::StateInfo::has_operation() const
{
for (std::size_t index=0; index<usage.len(); index++)
{
if(usage[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(custom_id.yfilter)
|| (registration != nullptr && registration->has_operation())
|| (authorization != nullptr && authorization->has_operation())
|| (utility != nullptr && utility->has_operation())
|| (transport != nullptr && transport->has_operation())
|| (privacy != nullptr && privacy->has_operation())
|| (evaluation != nullptr && evaluation->has_operation())
|| (udi != nullptr && udi->has_operation());
}
std::string Licensing::State::StateInfo::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "state-info";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (custom_id.is_set || is_set(custom_id.yfilter)) leaf_name_data.push_back(custom_id.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "registration")
{
if(registration == nullptr)
{
registration = std::make_shared<Licensing::State::StateInfo::Registration>();
}
return registration;
}
if(child_yang_name == "authorization")
{
if(authorization == nullptr)
{
authorization = std::make_shared<Licensing::State::StateInfo::Authorization>();
}
return authorization;
}
if(child_yang_name == "utility")
{
if(utility == nullptr)
{
utility = std::make_shared<Licensing::State::StateInfo::Utility>();
}
return utility;
}
if(child_yang_name == "transport")
{
if(transport == nullptr)
{
transport = std::make_shared<Licensing::State::StateInfo::Transport>();
}
return transport;
}
if(child_yang_name == "privacy")
{
if(privacy == nullptr)
{
privacy = std::make_shared<Licensing::State::StateInfo::Privacy>();
}
return privacy;
}
if(child_yang_name == "evaluation")
{
if(evaluation == nullptr)
{
evaluation = std::make_shared<Licensing::State::StateInfo::Evaluation>();
}
return evaluation;
}
if(child_yang_name == "udi")
{
if(udi == nullptr)
{
udi = std::make_shared<Licensing::State::StateInfo::Udi>();
}
return udi;
}
if(child_yang_name == "usage")
{
auto ent_ = std::make_shared<Licensing::State::StateInfo::Usage>();
ent_->parent = this;
usage.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(registration != nullptr)
{
_children["registration"] = registration;
}
if(authorization != nullptr)
{
_children["authorization"] = authorization;
}
if(utility != nullptr)
{
_children["utility"] = utility;
}
if(transport != nullptr)
{
_children["transport"] = transport;
}
if(privacy != nullptr)
{
_children["privacy"] = privacy;
}
if(evaluation != nullptr)
{
_children["evaluation"] = evaluation;
}
if(udi != nullptr)
{
_children["udi"] = udi;
}
count_ = 0;
for (auto ent_ : usage.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Licensing::State::StateInfo::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "custom-id")
{
custom_id = value;
custom_id.value_namespace = name_space;
custom_id.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "custom-id")
{
custom_id.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "registration" || name == "authorization" || name == "utility" || name == "transport" || name == "privacy" || name == "evaluation" || name == "udi" || name == "usage" || name == "custom-id")
return true;
return false;
}
Licensing::State::StateInfo::Registration::Registration()
:
registration_state{YType::enumeration, "registration-state"},
export_control_allowed{YType::boolean, "export-control-allowed"}
,
registration_in_progress(std::make_shared<Licensing::State::StateInfo::Registration::RegistrationInProgress>())
, registration_failed(std::make_shared<Licensing::State::StateInfo::Registration::RegistrationFailed>())
, registration_retry(std::make_shared<Licensing::State::StateInfo::Registration::RegistrationRetry>())
, registration_complete(std::make_shared<Licensing::State::StateInfo::Registration::RegistrationComplete>())
{
registration_in_progress->parent = this;
registration_failed->parent = this;
registration_retry->parent = this;
registration_complete->parent = this;
yang_name = "registration"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Registration::~Registration()
{
}
bool Licensing::State::StateInfo::Registration::has_data() const
{
if (is_presence_container) return true;
return registration_state.is_set
|| export_control_allowed.is_set
|| (registration_in_progress != nullptr && registration_in_progress->has_data())
|| (registration_failed != nullptr && registration_failed->has_data())
|| (registration_retry != nullptr && registration_retry->has_data())
|| (registration_complete != nullptr && registration_complete->has_data());
}
bool Licensing::State::StateInfo::Registration::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(registration_state.yfilter)
|| ydk::is_set(export_control_allowed.yfilter)
|| (registration_in_progress != nullptr && registration_in_progress->has_operation())
|| (registration_failed != nullptr && registration_failed->has_operation())
|| (registration_retry != nullptr && registration_retry->has_operation())
|| (registration_complete != nullptr && registration_complete->has_operation());
}
std::string Licensing::State::StateInfo::Registration::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Registration::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "registration";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Registration::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (registration_state.is_set || is_set(registration_state.yfilter)) leaf_name_data.push_back(registration_state.get_name_leafdata());
if (export_control_allowed.is_set || is_set(export_control_allowed.yfilter)) leaf_name_data.push_back(export_control_allowed.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Registration::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "registration-in-progress")
{
if(registration_in_progress == nullptr)
{
registration_in_progress = std::make_shared<Licensing::State::StateInfo::Registration::RegistrationInProgress>();
}
return registration_in_progress;
}
if(child_yang_name == "registration-failed")
{
if(registration_failed == nullptr)
{
registration_failed = std::make_shared<Licensing::State::StateInfo::Registration::RegistrationFailed>();
}
return registration_failed;
}
if(child_yang_name == "registration-retry")
{
if(registration_retry == nullptr)
{
registration_retry = std::make_shared<Licensing::State::StateInfo::Registration::RegistrationRetry>();
}
return registration_retry;
}
if(child_yang_name == "registration-complete")
{
if(registration_complete == nullptr)
{
registration_complete = std::make_shared<Licensing::State::StateInfo::Registration::RegistrationComplete>();
}
return registration_complete;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Registration::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(registration_in_progress != nullptr)
{
_children["registration-in-progress"] = registration_in_progress;
}
if(registration_failed != nullptr)
{
_children["registration-failed"] = registration_failed;
}
if(registration_retry != nullptr)
{
_children["registration-retry"] = registration_retry;
}
if(registration_complete != nullptr)
{
_children["registration-complete"] = registration_complete;
}
return _children;
}
void Licensing::State::StateInfo::Registration::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "registration-state")
{
registration_state = value;
registration_state.value_namespace = name_space;
registration_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "export-control-allowed")
{
export_control_allowed = value;
export_control_allowed.value_namespace = name_space;
export_control_allowed.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Registration::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "registration-state")
{
registration_state.yfilter = yfilter;
}
if(value_path == "export-control-allowed")
{
export_control_allowed.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Registration::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "registration-in-progress" || name == "registration-failed" || name == "registration-retry" || name == "registration-complete" || name == "registration-state" || name == "export-control-allowed")
return true;
return false;
}
Licensing::State::StateInfo::Registration::RegistrationInProgress::RegistrationInProgress()
:
start_time{YType::str, "start-time"}
{
yang_name = "registration-in-progress"; yang_parent_name = "registration"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Registration::RegistrationInProgress::~RegistrationInProgress()
{
}
bool Licensing::State::StateInfo::Registration::RegistrationInProgress::has_data() const
{
if (is_presence_container) return true;
return start_time.is_set;
}
bool Licensing::State::StateInfo::Registration::RegistrationInProgress::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(start_time.yfilter);
}
std::string Licensing::State::StateInfo::Registration::RegistrationInProgress::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/registration/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Registration::RegistrationInProgress::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "registration-in-progress";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Registration::RegistrationInProgress::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (start_time.is_set || is_set(start_time.yfilter)) leaf_name_data.push_back(start_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Registration::RegistrationInProgress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Registration::RegistrationInProgress::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Registration::RegistrationInProgress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "start-time")
{
start_time = value;
start_time.value_namespace = name_space;
start_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Registration::RegistrationInProgress::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "start-time")
{
start_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Registration::RegistrationInProgress::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "start-time")
return true;
return false;
}
Licensing::State::StateInfo::Registration::RegistrationFailed::RegistrationFailed()
:
fail_time{YType::str, "fail-time"},
fail_message{YType::str, "fail-message"}
{
yang_name = "registration-failed"; yang_parent_name = "registration"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Registration::RegistrationFailed::~RegistrationFailed()
{
}
bool Licensing::State::StateInfo::Registration::RegistrationFailed::has_data() const
{
if (is_presence_container) return true;
return fail_time.is_set
|| fail_message.is_set;
}
bool Licensing::State::StateInfo::Registration::RegistrationFailed::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(fail_time.yfilter)
|| ydk::is_set(fail_message.yfilter);
}
std::string Licensing::State::StateInfo::Registration::RegistrationFailed::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/registration/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Registration::RegistrationFailed::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "registration-failed";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Registration::RegistrationFailed::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (fail_time.is_set || is_set(fail_time.yfilter)) leaf_name_data.push_back(fail_time.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Registration::RegistrationFailed::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Registration::RegistrationFailed::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Registration::RegistrationFailed::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "fail-time")
{
fail_time = value;
fail_time.value_namespace = name_space;
fail_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Registration::RegistrationFailed::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "fail-time")
{
fail_time.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Registration::RegistrationFailed::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "fail-time" || name == "fail-message")
return true;
return false;
}
Licensing::State::StateInfo::Registration::RegistrationRetry::RegistrationRetry()
:
retry_next_time{YType::str, "retry-next-time"},
fail_time{YType::str, "fail-time"},
fail_message{YType::str, "fail-message"}
{
yang_name = "registration-retry"; yang_parent_name = "registration"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Registration::RegistrationRetry::~RegistrationRetry()
{
}
bool Licensing::State::StateInfo::Registration::RegistrationRetry::has_data() const
{
if (is_presence_container) return true;
return retry_next_time.is_set
|| fail_time.is_set
|| fail_message.is_set;
}
bool Licensing::State::StateInfo::Registration::RegistrationRetry::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(retry_next_time.yfilter)
|| ydk::is_set(fail_time.yfilter)
|| ydk::is_set(fail_message.yfilter);
}
std::string Licensing::State::StateInfo::Registration::RegistrationRetry::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/registration/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Registration::RegistrationRetry::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "registration-retry";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Registration::RegistrationRetry::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (retry_next_time.is_set || is_set(retry_next_time.yfilter)) leaf_name_data.push_back(retry_next_time.get_name_leafdata());
if (fail_time.is_set || is_set(fail_time.yfilter)) leaf_name_data.push_back(fail_time.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Registration::RegistrationRetry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Registration::RegistrationRetry::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Registration::RegistrationRetry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "retry-next-time")
{
retry_next_time = value;
retry_next_time.value_namespace = name_space;
retry_next_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-time")
{
fail_time = value;
fail_time.value_namespace = name_space;
fail_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Registration::RegistrationRetry::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "retry-next-time")
{
retry_next_time.yfilter = yfilter;
}
if(value_path == "fail-time")
{
fail_time.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Registration::RegistrationRetry::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "retry-next-time" || name == "fail-time" || name == "fail-message")
return true;
return false;
}
Licensing::State::StateInfo::Registration::RegistrationComplete::RegistrationComplete()
:
complete_time{YType::str, "complete-time"},
last_renew_time{YType::str, "last-renew-time"},
next_renew_time{YType::str, "next-renew-time"},
expire_time{YType::str, "expire-time"},
last_renew_success{YType::boolean, "last-renew-success"},
fail_message{YType::str, "fail-message"},
smart_account{YType::str, "smart-account"},
virtual_account{YType::str, "virtual-account"}
{
yang_name = "registration-complete"; yang_parent_name = "registration"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Registration::RegistrationComplete::~RegistrationComplete()
{
}
bool Licensing::State::StateInfo::Registration::RegistrationComplete::has_data() const
{
if (is_presence_container) return true;
return complete_time.is_set
|| last_renew_time.is_set
|| next_renew_time.is_set
|| expire_time.is_set
|| last_renew_success.is_set
|| fail_message.is_set
|| smart_account.is_set
|| virtual_account.is_set;
}
bool Licensing::State::StateInfo::Registration::RegistrationComplete::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(complete_time.yfilter)
|| ydk::is_set(last_renew_time.yfilter)
|| ydk::is_set(next_renew_time.yfilter)
|| ydk::is_set(expire_time.yfilter)
|| ydk::is_set(last_renew_success.yfilter)
|| ydk::is_set(fail_message.yfilter)
|| ydk::is_set(smart_account.yfilter)
|| ydk::is_set(virtual_account.yfilter);
}
std::string Licensing::State::StateInfo::Registration::RegistrationComplete::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/registration/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Registration::RegistrationComplete::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "registration-complete";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Registration::RegistrationComplete::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (complete_time.is_set || is_set(complete_time.yfilter)) leaf_name_data.push_back(complete_time.get_name_leafdata());
if (last_renew_time.is_set || is_set(last_renew_time.yfilter)) leaf_name_data.push_back(last_renew_time.get_name_leafdata());
if (next_renew_time.is_set || is_set(next_renew_time.yfilter)) leaf_name_data.push_back(next_renew_time.get_name_leafdata());
if (expire_time.is_set || is_set(expire_time.yfilter)) leaf_name_data.push_back(expire_time.get_name_leafdata());
if (last_renew_success.is_set || is_set(last_renew_success.yfilter)) leaf_name_data.push_back(last_renew_success.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
if (smart_account.is_set || is_set(smart_account.yfilter)) leaf_name_data.push_back(smart_account.get_name_leafdata());
if (virtual_account.is_set || is_set(virtual_account.yfilter)) leaf_name_data.push_back(virtual_account.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Registration::RegistrationComplete::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Registration::RegistrationComplete::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Registration::RegistrationComplete::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "complete-time")
{
complete_time = value;
complete_time.value_namespace = name_space;
complete_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "last-renew-time")
{
last_renew_time = value;
last_renew_time.value_namespace = name_space;
last_renew_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "next-renew-time")
{
next_renew_time = value;
next_renew_time.value_namespace = name_space;
next_renew_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "expire-time")
{
expire_time = value;
expire_time.value_namespace = name_space;
expire_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "last-renew-success")
{
last_renew_success = value;
last_renew_success.value_namespace = name_space;
last_renew_success.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
if(value_path == "smart-account")
{
smart_account = value;
smart_account.value_namespace = name_space;
smart_account.value_namespace_prefix = name_space_prefix;
}
if(value_path == "virtual-account")
{
virtual_account = value;
virtual_account.value_namespace = name_space;
virtual_account.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Registration::RegistrationComplete::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "complete-time")
{
complete_time.yfilter = yfilter;
}
if(value_path == "last-renew-time")
{
last_renew_time.yfilter = yfilter;
}
if(value_path == "next-renew-time")
{
next_renew_time.yfilter = yfilter;
}
if(value_path == "expire-time")
{
expire_time.yfilter = yfilter;
}
if(value_path == "last-renew-success")
{
last_renew_success.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
if(value_path == "smart-account")
{
smart_account.yfilter = yfilter;
}
if(value_path == "virtual-account")
{
virtual_account.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Registration::RegistrationComplete::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "complete-time" || name == "last-renew-time" || name == "next-renew-time" || name == "expire-time" || name == "last-renew-success" || name == "fail-message" || name == "smart-account" || name == "virtual-account")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::Authorization()
:
authorization_state{YType::enumeration, "authorization-state"}
,
authorization_none(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationNone>())
, authorization_eval(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationEval>())
, authorization_eval_expired(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired>())
, authorization_authorized(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationAuthorized>())
, authorization_authorized_reservation(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation>())
, authorization_out_of_compliance(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance>())
, authorization_authorization_expired(std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired>())
{
authorization_none->parent = this;
authorization_eval->parent = this;
authorization_eval_expired->parent = this;
authorization_authorized->parent = this;
authorization_authorized_reservation->parent = this;
authorization_out_of_compliance->parent = this;
authorization_authorization_expired->parent = this;
yang_name = "authorization"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::~Authorization()
{
}
bool Licensing::State::StateInfo::Authorization::has_data() const
{
if (is_presence_container) return true;
return authorization_state.is_set
|| (authorization_none != nullptr && authorization_none->has_data())
|| (authorization_eval != nullptr && authorization_eval->has_data())
|| (authorization_eval_expired != nullptr && authorization_eval_expired->has_data())
|| (authorization_authorized != nullptr && authorization_authorized->has_data())
|| (authorization_authorized_reservation != nullptr && authorization_authorized_reservation->has_data())
|| (authorization_out_of_compliance != nullptr && authorization_out_of_compliance->has_data())
|| (authorization_authorization_expired != nullptr && authorization_authorization_expired->has_data());
}
bool Licensing::State::StateInfo::Authorization::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(authorization_state.yfilter)
|| (authorization_none != nullptr && authorization_none->has_operation())
|| (authorization_eval != nullptr && authorization_eval->has_operation())
|| (authorization_eval_expired != nullptr && authorization_eval_expired->has_operation())
|| (authorization_authorized != nullptr && authorization_authorized->has_operation())
|| (authorization_authorized_reservation != nullptr && authorization_authorized_reservation->has_operation())
|| (authorization_out_of_compliance != nullptr && authorization_out_of_compliance->has_operation())
|| (authorization_authorization_expired != nullptr && authorization_authorization_expired->has_operation());
}
std::string Licensing::State::StateInfo::Authorization::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (authorization_state.is_set || is_set(authorization_state.yfilter)) leaf_name_data.push_back(authorization_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "authorization-none")
{
if(authorization_none == nullptr)
{
authorization_none = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationNone>();
}
return authorization_none;
}
if(child_yang_name == "authorization-eval")
{
if(authorization_eval == nullptr)
{
authorization_eval = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationEval>();
}
return authorization_eval;
}
if(child_yang_name == "authorization-eval-expired")
{
if(authorization_eval_expired == nullptr)
{
authorization_eval_expired = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired>();
}
return authorization_eval_expired;
}
if(child_yang_name == "authorization-authorized")
{
if(authorization_authorized == nullptr)
{
authorization_authorized = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationAuthorized>();
}
return authorization_authorized;
}
if(child_yang_name == "authorization-authorized-reservation")
{
if(authorization_authorized_reservation == nullptr)
{
authorization_authorized_reservation = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation>();
}
return authorization_authorized_reservation;
}
if(child_yang_name == "authorization-out-of-compliance")
{
if(authorization_out_of_compliance == nullptr)
{
authorization_out_of_compliance = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance>();
}
return authorization_out_of_compliance;
}
if(child_yang_name == "authorization-authorization-expired")
{
if(authorization_authorization_expired == nullptr)
{
authorization_authorization_expired = std::make_shared<Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired>();
}
return authorization_authorization_expired;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(authorization_none != nullptr)
{
_children["authorization-none"] = authorization_none;
}
if(authorization_eval != nullptr)
{
_children["authorization-eval"] = authorization_eval;
}
if(authorization_eval_expired != nullptr)
{
_children["authorization-eval-expired"] = authorization_eval_expired;
}
if(authorization_authorized != nullptr)
{
_children["authorization-authorized"] = authorization_authorized;
}
if(authorization_authorized_reservation != nullptr)
{
_children["authorization-authorized-reservation"] = authorization_authorized_reservation;
}
if(authorization_out_of_compliance != nullptr)
{
_children["authorization-out-of-compliance"] = authorization_out_of_compliance;
}
if(authorization_authorization_expired != nullptr)
{
_children["authorization-authorization-expired"] = authorization_authorization_expired;
}
return _children;
}
void Licensing::State::StateInfo::Authorization::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "authorization-state")
{
authorization_state = value;
authorization_state.value_namespace = name_space;
authorization_state.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "authorization-state")
{
authorization_state.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "authorization-none" || name == "authorization-eval" || name == "authorization-eval-expired" || name == "authorization-authorized" || name == "authorization-authorized-reservation" || name == "authorization-out-of-compliance" || name == "authorization-authorization-expired" || name == "authorization-state")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationNone::AuthorizationNone()
{
yang_name = "authorization-none"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationNone::~AuthorizationNone()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationNone::has_data() const
{
if (is_presence_container) return true;
return false;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationNone::has_operation() const
{
return is_set(yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationNone::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationNone::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-none";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationNone::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationNone::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationNone::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationNone::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Licensing::State::StateInfo::Authorization::AuthorizationNone::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationNone::has_leaf_or_child_of_name(const std::string & name) const
{
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationEval::AuthorizationEval()
:
seconds_left{YType::uint64, "seconds-left"}
{
yang_name = "authorization-eval"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationEval::~AuthorizationEval()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationEval::has_data() const
{
if (is_presence_container) return true;
return seconds_left.is_set;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationEval::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(seconds_left.yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationEval::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationEval::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-eval";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationEval::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (seconds_left.is_set || is_set(seconds_left.yfilter)) leaf_name_data.push_back(seconds_left.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationEval::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationEval::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationEval::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "seconds-left")
{
seconds_left = value;
seconds_left.value_namespace = name_space;
seconds_left.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::AuthorizationEval::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "seconds-left")
{
seconds_left.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::AuthorizationEval::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "seconds-left")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::AuthorizationEvalExpired()
:
expire_time{YType::str, "expire-time"}
{
yang_name = "authorization-eval-expired"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::~AuthorizationEvalExpired()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::has_data() const
{
if (is_presence_container) return true;
return expire_time.is_set;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(expire_time.yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-eval-expired";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (expire_time.is_set || is_set(expire_time.yfilter)) leaf_name_data.push_back(expire_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "expire-time")
{
expire_time = value;
expire_time.value_namespace = name_space;
expire_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "expire-time")
{
expire_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::AuthorizationEvalExpired::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "expire-time")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::AuthorizationAuthorized()
:
last_comm_status_success{YType::boolean, "last-comm-status-success"},
fail_message{YType::str, "fail-message"},
last_comm_time{YType::str, "last-comm-time"},
next_comm_time{YType::str, "next-comm-time"},
comm_deadline_time{YType::str, "comm-deadline-time"}
{
yang_name = "authorization-authorized"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::~AuthorizationAuthorized()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::has_data() const
{
if (is_presence_container) return true;
return last_comm_status_success.is_set
|| fail_message.is_set
|| last_comm_time.is_set
|| next_comm_time.is_set
|| comm_deadline_time.is_set;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(last_comm_status_success.yfilter)
|| ydk::is_set(fail_message.yfilter)
|| ydk::is_set(last_comm_time.yfilter)
|| ydk::is_set(next_comm_time.yfilter)
|| ydk::is_set(comm_deadline_time.yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-authorized";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (last_comm_status_success.is_set || is_set(last_comm_status_success.yfilter)) leaf_name_data.push_back(last_comm_status_success.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
if (last_comm_time.is_set || is_set(last_comm_time.yfilter)) leaf_name_data.push_back(last_comm_time.get_name_leafdata());
if (next_comm_time.is_set || is_set(next_comm_time.yfilter)) leaf_name_data.push_back(next_comm_time.get_name_leafdata());
if (comm_deadline_time.is_set || is_set(comm_deadline_time.yfilter)) leaf_name_data.push_back(comm_deadline_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "last-comm-status-success")
{
last_comm_status_success = value;
last_comm_status_success.value_namespace = name_space;
last_comm_status_success.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
if(value_path == "last-comm-time")
{
last_comm_time = value;
last_comm_time.value_namespace = name_space;
last_comm_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "next-comm-time")
{
next_comm_time = value;
next_comm_time.value_namespace = name_space;
next_comm_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "comm-deadline-time")
{
comm_deadline_time = value;
comm_deadline_time.value_namespace = name_space;
comm_deadline_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "last-comm-status-success")
{
last_comm_status_success.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
if(value_path == "last-comm-time")
{
last_comm_time.yfilter = yfilter;
}
if(value_path == "next-comm-time")
{
next_comm_time.yfilter = yfilter;
}
if(value_path == "comm-deadline-time")
{
comm_deadline_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorized::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "last-comm-status-success" || name == "fail-message" || name == "last-comm-time" || name == "next-comm-time" || name == "comm-deadline-time")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::AuthorizationAuthorizedReservation()
:
reservation_time{YType::str, "reservation-time"}
{
yang_name = "authorization-authorized-reservation"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::~AuthorizationAuthorizedReservation()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::has_data() const
{
if (is_presence_container) return true;
return reservation_time.is_set;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(reservation_time.yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-authorized-reservation";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (reservation_time.is_set || is_set(reservation_time.yfilter)) leaf_name_data.push_back(reservation_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "reservation-time")
{
reservation_time = value;
reservation_time.value_namespace = name_space;
reservation_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "reservation-time")
{
reservation_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorizedReservation::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "reservation-time")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::AuthorizationOutOfCompliance()
:
last_comm_status_success{YType::boolean, "last-comm-status-success"},
fail_message{YType::str, "fail-message"},
last_comm_time{YType::str, "last-comm-time"},
next_comm_time{YType::str, "next-comm-time"},
comm_deadline_time{YType::str, "comm-deadline-time"},
ooc_time{YType::str, "ooc-time"}
{
yang_name = "authorization-out-of-compliance"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::~AuthorizationOutOfCompliance()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::has_data() const
{
if (is_presence_container) return true;
return last_comm_status_success.is_set
|| fail_message.is_set
|| last_comm_time.is_set
|| next_comm_time.is_set
|| comm_deadline_time.is_set
|| ooc_time.is_set;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(last_comm_status_success.yfilter)
|| ydk::is_set(fail_message.yfilter)
|| ydk::is_set(last_comm_time.yfilter)
|| ydk::is_set(next_comm_time.yfilter)
|| ydk::is_set(comm_deadline_time.yfilter)
|| ydk::is_set(ooc_time.yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-out-of-compliance";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (last_comm_status_success.is_set || is_set(last_comm_status_success.yfilter)) leaf_name_data.push_back(last_comm_status_success.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
if (last_comm_time.is_set || is_set(last_comm_time.yfilter)) leaf_name_data.push_back(last_comm_time.get_name_leafdata());
if (next_comm_time.is_set || is_set(next_comm_time.yfilter)) leaf_name_data.push_back(next_comm_time.get_name_leafdata());
if (comm_deadline_time.is_set || is_set(comm_deadline_time.yfilter)) leaf_name_data.push_back(comm_deadline_time.get_name_leafdata());
if (ooc_time.is_set || is_set(ooc_time.yfilter)) leaf_name_data.push_back(ooc_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "last-comm-status-success")
{
last_comm_status_success = value;
last_comm_status_success.value_namespace = name_space;
last_comm_status_success.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
if(value_path == "last-comm-time")
{
last_comm_time = value;
last_comm_time.value_namespace = name_space;
last_comm_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "next-comm-time")
{
next_comm_time = value;
next_comm_time.value_namespace = name_space;
next_comm_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "comm-deadline-time")
{
comm_deadline_time = value;
comm_deadline_time.value_namespace = name_space;
comm_deadline_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ooc-time")
{
ooc_time = value;
ooc_time.value_namespace = name_space;
ooc_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "last-comm-status-success")
{
last_comm_status_success.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
if(value_path == "last-comm-time")
{
last_comm_time.yfilter = yfilter;
}
if(value_path == "next-comm-time")
{
next_comm_time.yfilter = yfilter;
}
if(value_path == "comm-deadline-time")
{
comm_deadline_time.yfilter = yfilter;
}
if(value_path == "ooc-time")
{
ooc_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::AuthorizationOutOfCompliance::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "last-comm-status-success" || name == "fail-message" || name == "last-comm-time" || name == "next-comm-time" || name == "comm-deadline-time" || name == "ooc-time")
return true;
return false;
}
Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::AuthorizationAuthorizationExpired()
:
last_comm_status_success{YType::boolean, "last-comm-status-success"},
fail_message{YType::str, "fail-message"},
last_comm_time{YType::str, "last-comm-time"},
next_comm_time{YType::str, "next-comm-time"},
comm_deadline_time{YType::str, "comm-deadline-time"}
{
yang_name = "authorization-authorization-expired"; yang_parent_name = "authorization"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::~AuthorizationAuthorizationExpired()
{
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::has_data() const
{
if (is_presence_container) return true;
return last_comm_status_success.is_set
|| fail_message.is_set
|| last_comm_time.is_set
|| next_comm_time.is_set
|| comm_deadline_time.is_set;
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(last_comm_status_success.yfilter)
|| ydk::is_set(fail_message.yfilter)
|| ydk::is_set(last_comm_time.yfilter)
|| ydk::is_set(next_comm_time.yfilter)
|| ydk::is_set(comm_deadline_time.yfilter);
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/authorization/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "authorization-authorization-expired";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (last_comm_status_success.is_set || is_set(last_comm_status_success.yfilter)) leaf_name_data.push_back(last_comm_status_success.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
if (last_comm_time.is_set || is_set(last_comm_time.yfilter)) leaf_name_data.push_back(last_comm_time.get_name_leafdata());
if (next_comm_time.is_set || is_set(next_comm_time.yfilter)) leaf_name_data.push_back(next_comm_time.get_name_leafdata());
if (comm_deadline_time.is_set || is_set(comm_deadline_time.yfilter)) leaf_name_data.push_back(comm_deadline_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "last-comm-status-success")
{
last_comm_status_success = value;
last_comm_status_success.value_namespace = name_space;
last_comm_status_success.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
if(value_path == "last-comm-time")
{
last_comm_time = value;
last_comm_time.value_namespace = name_space;
last_comm_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "next-comm-time")
{
next_comm_time = value;
next_comm_time.value_namespace = name_space;
next_comm_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "comm-deadline-time")
{
comm_deadline_time = value;
comm_deadline_time.value_namespace = name_space;
comm_deadline_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "last-comm-status-success")
{
last_comm_status_success.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
if(value_path == "last-comm-time")
{
last_comm_time.yfilter = yfilter;
}
if(value_path == "next-comm-time")
{
next_comm_time.yfilter = yfilter;
}
if(value_path == "comm-deadline-time")
{
comm_deadline_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Authorization::AuthorizationAuthorizationExpired::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "last-comm-status-success" || name == "fail-message" || name == "last-comm-time" || name == "next-comm-time" || name == "comm-deadline-time")
return true;
return false;
}
Licensing::State::StateInfo::Utility::Utility()
:
enabled{YType::boolean, "enabled"},
reporting{YType::enumeration, "reporting"}
,
reporting_times(std::make_shared<Licensing::State::StateInfo::Utility::ReportingTimes>())
, customer_info(std::make_shared<Licensing::State::StateInfo::Utility::CustomerInfo>())
{
reporting_times->parent = this;
customer_info->parent = this;
yang_name = "utility"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Utility::~Utility()
{
}
bool Licensing::State::StateInfo::Utility::has_data() const
{
if (is_presence_container) return true;
return enabled.is_set
|| reporting.is_set
|| (reporting_times != nullptr && reporting_times->has_data())
|| (customer_info != nullptr && customer_info->has_data());
}
bool Licensing::State::StateInfo::Utility::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(enabled.yfilter)
|| ydk::is_set(reporting.yfilter)
|| (reporting_times != nullptr && reporting_times->has_operation())
|| (customer_info != nullptr && customer_info->has_operation());
}
std::string Licensing::State::StateInfo::Utility::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Utility::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "utility";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Utility::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (enabled.is_set || is_set(enabled.yfilter)) leaf_name_data.push_back(enabled.get_name_leafdata());
if (reporting.is_set || is_set(reporting.yfilter)) leaf_name_data.push_back(reporting.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Utility::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "reporting-times")
{
if(reporting_times == nullptr)
{
reporting_times = std::make_shared<Licensing::State::StateInfo::Utility::ReportingTimes>();
}
return reporting_times;
}
if(child_yang_name == "customer-info")
{
if(customer_info == nullptr)
{
customer_info = std::make_shared<Licensing::State::StateInfo::Utility::CustomerInfo>();
}
return customer_info;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Utility::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(reporting_times != nullptr)
{
_children["reporting-times"] = reporting_times;
}
if(customer_info != nullptr)
{
_children["customer-info"] = customer_info;
}
return _children;
}
void Licensing::State::StateInfo::Utility::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "enabled")
{
enabled = value;
enabled.value_namespace = name_space;
enabled.value_namespace_prefix = name_space_prefix;
}
if(value_path == "reporting")
{
reporting = value;
reporting.value_namespace = name_space;
reporting.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Utility::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "enabled")
{
enabled.yfilter = yfilter;
}
if(value_path == "reporting")
{
reporting.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Utility::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "reporting-times" || name == "customer-info" || name == "enabled" || name == "reporting")
return true;
return false;
}
Licensing::State::StateInfo::Utility::ReportingTimes::ReportingTimes()
:
last_report_time{YType::str, "last-report-time"},
last_report_success{YType::boolean, "last-report-success"},
fail_message{YType::str, "fail-message"},
next_report_time{YType::str, "next-report-time"}
{
yang_name = "reporting-times"; yang_parent_name = "utility"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Utility::ReportingTimes::~ReportingTimes()
{
}
bool Licensing::State::StateInfo::Utility::ReportingTimes::has_data() const
{
if (is_presence_container) return true;
return last_report_time.is_set
|| last_report_success.is_set
|| fail_message.is_set
|| next_report_time.is_set;
}
bool Licensing::State::StateInfo::Utility::ReportingTimes::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(last_report_time.yfilter)
|| ydk::is_set(last_report_success.yfilter)
|| ydk::is_set(fail_message.yfilter)
|| ydk::is_set(next_report_time.yfilter);
}
std::string Licensing::State::StateInfo::Utility::ReportingTimes::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/utility/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Utility::ReportingTimes::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "reporting-times";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Utility::ReportingTimes::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (last_report_time.is_set || is_set(last_report_time.yfilter)) leaf_name_data.push_back(last_report_time.get_name_leafdata());
if (last_report_success.is_set || is_set(last_report_success.yfilter)) leaf_name_data.push_back(last_report_success.get_name_leafdata());
if (fail_message.is_set || is_set(fail_message.yfilter)) leaf_name_data.push_back(fail_message.get_name_leafdata());
if (next_report_time.is_set || is_set(next_report_time.yfilter)) leaf_name_data.push_back(next_report_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Utility::ReportingTimes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Utility::ReportingTimes::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Utility::ReportingTimes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "last-report-time")
{
last_report_time = value;
last_report_time.value_namespace = name_space;
last_report_time.value_namespace_prefix = name_space_prefix;
}
if(value_path == "last-report-success")
{
last_report_success = value;
last_report_success.value_namespace = name_space;
last_report_success.value_namespace_prefix = name_space_prefix;
}
if(value_path == "fail-message")
{
fail_message = value;
fail_message.value_namespace = name_space;
fail_message.value_namespace_prefix = name_space_prefix;
}
if(value_path == "next-report-time")
{
next_report_time = value;
next_report_time.value_namespace = name_space;
next_report_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Utility::ReportingTimes::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "last-report-time")
{
last_report_time.yfilter = yfilter;
}
if(value_path == "last-report-success")
{
last_report_success.yfilter = yfilter;
}
if(value_path == "fail-message")
{
fail_message.yfilter = yfilter;
}
if(value_path == "next-report-time")
{
next_report_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Utility::ReportingTimes::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "last-report-time" || name == "last-report-success" || name == "fail-message" || name == "next-report-time")
return true;
return false;
}
Licensing::State::StateInfo::Utility::CustomerInfo::CustomerInfo()
:
id{YType::str, "id"},
name{YType::str, "name"},
street{YType::str, "street"},
city{YType::str, "city"},
state{YType::str, "state"},
country{YType::str, "country"},
postal_code{YType::str, "postal-code"}
{
yang_name = "customer-info"; yang_parent_name = "utility"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Utility::CustomerInfo::~CustomerInfo()
{
}
bool Licensing::State::StateInfo::Utility::CustomerInfo::has_data() const
{
if (is_presence_container) return true;
return id.is_set
|| name.is_set
|| street.is_set
|| city.is_set
|| state.is_set
|| country.is_set
|| postal_code.is_set;
}
bool Licensing::State::StateInfo::Utility::CustomerInfo::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(id.yfilter)
|| ydk::is_set(name.yfilter)
|| ydk::is_set(street.yfilter)
|| ydk::is_set(city.yfilter)
|| ydk::is_set(state.yfilter)
|| ydk::is_set(country.yfilter)
|| ydk::is_set(postal_code.yfilter);
}
std::string Licensing::State::StateInfo::Utility::CustomerInfo::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/utility/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Utility::CustomerInfo::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "customer-info";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Utility::CustomerInfo::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (id.is_set || is_set(id.yfilter)) leaf_name_data.push_back(id.get_name_leafdata());
if (name.is_set || is_set(name.yfilter)) leaf_name_data.push_back(name.get_name_leafdata());
if (street.is_set || is_set(street.yfilter)) leaf_name_data.push_back(street.get_name_leafdata());
if (city.is_set || is_set(city.yfilter)) leaf_name_data.push_back(city.get_name_leafdata());
if (state.is_set || is_set(state.yfilter)) leaf_name_data.push_back(state.get_name_leafdata());
if (country.is_set || is_set(country.yfilter)) leaf_name_data.push_back(country.get_name_leafdata());
if (postal_code.is_set || is_set(postal_code.yfilter)) leaf_name_data.push_back(postal_code.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Utility::CustomerInfo::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Utility::CustomerInfo::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Utility::CustomerInfo::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "id")
{
id = value;
id.value_namespace = name_space;
id.value_namespace_prefix = name_space_prefix;
}
if(value_path == "name")
{
name = value;
name.value_namespace = name_space;
name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "street")
{
street = value;
street.value_namespace = name_space;
street.value_namespace_prefix = name_space_prefix;
}
if(value_path == "city")
{
city = value;
city.value_namespace = name_space;
city.value_namespace_prefix = name_space_prefix;
}
if(value_path == "state")
{
state = value;
state.value_namespace = name_space;
state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "country")
{
country = value;
country.value_namespace = name_space;
country.value_namespace_prefix = name_space_prefix;
}
if(value_path == "postal-code")
{
postal_code = value;
postal_code.value_namespace = name_space;
postal_code.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Utility::CustomerInfo::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "id")
{
id.yfilter = yfilter;
}
if(value_path == "name")
{
name.yfilter = yfilter;
}
if(value_path == "street")
{
street.yfilter = yfilter;
}
if(value_path == "city")
{
city.yfilter = yfilter;
}
if(value_path == "state")
{
state.yfilter = yfilter;
}
if(value_path == "country")
{
country.yfilter = yfilter;
}
if(value_path == "postal-code")
{
postal_code.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Utility::CustomerInfo::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "id" || name == "name" || name == "street" || name == "city" || name == "state" || name == "country" || name == "postal-code")
return true;
return false;
}
Licensing::State::StateInfo::Transport::Transport()
:
transport_type{YType::enumeration, "transport-type"}
,
url_settings(std::make_shared<Licensing::State::StateInfo::Transport::UrlSettings>())
{
url_settings->parent = this;
yang_name = "transport"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Transport::~Transport()
{
}
bool Licensing::State::StateInfo::Transport::has_data() const
{
if (is_presence_container) return true;
return transport_type.is_set
|| (url_settings != nullptr && url_settings->has_data());
}
bool Licensing::State::StateInfo::Transport::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(transport_type.yfilter)
|| (url_settings != nullptr && url_settings->has_operation());
}
std::string Licensing::State::StateInfo::Transport::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Transport::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "transport";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Transport::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (transport_type.is_set || is_set(transport_type.yfilter)) leaf_name_data.push_back(transport_type.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Transport::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "url-settings")
{
if(url_settings == nullptr)
{
url_settings = std::make_shared<Licensing::State::StateInfo::Transport::UrlSettings>();
}
return url_settings;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Transport::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(url_settings != nullptr)
{
_children["url-settings"] = url_settings;
}
return _children;
}
void Licensing::State::StateInfo::Transport::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "transport-type")
{
transport_type = value;
transport_type.value_namespace = name_space;
transport_type.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Transport::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "transport-type")
{
transport_type.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Transport::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "url-settings" || name == "transport-type")
return true;
return false;
}
Licensing::State::StateInfo::Transport::UrlSettings::UrlSettings()
:
url_registration{YType::str, "url-registration"},
url_utility{YType::str, "url-utility"}
{
yang_name = "url-settings"; yang_parent_name = "transport"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Transport::UrlSettings::~UrlSettings()
{
}
bool Licensing::State::StateInfo::Transport::UrlSettings::has_data() const
{
if (is_presence_container) return true;
return url_registration.is_set
|| url_utility.is_set;
}
bool Licensing::State::StateInfo::Transport::UrlSettings::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(url_registration.yfilter)
|| ydk::is_set(url_utility.yfilter);
}
std::string Licensing::State::StateInfo::Transport::UrlSettings::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/transport/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Transport::UrlSettings::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "url-settings";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Transport::UrlSettings::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (url_registration.is_set || is_set(url_registration.yfilter)) leaf_name_data.push_back(url_registration.get_name_leafdata());
if (url_utility.is_set || is_set(url_utility.yfilter)) leaf_name_data.push_back(url_utility.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Transport::UrlSettings::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Transport::UrlSettings::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Transport::UrlSettings::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "url-registration")
{
url_registration = value;
url_registration.value_namespace = name_space;
url_registration.value_namespace_prefix = name_space_prefix;
}
if(value_path == "url-utility")
{
url_utility = value;
url_utility.value_namespace = name_space;
url_utility.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Transport::UrlSettings::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "url-registration")
{
url_registration.yfilter = yfilter;
}
if(value_path == "url-utility")
{
url_utility.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Transport::UrlSettings::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "url-registration" || name == "url-utility")
return true;
return false;
}
Licensing::State::StateInfo::Privacy::Privacy()
:
hostname{YType::boolean, "hostname"},
version{YType::boolean, "version"}
{
yang_name = "privacy"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Privacy::~Privacy()
{
}
bool Licensing::State::StateInfo::Privacy::has_data() const
{
if (is_presence_container) return true;
return hostname.is_set
|| version.is_set;
}
bool Licensing::State::StateInfo::Privacy::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(hostname.yfilter)
|| ydk::is_set(version.yfilter);
}
std::string Licensing::State::StateInfo::Privacy::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Privacy::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "privacy";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Privacy::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (hostname.is_set || is_set(hostname.yfilter)) leaf_name_data.push_back(hostname.get_name_leafdata());
if (version.is_set || is_set(version.yfilter)) leaf_name_data.push_back(version.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Privacy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Privacy::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Privacy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "hostname")
{
hostname = value;
hostname.value_namespace = name_space;
hostname.value_namespace_prefix = name_space_prefix;
}
if(value_path == "version")
{
version = value;
version.value_namespace = name_space;
version.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Privacy::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "hostname")
{
hostname.yfilter = yfilter;
}
if(value_path == "version")
{
version.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Privacy::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "hostname" || name == "version")
return true;
return false;
}
Licensing::State::StateInfo::Evaluation::Evaluation()
:
eval_in_use{YType::boolean, "eval-in-use"},
eval_expired{YType::boolean, "eval-expired"}
,
eval_period_left(std::make_shared<Licensing::State::StateInfo::Evaluation::EvalPeriodLeft>())
, eval_expire_time(std::make_shared<Licensing::State::StateInfo::Evaluation::EvalExpireTime>())
{
eval_period_left->parent = this;
eval_expire_time->parent = this;
yang_name = "evaluation"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Evaluation::~Evaluation()
{
}
bool Licensing::State::StateInfo::Evaluation::has_data() const
{
if (is_presence_container) return true;
return eval_in_use.is_set
|| eval_expired.is_set
|| (eval_period_left != nullptr && eval_period_left->has_data())
|| (eval_expire_time != nullptr && eval_expire_time->has_data());
}
bool Licensing::State::StateInfo::Evaluation::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(eval_in_use.yfilter)
|| ydk::is_set(eval_expired.yfilter)
|| (eval_period_left != nullptr && eval_period_left->has_operation())
|| (eval_expire_time != nullptr && eval_expire_time->has_operation());
}
std::string Licensing::State::StateInfo::Evaluation::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Evaluation::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "evaluation";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Evaluation::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (eval_in_use.is_set || is_set(eval_in_use.yfilter)) leaf_name_data.push_back(eval_in_use.get_name_leafdata());
if (eval_expired.is_set || is_set(eval_expired.yfilter)) leaf_name_data.push_back(eval_expired.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Evaluation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "eval-period-left")
{
if(eval_period_left == nullptr)
{
eval_period_left = std::make_shared<Licensing::State::StateInfo::Evaluation::EvalPeriodLeft>();
}
return eval_period_left;
}
if(child_yang_name == "eval-expire-time")
{
if(eval_expire_time == nullptr)
{
eval_expire_time = std::make_shared<Licensing::State::StateInfo::Evaluation::EvalExpireTime>();
}
return eval_expire_time;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Evaluation::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(eval_period_left != nullptr)
{
_children["eval-period-left"] = eval_period_left;
}
if(eval_expire_time != nullptr)
{
_children["eval-expire-time"] = eval_expire_time;
}
return _children;
}
void Licensing::State::StateInfo::Evaluation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "eval-in-use")
{
eval_in_use = value;
eval_in_use.value_namespace = name_space;
eval_in_use.value_namespace_prefix = name_space_prefix;
}
if(value_path == "eval-expired")
{
eval_expired = value;
eval_expired.value_namespace = name_space;
eval_expired.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Evaluation::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "eval-in-use")
{
eval_in_use.yfilter = yfilter;
}
if(value_path == "eval-expired")
{
eval_expired.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Evaluation::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "eval-period-left" || name == "eval-expire-time" || name == "eval-in-use" || name == "eval-expired")
return true;
return false;
}
Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::EvalPeriodLeft()
:
time_left{YType::uint32, "time-left"}
{
yang_name = "eval-period-left"; yang_parent_name = "evaluation"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::~EvalPeriodLeft()
{
}
bool Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::has_data() const
{
if (is_presence_container) return true;
return time_left.is_set;
}
bool Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(time_left.yfilter);
}
std::string Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/evaluation/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "eval-period-left";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (time_left.is_set || is_set(time_left.yfilter)) leaf_name_data.push_back(time_left.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "time-left")
{
time_left = value;
time_left.value_namespace = name_space;
time_left.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "time-left")
{
time_left.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Evaluation::EvalPeriodLeft::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "time-left")
return true;
return false;
}
Licensing::State::StateInfo::Evaluation::EvalExpireTime::EvalExpireTime()
:
expire_time{YType::str, "expire-time"}
{
yang_name = "eval-expire-time"; yang_parent_name = "evaluation"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Evaluation::EvalExpireTime::~EvalExpireTime()
{
}
bool Licensing::State::StateInfo::Evaluation::EvalExpireTime::has_data() const
{
if (is_presence_container) return true;
return expire_time.is_set;
}
bool Licensing::State::StateInfo::Evaluation::EvalExpireTime::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(expire_time.yfilter);
}
std::string Licensing::State::StateInfo::Evaluation::EvalExpireTime::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/evaluation/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Evaluation::EvalExpireTime::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "eval-expire-time";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Evaluation::EvalExpireTime::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (expire_time.is_set || is_set(expire_time.yfilter)) leaf_name_data.push_back(expire_time.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Evaluation::EvalExpireTime::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Evaluation::EvalExpireTime::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Evaluation::EvalExpireTime::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "expire-time")
{
expire_time = value;
expire_time.value_namespace = name_space;
expire_time.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Evaluation::EvalExpireTime::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "expire-time")
{
expire_time.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Evaluation::EvalExpireTime::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "expire-time")
return true;
return false;
}
Licensing::State::StateInfo::Udi::Udi()
:
pid{YType::str, "pid"},
sn{YType::str, "sn"},
vid{YType::str, "vid"},
uuid{YType::str, "uuid"},
suvi{YType::str, "suvi"},
host_identifier{YType::str, "host-identifier"},
mac_address{YType::str, "mac-address"}
{
yang_name = "udi"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Udi::~Udi()
{
}
bool Licensing::State::StateInfo::Udi::has_data() const
{
if (is_presence_container) return true;
return pid.is_set
|| sn.is_set
|| vid.is_set
|| uuid.is_set
|| suvi.is_set
|| host_identifier.is_set
|| mac_address.is_set;
}
bool Licensing::State::StateInfo::Udi::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(pid.yfilter)
|| ydk::is_set(sn.yfilter)
|| ydk::is_set(vid.yfilter)
|| ydk::is_set(uuid.yfilter)
|| ydk::is_set(suvi.yfilter)
|| ydk::is_set(host_identifier.yfilter)
|| ydk::is_set(mac_address.yfilter);
}
std::string Licensing::State::StateInfo::Udi::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Udi::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "udi";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Udi::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (pid.is_set || is_set(pid.yfilter)) leaf_name_data.push_back(pid.get_name_leafdata());
if (sn.is_set || is_set(sn.yfilter)) leaf_name_data.push_back(sn.get_name_leafdata());
if (vid.is_set || is_set(vid.yfilter)) leaf_name_data.push_back(vid.get_name_leafdata());
if (uuid.is_set || is_set(uuid.yfilter)) leaf_name_data.push_back(uuid.get_name_leafdata());
if (suvi.is_set || is_set(suvi.yfilter)) leaf_name_data.push_back(suvi.get_name_leafdata());
if (host_identifier.is_set || is_set(host_identifier.yfilter)) leaf_name_data.push_back(host_identifier.get_name_leafdata());
if (mac_address.is_set || is_set(mac_address.yfilter)) leaf_name_data.push_back(mac_address.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Udi::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Udi::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Udi::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "pid")
{
pid = value;
pid.value_namespace = name_space;
pid.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sn")
{
sn = value;
sn.value_namespace = name_space;
sn.value_namespace_prefix = name_space_prefix;
}
if(value_path == "vid")
{
vid = value;
vid.value_namespace = name_space;
vid.value_namespace_prefix = name_space_prefix;
}
if(value_path == "uuid")
{
uuid = value;
uuid.value_namespace = name_space;
uuid.value_namespace_prefix = name_space_prefix;
}
if(value_path == "suvi")
{
suvi = value;
suvi.value_namespace = name_space;
suvi.value_namespace_prefix = name_space_prefix;
}
if(value_path == "host-identifier")
{
host_identifier = value;
host_identifier.value_namespace = name_space;
host_identifier.value_namespace_prefix = name_space_prefix;
}
if(value_path == "mac-address")
{
mac_address = value;
mac_address.value_namespace = name_space;
mac_address.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Udi::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "pid")
{
pid.yfilter = yfilter;
}
if(value_path == "sn")
{
sn.yfilter = yfilter;
}
if(value_path == "vid")
{
vid.yfilter = yfilter;
}
if(value_path == "uuid")
{
uuid.yfilter = yfilter;
}
if(value_path == "suvi")
{
suvi.yfilter = yfilter;
}
if(value_path == "host-identifier")
{
host_identifier.yfilter = yfilter;
}
if(value_path == "mac-address")
{
mac_address.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Udi::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "pid" || name == "sn" || name == "vid" || name == "uuid" || name == "suvi" || name == "host-identifier" || name == "mac-address")
return true;
return false;
}
Licensing::State::StateInfo::Usage::Usage()
:
entitlement_tag{YType::str, "entitlement-tag"},
short_name{YType::str, "short-name"},
license_name{YType::str, "license-name"},
description{YType::str, "description"},
count{YType::uint32, "count"},
enforcement_mode{YType::enumeration, "enforcement-mode"},
post_paid{YType::boolean, "post-paid"},
subscription_id{YType::str, "subscription-id"}
{
yang_name = "usage"; yang_parent_name = "state-info"; is_top_level_class = false; has_list_ancestor = false;
}
Licensing::State::StateInfo::Usage::~Usage()
{
}
bool Licensing::State::StateInfo::Usage::has_data() const
{
if (is_presence_container) return true;
return entitlement_tag.is_set
|| short_name.is_set
|| license_name.is_set
|| description.is_set
|| count.is_set
|| enforcement_mode.is_set
|| post_paid.is_set
|| subscription_id.is_set;
}
bool Licensing::State::StateInfo::Usage::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(entitlement_tag.yfilter)
|| ydk::is_set(short_name.yfilter)
|| ydk::is_set(license_name.yfilter)
|| ydk::is_set(description.yfilter)
|| ydk::is_set(count.yfilter)
|| ydk::is_set(enforcement_mode.yfilter)
|| ydk::is_set(post_paid.yfilter)
|| ydk::is_set(subscription_id.yfilter);
}
std::string Licensing::State::StateInfo::Usage::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "cisco-smart-license:licensing/state/state-info/" << get_segment_path();
return path_buffer.str();
}
std::string Licensing::State::StateInfo::Usage::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "usage";
ADD_KEY_TOKEN(entitlement_tag, "entitlement-tag");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Licensing::State::StateInfo::Usage::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (entitlement_tag.is_set || is_set(entitlement_tag.yfilter)) leaf_name_data.push_back(entitlement_tag.get_name_leafdata());
if (short_name.is_set || is_set(short_name.yfilter)) leaf_name_data.push_back(short_name.get_name_leafdata());
if (license_name.is_set || is_set(license_name.yfilter)) leaf_name_data.push_back(license_name.get_name_leafdata());
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
if (count.is_set || is_set(count.yfilter)) leaf_name_data.push_back(count.get_name_leafdata());
if (enforcement_mode.is_set || is_set(enforcement_mode.yfilter)) leaf_name_data.push_back(enforcement_mode.get_name_leafdata());
if (post_paid.is_set || is_set(post_paid.yfilter)) leaf_name_data.push_back(post_paid.get_name_leafdata());
if (subscription_id.is_set || is_set(subscription_id.yfilter)) leaf_name_data.push_back(subscription_id.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Licensing::State::StateInfo::Usage::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Licensing::State::StateInfo::Usage::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Licensing::State::StateInfo::Usage::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "entitlement-tag")
{
entitlement_tag = value;
entitlement_tag.value_namespace = name_space;
entitlement_tag.value_namespace_prefix = name_space_prefix;
}
if(value_path == "short-name")
{
short_name = value;
short_name.value_namespace = name_space;
short_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "license-name")
{
license_name = value;
license_name.value_namespace = name_space;
license_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
if(value_path == "count")
{
count = value;
count.value_namespace = name_space;
count.value_namespace_prefix = name_space_prefix;
}
if(value_path == "enforcement-mode")
{
enforcement_mode = value;
enforcement_mode.value_namespace = name_space;
enforcement_mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "post-paid")
{
post_paid = value;
post_paid.value_namespace = name_space;
post_paid.value_namespace_prefix = name_space_prefix;
}
if(value_path == "subscription-id")
{
subscription_id = value;
subscription_id.value_namespace = name_space;
subscription_id.value_namespace_prefix = name_space_prefix;
}
}
void Licensing::State::StateInfo::Usage::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "entitlement-tag")
{
entitlement_tag.yfilter = yfilter;
}
if(value_path == "short-name")
{
short_name.yfilter = yfilter;
}
if(value_path == "license-name")
{
license_name.yfilter = yfilter;
}
if(value_path == "description")
{
description.yfilter = yfilter;
}
if(value_path == "count")
{
count.yfilter = yfilter;
}
if(value_path == "enforcement-mode")
{
enforcement_mode.yfilter = yfilter;
}
if(value_path == "post-paid")
{
post_paid.yfilter = yfilter;
}
if(value_path == "subscription-id")
{
subscription_id.yfilter = yfilter;
}
}
bool Licensing::State::StateInfo::Usage::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "entitlement-tag" || name == "short-name" || name == "license-name" || name == "description" || name == "count" || name == "enforcement-mode" || name == "post-paid" || name == "subscription-id")
return true;
return false;
}
const Enum::YLeaf TransportTypeEnum::transport_type_callhome {0, "transport-type-callhome"};
const Enum::YLeaf TransportTypeEnum::transport_type_smart {1, "transport-type-smart"};
const Enum::YLeaf ErrorEnum::success {0, "success"};
const Enum::YLeaf ErrorEnum::malloc {1, "malloc"};
const Enum::YLeaf ErrorEnum::nullpointer {2, "nullpointer"};
const Enum::YLeaf ErrorEnum::error3 {3, "error3"};
const Enum::YLeaf ErrorEnum::error4 {4, "error4"};
const Enum::YLeaf ErrorEnum::error5 {5, "error5"};
const Enum::YLeaf ErrorEnum::BadInputParams {6, "BadInputParams"};
const Enum::YLeaf ErrorEnum::error7 {7, "error7"};
const Enum::YLeaf ErrorEnum::badhandle {8, "badhandle"};
const Enum::YLeaf ErrorEnum::notfound {9, "notfound"};
const Enum::YLeaf ErrorEnum::notsupported {10, "notsupported"};
const Enum::YLeaf ErrorEnum::alreadyinit {11, "alreadyinit"};
const Enum::YLeaf ErrorEnum::notinit {12, "notinit"};
const Enum::YLeaf ErrorEnum::smfailtocreate {13, "smfailtocreate"};
const Enum::YLeaf ErrorEnum::smfailtorun {14, "smfailtorun"};
const Enum::YLeaf ErrorEnum::smfailtoinit {15, "smfailtoinit"};
const Enum::YLeaf ErrorEnum::smfailtodestroy {16, "smfailtodestroy"};
const Enum::YLeaf ErrorEnum::msgparse {17, "msgparse"};
const Enum::YLeaf ErrorEnum::msgbuild {18, "msgbuild"};
const Enum::YLeaf ErrorEnum::notenabled {19, "notenabled"};
const Enum::YLeaf ErrorEnum::invalidrequest {20, "invalidrequest"};
const Enum::YLeaf ErrorEnum::init {21, "init"};
const Enum::YLeaf ErrorEnum::failtosetstate {22, "failtosetstate"};
const Enum::YLeaf ErrorEnum::unsupportedresponse {23, "unsupportedresponse"};
const Enum::YLeaf ErrorEnum::invalidresponse {24, "invalidresponse"};
const Enum::YLeaf ErrorEnum::storagefailtostore {25, "storagefailtostore"};
const Enum::YLeaf ErrorEnum::storagefailtoretrieve {26, "storagefailtoretrieve"};
const Enum::YLeaf ErrorEnum::nullccoidtoken {27, "nullccoidtoken"};
const Enum::YLeaf ErrorEnum::matchidentifier {28, "matchidentifier"};
const Enum::YLeaf ErrorEnum::matchvendor {29, "matchvendor"};
const Enum::YLeaf ErrorEnum::matchnonce {30, "matchnonce"};
const Enum::YLeaf ErrorEnum::commdisabled {31, "commdisabled"};
const Enum::YLeaf ErrorEnum::commsend {32, "commsend"};
const Enum::YLeaf ErrorEnum::commresponse {33, "commresponse"};
const Enum::YLeaf ErrorEnum::communkown {34, "communkown"};
const Enum::YLeaf ErrorEnum::smpostnotallow {35, "smpostnotallow"};
const Enum::YLeaf ErrorEnum::reqmsgmissingmandatoryfield {36, "reqmsgmissingmandatoryfield"};
const Enum::YLeaf ErrorEnum::responsefailed {37, "responsefailed"};
const Enum::YLeaf ErrorEnum::pinotinit {38, "pinotinit"};
const Enum::YLeaf ErrorEnum::alreadyenabled {39, "alreadyenabled"};
const Enum::YLeaf ErrorEnum::alreadyregistered {40, "alreadyregistered"};
const Enum::YLeaf ErrorEnum::certinvalid {41, "certinvalid"};
const Enum::YLeaf ErrorEnum::certexpired {42, "certexpired"};
const Enum::YLeaf ErrorEnum::notregistered {43, "notregistered"};
const Enum::YLeaf ErrorEnum::csrgenerationfailed {44, "csrgenerationfailed"};
const Enum::YLeaf ErrorEnum::verifysignaturefailed {45, "verifysignaturefailed"};
const Enum::YLeaf ErrorEnum::generatesignaturefailed {46, "generatesignaturefailed"};
const Enum::YLeaf ErrorEnum::signcertverificationfailed {47, "signcertverificationfailed"};
const Enum::YLeaf ErrorEnum::nodecertverificationfailed {48, "nodecertverificationfailed"};
const Enum::YLeaf ErrorEnum::parsecertificatefailed {49, "parsecertificatefailed"};
const Enum::YLeaf ErrorEnum::cryptorootcaimportfailed {50, "cryptorootcaimportfailed"};
const Enum::YLeaf ErrorEnum::taginvalid {51, "taginvalid"};
const Enum::YLeaf ErrorEnum::standby {52, "standby"};
const Enum::YLeaf ErrorEnum::registrationinprogress {53, "registrationinprogress"};
const Enum::YLeaf ErrorEnum::commretry {54, "commretry"};
const Enum::YLeaf ErrorEnum::authrenewinprogress {55, "authrenewinprogress"};
const Enum::YLeaf ErrorEnum::idcertrenewinprogress {56, "idcertrenewinprogress"};
const Enum::YLeaf ErrorEnum::noudichange {57, "noudichange"};
const Enum::YLeaf ErrorEnum::callhomeserviceoff {58, "callhomeserviceoff"};
const Enum::YLeaf ErrorEnum::msgexecinprogress {59, "msgexecinprogress"};
const Enum::YLeaf ErrorEnum::msgexecinproglocked {60, "msgexecinproglocked"};
const Enum::YLeaf ErrorEnum::certmatchessubsetudis {61, "certmatchessubsetudis"};
const Enum::YLeaf ErrorEnum::storagegroupchangeincomplete {62, "storagegroupchangeincomplete"};
const Enum::YLeaf ErrorEnum::storagemgmtnotinit {63, "storagemgmtnotinit"};
const Enum::YLeaf ErrorEnum::tspathnotchanged {64, "tspathnotchanged"};
const Enum::YLeaf ErrorEnum::cryptoinitnotcompleted {65, "cryptoinitnotcompleted"};
const Enum::YLeaf ErrorEnum::notinunidentified {66, "notinunidentified"};
const Enum::YLeaf ErrorEnum::platformpathinvalid {67, "platformpathinvalid"};
const Enum::YLeaf ErrorEnum::platformudiinvalid {68, "platformudiinvalid"};
const Enum::YLeaf ErrorEnum::storageobjfailtocreate {69, "storageobjfailtocreate"};
const Enum::YLeaf ErrorEnum::storageobjfailtoerase {70, "storageobjfailtoerase"};
const Enum::YLeaf ErrorEnum::storageobjdoesnotexist {71, "storageobjdoesnotexist"};
const Enum::YLeaf ErrorEnum::messageeventexceedspeer {72, "messageeventexceedspeer"};
const Enum::YLeaf ErrorEnum::codevalidationfailed {73, "codevalidationfailed"};
const Enum::YLeaf ErrorEnum::reserved {74, "reserved"};
const Enum::YLeaf ErrorEnum::noreservationinprogress {75, "noreservationinprogress"};
const Enum::YLeaf ErrorEnum::noauthorizationinstalled {76, "noauthorizationinstalled"};
const Enum::YLeaf ErrorEnum::reservationmismatch {77, "reservationmismatch"};
const Enum::YLeaf ErrorEnum::notreservationmode {78, "notreservationmode"};
const Enum::YLeaf ErrorEnum::reservationerror {79, "reservationerror"};
const Enum::YLeaf ErrorEnum::sysmgrinit {80, "sysmgrinit"};
const Enum::YLeaf ErrorEnum::alreadyexists {81, "alreadyexists"};
const Enum::YLeaf ErrorEnum::listinsertfailed {82, "listinsertfailed"};
const Enum::YLeaf ErrorEnum::sessionmgmtnotinit {83, "sessionmgmtnotinit"};
const Enum::YLeaf ErrorEnum::listinitfailed {84, "listinitfailed"};
const Enum::YLeaf ErrorEnum::listbusy {85, "listbusy"};
const Enum::YLeaf ErrorEnum::noclients {86, "noclients"};
const Enum::YLeaf ErrorEnum::ipc {87, "ipc"};
const Enum::YLeaf ErrorEnum::ipcopen {88, "ipcopen"};
const Enum::YLeaf ErrorEnum::ipcinit {89, "ipcinit"};
const Enum::YLeaf ErrorEnum::ipcconnect {90, "ipcconnect"};
const Enum::YLeaf ErrorEnum::ipcevents {91, "ipcevents"};
const Enum::YLeaf ErrorEnum::ipcmgmt {92, "ipcmgmt"};
const Enum::YLeaf ErrorEnum::ipcsend {93, "ipcsend"};
const Enum::YLeaf ErrorEnum::ipcreceive {94, "ipcreceive"};
const Enum::YLeaf ErrorEnum::ipctimeout {95, "ipctimeout"};
const Enum::YLeaf ErrorEnum::enqueuefailed {96, "enqueuefailed"};
const Enum::YLeaf ErrorEnum::dequeuefailed {97, "dequeuefailed"};
const Enum::YLeaf ErrorEnum::shuttingdown {98, "shuttingdown"};
const Enum::YLeaf ErrorEnum::couldnotvalidatetrustchain {99, "couldnotvalidatetrustchain"};
const Enum::YLeaf ErrorEnum::reservationalreadyinstalled {100, "reservationalreadyinstalled"};
const Enum::YLeaf ErrorEnum::reservationinstallparsefail {101, "reservationinstallparsefail"};
const Enum::YLeaf ErrorEnum::base64encoding {102, "base64encoding"};
const Enum::YLeaf ErrorEnum::base64decoding {103, "base64decoding"};
const Enum::YLeaf ErrorEnum::invalidsoftwareidtag {104, "invalidsoftwareidtag"};
const Enum::YLeaf ErrorEnum::certificatemismatch {105, "certificatemismatch"};
const Enum::YLeaf ErrorEnum::noreservation {106, "noreservation"};
const Enum::YLeaf ErrorEnum::agentunreachable {107, "agentunreachable"};
const Enum::YLeaf ErrorEnum::ignoreevent {108, "ignoreevent"};
const Enum::YLeaf ErrorEnum::b58overflow {109, "b58overflow"};
const Enum::YLeaf ErrorEnum::b58decode {110, "b58decode"};
const Enum::YLeaf ErrorEnum::b58badlen {111, "b58badlen"};
const Enum::YLeaf ErrorEnum::b58invdigit {112, "b58invdigit"};
const Enum::YLeaf ErrorEnum::b58decodeoverflow {113, "b58decodeoverflow"};
const Enum::YLeaf ErrorEnum::reservationversionoutofbound {114, "reservationversionoutofbound"};
const Enum::YLeaf ErrorEnum::base58encode {115, "base58encode"};
const Enum::YLeaf ErrorEnum::duplicatedentry {116, "duplicatedentry"};
const Enum::YLeaf ErrorEnum::missingentry {117, "missingentry"};
const Enum::YLeaf ErrorEnum::badpeerinfoformat {118, "badpeerinfoformat"};
const Enum::YLeaf ErrorEnum::badapplicationhaattributedataset {119, "badapplicationhaattributedataset"};
const Enum::YLeaf ErrorEnum::reservationinprogress {120, "reservationinprogress"};
const Enum::YLeaf ErrorEnum::xdmcreatehandle {121, "xdmcreatehandle"};
const Enum::YLeaf ErrorEnum::versionmismatchinentitlementrsp {122, "versionmismatchinentitlementrsp"};
const Enum::YLeaf ErrorEnum::harolenotsupported {123, "harolenotsupported"};
const Enum::YLeaf ErrorEnum::apphainvalidcharacter {124, "apphainvalidcharacter"};
const Enum::YLeaf ErrorEnum::apphaaddpeerfromsamedevice {125, "apphaaddpeerfromsamedevice"};
const Enum::YLeaf ErrorEnum::apphaappduplicatedinstance {126, "apphaappduplicatedinstance"};
const Enum::YLeaf ErrorEnum::versionmismatchinregresponse {127, "versionmismatchinregresponse"};
const Enum::YLeaf ErrorEnum::conversionnocb {128, "conversionnocb"};
const Enum::YLeaf ErrorEnum::conversionnotallowed {129, "conversionnotallowed"};
const Enum::YLeaf ErrorEnum::conversioninprogress {130, "conversioninprogress"};
const Enum::YLeaf ErrorEnum::conversionalreadystarted {131, "conversionalreadystarted"};
const Enum::YLeaf ErrorEnum::conversionnotenabled {132, "conversionnotenabled"};
const Enum::YLeaf ErrorEnum::versionconversionnotsupported {133, "versionconversionnotsupported"};
const Enum::YLeaf ErrorEnum::noconversioninprogress {134, "noconversioninprogress"};
const Enum::YLeaf ErrorEnum::cryptoversionmismatch {135, "cryptoversionmismatch"};
const Enum::YLeaf ErrorEnum::conversionstoppedpartially {136, "conversionstoppedpartially"};
const Enum::YLeaf ErrorEnum::utilityenabled {137, "utilityenabled"};
const Enum::YLeaf ErrorEnum::utilitynotenabled {138, "utilitynotenabled"};
const Enum::YLeaf ErrorEnum::transportnotavailable {139, "transportnotavailable"};
const Enum::YLeaf ErrorEnum::fqdn {140, "fqdn"};
const Enum::YLeaf ErrorEnum::thirdparty {141, "thirdparty"};
const Enum::YLeaf ErrorEnum::transporttype {142, "transporttype"};
const Enum::YLeaf ErrorEnum::max {143, "max"};
const Enum::YLeaf UtilityReportingTypeEnum::utility_reporting_type_none {0, "utility-reporting-type-none"};
const Enum::YLeaf UtilityReportingTypeEnum::utility_reporting_type_subscription {1, "utility-reporting-type-subscription"};
const Enum::YLeaf UtilityReportingTypeEnum::utility_reporting_type_certificate {2, "utility-reporting-type-certificate"};
const Enum::YLeaf EnforcementModeEnum::enforcement_waiting {0, "enforcement-waiting"};
const Enum::YLeaf EnforcementModeEnum::enforcement_in_compliance {1, "enforcement-in-compliance"};
const Enum::YLeaf EnforcementModeEnum::enforcement_out_of_compliance {2, "enforcement-out-of-compliance"};
const Enum::YLeaf EnforcementModeEnum::enforcement_overage {3, "enforcement-overage"};
const Enum::YLeaf EnforcementModeEnum::enforcement_evaluation {4, "enforcement-evaluation"};
const Enum::YLeaf EnforcementModeEnum::enforcement_evaluation_expired {5, "enforcement-evaluation-expired"};
const Enum::YLeaf EnforcementModeEnum::enforcement_authorization_expired {6, "enforcement-authorization-expired"};
const Enum::YLeaf EnforcementModeEnum::enforcement_reservation_in_compliance {7, "enforcement-reservation-in-compliance"};
const Enum::YLeaf EnforcementModeEnum::enforcement_invalid_tag {8, "enforcement-invalid-tag"};
const Enum::YLeaf EnforcementModeEnum::enforcement_disabled {9, "enforcement-disabled"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_none {0, "auth-state-none"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_eval {1, "auth-state-eval"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_eval_expired {2, "auth-state-eval-expired"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_authorized {3, "auth-state-authorized"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_authorized_reservation {4, "auth-state-authorized-reservation"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_out_of_compliance {5, "auth-state-out-of-compliance"};
const Enum::YLeaf AuthorizationStateEnum::auth_state_authorization_expired {6, "auth-state-authorization-expired"};
const Enum::YLeaf RegistrationStateEnum::reg_state_not_registered {0, "reg-state-not-registered"};
const Enum::YLeaf RegistrationStateEnum::reg_state_complete {1, "reg-state-complete"};
const Enum::YLeaf RegistrationStateEnum::reg_state_in_progress {2, "reg-state-in-progress"};
const Enum::YLeaf RegistrationStateEnum::reg_state_retry {3, "reg-state-retry"};
const Enum::YLeaf RegistrationStateEnum::reg_state_failed {4, "reg-state-failed"};
const Enum::YLeaf NotifRegisterFailureEnum::general_failure {0, "general-failure"};
const Enum::YLeaf NotifRegisterFailureEnum::already_registered_failure {1, "already-registered-failure"};
const Enum::YLeaf NotifRegisterFailureEnum::de_register_failure {2, "de-register-failure"};
}
}
| 32.756443 | 323 | 0.708671 | [
"vector"
] |
ef647f29f39e807b4ec4d3d14f1c62381c2f4616 | 3,860 | cpp | C++ | ProceduralGeneration/Texture.cpp | cristi191096/ProceduralGeneration | 912b738ced73d676f9d0885d917a94c710857396 | [
"Apache-2.0"
] | null | null | null | ProceduralGeneration/Texture.cpp | cristi191096/ProceduralGeneration | 912b738ced73d676f9d0885d917a94c710857396 | [
"Apache-2.0"
] | null | null | null | ProceduralGeneration/Texture.cpp | cristi191096/ProceduralGeneration | 912b738ced73d676f9d0885d917a94c710857396 | [
"Apache-2.0"
] | null | null | null | #include "Texture.h"
#include "stb_image.h"
#include <iostream>
Texture::Texture(const std::string& path, bool enableTransparency)
: id(0), filePath(path), localBuffer(nullptr),
width(0), height(0), BPP(0)
{
//if (enableTransparency) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//}
//else
//{
// glDisable(GL_BLEND);
//}
stbi_set_flip_vertically_on_load(0);
localBuffer = stbi_load(path.c_str(), &width, &height, &BPP, 4);
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &id);
if (localBuffer) {
GLenum format;
if (BPP == 1) format = GL_RGBA;
else if (BPP == 3) format = GL_RGBA;
else if (BPP == 4) format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, localBuffer);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(localBuffer);
}
else
{
std::cout << "Texture at path: " << path << " failed to load!" << std::endl;
stbi_image_free(localBuffer);
}
glDisable(GL_TEXTURE_2D);
}
Texture::Texture(std::vector<std::string> faces)
: id(0), localBuffer(nullptr),
width(0), height(0), BPP(0)
{
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_CUBE_MAP, id);
for (unsigned int i = 0; i < faces.size(); i++) {
localBuffer = stbi_load(faces[i].c_str(), &width, &height, &BPP, 0); //Read texture file
if (localBuffer) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, localBuffer);
stbi_image_free(localBuffer);
}
else
{
std::cout << "Failed to load skybox face: " << faces[i] << std::endl;
stbi_image_free(localBuffer);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
Texture::Texture(std::vector<glm::vec4> imageData, bool enableTransparency) {
float* imageLoader = new float[imageData.size() * 4]();
for (int i = 0; i < imageData.size(); i++) {
imageLoader[i * 4] = (float)imageData[i].r;
imageLoader[i * 4 + 1] = (float)imageData[i].g;
imageLoader[i * 4 + 2] = (float)imageData[i].b;
imageLoader[i * 4 + 3] = (float)imageData[i].a;
}
if (enableTransparency) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
glDisable(GL_BLEND);
}
float sizeImage = std::sqrt(imageData.size());
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sizeImage, sizeImage, 0, GL_RGBA, GL_FLOAT, imageLoader);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}
Texture::~Texture()
{
/*if (id)
{
glDeleteTextures(1, &id);
id = 0;
}*/
}
void Texture::Bind(unsigned int slot, GLenum glTarget) const
{
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(glTarget, id);
}
void Texture::Unbind(unsigned int slot) const
{
glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, 0);
}
| 26.258503 | 120 | 0.724611 | [
"vector"
] |
ef66e758a34ee206c9b900f8f4531c79a092975b | 946 | hpp | C++ | src/blackhole/sink/elasticsearch/settings.hpp | bioothod/blackhole | 2bd242e6027f20019e60b600f50a9e25127db640 | [
"MIT"
] | 1 | 2015-01-12T05:23:28.000Z | 2015-01-12T05:23:28.000Z | src/blackhole/sink/elasticsearch/settings.hpp | tomzhang/blackhole | 4f9b7dec11b9a617b51f188bb792a1514b0bb763 | [
"MIT"
] | null | null | null | src/blackhole/sink/elasticsearch/settings.hpp | tomzhang/blackhole | 4f9b7dec11b9a617b51f188bb792a1514b0bb763 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <boost/asio.hpp>
namespace elasticsearch {
namespace defaults {
typedef boost::asio::ip::tcp::endpoint endpoint_type;
const endpoint_type endpoint(boost::asio::ip::address_v4(), 9200);
} // namespace defaults
struct settings_t {
typedef boost::asio::ip::tcp::endpoint endpoint_type;
std::string index;
std::string type;
std::vector<endpoint_type> endpoints;
struct sniffer_t {
struct {
bool start;
bool error;
} when;
std::uint64_t invertal;
} sniffer;
int connections;
int retries;
std::uint64_t timeout;
settings_t() :
index("logs"),
type("log"),
endpoints(std::vector<endpoint_type>({ defaults::endpoint })),
sniffer({{ true, true }, 60000 }),
connections(20),
retries(3),
timeout(1000)
{}
};
} // namespace elasticsearch
| 18.54902 | 70 | 0.610994 | [
"vector"
] |
ef6808aa722c6add2ab9376e0c497b7683d184a4 | 8,117 | hpp | C++ | src/pTensor/ops/tflm/depthwise_separable_convolution_kernels.hpp | victorromeo/ptensor | 71b7100087795017c086d449c8c79e07799d3426 | [
"Apache-2.0"
] | null | null | null | src/pTensor/ops/tflm/depthwise_separable_convolution_kernels.hpp | victorromeo/ptensor | 71b7100087795017c086d449c8c79e07799d3426 | [
"Apache-2.0"
] | null | null | null | src/pTensor/ops/tflm/depthwise_separable_convolution_kernels.hpp | victorromeo/ptensor | 71b7100087795017c086d449c8c79e07799d3426 | [
"Apache-2.0"
] | null | null | null | #ifndef UTENSOR_S_QUANTIZED_DWS_OPS_KERNELS_H
#define UTENSOR_S_QUANTIZED_DWS_OPS_KERNELS_H
#include "context.hpp"
#include "symmetric_quantization_utils.hpp"
#include "tensor.hpp"
#include "types.hpp"
#include "pTensor_util.hpp"
#include "convolution_helper.hpp"
namespace pTensor {
namespace TFLM {
DECLARE_ERROR(InvalidQDwsActivationRangeError);
DECLARE_ERROR(InvalidQDwsOutputDepthError);
struct TfLiteDepthwiseConvParams {
// Parameters for DepthwiseConv version 1 or above.
TfLitePadding padding;
int stride_width;
int stride_height;
// `depth_multiplier` is redundant. It's used by CPU kernels in
// TensorFlow 2.0 or below, but ignored in versions above.
//
// The information can be deduced from the shape of input and the shape of
// weights. Since the TFLiteConverter toolchain doesn't support partially
// specified shapes, relying on `depth_multiplier` stops us from supporting
// graphs with dynamic shape tensors.
//
// Note: Some of the delegates (e.g. NNAPI, GPU) are still relying on this
// field.
int depth_multiplier;
TfLiteFusedActivation activation;
// Parameters for DepthwiseConv version 2 or above.
int dilation_width_factor;
int dilation_height_factor;
};
struct DepthwiseParams {
PaddingType padding_type;
PaddingValues padding_values;
int16_t stride_width;
int16_t stride_height;
int16_t dilation_width_factor;
int16_t dilation_height_factor;
int16_t depth_multiplier;
// uint8 inference params.
// TODO(b/65838351): Use smaller types if appropriate.
int32_t input_offset;
int32_t weights_offset;
int32_t output_offset;
int32_t output_multiplier;
int output_shift;
// uint8, etc, activation params.
int32_t quantized_activation_min;
int32_t quantized_activation_max;
// float activation params.
float float_activation_min;
float float_activation_max;
const int32_t* output_multiplier_per_channel;
const int32_t* output_shift_per_channel;
};
template <typename Tout>
void DepthwiseConvPerChannel(const DepthwiseParams& params,
const int32_t* output_multiplier,
const int32_t* output_shift, Tensor& input,
Tensor& filter, Tensor& bias, Tensor& output) {
// Get parameters.
// TODO(b/141565753): Re-introduce ScopedProfilingLabel on Micro.
const int stride_width = params.stride_width;
const int stride_height = params.stride_height;
const int dilation_width_factor = params.dilation_width_factor;
const int dilation_height_factor = params.dilation_height_factor;
const int pad_width = params.padding_values.width;
const int pad_height = params.padding_values.height;
const int depth_multiplier = params.depth_multiplier;
const int32_t input_offset = params.input_offset;
const int32_t output_offset = params.output_offset;
const int32_t output_activation_min = params.quantized_activation_min;
const int32_t output_activation_max = params.quantized_activation_max;
// Check dimensions of the tensors.
const TensorShape& input_shape = input->get_shape();
const TensorShape& filter_shape = filter->get_shape();
TensorShape& output_shape = output->get_shape();
if (!(input_shape.num_dims() == 4)) {
Context::get_default_context()->throwError(
new InvalidTensorDimensionsError);
}
if (!(filter_shape.num_dims() == 4)) {
Context::get_default_context()->throwError(
new InvalidTensorDimensionsError);
}
if (!(output_shape.num_dims() == 4)) {
Context::get_default_context()->throwError(
new InvalidTensorDimensionsError);
}
if (!(output_activation_min < output_activation_max)) {
Context::get_default_context()->throwError(
new InvalidQDwsActivationRangeError);
}
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
const int output_depth = MatchingDim(filter_shape, 3, output_shape, 3);
const int input_height = input_shape[1];
const int input_width = input_shape[2];
const int input_depth = input_shape[3];
const int filter_height = filter_shape[1];
const int filter_width = filter_shape[2];
const int output_height = output_shape[1];
const int output_width = output_shape[2];
if (!(output_depth == input_depth * depth_multiplier)) {
Context::get_default_context()->throwError(new InvalidQDwsOutputDepthError);
}
if (!(bias->get_shape().get_linear_size() == (uint16_t)output_depth)) {
Context::get_default_context()->throwError(new InvalidQDwsOutputDepthError);
}
for (int batch = 0; batch < batches; ++batch) {
for (int out_y = 0; out_y < output_height; ++out_y) {
for (int out_x = 0; out_x < output_width; ++out_x) {
for (int in_channel = 0; in_channel < input_depth; ++in_channel) {
for (int m = 0; m < depth_multiplier; ++m) {
const int output_channel = m + in_channel * depth_multiplier;
const int in_x_origin = (out_x * stride_width) - pad_width;
const int in_y_origin = (out_y * stride_height) - pad_height;
int32_t acc = 0;
for (int filter_y = 0; filter_y < filter_height; ++filter_y) {
for (int filter_x = 0; filter_x < filter_width; ++filter_x) {
const int in_x = in_x_origin + dilation_width_factor * filter_x;
const int in_y =
in_y_origin + dilation_height_factor * filter_y;
// Zero padding by omitting the areas outside the image.
const bool is_point_inside_image =
(in_x >= 0) && (in_x < input_width) && (in_y >= 0) &&
(in_y < input_height);
if (is_point_inside_image) {
// int32_t input_val = input_data[Offset(input_shape, batch,
// in_y,
// in_x, in_channel)];
int32_t input_val =
static_cast<int8_t>(input(batch, in_y, in_x, in_channel));
// int32_t filter_val = filter_data[Offset(
// filter_shape, 0, filter_y, filter_x, output_channel)];
int32_t filter_val = static_cast<int8_t>(
filter(0, filter_y, filter_x, output_channel));
// Accumulate with 32 bits accumulator.
// In the nudging process during model quantization, we force
// real value of 0.0 be represented by a quantized value. This
// guarantees that the input_offset is a int8, even though it
// is represented using int32.
// int32 += int8 * (int8 - int8) so the highest value we can
// get from each accumulation is [-127, 127] * ([-128, 127] -
// [-128, 127]), which is [-32512, 32512]. log2(32512)
// = 14.98, which means we can accumulate at least 2^16
// multiplications without overflow. The accumulator is
// applied to a filter so the accumulation logic will hold as
// long as the filter size (filter_y * filter_x * in_channel)
// does not exceed 2^16, which is the case in all the models
// we have seen so far.
// TODO(jianlijianli): Add a check to make sure the
// accumulator depth is smaller than 2^16.
acc += filter_val * (input_val + input_offset);
}
}
}
// assuming bias data will always be provided
acc += static_cast<int32_t>(bias(output_channel));
acc = MultiplyByQuantizedMultiplier(
acc, output_multiplier[output_channel],
output_shift[output_channel]);
acc += output_offset;
acc = std::max(acc, output_activation_min);
acc = std::min(acc, output_activation_max);
output(batch, out_y, out_x, output_channel) =
static_cast<Tout>(acc);
}
}
}
}
}
}
} // namespace TFLM
} // namespace pTensor
#endif
| 42.94709 | 80 | 0.654922 | [
"shape",
"model"
] |
ef6b47ced6385c056a6696a8be38e8c43976877e | 1,896 | hpp | C++ | bunsan/utility/src/builders/meson.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | null | null | null | bunsan/utility/src/builders/meson.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 10 | 2018-02-06T14:46:36.000Z | 2018-03-20T13:37:20.000Z | bunsan/utility/src/builders/meson.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 1 | 2021-11-26T10:59:09.000Z | 2021-11-26T10:59:09.000Z | #pragma once
#include "conf_make_install.hpp"
#include <bunsan/stream_enum.hpp>
#include <bunsan/utility/maker.hpp>
#include <boost/optional.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <string>
#include <unordered_map>
#include <vector>
namespace bunsan::utility::builders {
class meson : public conf_make_install {
public:
struct config {
template <typename Archive>
void serialize(Archive &ar, const unsigned int) {
ar & BOOST_SERIALIZATION_NVP(meson);
ar & BOOST_SERIALIZATION_NVP(maker);
}
struct {
template <typename Archive>
void serialize(Archive &ar, const unsigned int) {
ar & BOOST_SERIALIZATION_NVP(options);
ar & BOOST_SERIALIZATION_NVP(flags);
}
/// for example {"prefix": "/usr"}
/// translated into -Dprefix=/usr
std::unordered_map<std::string, std::string> options;
/// for example {"buildtype": "release"}
/// translated into --buildtype=release
std::unordered_map<std::string, std::string> flags;
} meson;
boost::property_tree::ptree maker;
};
public:
meson(const utility_config &ptree, resolver &resolver_);
protected:
void configure_(const boost::filesystem::path &src,
const boost::filesystem::path &bin) override;
void make_(const boost::filesystem::path &src,
const boost::filesystem::path &bin) override;
void install_(const boost::filesystem::path &src,
const boost::filesystem::path &bin,
const boost::filesystem::path &root) override;
private:
std::vector<std::string> arguments_(const boost::filesystem::path &src) const;
private:
const config m_config;
const boost::filesystem::path m_meson_exe;
const maker_ptr m_maker;
};
struct meson_error : virtual error {};
} // namespace bunsan::utility::builders
| 26.704225 | 80 | 0.678797 | [
"vector"
] |
ef6b5cb4afc85bc52a677a9945b51a150f954f08 | 3,177 | cpp | C++ | todo.cpp | Edmi6163/todo-cli | 347c1cd3911c902eaa7b6ef766d2dbca5704164d | [
"MIT"
] | null | null | null | todo.cpp | Edmi6163/todo-cli | 347c1cd3911c902eaa7b6ef766d2dbca5704164d | [
"MIT"
] | null | null | null | todo.cpp | Edmi6163/todo-cli | 347c1cd3911c902eaa7b6ef766d2dbca5704164d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define vector vector<string>
using namespace std;
// 3 line
int main(int arg ,char ** arv) {
if(arg == 1) { //basic guide for using todo list
cout << "Usage :-" << "\n" << "$todo add " << "\"todo item\""
<< " # Add a new todo"<<"\n"
<< "$todo ls # Show a list of todos"
<< "\n" << "$todo del NUMBER # Delete a todo"<<"\n"
<< "$todo done NUMBER # Complete a todo"<<"\n"
<< "$todo help # Show usage" << "\n";
return 0;
}
else if(*arv[1] == 'h') { //help
cout << "Usage :-" << "\n" << "$todo add "
<< "\"todo item\"" << " # Add a new todo" << "\n"
<< "$todo ls # Show a list of todos"<< "\n"
<< "$todo rm NUMBER # Delete a todo" << "\n"
<< "$todo done NUMBER # Complete a todo" << "\n"
<< "$todo help # Show usage"<< "\n";
return 0;
}
string rr=arv[1];
time_t ttime = time(0);
tm *local_time = localtime(&ttime);
fstream fio;
string line;
fio.open(".todo.txt", ios::out | ios::in |ios::app) ;
if(rr=="add") { //add
vector v;
line=arv[2];
cout<<"Added todo:"<<" "<<line<<endl;
fio <<line<<endl;
fio.seekg(0, ios::beg);
while(fio) {
string str;
getline(fio,str);
v.push_back(str);
}
if(v.size()>1) {
reverse(v.begin(),v.end());
fio.close();
fio.open(".todo.txt", ios::out | ios::in | ios::trunc) ;
for(int i=1;i<v.size();i++) {
fio<<v[i]<<endl;
}
}
} //if ended
else if(rr=="rm") { //delete
string x=arv[2];
int z;
string t;
vector p;
while(fio) {
getline(fio,t);
p.push_back(t);
}
fio.close();
z=stoi(x);
if(z==0 || z>(p.size()-1) || z<0) {
cout<<"todo #"<<z<<"does not exist"<<endl;
return 0;
}
cout<<"Deleted todo #"<<z<<endl;
fio.open(".todo.txt", ios::out | ios::in | ios::trunc) ;
for(int i=0;i<p.size()-1;i++) {
if(i==(p.size()-1)-z)
continue;
else
fio<<p[i]<<endl;
}
}
else if(rr=="ls") { //list
fio.seekg(0, ios::beg);
vector l;
while(fio) {
getline(fio, line);
l.push_back(line);
}
int a=l.size()-1;
for(int i=0;i<l.size()-1;i++) {
if(i==(l.size()-1))
cout<<"["<<a<<"]"<<l[i];
else
cout<<"["<<a<<"]"<<l[i]<<endl;
a--;
}
}
else if(rr=="done") { //done
int u=local_time->tm_mday;
int q=local_time->tm_mon;
int f=local_time->tm_year;
string str ="x ";
str=str+to_string(u)+"-"+to_string(q)+"-"+to_string(f)+" ";
string a=arv[2];
int n;
vector g;
fstream ff;
ff.open("done.txt", ios::in | ios::out | ios::app) ;
fio.seekg(0, ios::beg);
while(fio) {
string rr;
getline(fio,rr);
g.push_back(rr);
}
fio.close();
n=stoi(a);
if(n==0 || n>(g.size()-1) || n<0) {
cout<<"todo #"<<n<<"does not exist"<<endl;
return 0;
}
cout<<"Marked todo #"<<n<<" as done ."<<endl;
fio.open(".todo.txt", ios::out | ios::in | ios::trunc) ;
for(int i=0;i<g.size()-1;i++) {
if(i==(g.size()-1)-n){
str=str+g[i];
ff<<str<<endl;
}
else
fio<<g[i]<<endl;
}
ff.close();
}
else
cout << "invalid command" << "\n";
fio.close();
return 0;
} | 20.365385 | 64 | 0.485678 | [
"vector"
] |
ef7534db2c9c46d0146cfb067606e951e7e79944 | 4,743 | cxx | C++ | smtk/bridge/cgm/operators/BooleanIntersection.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | smtk/bridge/cgm/operators/BooleanIntersection.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | smtk/bridge/cgm/operators/BooleanIntersection.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/bridge/cgm/operators/BooleanIntersection.h"
#include "smtk/bridge/cgm/Session.h"
#include "smtk/bridge/cgm/CAUUID.h"
#include "smtk/bridge/cgm/Engines.h"
#include "smtk/bridge/cgm/TDUUID.h"
#include "smtk/io/Logger.h"
#include "smtk/model/CellEntity.h"
#include "smtk/model/Manager.h"
#include "smtk/model/Model.h"
#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/ModelEntityItem.h"
#include "smtk/attribute/StringItem.h"
#include "CGMApp.hpp"
#include "DagType.hpp"
#include "CubitAttribManager.hpp"
#include "CubitCompat.hpp"
#include "CubitDefines.h"
#include "DLIList.hpp"
#include "InitCGMA.hpp"
#include "GeometryModifyTool.hpp"
#include "GeometryQueryEngine.hpp"
#include "GeometryQueryTool.hpp"
#include "RefEntity.hpp"
#include "RefEntityFactory.hpp"
#include "RefGroup.hpp"
#include "Body.hpp"
#include "smtk/bridge/cgm/BooleanIntersection_xml.h"
using namespace smtk::model;
using smtk::attribute::ModelEntityItemPtr;
namespace smtk {
namespace bridge {
namespace cgm {
/// Verify that at least two input bodies have been specified.
bool BooleanIntersection::ableToOperate()
{
this->ensureSpecification();
bool result = true;
std::size_t numWorkpieces = this->associatedEntitiesAs<Models>().size();
std::size_t numTools = this->findModelEntity("tool")->numberOfValues();
if (numWorkpieces + numTools < 2)
{
result = false;
smtkInfoMacro(
log(),
"Need multiple bodies to intersect, given "
<< numWorkpieces << " workpieces and "
<< numTools << " tools.");
}
return result;
}
smtk::model::OperatorResult BooleanIntersection::operateInternal()
{
int keepInputs = this->findInt("keep inputs")->value();
Models bodiesIn = this->associatedEntitiesAs<Models>();
ModelEntityItemPtr toolIn = this->findModelEntity("tool");
Body* cgmToolBody = NULL;
Models::iterator it;
DLIList<Body*> cgmBodiesIn;
DLIList<Body*> cgmBodiesOut;
EntityRefArray expunged;
bool ok = true;
ok &= this->cgmEntities(
*this->specification()->associations().get(),
cgmBodiesIn,
/* keep_inputs */ 1,
expunged);
// Stop if any of the workpieces don't exist as CGM entities:
if (!ok)
{
smtkInfoMacro(log(),
"One or more workpiece inputs had no matching CGM entity.");
return this->createResult(smtk::model::OPERATION_FAILED);
}
if (toolIn->numberOfValues() > 0)
{
DLIList<Body*> cgmToolBodies;
ok &= this->cgmEntities(
*this->findModelEntity("tool").get(),
cgmToolBodies, keepInputs, expunged);
if (!ok)
{
smtkInfoMacro(
log(),
"Tool body specified as "
<< toolIn->value().name() << " ("
<< toolIn->value().flagSummary() << ")"
<< " but no matching CGM entity exists.");
return this->createResult(smtk::model::OPERATION_FAILED);
}
cgmToolBody = cgmToolBodies[0];
}
else if (!keepInputs)
{ // All but the first input will be expunged.
EntityRefArray::const_iterator wit;
smtk::attribute::ModelEntityItemPtr assoc =
this->specification()->associations();
wit = assoc->begin();
for (++wit; wit != assoc->end(); ++wit)
{
this->manager()->erase(*wit);
expunged.push_back(*wit);
}
}
CubitStatus s;
DLIList<RefEntity*> imported;
if (cgmToolBody)
s = GeometryModifyTool::instance()->intersect(cgmToolBody, cgmBodiesIn, cgmBodiesOut, keepInputs);
else
s = GeometryModifyTool::instance()->intersect(cgmBodiesIn, cgmBodiesOut, keepInputs);
if (s != CUBIT_SUCCESS)
{
smtkInfoMacro(log(), "Failed to perform intersection (status " << s << ").");
return this->createResult(smtk::model::OPERATION_FAILED);
}
smtk::model::OperatorResult result = this->createResult(
smtk::model::OPERATION_SUCCEEDED);
this->addEntitiesToResult(cgmBodiesOut, result, MODIFIED);
result->findModelEntity("expunged")->setValues(expunged.begin(), expunged.end());
return result;
}
} // namespace cgm
} //namespace bridge
} // namespace smtk
smtkImplementsModelOperator(
SMTKCGMSESSION_EXPORT,
smtk::bridge::cgm::BooleanIntersection,
cgm_boolean_intersection,
"intersection",
BooleanIntersection_xml,
smtk::bridge::cgm::Session);
| 29.459627 | 102 | 0.668353 | [
"model"
] |
ef78d65442750d9286829153d34a1f78f9c53aad | 1,607 | cpp | C++ | emulation/hel/lib/ChipObject/NiIRQImpl.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | emulation/hel/lib/ChipObject/NiIRQImpl.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | emulation/hel/lib/ChipObject/NiIRQImpl.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | #include "ChipObject/NiIRQImpl.h"
#include <stdint.h>
NiIRQ_Impl::NiIRQ_Impl() {
}
void NiIRQ_Impl::signal(INTERRUPT_MASK mask) {
waitQueueMutex.take();
lastSignal = mask;
for (int i = 0; i<INTERRUPT_COUNT; i++) {
if (mask & (1 << i)) { // If we want to signal this interrupt
for (std::vector<WaitSemaphore*>::iterator itr = waitQueue[i].begin();
itr != waitQueue[i].end(); itr++) { // Notify all waiting threads
(*itr)->notify();
}
}
}
waitQueueMutex.give();
}
void NiIRQ_Impl::waitFor(uint32_t mask, unsigned long time, uint32_t *signaled, uint8_t *timedout) {
WaitSemaphore *sig = new WaitSemaphore();
// Add signals...
waitQueueMutex.take();
for (int i = 0; i<sizeof(INTERRUPT_MASK) * 8; i++) {
if (mask & (1 << i)) { // If we want to wait on this interrupt
waitQueue[i].push_back(sig); // Add the semaphore to the notification list
}
}
waitQueueMutex.give();
// Wait for signal...
bool success = sig->wait(time); // Wait for the semaphore to be notified.
if (timedout != NULL) {
*timedout = !success;
}
// Remove signals
waitQueueMutex.take();
if (signaled != NULL){
*signaled = lastSignal;
}
for (int i = 0; i<INTERRUPT_COUNT; i++) {
if (mask & (1 << i)) { // If we wanted to signal this interrupt
// Remove the sempahore from the notification list
for (std::vector<WaitSemaphore*>::iterator itr = waitQueue[i].begin(); itr != waitQueue[i].end(); itr++) {
if ((*itr) == sig) {
waitQueue[i].erase(itr);
break;
}
}
}
}
waitQueueMutex.give();
delete sig;
if (success && timedout != NULL) {
*timedout = false;
}
} | 27.706897 | 109 | 0.635968 | [
"vector"
] |
ef7fb9f9c7e5260b20faf93ec34066597d4b937b | 14,346 | cpp | C++ | source/executive.cpp | andrewtrotman/BASIC | 92edcd800397336daace8c1bf062b88bd0c77d94 | [
"BSD-2-Clause"
] | null | null | null | source/executive.cpp | andrewtrotman/BASIC | 92edcd800397336daace8c1bf062b88bd0c77d94 | [
"BSD-2-Clause"
] | null | null | null | source/executive.cpp | andrewtrotman/BASIC | 92edcd800397336daace8c1bf062b88bd0c77d94 | [
"BSD-2-Clause"
] | null | null | null | /*
EXECUTIVE.CPP
-------------
*/
#include <math.h>
#include <ctype.h>
#include "error.h"
#include "executive.h"
#include "symbol_table.h"
#include "reserved_word.h"
#include "parse_tree_node.h"
namespace BASIC
{
/*
EXECUTIVE::EVALUATE_PRINT_PART()
--------------------------------
return true on print cr/lf
*/
bool executive::evaluate_print_part(const std::shared_ptr<parse_tree_node> &root)
{
if (root->command == &executive::evaluate_print_comma)
std::cout << "\t";
if (root->left == nullptr && root->right == nullptr) // we end with a semicolon or a comma
{
if (root->command == &executive::evaluate_print)
return true;
else
return false;
}
if (root->left != nullptr)
{
auto value = evaluate_expression(root->left);
if (value.isstring())
std::cout << (std::string)value;
else
std::cout << (double)value;
}
if (root->right != nullptr)
return evaluate_print_part(root->right);
return true;
}
/*
EXECUTIVE::EVALUATE_PRINT()
---------------------------
*/
void executive::evaluate_print(const std::shared_ptr<parse_tree_node> &root)
{
if (evaluate_print_part(root))
std::cout << "\n";
}
/*
EXECUTIVE::EVALUATE_GOTO()
--------------------------
*/
void executive::evaluate_goto(const std::shared_ptr<parse_tree_node> &root)
{
size_t next_line_number = static_cast<size_t>(root->left->number);
next_line = parsed_code->lower_bound(next_line_number);
if (next_line != parsed_code->end())
if (next_line->first != next_line_number)
throw error::undefined_statement();
}
/*
EXECUTIVE::EVALUATE_GOSUB()
---------------------------
*/
void executive::evaluate_gosub(const std::shared_ptr<parse_tree_node> &root)
{
auto return_address = next_line;
size_t next_line_number = static_cast<size_t>(root->left->number);
next_line = parsed_code->lower_bound(next_line_number);
if (next_line != parsed_code->end())
{
if (next_line->first != next_line_number)
throw error::undefined_statement();
else
gosub_stack.push_back(return_address);
}
}
/*
EXECUTIVE::EVALUATE_RETURN()
----------------------------
*/
void executive::evaluate_return(const std::shared_ptr<parse_tree_node> &root)
{
if (gosub_stack.size() == 0)
throw error::return_without_gosub();
next_line = gosub_stack.back();
gosub_stack.pop_back();
}
/*
EXECUTIVE::EVALUATE_POP()
-------------------------
*/
void executive::evaluate_pop(const std::shared_ptr<parse_tree_node> &root)
{
if (gosub_stack.size() <= 0)
throw error::return_without_gosub();
gosub_stack.pop_back();
}
/*
EXECUTIVE::EVALUATE_REM()
-------------------------
*/
void executive::evaluate_rem(const std::shared_ptr<parse_tree_node> &root)
{
/*
Nothing
*/
}
/*
EXECUTIVE::EVALUATE_DATA()
--------------------------
*/
void executive::evaluate_data(const std::shared_ptr<parse_tree_node> &root)
{
/*
Nothing
*/
}
/*
EXECUTIVE::EVALUATE_RESTORE()
-----------------------------
*/
void executive::evaluate_restore(const std::shared_ptr<parse_tree_node> &root)
{
data_pointer = nullptr;
}
/*
EXECUTIVE::EVALUATE_READ_ONE()
------------------------------
*/
symbol executive::evaluate_read_one(void)
{
if (data_pointer == nullptr)
for (data_pointer_line = parsed_code->begin(); data_pointer_line != parsed_code->end(); ++data_pointer_line)
if (data_pointer_line->second->command == &executive::evaluate_data)
{
data_pointer = data_pointer_line->second->right;
break;
}
if (data_pointer == nullptr)
throw error::out_of_data_error();
auto source = data_pointer->left->string;
data_pointer = data_pointer->right;
if (data_pointer == nullptr)
{
while (data_pointer_line != parsed_code->end())
if (data_pointer_line->second->command == &executive::evaluate_data)
{
data_pointer = data_pointer_line->second;
break;
}
}
if (data_pointer == nullptr)
throw error::out_of_data_error();
if (::isdigit(source[0]))
return symbol(atof(source.c_str()));
else if (source[0] == '"')
return symbol(source.substr(1, source.size() - 2));
else
return symbol(source);
}
/*
EXECUTIVE::EVALUATE_READ()
--------------------------
*/
void executive::evaluate_read(const std::shared_ptr<parse_tree_node> &root)
{
for (auto node = root->right; node != nullptr; node = node->right)
symbol_table[node->left] = evaluate_read_one();
}
/*
EXECUTIVE::EVALUATE_END()
-------------------------
*/
void executive::evaluate_end(const std::shared_ptr<parse_tree_node> &root)
{
end = true;
}
/*
EXECUTIVE::EVALUATE_IF()
------------------------
*/
void executive::evaluate_if(const std::shared_ptr<parse_tree_node> &root)
{
if (evaluate_expression(root->left))
evaluate(root->right);
}
/*
EXECUTIVE::EVALUATE_FOR()
-------------------------
*/
void executive::evaluate_for(const std::shared_ptr<parse_tree_node> &root)
{
evaluate(root->left);
symbol &from = symbol_table[root->left->left];
symbol to = evaluate_expression(root->right->left);
symbol step = evaluate_expression(root->right->right);
for_stack.push_back(for_tuple(root->left->left->symbol, from, to, step, next_line));
}
/*
EXECUTIVE::EVALUATE_DIM()
-------------------------
*/
void executive::evaluate_dim(const std::shared_ptr<parse_tree_node> &root)
{
std::vector<size_t> sizes;
auto name = root->left->string;
for (auto current = root->right; current != nullptr; current = current->right)
sizes.push_back(evaluate_expression(current->left));
symbol_table.create_array(name, sizes);
}
/*
EXECUTIVE::STEP()
-----------------
Returns true if a loop was iterated, or false if we leave a loop.
*/
bool executive::step(int64_t which_for_loop)
{
for_tuple &who = for_stack[which_for_loop];
who.variable = static_cast<double>(who.variable) + who.step;
double step = static_cast<double>(who.step);
if (step > 0)
{
if (static_cast<double>(who.variable) <= who.to)
next_line = who.line;
else
return false;
}
else if (step < 0)
{
if (static_cast<double>(who.variable) >= who.to)
next_line = who.line;
else
return false;
}
else
next_line = who.line;
return true;
}
/*
EXECUTIVE::EVALUATE_NEXT()
--------------------------
*/
void executive::evaluate_next(const std::shared_ptr<parse_tree_node> &root)
{
int64_t which_for_loop = for_stack.size() - 1;
if (which_for_loop < 0)
throw error::next_without_for();
if (root->string == "")
{
if (!step(which_for_loop))
for_stack.pop_back();
}
else
{
const char *list = root->string.c_str();
do
{
const char *from = list;
const char *to = strchr(from, ',');
if (to == nullptr)
to = from + strlen(from);
while (for_stack[which_for_loop].variable_name != std::string(from, to - from))
if (--which_for_loop < 0)
throw error::next_without_for();
if (step(which_for_loop))
return;
else
for_stack.pop_back();
list = to + 1; // skip over the ",".
}
while (*list != '\0');
}
}
/*
EXECUTIVE::EVALUATE_INPUT_PART()
--------------------------------
*/
void executive::evaluate_input_part(const std::shared_ptr<parse_tree_node> &the_root)
{
char input[1024];
std::cout << the_root->left->string;
std::shared_ptr<parse_tree_node> root = the_root->right;
while (1)
{
fgets(input, sizeof(input), stdin);
char *ch = input;
do
{
if (root == nullptr)
throw error::extra_ignored();
/*
remove whitespace before the data
*/
while (isspace(*ch))
ch++;
char *start = ch;
/*
extract the data
*/
if (isdigit(*ch))
while (isdigit(*ch))
ch++;
else if (*ch == '"')
{
ch++;
while (*ch != '"' && *ch != '\0' && *ch != '\n' && *ch != '\r')
ch++;
if (*ch == '"')
ch++;
}
else
while (*ch != ',' && *ch != '\0' && *ch != '\n' && *ch != '\r')
ch++;
/*
remove whitespace after the data
*/
while (isspace(*ch))
*ch++ = '\0';
if (*ch != ',' && *ch != '\0')
throw error::reenter();
if (*ch != '\0')
*ch++ = '\0';
if (isdigit(*start))
symbol_table[root->left] = atof(start);
else if (*start == '"')
symbol_table[root->left] = std::string(start + 1, strlen(start + 1) - 1);
else
symbol_table[root->left] = std::string(start);
/*
next variable.
*/
root = root->right;
}
while (*ch != '\0');
if (root == nullptr)
return;
std::cout << "??";
}
}
/*
EXECUTIVE::EVALUATE_INPUT()
---------------------------
*/
void executive::evaluate_input(const std::shared_ptr<parse_tree_node> &root)
{
while (1)
try
{
evaluate_input_part(root);
break;
}
catch (error::reenter)
{
/* Nothing */
}
}
/*
EXECUTIVE::EVALUATE_LET()
-------------------------
*/
void executive::evaluate_let(const std::shared_ptr<parse_tree_node> &root)
{
symbol_table[root->left] = symbol(evaluate_expression(root->right));
}
/*
EXECUTIVE::EVALUATE_PLUS()
--------------------------
*/
symbol executive::evaluate_plus(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left + right;
}
/*
EXECUTIVE::EVALUATE_MINUS()
---------------------------
*/
symbol executive::evaluate_minus(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left - right;
}
/*
EXECUTIVE::EVALUATE_MULTIPLY()
------------------------------
*/
symbol executive::evaluate_multiply(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left * right;
}
/*
EXECUTIVE::EVALUATE_MULTIPLY()
------------------------------
*/
symbol executive::evaluate_divide(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left / right;
}
/*
EXECUTIVE::EVALUATE_POWER()
---------------------------
*/
symbol executive::evaluate_power(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return pow(left, right);
}
/*
EXECUTIVE::EVALUATE_UNARY_PLUS()
--------------------------------
*/
symbol executive::evaluate_unary_plus(const std::shared_ptr<parse_tree_node> &root)
{
return evaluate_expression(root->right);
}
/*
EXECUTIVE::EVALUATE_UNARY_MINUS()
---------------------------------
*/
symbol executive::evaluate_unary_minus(const std::shared_ptr<parse_tree_node> &root)
{
return -(double)evaluate_expression(root->right);
}
/*
EXECUTIVE::EVALUATE_EQUALS_EQUALS()
-----------------------------------
*/
symbol executive::evaluate_equals_equals(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left == right;
}
/*
EXECUTIVE::EVALUATE_NOT_EQUALS()
--------------------------------
*/
symbol executive::evaluate_not_equals(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left != right;
}
/*
EXECUTIVE::EVALUATE_GREATER_THAN()
----------------------------------
*/
symbol executive::evaluate_greater_than(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left > right;
}
/*
EXECUTIVE::EVALUATE_LESS_THAN()
-------------------------------
*/
symbol executive::evaluate_less_than(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left < right;
}
/*
EXECUTIVE::EVALUATE_GREATER_THAN_EQUALS()
-----------------------------------------
*/
symbol executive::evaluate_greater_than_equals(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left >= right;
}
/*
EXECUTIVE::EVALUATE_LESS_THAN_EQUALS()
--------------------------------------
*/
symbol executive::evaluate_less_than_equals(const std::shared_ptr<parse_tree_node> &root)
{
auto left = evaluate_expression(root->left);
auto right = evaluate_expression(root->right);
return left <= right;
}
/*
EXECUTIVE::EVALUATE_EXPRESSION()
--------------------------------
*/
symbol executive::evaluate_expression(const std::shared_ptr<parse_tree_node> &root)
{
if (root == nullptr)
return 0;
else if (root->type == parse_tree_node::STRING)
return root->string;
else if (root->type == parse_tree_node::NUMBER)
return root->number;
else if (root->type == parse_tree_node::SYMBOL)
return symbol_table[root];
else if (root->type == parse_tree_node::OPERATOR)
return (this->*(root->operation))(root);
else
return 0;
}
/*
EXECUTIVE::EVALUATE()
---------------------
*/
void executive::evaluate(const std::shared_ptr<parse_tree_node> &root)
{
if (root == nullptr)
return;
else if (root->type == parse_tree_node::COMMAND)
(this->*(root->command))(root);
else
evaluate_expression(root);
}
/*
EXECUTIVE::EVALUATE()
---------------------
*/
void executive::evaluate(const executive::program &parsed_code, size_t start_line)
{
this->parsed_code = &parsed_code;
auto current_line = parsed_code.lower_bound(start_line);
while (current_line != parsed_code.end())
{
try
{
end = false;
// std::cout << current_line->second << "\n";
next_line = current_line; // done like this so that GOTO works
next_line++;
evaluate(current_line->second);
current_line = next_line;
if (end)
break;
}
catch (BASIC::error::extra_ignored)
{
std::cout << "EXTRA IGNORED";
}
}
}
}
| 22.9536 | 111 | 0.60421 | [
"vector"
] |
ef830a8fdb2c65df6581f5b9cb7621cdf565646a | 4,334 | hpp | C++ | src/bvh.hpp | ddiakopoulos/light-transport | b82ceba5fa5719d1d986be968f28b1581c2d72ba | [
"BSD-3-Clause"
] | 3 | 2017-10-26T16:58:39.000Z | 2017-10-31T02:24:41.000Z | src/bvh.hpp | ddiakopoulos/light-transport | b82ceba5fa5719d1d986be968f28b1581c2d72ba | [
"BSD-3-Clause"
] | null | null | null | src/bvh.hpp | ddiakopoulos/light-transport | b82ceba5fa5719d1d986be968f28b1581c2d72ba | [
"BSD-3-Clause"
] | 1 | 2020-08-08T23:20:23.000Z | 2020-08-08T23:20:23.000Z | #ifndef bvh_hpp
#define bvh_hpp
#pragma once
#include "objects.hpp"
#include <vector>
#include <memory>
// This implementation only accounts for axis-aligned bounding boxes of mesh objects, mostly as a learning exercise. It will
// later move to Embree's native BVH accelerator which correctly buckets individual triangles across all meshes in the scene.
class BVH
{
struct ObjectComparator
{
uint32_t split;
ObjectComparator(const uint32_t axis = 0) : split(axis) { }
bool operator() (const std::shared_ptr<Traceable> & a, const std::shared_ptr<Traceable> & b) const
{
return a->world_bounds().center()[split] < b->world_bounds().center()[split];
}
};
struct Node
{
Node * left = nullptr;
Node * right = nullptr;
Bounds3D bounds;
uint32_t axis = 0; // split axis
float position = 0.f; // split position
std::vector<std::shared_ptr<Traceable>> data;
Node(const uint32_t axis = 0, const float position = 0.f) : axis(axis), position(position) {}
~Node() { if (left) delete left; if (right) delete right; }
bool is_leaf() const { return (left == nullptr && right == nullptr); }
};
std::vector<std::shared_ptr<Traceable>> objects;
bool initialized = false;
float leafThreshold = 1.f;
Node * root = nullptr;
public:
BVH(std::vector<std::shared_ptr<Traceable>> objects) : objects(objects) {}
~BVH() { if (root) delete root; }
Node * get_root() { if (root) return root; else return nullptr; }
void build()
{
root = new Node();
build_recursive(root, 0, objects);
initialized = true;
}
void build_recursive(Node * node, uint32_t depth, std::vector<std::shared_ptr<Traceable>> & objects)
{
Bounds3D nodeBounds = objects[0]->world_bounds();
for (size_t i = 0; i < objects.size(); i++)
{
nodeBounds = nodeBounds.add(objects[i]->world_bounds());
}
node->bounds = nodeBounds;
// Recursion limit was reached, create a new leaf
if (objects.size() <= leafThreshold)
{
node->data.insert(node->data.end(), objects.begin(), objects.end());
return;
}
// Split the node based on its longest axis
node->axis = nodeBounds.maximum_extent();
const size_t median = objects.size() >> 1;
std::nth_element(objects.begin(), objects.begin() + median, objects.end(), ObjectComparator(node->axis));
node->position = objects[median]->world_bounds().center()[node->axis];
node->left = new Node();
node->right = new Node();
std::vector<std::shared_ptr<Traceable>> leftList(median);
std::vector<std::shared_ptr<Traceable>> rightList(objects.size() - median);
std::copy(objects.begin(), objects.begin() + median, leftList.begin());
std::copy(objects.begin() + median, objects.end(), rightList.begin());
build_recursive(node->left, depth + 1, leftList);
build_recursive(node->right, depth + 1, rightList);
}
void debug_traverse(const Node * node) const
{
if (!node) return;
std::cout << node->bounds << ", is leaf " << node->is_leaf() << std::endl;
if (node->left) debug_traverse(node->left);
if (node->right) debug_traverse(node->right);
}
RayIntersection intersect(const Ray & ray)
{
RayIntersection result;
traverse(root, ray, result);
return result;
}
void traverse(Node * node, const Ray & ray, RayIntersection & result)
{
// Test directly against object
if (node->is_leaf())
{
RayIntersection best;
for (auto & n : node->data)
{
RayIntersection r = n->intersects(ray);
if (r.d < result.d) best = r;
if (best())
{
result = best;
return;
}
}
}
else
{ // Otherwise continue traversal
if (intersect_ray_box(ray, node->left->bounds)) traverse(node->left, ray, result);
if (intersect_ray_box(ray, node->right->bounds)) traverse(node->right, ray, result);
}
}
};
#endif
| 31.635036 | 126 | 0.579603 | [
"mesh",
"object",
"vector"
] |
ef83343b5fd0ae70342fab883cde71a72db54eee | 1,032 | cpp | C++ | source/model-generator/FieldModelTemplate.cpp | daetalys/mariana-trench | 9c07393cf18395ec7ed05a1650e7f764ae216be2 | [
"MIT"
] | null | null | null | source/model-generator/FieldModelTemplate.cpp | daetalys/mariana-trench | 9c07393cf18395ec7ed05a1650e7f764ae216be2 | [
"MIT"
] | null | null | null | source/model-generator/FieldModelTemplate.cpp | daetalys/mariana-trench | 9c07393cf18395ec7ed05a1650e7f764ae216be2 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <mariana-trench/JsonValidation.h>
#include <mariana-trench/model-generator/FieldModelTemplate.h>
namespace marianatrench {
FieldModelTemplate::FieldModelTemplate(const FieldModel& field_model)
: field_model_(field_model) {
mt_assert(field_model.field() == nullptr);
}
std::optional<FieldModel> FieldModelTemplate::instantiate(
const Field* field) const {
auto field_model = field_model_.instantiate(field);
return !field_model.empty() ? std::optional<FieldModel>{field_model}
: std::nullopt;
}
FieldModelTemplate FieldModelTemplate::from_json(
const Json::Value& field_model,
Context& context) {
JsonValidation::validate_object(field_model);
return FieldModelTemplate(FieldModel::from_json(
/* field */ nullptr, field_model, context));
}
} // namespace marianatrench
| 30.352941 | 70 | 0.733527 | [
"model"
] |
ef84a5e8f0afcdbfd186b0562d76b0b8b14b3038 | 21,409 | cpp | C++ | extern/eltopo/common/ccd_wrapper.cpp | wycivil08/blendocv | f6cce83e1f149fef39afa8043aade9c64378f33e | [
"Unlicense"
] | 30 | 2015-01-29T14:06:05.000Z | 2022-01-10T07:47:29.000Z | extern/eltopo/common/ccd_wrapper.cpp | ttagu99/blendocv | f6cce83e1f149fef39afa8043aade9c64378f33e | [
"Unlicense"
] | 1 | 2017-02-20T20:57:48.000Z | 2018-12-19T23:44:38.000Z | extern/eltopo/common/ccd_wrapper.cpp | ttagu99/blendocv | f6cce83e1f149fef39afa8043aade9c64378f33e | [
"Unlicense"
] | 15 | 2015-04-23T02:38:36.000Z | 2021-03-01T20:09:39.000Z |
// ---------------------------------------------------------
//
// ccd_wrapper.cpp
// Tyson Brochu 2009
//
// Tunicate-based implementation of collision and intersection queries. (See Robert Bridson's "Tunicate" library.)
//
// ---------------------------------------------------------
#include <ccd_wrapper.h>
#ifdef USE_TUNICATE_CCD
#include <collisionqueries.h>
#include <tunicate.h>
#include <vec.h>
const unsigned int nv = 1000000;
// return a unit-length vector orthogonal to u and v
static Vec3d get_normal(const Vec3d& u, const Vec3d& v)
{
Vec3d c=cross(u,v);
double m=mag(c);
if(m) return c/m;
// degenerate case: either u and v are parallel, or at least one is zero; pick an arbitrary orthogonal vector
if(mag2(u)>=mag2(v)){
if(std::fabs(u[0])>=std::fabs(u[1]) && std::fabs(u[0])>=std::fabs(u[2]))
c=Vec3d(-u[1]-u[2], u[0], u[0]);
else if(std::fabs(u[1])>=std::fabs(u[2]))
c=Vec3d(u[1], -u[0]-u[2], u[1]);
else
c=Vec3d(u[2], u[2], -u[0]-u[1]);
}else{
if(std::fabs(v[0])>=std::fabs(v[1]) && std::fabs(v[0])>=std::fabs(v[2]))
c=Vec3d(-v[1]-v[2], v[0], v[0]);
else if(std::fabs(v[1])>=std::fabs(v[2]))
c=Vec3d(v[1], -v[0]-v[2], v[1]);
else
c=Vec3d(v[2], v[2], -v[0]-v[1]);
}
m=mag(c);
if(m) return c/m;
// really degenerate case: u and v are both zero vectors; pick a random unit-length vector
c[0]=random()%2 ? -0.577350269189626 : 0.577350269189626;
c[1]=random()%2 ? -0.577350269189626 : 0.577350269189626;
c[2]=random()%2 ? -0.577350269189626 : 0.577350269189626;
return c;
}
// --------------------------------------------------------------------------------------------------------------
bool point_triangle_collision(const Vec3d& x0, const Vec3d& xnew0, unsigned int index0,
const Vec3d& x1, const Vec3d& xnew1, unsigned int index1,
const Vec3d& x2, const Vec3d& xnew2, unsigned int index2,
const Vec3d& x3, const Vec3d& xnew3, unsigned int index3 )
{
assert( index1 < index2 && index2 < index3 );
const int segment_tetrahedron_test = 2;
double p0[4] = { x0[0], x0[1], x0[2], 0.0 };
double pnew0[4] = { xnew0[0], xnew0[1], xnew0[2], 1.0 };
double p1[4] = { x1[0], x1[1], x1[2], 0.0 };
double pnew1[4] = { xnew1[0], xnew1[1], xnew1[2], 1.0 };
double p2[4] = { x2[0], x2[1], x2[2], 0.0 };
double pnew2[4] = { xnew2[0], xnew2[1], xnew2[2], 1.0 };
double p3[4] = { x3[0], x3[1], x3[2], 0.0 };
double pnew3[4] = { xnew3[0], xnew3[1], xnew3[2], 1.0 };
double bary[6];
if ( simplex_intersection4d( segment_tetrahedron_test,
p0, pnew0, p1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
if ( simplex_intersection4d( segment_tetrahedron_test,
p0, pnew0, p1, p2, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
if ( simplex_intersection4d( segment_tetrahedron_test,
p0, pnew0, p1, pnew1, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
return false;
}
// --------------------------------------------------------------------------------------------------------------
static void out4d( double* x )
{
std::cout << x[0] << " " << x[1] << " " << x[2] << " " << x[3] << std::endl;
}
bool point_triangle_collision(const Vec3d& x0, const Vec3d& xnew0, unsigned int index0,
const Vec3d& x1, const Vec3d& xnew1, unsigned int index1,
const Vec3d& x2, const Vec3d& xnew2, unsigned int index2,
const Vec3d& x3, const Vec3d& xnew3, unsigned int index3,
double& bary1, double& bary2, double& bary3,
Vec3d& normal,
double& t,
double& relative_normal_displacement,
bool verbose )
{
assert( index1 < index2 && index2 < index3 );
const int segment_tetrahedron_test = 2;
double p0[4] = { x0[0], x0[1], x0[2], 0.0 };
double pnew0[4] = { xnew0[0], xnew0[1], xnew0[2], 1.0 };
double p1[4] = { x1[0], x1[1], x1[2], 0.0 };
double pnew1[4] = { xnew1[0], xnew1[1], xnew1[2], 1.0 };
double p2[4] = { x2[0], x2[1], x2[2], 0.0 };
double pnew2[4] = { xnew2[0], xnew2[1], xnew2[2], 1.0 };
double p3[4] = { x3[0], x3[1], x3[2], 0.0 };
double pnew3[4] = { xnew3[0], xnew3[1], xnew3[2], 1.0 };
bool collision=false;
double bary[6];
if ( simplex_intersection4d( segment_tetrahedron_test,
p0, pnew0, p1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
collision=true;
bary1=0;
bary2=0;
bary3=1;
t=bary[1];
normal=get_normal(x2-x1, x3-x1);
relative_normal_displacement=dot(normal, (xnew0-x0)-(xnew3-x3));
if ( verbose )
{
std::cout << "segment_tetrahedron_test positive with these inputs: " << std::endl;
std::cout.precision(20);
out4d(p0);
out4d(pnew0);
out4d(p1);
out4d(p2);
out4d(p3);
out4d(pnew3);
}
}
if ( simplex_intersection4d( segment_tetrahedron_test,
p0, pnew0, p1, p2, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
if(!collision || bary[1]<t)
{
collision=true;
bary1=0;
bary2=(bary[4]+1e-300)/(bary[4]+bary[5]+2e-300); // guard against zero/zero
bary3=1-bary2;
t=bary[1];
normal=get_normal(x2-x1, xnew3-xnew2);
relative_normal_displacement=dot(normal, (xnew0-x0)-(xnew2-x2));
if ( verbose )
{
std::cout << "segment_tetrahedron_test positive with these inputs: " << std::endl;
std::cout.precision(20);
out4d(p0);
out4d(pnew0);
out4d(p1);
out4d(p2);
out4d(pnew2);
out4d(pnew3);
}
}
}
if ( simplex_intersection4d( segment_tetrahedron_test,
p0, pnew0, p1, pnew1, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
if(!collision || bary[1]<t)
{
collision=true;
bary1=(bary[3]+1e-300)/(bary[3]+bary[4]+bary[5]+3e-300); // guard against zero/zero
bary2=(bary[4]+1e-300)/(bary[3]+bary[4]+bary[5]+3e-300); // guard against zero/zero
bary3=1-bary1-bary2;
t=bary[1];
normal=get_normal(xnew2-xnew1, xnew3-xnew1);
relative_normal_displacement=dot(normal, (xnew0-x0)-(xnew1-x1));
if ( verbose )
{
std::cout << "segment_tetrahedron_test positive with these inputs: " << std::endl;
std::cout.precision(20);
out4d(p0);
out4d(pnew0);
out4d(p1);
out4d(pnew1);
out4d(pnew2);
out4d(pnew3);
}
}
}
if ( collision )
{
Vec3d dx0 = xnew0 - x0;
Vec3d dx1 = xnew1 - x1;
Vec3d dx2 = xnew2 - x2;
Vec3d dx3 = xnew3 - x3;
relative_normal_displacement = dot( normal, dx0 - bary1*dx1 - bary2*dx2 - bary3*dx3 );
}
return collision;
}
// --------------------------------------------------------------------------------------------------------------
bool segment_segment_collision(const Vec3d& x0, const Vec3d& xnew0, unsigned int index0,
const Vec3d& x1, const Vec3d& xnew1, unsigned int index1,
const Vec3d& x2, const Vec3d& xnew2, unsigned int index2,
const Vec3d& x3, const Vec3d& xnew3, unsigned int index3)
{
assert( index0 < index1 && index2 < index3 );
const int triangle_triangle_test = 3;
double p0[4] = { x0[0], x0[1], x0[2], 0.0 };
double pnew0[4] = { xnew0[0], xnew0[1], xnew0[2], 1.0 };
double p1[4] = { x1[0], x1[1], x1[2], 0.0 };
double pnew1[4] = { xnew1[0], xnew1[1], xnew1[2], 1.0 };
double p2[4] = { x2[0], x2[1], x2[2], 0.0 };
double pnew2[4] = { xnew2[0], xnew2[1], xnew2[2], 1.0 };
double p3[4] = { x3[0], x3[1], x3[2], 0.0 };
double pnew3[4] = { xnew3[0], xnew3[1], xnew3[2], 1.0 };
double bary[6];
if ( simplex_intersection4d( triangle_triangle_test,
p0, p1, p1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
if ( simplex_intersection4d( triangle_triangle_test,
p0, pnew0, pnew1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
if ( simplex_intersection4d( triangle_triangle_test,
p0, p1, pnew1, p2, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
if ( simplex_intersection4d( triangle_triangle_test,
p0, pnew0, pnew1, p2, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
return true;
}
return false;
}
// --------------------------------------------------------------------------------------------------------------
static void output_4d( const double* v )
{
int old_precision = std::cout.precision();
std::cout.precision(20);
std::cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << std::endl;
std::cout.precision(old_precision);
}
bool g_verbose = false;
bool segment_segment_collision(const Vec3d& x0, const Vec3d& xnew0, unsigned int index0,
const Vec3d& x1, const Vec3d& xnew1, unsigned int index1,
const Vec3d& x2, const Vec3d& xnew2, unsigned int index2,
const Vec3d& x3, const Vec3d& xnew3, unsigned int index3,
double& bary0, double& bary2,
Vec3d& normal,
double& t,
double& relative_normal_displacement,
bool verbose )
{
assert( index0 < index1 && index2 < index3 );
const int triangle_triangle_test = 3;
double p0[4] = { x0[0], x0[1], x0[2], 0.0 };
double pnew0[4] = { xnew0[0], xnew0[1], xnew0[2], 1.0 };
double p1[4] = { x1[0], x1[1], x1[2], 0.0 };
double pnew1[4] = { xnew1[0], xnew1[1], xnew1[2], 1.0 };
double p2[4] = { x2[0], x2[1], x2[2], 0.0 };
double pnew2[4] = { xnew2[0], xnew2[1], xnew2[2], 1.0 };
double p3[4] = { x3[0], x3[1], x3[2], 0.0 };
double pnew3[4] = { xnew3[0], xnew3[1], xnew3[2], 1.0 };
bool collision=false;
double bary[6];
if ( simplex_intersection4d( triangle_triangle_test,
p0, p1, pnew1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
collision=true;
bary0=0;
bary2=0;
t=bary[2];
normal=get_normal(x1-x0, x3-x2);
relative_normal_displacement=dot(normal, (xnew1-x1)-(xnew3-x3));
if ( verbose )
{
std::cout << "triangle_triangle_test positive with these inputs: " << std::endl;
output_4d(p0);
output_4d(p1);
output_4d(pnew1);
output_4d(p2);
output_4d(p3);
output_4d(pnew3);
std::cout << "barycentric coords: " << std::endl;
for ( unsigned int i = 0; i < 6; ++i ) { std::cout << bary[i] << " " << std::endl; }
g_verbose = true;
simplex_intersection4d( triangle_triangle_test,
p0, p1, pnew1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] );
g_verbose = false;
assert(0);
}
}
if ( simplex_intersection4d( triangle_triangle_test,
p0, pnew0, pnew1, p2, p3, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
if(!collision || bary[5]<t)
{
collision=true;
bary0=(bary[1]+1e-300)/(bary[1]+bary[2]+2e-300); // guard against zero/zero
bary2=0;
t=bary[5];
normal=get_normal(xnew1-xnew0, x3-x2);
relative_normal_displacement=dot(normal, (xnew0-x0)-(xnew3-x3));
if ( verbose )
{
std::cout << "triangle_triangle_test positive with these inputs: " << std::endl;
output_4d(p0);
output_4d(pnew0);
output_4d(pnew1);
output_4d(p2);
output_4d(p3);
output_4d(pnew3);
}
}
}
if ( simplex_intersection4d( triangle_triangle_test,
p0, p1, pnew1, p2, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
if(!collision || bary[2]<t){
collision=true;
bary0=0;
bary2=(bary[4]+1e-300)/(bary[4]+bary[5]+2e-300); // guard against zero/zero
t=bary[2];
normal=get_normal(x1-x0, xnew3-xnew2);
relative_normal_displacement=dot(normal, (xnew1-x1)-(xnew2-x2));
if ( verbose )
{
std::cout << "triangle_triangle_test positive with these inputs: " << std::endl;
output_4d(p0);
output_4d(p1);
output_4d(pnew1);
output_4d(p2);
output_4d(pnew2);
output_4d(pnew3);
}
}
}
if ( simplex_intersection4d( triangle_triangle_test,
p0, pnew0, pnew1, p2, pnew2, pnew3,
&bary[0], &bary[1], &bary[2], &bary[3], &bary[4], &bary[5] ) )
{
if(!collision || 1-bary[0]<t){
collision=true;
bary0=(bary[1]+1e-300)/(bary[1]+bary[2]+2e-300); // guard against zero/zero
bary2=(bary[4]+1e-300)/(bary[4]+bary[5]+2e-300); // guard against zero/zero
t=1-bary[0];
normal=get_normal(xnew1-xnew0, xnew3-xnew2);
relative_normal_displacement=dot(normal, (xnew0-x0)-(xnew2-x2));
if ( verbose )
{
std::cout << "triangle_triangle_test positive with these inputs: " << std::endl;
output_4d(p0);
output_4d(pnew0);
output_4d(pnew1);
output_4d(p2);
output_4d(pnew2);
output_4d(pnew3);
}
}
}
if ( collision )
{
Vec3d dx0 = xnew0 - x0;
Vec3d dx1 = xnew1 - x1;
Vec3d dx2 = xnew2 - x2;
Vec3d dx3 = xnew3 - x3;
relative_normal_displacement = dot( normal, bary0*dx0 + (1.0-bary0)*dx1 - bary2*dx2 - (1.0-bary2)*dx3 );
}
return collision;
}
// --------------------------------------------------------------------------------------------------
// 3D Static intersection detection
// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
// x0-x1 is the segment and and x2-x3-x4 is the triangle.
bool segment_triangle_intersection(const Vec3d& x0, unsigned int index0,
const Vec3d& x1, unsigned int index1,
const Vec3d& x2, unsigned int index2,
const Vec3d& x3, unsigned int index3,
const Vec3d& x4, unsigned int index4,
bool degenerate_counts_as_intersection,
bool verbose )
{
double bary[5];
return simplex_intersection3d( 2, x0.v, x1.v, x2.v, x3.v, x4.v, &bary[0], &bary[1], &bary[2], &bary[3], &bary[4] );
}
// --------------------------------------------------------------------------------------------------
// x0 is the point and x1-x2-x3-x4 is the tetrahedron. Order is irrelevant.
bool point_tetrahedron_intersection(const Vec3d& x0, unsigned int index0,
const Vec3d& x1, unsigned int index1,
const Vec3d& x2, unsigned int index2,
const Vec3d& x3, unsigned int index3,
const Vec3d& x4, unsigned int index4)
{
double bary[5];
return simplex_intersection3d( 1, x0.v, x1.v, x2.v, x3.v, x4.v, &bary[0], &bary[1], &bary[2], &bary[3], &bary[4] );
}
// --------------------------------------------------------------------------------------------------
// 3D Static distance
// --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
void point_segment_distance( bool update,
const Vec3d &x0, unsigned int index0,
const Vec3d &x1, unsigned int index1,
const Vec3d &x2, unsigned int index2,
double &distance)
{
check_point_edge_proximity( update, x0, x1, x2, distance);
}
// --------------------------------------------------------------------------------------------------
void point_segment_distance( bool update,
const Vec3d &x0, unsigned int index0,
const Vec3d &x1, unsigned int index1,
const Vec3d &x2, unsigned int index2,
double &distance, double &s, Vec3d &normal, double normal_multiplier )
{
check_point_edge_proximity( update, x0, x1, x2, distance, s, normal, normal_multiplier );
}
// --------------------------------------------------------------------------------------------------
void point_triangle_distance( const Vec3d& x0, unsigned int index0,
const Vec3d& x1, unsigned int index1,
const Vec3d& x2, unsigned int index2,
const Vec3d& x3, unsigned int index3,
double& distance )
{
check_point_triangle_proximity( x0, x1, x2, x3, distance );
}
// --------------------------------------------------------------------------------------------------
void point_triangle_distance( const Vec3d& x0, unsigned int index0,
const Vec3d& x1, unsigned int index1,
const Vec3d& x2, unsigned int index2,
const Vec3d& x3, unsigned int index3,
double& distance,
double& bary1, double& bary2, double& bary3,
Vec3d& normal )
{
check_point_triangle_proximity( x0, x1, x2, x3, distance, bary1, bary2, bary3, normal );
}
// --------------------------------------------------------------------------------------------------
void segment_segment_distance( const Vec3d& x0, unsigned int index0,
const Vec3d& x1, unsigned int index1,
const Vec3d& x2, unsigned int index2,
const Vec3d& x3, unsigned int index3,
double& distance )
{
check_edge_edge_proximity( x0, x1, x2, x3, distance );
}
// --------------------------------------------------------------------------------------------------
void segment_segment_distance( const Vec3d& x0, unsigned int index0,
const Vec3d& x1, unsigned int index1,
const Vec3d& x2, unsigned int index2,
const Vec3d& x3, unsigned int index3,
double& distance,
double& bary0, double& bary2,
Vec3d& normal )
{
check_edge_edge_proximity( x0, x1, x2, x3, distance, bary0, bary2, normal );
}
// --------------------------------------------------------------------------------------------------
double tetrahedron_signed_volume(const Vec3d &x0, const Vec3d &x1, const Vec3d &x2, const Vec3d &x3)
{
return signed_volume( x0, x1, x2, x3 );
}
#endif
| 36.596581 | 121 | 0.447569 | [
"vector",
"3d"
] |
ef87ca0e45a5ee8dd022091190de96fdfe9da2fb | 1,372 | cpp | C++ | aws-cpp-sdk-appstream/source/model/DisassociateApplicationFromEntitlementRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-appstream/source/model/DisassociateApplicationFromEntitlementRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-appstream/source/model/DisassociateApplicationFromEntitlementRequest.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"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/appstream/model/DisassociateApplicationFromEntitlementRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::AppStream::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DisassociateApplicationFromEntitlementRequest::DisassociateApplicationFromEntitlementRequest() :
m_stackNameHasBeenSet(false),
m_entitlementNameHasBeenSet(false),
m_applicationIdentifierHasBeenSet(false)
{
}
Aws::String DisassociateApplicationFromEntitlementRequest::SerializePayload() const
{
JsonValue payload;
if(m_stackNameHasBeenSet)
{
payload.WithString("StackName", m_stackName);
}
if(m_entitlementNameHasBeenSet)
{
payload.WithString("EntitlementName", m_entitlementName);
}
if(m_applicationIdentifierHasBeenSet)
{
payload.WithString("ApplicationIdentifier", m_applicationIdentifier);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DisassociateApplicationFromEntitlementRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "PhotonAdminProxyService.DisassociateApplicationFromEntitlement"));
return headers;
}
| 23.655172 | 127 | 0.787901 | [
"model"
] |
ef8a98c4d4eeff19a436f878ed38f36985caaf99 | 5,219 | cpp | C++ | src/main.cpp | dsimonkay/CarND-PID-Control-Project | d0bd84d5956ea89dd428b174c39f307021544b52 | [
"MIT"
] | null | null | null | src/main.cpp | dsimonkay/CarND-PID-Control-Project | d0bd84d5956ea89dd428b174c39f307021544b52 | [
"MIT"
] | null | null | null | src/main.cpp | dsimonkay/CarND-PID-Control-Project | d0bd84d5956ea89dd428b174c39f307021544b52 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include "helper_functions.h"
#include "json.hpp"
#include "PID.h"
#include "Twiddle.h"
// for convenience
using json = nlohmann::json;
int main(int argc, char* argv[]) {
uWS::Hub h;
// Flag for twiddle mode. Its value can be set to `true` by providing the command line parameter "-t" or "--twiddle".
bool do_twiddling = false;
// Initializing the P, I and D coefficients. These can be overridden by command line parameters "-Kp", "-Ki" and "-Kd"
// Example: user@localhost:~/CarND-PID-Control-Project/build$ ./pid -Kp 0.04 -Ki 0.001 -Kd 1.4 --twiddle
// double Kp = 0.04;
// double Ki = 0.001;
// double Kd = 1.4;
// double Kp = 0.05;
// double Ki = 0.001;
// double Kd = 1.2;
// double Kp = 0.05;
// double Ki = 0.003;
// double Kd = 1.4;
double Kp = 0.0655369;
double Ki = 0.00399;
double Kd = 1.49544;
// Processing command line parameters
for( int i = 1; i < argc; i++ ) {
std::string param = std::string(argv[i]);
std::string next_param = argc > (i+1) ? std::string(argv[i+1]) : "x";
std::string param_lower;
std::transform(param.begin(), param.end(), std::back_inserter(param_lower), ::tolower);
if ( is_numeric(next_param) ) {
if ( param_lower == "-kp" ) {
Kp = std::stod(next_param);
} else if ( param_lower == "-ki" ) {
Ki = std::stod(next_param);
} else if ( param_lower == "-kd" ) {
Kd = std::stod(next_param);
}
} else if ( param_lower == "-t" || param_lower == "--twiddle" ) {
do_twiddling = true;
}
}
std::cout << "Base parameters: [Kp, Ki, Kd]: [" << Kp << ", " << Ki << ", " << Kd << "]" << std::endl;
// The PID variable will be initialized implicitly by the twiddler
// (regardless of whether we'll do the twiddle thing or not).
PID pid;
Twiddle twiddle(do_twiddling, Kp, Ki, Kd);
twiddle.startLoop(pid);
h.onMessage([&pid, &twiddle](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(std::string(data).substr(0, length));
if (s != "") {
auto j = json::parse(s);
std::string event = j[0].get<std::string>();
if (event == "telemetry") {
// j[1] is the data JSON object
double cte = std::stod(j[1]["cte"].get<std::string>());
// Sorry, guys, but you're out of the game.
// double speed = std::stod(j[1]["speed"].get<std::string>());
// double angle = std::stod(j[1]["steering_angle"].get<std::string>());
// classic PID processing steps
pid.updateError(cte);
double steering = pid.calculateSteering(cte);
double throttle = pid.calculateThrottle(cte);
// we have things to do in case twiddling is active
if ( twiddle.isActive() ) {
int twiddle_status = twiddle.check(pid, cte);
if ( twiddle_status == Twiddle::FINISHED ) {
// goodbye, Mr. Anderson
exit(0);
} else if ( twiddle_status == Twiddle::RESTART_LOOP ) {
// restarting the simulator and the PID controller as well
twiddle.endLoop(pid);
resetSimulator(ws);
twiddle.startLoop(pid);
return;
}
} else {
// basic debug output
std::cout << "Max.CTE so far current CTE steering throttle --- " << pid.getMaxCTE() << " " <<
cte << " " << steering << " " << throttle << std::endl;
}
json msgJson;
msgJson["steering_angle"] = steering;
msgJson["throttle"] = throttle;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| 30.520468 | 120 | 0.552021 | [
"object",
"transform"
] |
ef8b064b7d33cd860186a5f29a4e9acff6fe7db4 | 1,457 | hxx | C++ | planners/lapkt-public/interfaces/agnostic/h_null.hxx | miquelramirez/aamas18-planning-for-transparency | dff3e635102bf351906807c5181113fbf4b67083 | [
"MIT"
] | null | null | null | planners/lapkt-public/interfaces/agnostic/h_null.hxx | miquelramirez/aamas18-planning-for-transparency | dff3e635102bf351906807c5181113fbf4b67083 | [
"MIT"
] | null | null | null | planners/lapkt-public/interfaces/agnostic/h_null.hxx | miquelramirez/aamas18-planning-for-transparency | dff3e635102bf351906807c5181113fbf4b67083 | [
"MIT"
] | null | null | null | /*
Lightweight Automated Planning Toolkit
Copyright (C) 2012
Miquel Ramirez <miquel.ramirez@rmit.edu.au>
Nir Lipovetzky <nirlipo@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __H_NULL__
#define __H_NULL__
#include <aptk/search_prob.hxx>
#include <aptk/heuristic.hxx>
#include <strips_state.hxx>
#include <strips_prob.hxx>
namespace aptk {
namespace agnostic {
template < typename Search_Model >
class Null_Heuristic : public Heuristic<State> {
public:
Null_Heuristic( const Search_Model& prob )
: Heuristic<State>( prob ), m_strips_model( prob.task() ) {
}
virtual ~Null_Heuristic() {
}
virtual void eval( const State& s, float& h_val ) {
h_val = 0.0f;
}
virtual void eval( const State& s, float& h_val, std::vector<Action_Idx>& pref_ops ) {
h_val = 0.0f;
}
protected:
const STRIPS_Problem& m_strips_model;
};
}
}
#endif // h_null.hxx
| 23.126984 | 88 | 0.748799 | [
"vector"
] |
ef8cdc1806ed7e9bae96fe2ebe928a6a7de28914 | 2,483 | cpp | C++ | test/basic/PerformanceTest.cpp | wumo/SimGraphicsNative | f46153b20b1131930b07c9ebb44640978481e319 | [
"MIT"
] | null | null | null | test/basic/PerformanceTest.cpp | wumo/SimGraphicsNative | f46153b20b1131930b07c9ebb44640978481e319 | [
"MIT"
] | null | null | null | test/basic/PerformanceTest.cpp | wumo/SimGraphicsNative | f46153b20b1131930b07c9ebb44640978481e319 | [
"MIT"
] | null | null | null |
#include "sim/graphics/renderer/basic/basic_renderer.h"
#include "sim/graphics/renderer/basic/util/panning_camera.h"
#include "sim/graphics/util/fps_meter.h"
#include "sim/graphics/util/colors.h"
using namespace sim;
using namespace sim::graphics;
using namespace sim::graphics::renderer::basic;
using namespace glm;
using namespace sim::graphics::material;
auto main(int argc, const char **argv) -> int {
Config config{};
config.sampleCount = 4;
config.vsync = false;
BasicRenderer app{config, {}, {}, {true, false}};
auto &mm = app.sceneManager();
auto &camera = mm.camera();
camera.setLocation({2.f, 2.f, 2.f});
mm.addLight(LightType ::Directional, {-1, -1, -1});
std::string name = "CesiumMilkTruck";
auto path = "assets/private/gltf/" + name + "/glTF/" + name + ".gltf";
// std::string path = "assets/private/models/DamagedHelmet.glb";
auto model = mm.loadModel(path);
auto aabb = model->aabb();
println(aabb);
auto range = aabb.max - aabb.min;
auto scale = 1 / std::max(std::max(range.x, range.y), range.z);
auto center = aabb.center();
auto halfRange = aabb.halfRange();
auto width = 100;
vec3 origin{-width / 2, 0, -width / 2};
for(int nx = 0; nx < width; ++nx)
for(int ny = 0; ny < width; ++ny) {
Transform t{{origin + -center * scale + vec3{nx, 0, ny}}, glm::vec3{scale}};
// t.translation = -center;
auto instance = mm.newModelInstance(model, t);
}
// auto envCube = mm.newCubeTexture("assets/private/environments/noga_2k.ktx");
// mm.useEnvironmentMap(envCube);
mm.useSky();
auto kPi = glm::pi<float>();
float sun_zenith_angle_radians_{0};
float sun_azimuth_angle_radians_{kPi / 2};
mm.setSunPosition(sun_zenith_angle_radians_, sun_azimuth_angle_radians_);
mm.debugInfo();
PanningCamera panningCamera(camera);
bool pressed{false};
bool rotate{false};
sim::graphics::FPSMeter mFPSMeter;
app.run([&](uint32_t imageIndex, float elapsedDuration) {
mFPSMeter.update(elapsedDuration);
panningCamera.updateCamera(app.input);
auto frameStats = sim::toString(
" ", int32_t(mFPSMeter.FPS()), " FPS (", mFPSMeter.FrameTime(), " ms)");
auto fullTitle = "Test " + frameStats;
app.setWindowTitle(fullTitle);
for(auto &animation: model->animations())
animation.animateAll(elapsedDuration);
if(app.input.keyPressed[KeyW]) pressed = true;
else if(pressed) {
mm.setWireframe(!mm.wireframe());
pressed = false;
}
});
}
| 33.106667 | 82 | 0.670963 | [
"model",
"transform"
] |
ef8f6f2f3488a3bcb91bd2be2799055894fb3dc8 | 2,070 | cpp | C++ | USACOcontests/gold/2018.02/dirtraverse.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 14 | 2019-08-14T00:43:10.000Z | 2021-12-16T05:43:31.000Z | USACOcontests/gold/2018.02/dirtraverse.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | null | null | null | USACOcontests/gold/2018.02/dirtraverse.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 6 | 2020-12-30T03:30:17.000Z | 2022-03-11T03:40:02.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef pair<ll, ll> pii;
template <typename T1, typename T2>
ostream &operator <<(ostream &os, pair<T1, T2> p){os << p.first << " " << p.second; return os;}
template <typename T>
ostream &operator <<(ostream &os, vector<T> &v){for(T i : v)os << i << ", "; return os;}
template <typename T>
ostream &operator <<(ostream &os, set<T> s){for(T i : s) os << i << ", "; return os;}
template <typename T1, typename T2>
ostream &operator <<(ostream &os, map<T1, T2> m){for(pair<T1, T2> i : m) os << i << endl; return os;}
ll dfscnt(ll N, vi (&graph)[100000], ll idx, ll (&fcnt)[100000]){
ll ret = 0;
for(ll i : graph[idx]){
ret += dfscnt(N, graph, i, fcnt);
}
fcnt[idx] = max(1LL, ret);
return max(1LL, ret);
}
ll dfs(ll N, vi (&graph)[100000], ll idx, ll (&lens)[100000], ll (&fcnt)[100000], ll (&ans)[100000], ll prnt){
ll delta = 0;
if(prnt != -1){
delta += 3 * (fcnt[0] - fcnt[idx]);
delta -= lens[idx] * fcnt[idx];
delta += ans[prnt];
}
ans[idx] = delta;
ll ret = delta;
for(ll i : graph[idx]){
ret = min(ret, dfs(N, graph, i, lens, fcnt, ans, idx));
}
return ret;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
freopen("dirtraverse.in", "r", stdin);
freopen("dirtraverse.out", "w", stdout);
ll N; cin >> N;
vi graph[100000];
ll lengths[100000];
for(ll i = 0; i < N; i++){
string fname; cin >> fname;
lengths[i] = (ll)fname.length()+1;
ll m; cin >> m;
for(ll j = 0; j < m; j++){
ll child; cin >> child;
graph[i].push_back(child-1);
}
if(m == 0){
lengths[i]--;
}
}
ll fcnt[100000];
dfscnt(N, graph, 0, fcnt);
ll ans[100000];
ll mindel = dfs(N, graph, 0, lengths, fcnt, ans, -1);
ll bcost = 0;
for(ll i = 1; i < N; i++){
bcost += lengths[i] * fcnt[i];
}
cout << bcost+mindel << endl;
return 0;
}
| 27.972973 | 110 | 0.527053 | [
"vector"
] |
ef929ca42440036f8c6a4ebea92781cd7eba286c | 1,864 | cc | C++ | physics/neutron/nudy/EndfToRoot/EndfToPointRoot.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-10-16T14:37:42.000Z | 2018-04-05T15:49:09.000Z | physics/neutron/nudy/EndfToRoot/EndfToPointRoot.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | physics/neutron/nudy/EndfToRoot/EndfToPointRoot.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cmath>
#include <vector>
#include <iterator>
#include <algorithm>
#include <iomanip>
#include <dirent.h>
#include "Geant/TNudyENDF.h"
#include "Geant/TNudyEndfSigma.h"
using namespace Nudy;
int main(int, char *argv[]) {
std::clock_t startTime = clock();
std::ofstream out, outtotal;
std::string str,str2,tmp,tmp2,tmp3,tmp4,tmp5,tmp6, name;
const char* fENDF = argv[1];
str = argv[1];
std::size_t found = str.find_last_of(".");
name = str.substr(0,found) + ".root";
const char* rENDF = name.c_str();
Nudy::TNudyENDF *proc = new Nudy::TNudyENDF(fENDF, rENDF, "recreate");
proc->SetPreProcess (0) ;
proc->Process();
tmp6 = (str.substr(1,found+5));
tmp5 = "nfy"+tmp6 ;
std::string fENDFSUB = tmp5;
proc->SetEndfSub(fENDFSUB);
proc->Process();
NudyPhysics::TNudyEndfSigma *sigma = new NudyPhysics::TNudyEndfSigma();
sigma->outstring = str.substr(0,found) +"_300.txt";
tmp5 = str.substr(0,found)+"_total.txt";
sigma->outstringTotal.assign(tmp5);
if(tmp2=="m1")sigma->outstringTotal = tmp5+"m"+"_total.txt";
sigma->out.open(sigma->outstring.c_str(),std::ios::out);
if(sigma->out.is_open()){std::cout<<" yes reco open "<< std::endl;}
sigma->outtotal.open(sigma->outstringTotal.c_str(),std::ios::out);
if(sigma->outtotal.is_open()){std::cout<<" yes total open "<< std::endl;}
sigma->SetPreProcess (0) ;
sigma->SetInitTempDop(0);
sigma->SetOutTempDop(293.6);
sigma ->GetData(rENDF, 1E-3);
std::clock_t endTime = clock();
std::clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
std::cout<<"Time in seconds = "<< timeInSeconds <<std::endl;
sigma->out<<"Time in seconds = "<< timeInSeconds <<std::endl;
sigma->out.close();
sigma->outtotal.close();
}
| 35.169811 | 75 | 0.677575 | [
"vector"
] |
ef94752adba695ff874e876033913a2e784a4074 | 8,715 | cpp | C++ | emulator/src/mame/machine/primo.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/machine/primo.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/machine/primo.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Krzysztof Strzecha
/*******************************************************************************
primo.c
Functions to emulate general aspects of Microkey Primo computers
(RAM, ROM, interrupts, I/O ports)
Krzysztof Strzecha
*******************************************************************************/
/* Core includes */
#include "emu.h"
#include "includes/primo.h"
/* Components */
#include "cpu/z80/z80.h"
#include "screen.h"
/*******************************************************************************
Interrupt callback
*******************************************************************************/
WRITE_LINE_MEMBER(primo_state::vblank_irq)
{
if (state && m_nmi)
m_maincpu->set_input_line(INPUT_LINE_NMI, PULSE_LINE);
}
/*******************************************************************************
Memory banking
*******************************************************************************/
void primo_state::primo_update_memory()
{
address_space& space = m_maincpu->space(AS_PROGRAM);
switch (m_port_FD & 0x03)
{
case 0x00: /* Original ROM */
space.unmap_write(0x0000, 0x3fff);
membank("bank1")->set_base(memregion("maincpu")->base() + 0x10000);
break;
case 0x01: /* EPROM extension 1 */
space.unmap_write(0x0000, 0x3fff);
membank("bank1")->set_base(m_cart2_rom->base());
break;
case 0x02: /* RAM */
space.install_write_bank(0x0000, 0x3fff, "bank1");
membank("bank1")->set_base(memregion("maincpu")->base());
break;
case 0x03: /* EPROM extension 2 */
space.unmap_write(0x0000, 0x3fff);
membank("bank1")->set_base(m_cart1_rom->base());
break;
}
logerror ("Memory update: %02x\n", m_port_FD);
}
/*******************************************************************************
IO read/write handlers
*******************************************************************************/
READ8_MEMBER(primo_state::primo_be_1_r)
{
uint8_t data = 0x00;
static const char *const portnames[] = { "IN0", "IN1", "IN2", "IN3" };
// bit 7, 6 - not used
// bit 5 - VBLANK
data |= m_screen->vblank() ? 0x20 : 0x00;
// bit 4 - I4 (external bus)
// bit 3 - I3 (external bus)
// bit 2 - cassette
data |= (m_cassette->input() < 0.1) ? 0x04 : 0x00;
// bit 1 - reset button
data |= (ioport("RESET")->read()) ? 0x02 : 0x00;
// bit 0 - keyboard
data |= (ioport(portnames[(offset & 0x0030) >> 4])->read() >> (offset&0x000f)) & 0x0001 ? 0x01 : 0x00;
return data;
}
READ8_MEMBER(primo_state::primo_be_2_r)
{
uint8_t data = 0xff;
// bit 7, 6 - not used
// bit 5 - SCLK
if (!m_iec->clk_r())
data &= ~0x20;
// bit 4 - SDATA
if (!m_iec->data_r())
data &= ~0x10;
// bit 3 - SRQ
if (!m_iec->srq_r())
data &= ~0x08;
// bit 2 - joystic 2 (not implemeted yet)
// bit 1 - ATN
if (!m_iec->atn_r())
data &= ~0x02;
// bit 0 - joystic 1 (not implemeted yet)
logerror ("IOR BE-2 data:%02x\n", data);
return data;
}
WRITE8_MEMBER(primo_state::primo_ki_1_w)
{
// bit 7 - NMI generator enable/disable
m_nmi = (data & 0x80) ? 1 : 0;
// bit 6 - joystick register shift (not emulated)
// bit 5 - V.24 (2) / tape control (not emulated)
// bit 4 - speaker
m_speaker->level_w(BIT(data, 4));
// bit 3 - display buffer
if (data & 0x08)
m_video_memory_base |= 0x2000;
else
m_video_memory_base &= 0xdfff;
// bit 2 - V.24 (1) / tape control (not emulated)
// bit 1, 0 - cassette output
switch (data & 0x03)
{
case 0:
m_cassette->output(-1.0);
break;
case 1:
case 2:
m_cassette->output(0.0);
break;
case 3:
m_cassette->output(1.0);
break;
}
}
WRITE8_MEMBER(primo_state::primo_ki_2_w)
{
// bit 7, 6 - not used
// bit 5 - SCLK
m_iec->clk_w(!BIT(data, 5));
// bit 4 - SDATA
m_iec->data_w(!BIT(data, 4));
// bit 3 - not used
// bit 2 - SRQ
m_iec->srq_w(!BIT(data, 2));
// bit 1 - ATN
m_iec->atn_w(!BIT(data, 1));
// bit 0 - not used
// logerror ("IOW KI-2 data:%02x\n", data);
}
WRITE8_MEMBER(primo_state::primo_FD_w)
{
if (!ioport("MEMORY_EXPANSION")->read())
{
m_port_FD = data;
primo_update_memory();
}
}
/*******************************************************************************
Driver initialization
*******************************************************************************/
void primo_state::primo_common_driver_init (primo_state *state)
{
m_port_FD = 0x00;
}
DRIVER_INIT_MEMBER(primo_state,primo32)
{
primo_common_driver_init(this);
m_video_memory_base = 0x6800;
}
DRIVER_INIT_MEMBER(primo_state,primo48)
{
primo_common_driver_init(this);
m_video_memory_base = 0xa800;
}
DRIVER_INIT_MEMBER(primo_state,primo64)
{
primo_common_driver_init(this);
m_video_memory_base = 0xe800;
}
/*******************************************************************************
Machine initialization
*******************************************************************************/
void primo_state::primo_common_machine_init ()
{
if (ioport("MEMORY_EXPANSION")->read())
m_port_FD = 0x00;
primo_update_memory();
machine().device("maincpu")->set_clock_scale(ioport("CPU_CLOCK")->read() ? 1.5 : 1.0);
}
void primo_state::machine_start()
{
std::string region_tag;
m_cart1_rom = memregion(region_tag.assign(m_cart1->tag()).append(GENERIC_ROM_REGION_TAG).c_str());
m_cart2_rom = memregion(region_tag.assign(m_cart2->tag()).append(GENERIC_ROM_REGION_TAG).c_str());
}
void primo_state::machine_reset()
{
primo_common_machine_init();
}
MACHINE_RESET_MEMBER(primo_state,primob)
{
primo_common_machine_init();
//removed cbm_drive_0_config(SERIAL, 8);
//removed cbm_drive_1_config(SERIAL, 9);
}
/*******************************************************************************
Snapshot files (.pss)
*******************************************************************************/
void primo_state::primo_setup_pss (uint8_t* snapshot_data, uint32_t snapshot_size)
{
/* Z80 registers */
m_maincpu->set_state_int(Z80_BC, snapshot_data[4] + snapshot_data[5]*256);
m_maincpu->set_state_int(Z80_DE, snapshot_data[6] + snapshot_data[7]*256);
m_maincpu->set_state_int(Z80_HL, snapshot_data[8] + snapshot_data[9]*256);
m_maincpu->set_state_int(Z80_AF, snapshot_data[10] + snapshot_data[11]*256);
m_maincpu->set_state_int(Z80_BC2, snapshot_data[12] + snapshot_data[13]*256);
m_maincpu->set_state_int(Z80_DE2, snapshot_data[14] + snapshot_data[15]*256);
m_maincpu->set_state_int(Z80_HL2, snapshot_data[16] + snapshot_data[17]*256);
m_maincpu->set_state_int(Z80_AF2, snapshot_data[18] + snapshot_data[19]*256);
m_maincpu->set_state_int(Z80_PC, snapshot_data[20] + snapshot_data[21]*256);
m_maincpu->set_state_int(Z80_SP, snapshot_data[22] + snapshot_data[23]*256);
m_maincpu->set_state_int(Z80_I, snapshot_data[24]);
m_maincpu->set_state_int(Z80_R, snapshot_data[25]);
m_maincpu->set_state_int(Z80_IX, snapshot_data[26] + snapshot_data[27]*256);
m_maincpu->set_state_int(Z80_IY, snapshot_data[28] + snapshot_data[29]*256);
/* IO ports */
// KI-1 bit 7 - NMI generator enable/disable
m_nmi = (snapshot_data[30] & 0x80) ? 1 : 0;
// KI-1 bit 4 - speaker
m_speaker->level_w(BIT(snapshot_data[30], 4));
/* memory */
for (int i = 0; i < 0xc000; i++)
m_maincpu->space(AS_PROGRAM).write_byte(i + 0x4000, snapshot_data[i + 38]);
}
SNAPSHOT_LOAD_MEMBER( primo_state, primo )
{
std::vector<uint8_t> snapshot_data(snapshot_size);
if (image.fread(&snapshot_data[0], snapshot_size) != snapshot_size)
{
return image_init_result::FAIL;
}
if (strncmp((char *)&snapshot_data[0], "PS01", 4))
{
return image_init_result::FAIL;
}
primo_setup_pss(&snapshot_data[0], snapshot_size);
return image_init_result::PASS;
}
/*******************************************************************************
Quicload files (.pp)
*******************************************************************************/
void primo_state::primo_setup_pp(uint8_t* quickload_data, uint32_t quickload_size)
{
uint16_t load_addr;
uint16_t start_addr;
load_addr = quickload_data[0] + quickload_data[1]*256;
start_addr = quickload_data[2] + quickload_data[3]*256;
for (int i = 4; i < quickload_size; i++)
m_maincpu->space(AS_PROGRAM).write_byte(start_addr+i-4, quickload_data[i]);
m_maincpu->set_state_int(Z80_PC, start_addr);
logerror ("Quickload .pp l: %04x r: %04x s: %04x\n", load_addr, start_addr, quickload_size-4);
}
QUICKLOAD_LOAD_MEMBER( primo_state, primo )
{
std::vector<uint8_t> quickload_data(quickload_size);
if (image.fread(&quickload_data[0], quickload_size) != quickload_size)
{
return image_init_result::FAIL;
}
primo_setup_pp(&quickload_data[0], quickload_size);
return image_init_result::PASS;
}
| 24.618644 | 103 | 0.589788 | [
"vector"
] |
aab412be632269289271fedc67a7d5f932fb2cb2 | 5,157 | cpp | C++ | gtn/graph.cpp | csukuangfj/gtn | 7607bdef9014b55db6e1eaa7953fc23987e6bacb | [
"MIT"
] | 1 | 2021-01-27T16:01:51.000Z | 2021-01-27T16:01:51.000Z | gtn/graph.cpp | KonstantinKlepikov/gtn | 319e939f292121dcfc6bcb001773889b18227034 | [
"MIT"
] | null | null | null | gtn/graph.cpp | KonstantinKlepikov/gtn | 319e939f292121dcfc6bcb001773889b18227034 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <stdexcept>
#include "graph.h"
namespace gtn {
Graph::Graph(GradFunc gradFunc, std::vector<Graph> inputs) {
sharedGrad_->calcGrad = false;
// If any inputs require a gradient, then this should
// also compute a gradient.
for (auto& g : inputs) {
sharedGrad_->calcGrad |= g.calcGrad();
}
if (calcGrad()) {
sharedGrad_->gradFunc = std::move(gradFunc);
sharedGrad_->inputs = std::move(inputs);
}
}
Graph::Graph(bool calcGrad /* = true */) {
sharedGrad_->calcGrad = calcGrad;
}
int Graph::addNode(bool start /* = false */, bool accept /* = false */) {
int idx = numNodes();
sharedGraph_->nodes.emplace_back(start, accept);
if (start) {
sharedGraph_->start.push_back(idx);
}
if (accept) {
sharedGraph_->accept.push_back(idx);
}
sharedGraph_->ilabelSorted = false;
sharedGraph_->olabelSorted = false;
return idx;
}
int Graph::addArc(int srcNode, int dstNode, int label) {
return addArc(srcNode, dstNode, label, label);
}
int Graph::addArc(
int srcNode,
int dstNode,
int ilabel,
int olabel,
float weight /* = 0 */) {
assert(ilabel >= epsilon && olabel >= epsilon);
auto idx = numArcs();
sharedGraph_->arcs.emplace_back(srcNode, dstNode, ilabel, olabel);
sharedWeights_->push_back(weight);
node(srcNode).out.push_back(idx);
node(dstNode).in.push_back(idx);
sharedGraph_->ilabelSorted = false;
sharedGraph_->olabelSorted = false;
return idx;
}
float Graph::item() const {
if (numArcs() != 1) {
throw std::invalid_argument(
"[Graph::item] Cannot convert Graph with more than 1 arc to a scalar.");
}
return weight(0);
}
Graph& Graph::grad() {
return const_cast<Graph&>(static_cast<const Graph&>(*this).grad());
}
const Graph& Graph::grad() const {
if (!calcGrad()) {
throw std::logic_error("[Graph::grad] Gradient calculation disabled.");
}
if (!sharedGrad_->grad) {
throw std::logic_error("[Graph::grad] Gradient not calculated yet.");
}
return *sharedGrad_->grad;
}
void Graph::addGrad(std::vector<float>&& other) {
if (calcGrad()) {
if (other.size() != numArcs()) {
throw std::logic_error("[Graph::addGrad] Invalid grad size.");
}
std::lock_guard<std::mutex> lock(sharedGraph_->grad_lock);
if (isGradAvailable()) {
for (int i = 0; i < numArcs(); i++) {
grad().setWeight(i, grad().weight(i) + other[i]);
}
} else {
sharedGrad_->grad = std::make_unique<Graph>(false);
sharedGrad_->grad->sharedGraph_ = sharedGraph_;
*(sharedGrad_->grad->sharedWeights_) = std::move(other);
}
}
}
void Graph::addGrad(const std::vector<float>& other) {
if (calcGrad()) {
if (other.size() != numArcs()) {
throw std::logic_error("[Graph::addGrad] Invalid grad size.");
}
std::lock_guard<std::mutex> lock(sharedGraph_->grad_lock);
if (isGradAvailable()) {
for (int i = 0; i < numArcs(); i++) {
grad().setWeight(i, grad().weight(i) + other[i]);
}
} else {
sharedGrad_->grad = std::make_unique<Graph>(false);
sharedGrad_->grad->sharedGraph_ = sharedGraph_;
*(sharedGrad_->grad->sharedWeights_) = other;
}
}
}
void Graph::addGrad(const Graph& other) {
addGrad(*other.sharedWeights_);
}
void Graph::setCalcGrad(bool calcGrad) {
sharedGrad_->calcGrad = calcGrad;
if (!calcGrad) {
sharedGrad_->gradFunc = nullptr;
sharedGrad_->inputs.clear();
sharedGrad_->grad.reset();
}
}
void Graph::zeroGrad() {
sharedGrad_->grad.reset();
}
std::uintptr_t Graph::id() {
return reinterpret_cast<std::uintptr_t>(sharedGrad_.get());
}
Graph Graph::deepCopy(const Graph& src) {
Graph out(src.calcGrad());
out.sharedGraph_->arcs = src.sharedGraph_->arcs;
out.sharedGraph_->nodes = src.sharedGraph_->nodes;
out.sharedGraph_->start = src.sharedGraph_->start;
out.sharedGraph_->accept = src.sharedGraph_->accept;
*out.sharedWeights_ = *src.sharedWeights_;
return out;
}
void Graph::arcSort(bool olabel /* = false */) {
if ((olabel && sharedGraph_->olabelSorted) ||
(!olabel && sharedGraph_->ilabelSorted)) {
return;
}
sharedGraph_->olabelSorted = olabel;
sharedGraph_->ilabelSorted = !olabel;
auto sortFn = [olabel, &arcs = sharedGraph_->arcs](int a, int b) {
return olabel ? arcs[a].olabel < arcs[b].olabel
: arcs[a].ilabel < arcs[b].ilabel;
};
for (auto& n : sharedGraph_->nodes) {
std::sort(n.in.begin(), n.in.end(), sortFn);
std::sort(n.out.begin(), n.out.end(), sortFn);
}
}
void Graph::setWeights(const float* weights) {
std::copy(weights, weights + numArcs(), sharedWeights_->data());
}
void Graph::labelsToArray(int* out, bool ilabel) {
for (int i = 0; i < numArcs(); ++i) {
out[i] = ilabel ? this->ilabel(i) : olabel(i);
}
}
std::vector<int> Graph::labelsToVector(bool ilabel) {
std::vector<int> out(numArcs());
labelsToArray(out.data(), ilabel);
return out;
}
} // namespace gtn
| 27.142105 | 80 | 0.645724 | [
"vector"
] |
aabad047e07d9759e38701749955307aecfc30f3 | 8,389 | hpp | C++ | include/avk/shader_info.hpp | cg-tuwien/auto_vulkan | 187654cf2b18c7f0ff1d4d743e695c5ed6e3b32b | [
"MIT"
] | null | null | null | include/avk/shader_info.hpp | cg-tuwien/auto_vulkan | 187654cf2b18c7f0ff1d4d743e695c5ed6e3b32b | [
"MIT"
] | null | null | null | include/avk/shader_info.hpp | cg-tuwien/auto_vulkan | 187654cf2b18c7f0ff1d4d743e695c5ed6e3b32b | [
"MIT"
] | null | null | null | #pragma once
#include <avk/avk.hpp>
namespace avk
{
struct specialization_constants
{
uint32_t num_entries() const { return static_cast<uint32_t>(mMapEntries.size()); }
size_t data_size() const { return mData.size() * sizeof(decltype(mData)::value_type); }
std::vector<vk::SpecializationMapEntry> mMapEntries;
std::vector<uint8_t> mData;
};
static bool operator ==(const specialization_constants& left, const specialization_constants& right)
{
if (left.mMapEntries.size() != right.mMapEntries.size()) { return false; }
for (size_t i = 0; i < left.mMapEntries.size(); ++i) {
if (left.mMapEntries[i] != right.mMapEntries[i]) { return false; }
}
if (left.mData.size() != right.mData.size()) { return false; }
for (size_t i = 0; i < left.mData.size(); ++i) {
if (left.mData[i] != right.mData[i]) { return false; }
}
return true;
}
static bool operator !=(const specialization_constants& left, const specialization_constants& right)
{
return !(left == right);
}
struct shader_info
{
static shader_info describe(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false, std::optional<avk::shader_type> pShaderType = {});
/** Add one specialization constant to this shader.
* @param aConstantId The ID that is used to identify this constant
* @param aValue The value of this constant. Pay attention to specify the correct type!
* Example usages:
* - set_specialization_constant(1u, uint32_t{123})
* - set_specialization_constant(50u, float{1.1f})
* - set_specialization_constant(2u, int64_t{456})
*/
template <typename T>
shader_info& set_specialization_constant(uint32_t aConstantId, const T& aValue)
{
if (!mSpecializationConstants.has_value()) {
mSpecializationConstants = specialization_constants{};
}
auto& entries = mSpecializationConstants->mMapEntries;
auto& data = mSpecializationConstants->mData;
const auto align = sizeof(uint64_t);
const auto currentSize = data.size();
const auto insertSize = sizeof(T);
const auto numAlloc = std::max(align, insertSize / sizeof(typename decltype(mSpecializationConstants->mData)::value_type));
assert (insertSize % sizeof(typename decltype(mSpecializationConstants->mData)::value_type) == 0);
data.resize(currentSize + numAlloc);
// copy data:
memcpy(data.data() + currentSize, &aValue, insertSize);
// make entry:
entries.emplace_back(aConstantId, static_cast<uint32_t>(currentSize), insertSize);
return *this;
}
std::string mPath;
avk::shader_type mShaderType;
std::string mEntryPoint;
bool mDontMonitorFile;
std::optional<specialization_constants> mSpecializationConstants;
};
static bool operator ==(const shader_info& left, const shader_info& right)
{
return are_paths_equal(left.mPath, right.mPath)
&& left.mShaderType == right.mShaderType
&& trim_spaces(left.mEntryPoint) == trim_spaces(right.mEntryPoint)
&& left.mSpecializationConstants == right.mSpecializationConstants;
}
static bool operator !=(const shader_info& left, const shader_info& right)
{
return !(left == right);
}
/** @brief Shader source information and shader loading options
*
* This information is important especially for shader hot reloading.
*/
enum struct shader_source_info : uint32_t
{
nothing = 0x0000,
/** Shader source is loaded from a file */
from_file = 0x0001,
/** Shader source is loaded from memory (a string most likely) */
from_memory = 0x0002,
/** Load the shader and append a new-line to the source */
append_newline = 0x0004,
};
inline shader_source_info operator| (shader_source_info a, shader_source_info b)
{
typedef std::underlying_type<shader_source_info>::type EnumType;
return static_cast<shader_source_info>(static_cast<EnumType>(a) | static_cast<EnumType>(b));
}
inline shader_source_info operator& (shader_source_info a, shader_source_info b)
{
typedef std::underlying_type<shader_source_info>::type EnumType;
return static_cast<shader_source_info>(static_cast<EnumType>(a) & static_cast<EnumType>(b));
}
inline shader_source_info& operator |= (shader_source_info& a, shader_source_info b)
{
return a = a | b;
}
inline shader_source_info& operator &= (shader_source_info& a, shader_source_info b)
{
return a = a & b;
}
inline shader_info vertex_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::vertex); }
inline shader_info tessellation_control_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::tessellation_control); }
inline shader_info tessellation_evaluation_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::tessellation_evaluation); }
inline shader_info geometry_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::geometry); }
inline shader_info fragment_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::fragment); }
inline shader_info compute_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::compute); }
inline shader_info ray_generation_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::ray_generation); }
inline shader_info any_hit_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::any_hit); }
inline shader_info closest_hit_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::closest_hit); }
inline shader_info miss_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::miss); }
inline shader_info intersection_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::intersection); }
inline shader_info callable_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::callable); }
inline shader_info task_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::task); }
inline shader_info mesh_shader(std::string pPath, std::string pEntryPoint = "main", bool pDontMonitorFile = false) { return shader_info::describe(std::move(pPath), std::move(pEntryPoint), pDontMonitorFile, avk::shader_type::mesh); }
}
namespace std // Inject hash for `ak::shader_info` into std::
{
template<> struct hash<avk::shader_info>
{
std::size_t operator()(avk::shader_info const& o) const noexcept
{
std::size_t h = 0;
avk::hash_combine(h,
avk::transform_path_for_comparison(o.mPath),
static_cast<std::underlying_type<avk::shader_type>::type>(o.mShaderType),
avk::trim_spaces(o.mEntryPoint)
);
return h;
}
};
}
| 52.43125 | 272 | 0.726666 | [
"mesh",
"geometry",
"vector"
] |
aabd9f1a22aa824b8a249685bab8f3661a9c12b4 | 2,544 | cpp | C++ | BackTracking/trials/NQueens/nqueens.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | BackTracking/trials/NQueens/nqueens.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | 3 | 2020-05-08T18:02:51.000Z | 2020-05-09T08:37:35.000Z | BackTracking/trials/NQueens/nqueens.cpp | UltraProton/PlacementPrep | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
bool is_safe(vector<vector<int>> &Grid, int n, int row, int col);
bool solve(vector<vector<int>> &Grid, int n, int row);
void print_grid(vector<vector<int>> &Grid);
int main(int argc, char const *argv[])
{
vector<vector<int>> Grid(4,vector<int>(4,0));
solve(Grid, 4,0);
print_grid(Grid);
return 0;
}
/*
is_safe() is called when the rows till row-1 are already filled. So we need to check the upper left diagonal,
upper right diagonal and the column col
*/
bool is_safe(vector<vector<int>> &Grid, int n, int row, int col){
//check if the col is safe
for(int i=row;i>=0;i--){
if(Grid[i][col]){
return false;
}
}
//check if the upper left diagonal is safe
for(int i=row,j=col;i>=0 && j>=0;i--,j--){
if(Grid[i][j]){
return false;
}
}
//check if the upper right diagonal is safe
for(int i=row, j=col;i>=0 && j<n; i--,j++){
if(Grid[i][j]){
return false;
}
}
return true;
}
bool solve(vector<vector<int>> &Grid, int n, int row){
//print_grid(Grid);
//we have solved each row so we can return true
if(row==n){
return true;
}
else{
for(int col=0;col<n;col++){
//if a queen can be placed at the current row and column
if(is_safe(Grid,n,row,col)){
//place the queen at this position
Grid[row][col]=1;
//check if placing the queen here can lead to a solution
bool finished=solve(Grid, n, row+1);
if(finished){
return true;
}
/* ...bug..
if we say return false here then it finished too earyl i.e as soon as it couldn't find a solution
it will return false but we wanna keep trying until we couldn't find the solution
else{
return false;
}
*/
//could not solve the Grid by placing the queen at the current position so backtrack
Grid[row][col]=0;
}
}
//we have tried each column of the current row and couln't place the queen so return false i.e we couldn't find
//solution
return false;
}
}
void print_grid(vector<vector<int>> &Grid){
for(auto x:Grid){
for(auto y:x){
cout<<y<<" ";
}
cout<<endl;
}
}
| 26.226804 | 119 | 0.526336 | [
"vector"
] |
aac31826b7762a95abb1ab3bcaa6bc1ad1e18733 | 7,084 | hpp | C++ | test/performance-regression/full-apps/qmcpack/src/spline/einspline_util.hpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/qmcpack/src/spline/einspline_util.hpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/qmcpack/src/spline/einspline_util.hpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | //////////////////////////////////////////////////////////////////
// (c) Copyright 2006- by Jeongnim Kim and Ken Esler //
//////////////////////////////////////////////////////////////////
/** @file einspline_util.hpp
* @brief utility functions for i/o and bcast of einspline objects
*
*/
#ifndef QMCPLUSPLUS_EINSPLINE_UTILITIES_H
#define QMCPLUSPLUS_EINSPLINE_UTILITIES_H
#include <Message/CommOperators.h>
#include <OhmmsData/FileUtility.h>
#include <io/hdf_archive.h>
#include <einspline/multi_bspline_copy.h>
namespace qmcplusplus
{
///handles i/o and bcast, testing for now
template<typename T>
inline void chunked_bcast(Communicate* comm, T* buffer, size_t ntot)
{
if(comm->size()==1) return;
size_t chunk_size=(1<<30)/sizeof(T); //256 MB
int n=static_cast<int>(ntot/chunk_size);
size_t offset=0;
for(int i=0; i<n; ++i, offset+=chunk_size)
{
comm->bcast(buffer+offset,static_cast<int>(chunk_size));
}
if(offset<ntot)
{
comm->bcast(buffer+offset,static_cast<int>(ntot-offset));
}
}
template<typename ENGT>
inline void chunked_bcast(Communicate* comm, ENGT* buffer)
{
chunked_bcast(comm,buffer->coefs, buffer->coefs_size);
}
/** specialization of h5data_proxy for einspline_engine
*/
template<typename ENGT>
struct h5data_proxy<einspline_engine<ENGT> >
: public h5_space_type<typename einspline_engine<ENGT>::value_type,4>
{
typedef typename einspline_engine<ENGT>::value_type value_type;
using h5_space_type<value_type,4>::dims;
using h5_space_type<value_type,4>::get_address;
typedef einspline_engine<ENGT> data_type;
data_type& ref_;
inline h5data_proxy(data_type& a): ref_(a)
{
dims[0]=a.spliner->x_grid.num+3;
dims[1]=a.spliner->y_grid.num+3;
dims[2]=a.spliner->z_grid.num+3;
dims[3]=a.spliner->z_stride;
}
inline bool read(hid_t grp, const std::string& aname, hid_t xfer_plist=H5P_DEFAULT)
{
if(ref_.spliner)
return h5d_read(grp,aname,get_address(ref_.spliner->coefs),xfer_plist);
else
return false;
}
inline bool write(hid_t grp, const std::string& aname, hid_t xfer_plist=H5P_DEFAULT)
{
return h5d_write(grp,aname.c_str(),this->size(),dims,get_address(ref_.spliner->coefs),xfer_plist);
}
};
inline string make_spline_filename(const string& old, int spin, int twist, const TinyVector<int,3>& mesh)
{
string aname(old);
if(getExtension(aname) == "h5")
{
aname.erase(aname.end()-3,aname.end());
}
ostringstream oo;
oo<<".spin_"<< spin << ".tw" << twist <<".g"<<mesh[0]<<"x"<<mesh[1]<<"x"<<mesh[2]<<".h5";
aname+=oo.str();
return aname;
}
inline string make_spline_filename(const string& old, const Tensor<int,3>& tilematrix,int spin, int twist, const TinyVector<int,3>& mesh)
{
string aname(old);
if(getExtension(aname) == "h5")
{
aname.erase(aname.end()-3,aname.end());
}
ostringstream oo;
oo<<".tile_"
<< tilematrix(0,0) <<tilematrix(0,1) <<tilematrix(0,2)
<< tilematrix(1,0) <<tilematrix(1,1) <<tilematrix(1,2)
<< tilematrix(2,0) <<tilematrix(2,1) <<tilematrix(2,2)
<< ".spin_"<< spin << ".tw" << twist <<".g"<<mesh[0]<<"x"<<mesh[1]<<"x"<<mesh[2]<<".h5";
aname+=oo.str();
return aname;
}
inline string make_spline_filename(const string& old, const Tensor<int,3>& tilematrix,int spin, int twist,
int bg, const TinyVector<int,3>& mesh)
{
string aname(old);
if(getExtension(aname) == "h5")
{
aname.erase(aname.end()-3,aname.end());
}
ostringstream oo;
oo<<".tile_"
<< tilematrix(0,0) <<tilematrix(0,1) <<tilematrix(0,2)
<< tilematrix(1,0) <<tilematrix(1,1) <<tilematrix(1,2)
<< tilematrix(2,0) <<tilematrix(2,1) <<tilematrix(2,2)
<< ".spin_"<< spin << ".tw" << twist
<< ".b" << bg <<".g"<<mesh[0]<<"x"<<mesh[1]<<"x"<<mesh[2]<<".h5";
aname+=oo.str();
return aname;
}
template<typename T>
string make_spline_filename(const string& old,int spin, const TinyVector<T,3>& twistangle, const TinyVector<int,3>& mesh)
{
string aname(old);
if(getExtension(aname) == "h5")
{
aname.erase(aname.end()-3,aname.end());
}
char a[128];
sprintf(a,".spin_%d.k%5.3f_%5.3f_%5.3f.g%dx%dx%d.h5",
spin,twistangle[0],twistangle[1],twistangle[2],mesh[0],mesh[1],mesh[2]);
aname+=a;
return aname;
}
template<typename GT>
void print_grid(GT& grid)
{
std::cout << grid.start << " " << grid.end << " "
<< grid.num << " "
<< grid.delta << " " << grid.delta_inv << std::endl;
}
template<typename ENGT>
void print_spliner(ENGT* spline)
{
cout << "xgrid "; print_grid(spline->x_grid);
cout << "ygrid "; print_grid(spline->y_grid);
cout << "zgrid "; print_grid(spline->z_grid);
}
/** engine to create a einspline based on the input einspline
*/
template <typename T>
struct GridConvert
{
///number of points in each direction including BC
int N[3];
///offset
int Offset[3];
///number of points of the original grid
int BaseN[3];
///offset of the original grid, always 0
int BaseOffset[3];
///spacing to be added or removed from the buffer
TinyVector<T,3> Delta;
template<typename ENGT1, typename ENGT2, typename PT>
void create(ENGT1*& out, ENGT2* in, PT& lower, PT& upper, int num)
{
typedef typename bspline_engine_traits<ENGT1>::real_type real_type;
Ugrid agrid[3];
agrid[0]=in->x_grid;
agrid[1]=in->y_grid;
agrid[2]=in->z_grid;
typename bspline_engine_traits<ENGT1>::BCType xyz_bc[3];
xyz_bc[0].lCode=in->xBC.lCode;xyz_bc[0].rCode=in->xBC.rCode;
xyz_bc[1].lCode=in->yBC.lCode;xyz_bc[1].rCode=in->yBC.rCode;
xyz_bc[2].lCode=in->zBC.lCode;xyz_bc[2].rCode=in->zBC.rCode;
for(int i=0; i<3; ++i)
{
int ngi=(int)(lower[i]*agrid[i].delta_inv);
int ngf=(int)(upper[i]*agrid[i].delta_inv)+1;
agrid[i].num =std::min(agrid[i].num,ngf-ngi);
ngf=agrid[i].num+ngi;
agrid[i].start=static_cast<real_type>(ngi)*agrid[i].delta;
agrid[i].end =static_cast<real_type>(ngf)*agrid[i].delta;
if (xyz_bc[i].lCode == PERIODIC || xyz_bc[i].lCode == ANTIPERIODIC)
N[i] = agrid[i].num+3;
else
N[i] = agrid[i].num+2;
Delta[i]=agrid[i].delta;
Offset[i]=ngi;
}
out=einspline::create(out,agrid,xyz_bc,num);
}
};
namespace einspline
{
template<typename IV>
bool outOfBound(const IV& a)
{
for(int i=0; i<a.size(); ++i) if(a[i]<0.0 || a[i] >=1.0) return true;
return false;
}
template<typename IV>
bool validRange(const IV& low, const IV& up)
{
bool ok=low[0]<up[0];
for(int i=1; i<low.size(); ++i) ok &= (low[i]<up[i]);
return ok;
}
}
}
#endif
| 30.016949 | 139 | 0.592462 | [
"mesh"
] |
aac6bcd451ff2f4f1053f20c3147fb4ca8982ef2 | 4,561 | cpp | C++ | core/Properties/acsdkProperties/testCrypto/DataPropertyCodecTest.cpp | immortalkrazy/avs-device-sdk | 703b06188eae146af396f58be4e47442d7ce5b1e | [
"Apache-2.0"
] | 1 | 2018-07-09T16:44:28.000Z | 2018-07-09T16:44:28.000Z | core/Properties/acsdkProperties/testCrypto/DataPropertyCodecTest.cpp | immortalkrazy/avs-device-sdk | 703b06188eae146af396f58be4e47442d7ce5b1e | [
"Apache-2.0"
] | null | null | null | core/Properties/acsdkProperties/testCrypto/DataPropertyCodecTest.cpp | immortalkrazy/avs-device-sdk | 703b06188eae146af396f58be4e47442d7ce5b1e | [
"Apache-2.0"
] | 2 | 2019-02-05T23:42:48.000Z | 2020-03-01T11:11:30.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
#include <acsdkCodecUtils/Hex.h>
#include <acsdkCryptoInterfaces/test/MockCryptoFactory.h>
#include <acsdkCryptoInterfaces/test/MockDigest.h>
#include <acsdkProperties/private/DataPropertyCodec.h>
// Workaround for GCC < 5.x
#if (defined(__GNUC__) && (__GNUC___ < 5))
#define RETURN_UNIQUE_PTR(x) std::move(x)
#else
#define RETURN_UNIQUE_PTR(x) (x)
#endif
namespace alexaClientSDK {
namespace acsdkProperties {
namespace test {
using namespace ::testing;
using namespace ::alexaClientSDK::acsdkCodecUtils;
using namespace ::alexaClientSDK::acsdkCryptoInterfaces;
using namespace ::alexaClientSDK::acsdkCryptoInterfaces::test;
/// @private
static const DataPropertyCodec::IV TEST_IV{0x10, 0x10, 0x10, 0x10};
/// @private
static const DataPropertyCodec::DataBlock TEST_DATA_CIPHERTEXT{0xAA, 0xAA, 0xAA, 0xAA};
/// @private
static const DataPropertyCodec::DataBlock TEST_DATA_TAG{0x05, 0x05};
/// @private
static const DigestInterface::DataBlock TEST_DIGEST{0xDD, 0xDD};
/// @private
static const DigestInterface::DataBlock TEST_DIGEST2{0xEE, 0xEE};
/// @private
static const std::string TEST_DER_DIGEST_HEX{"301630100404101010100404aaaaaaaa040205050402dddd"};
/// @private
static const std::string TEST_DER_DIGEST2_HEX{"301630100404101010100404aaaaaaaa040205050402eeee"};
TEST(DataPropertyCodecTest, test_encodeDer) {
auto mockCryptoFactory = std::make_shared<MockCryptoFactory>();
EXPECT_CALL(*mockCryptoFactory, _createDigest(DigestType::SHA_256))
.WillOnce(Invoke([](DigestType type) -> std::unique_ptr<DigestInterface> {
auto mockDigest = std::unique_ptr<MockDigest>(new MockDigest);
EXPECT_CALL(*mockDigest, _process(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*mockDigest, _finalize(_)).WillOnce(Invoke([](DigestInterface::DataBlock& res) -> bool {
res.insert(res.end(), TEST_DIGEST.begin(), TEST_DIGEST.end());
return true;
}));
return RETURN_UNIQUE_PTR(mockDigest);
}));
std::vector<uint8_t> derEncoded;
ASSERT_TRUE(DataPropertyCodec::encode(mockCryptoFactory, TEST_IV, TEST_DATA_CIPHERTEXT, TEST_DATA_TAG, derEncoded));
std::string hexDer;
EXPECT_TRUE(encodeHex(derEncoded, hexDer));
ASSERT_EQ(TEST_DER_DIGEST_HEX, hexDer);
}
TEST(DataPropertyCodecTest, test_decodeDer) {
auto mockCryptoFactory = std::make_shared<MockCryptoFactory>();
EXPECT_CALL(*mockCryptoFactory, _createDigest(DigestType::SHA_256))
.WillRepeatedly(Invoke([](DigestType type) -> std::unique_ptr<DigestInterface> {
auto mockDigest = std::unique_ptr<MockDigest>(new MockDigest);
EXPECT_CALL(*mockDigest, _process(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*mockDigest, _finalize(_)).WillOnce(Invoke([](DigestInterface::DataBlock& res) -> bool {
res.insert(res.end(), TEST_DIGEST2.begin(), TEST_DIGEST2.end());
return true;
}));
return RETURN_UNIQUE_PTR(mockDigest);
}));
DataPropertyCodec::IV dataKeyIV;
DataPropertyCodec::DataBlock dataKeyCiphertext;
DataPropertyCodec::Tag dataKeyTag;
DataPropertyCodec::DataBlock digestDecoded, digestActual;
DataPropertyCodec::DataBlock derEncoded;
decodeHex(TEST_DER_DIGEST_HEX, derEncoded);
ASSERT_TRUE(DataPropertyCodec::decode(
mockCryptoFactory, derEncoded, dataKeyIV, dataKeyCiphertext, dataKeyTag, digestDecoded, digestActual));
ASSERT_EQ(TEST_IV, dataKeyIV);
ASSERT_EQ(TEST_DATA_CIPHERTEXT, dataKeyCiphertext);
ASSERT_EQ(TEST_DATA_TAG, dataKeyTag);
ASSERT_TRUE(DataPropertyCodec::encode(mockCryptoFactory, dataKeyIV, dataKeyCiphertext, dataKeyTag, derEncoded));
std::string hexDer;
EXPECT_TRUE(encodeHex(derEncoded, hexDer));
EXPECT_EQ(TEST_DER_DIGEST2_HEX, hexDer);
}
} // namespace test
} // namespace acsdkProperties
} // namespace alexaClientSDK
| 38.982906 | 120 | 0.734488 | [
"vector"
] |
aac96248048daffc46781223b3766ab31c629454 | 1,183 | hpp | C++ | src/cpp/socket.hpp | yesleekm/capstone_xu4 | da42dcef3772946bff83cffe98c5d648b212ecae | [
"Beerware"
] | null | null | null | src/cpp/socket.hpp | yesleekm/capstone_xu4 | da42dcef3772946bff83cffe98c5d648b212ecae | [
"Beerware"
] | null | null | null | src/cpp/socket.hpp | yesleekm/capstone_xu4 | da42dcef3772946bff83cffe98c5d648b212ecae | [
"Beerware"
] | null | null | null | #ifndef SOCKET
#define SOCKET
#include "common.hpp"
#include "admin.hpp"
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;
#define GO_TAKE_PICTURE 0
#define UNTIL_TAKE_PICTURE 1
#define DONE_TAKE_PICTURE 2
#define GO_INFERENCE 3
#define MAXBUFSIZE 512
#define PORT 10001
// Maximum number of requests to wait for a connection.
static const int MAXPENDING = 10;
ssize_t
Recv (const int& sock, const void *buf, ssize_t size, ssize_t unit);
void
send_mode_flag (const int& clntSock, int& MODE_FLAG);
void
send_res (const int& clntSock, int& width, int& height);
void
send_notification (const int& clntSock);
void
handle_thread (const int& clntSock, std::vector<cv::Mat>& imgs,
int& width, int& height, bool& picture_flag,
int& MODE_FLAG, std::mutex& m);
void
camera_handler (io_data& _io_data, config_data& _conf_data,
std::vector<string>& clnt_addrs, bool& allConnected,
int& WORK_FLAG, int& MODE_FLAG, std::mutex& m);
#endif
| 22.75 | 70 | 0.672866 | [
"vector"
] |
aae8da6a551c7e3092c1feca5bb4be8c25c460c3 | 9,816 | cpp | C++ | headpose/posit/src/ModernPosit.cpp | bobetocalo/faces_framework | 05f6192b574a0b79891673df480330b7d94daf7b | [
"BSD-2-Clause"
] | 16 | 2018-09-07T05:39:02.000Z | 2021-02-22T06:59:59.000Z | headpose/posit/src/ModernPosit.cpp | bobetocalo/faces_framework | 05f6192b574a0b79891673df480330b7d94daf7b | [
"BSD-2-Clause"
] | 1 | 2020-02-12T02:23:27.000Z | 2020-02-12T14:48:28.000Z | headpose/posit/src/ModernPosit.cpp | bobetocalo/faces_framework | 05f6192b574a0b79891673df480330b7d94daf7b | [
"BSD-2-Clause"
] | 8 | 2018-11-12T07:58:20.000Z | 2021-02-21T12:50:01.000Z | /** ****************************************************************************
* @file ModernPosit.cpp
* @brief Face detection and recognition framework
* @author Roberto Valle Fernandez
* @date 2018/06
* @copyright All rights reserved.
* Software developed by UPM PCR Group: http://www.dia.fi.upm.es/~pcr
******************************************************************************/
#include <ModernPosit.h>
#include <MeanFace3DModel.hpp>
#include <trace.hpp>
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
void
ModernPosit::loadWorldShape
(
const std::string &path,
const std::vector<unsigned int> &mask,
std::vector<cv::Point3f> &world_all,
std::vector<unsigned int> &index_all
)
{
/// Load 3D mean face coordinates
MeanFace3DModel mean_face_3D;
std::vector<int> posit_landmarks;
mean_face_3D.load(path + "mean_face_3D_" + std::to_string(mask.size()) + ".txt");
for (unsigned int feature_idx: mask)
{
cv::Point3f pt = mean_face_3D.getCoordinatesById(feature_idx);
pt = cv::Point3f(pt.z, -pt.x, -pt.y);
world_all.emplace_back(pt);
index_all.emplace_back(feature_idx);
}
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
void
ModernPosit::setCorrespondences
(
const std::vector<cv::Point3f> &world_all,
const std::vector<unsigned int> &index_all,
const upm::FaceAnnotation &ann,
const std::vector<unsigned int> &mask,
std::vector<cv::Point3f> &world_pts,
std::vector<cv::Point2f> &image_pts
)
{
/// Set correspondences between 3D face and 2D image
for (const upm::FacePart &ann_part : ann.parts)
for (const upm::FaceLandmark &ann_landmark : ann_part.landmarks)
{
auto pos = std::distance(index_all.begin(), std::find(index_all.begin(),index_all.end(),ann_landmark.feature_idx));
if (std::find(mask.begin(),mask.end(),ann_landmark.feature_idx) == mask.end())
continue;
world_pts.emplace_back(world_all[pos]);
image_pts.emplace_back(ann_landmark.pos);
}
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
void
ModernPosit::run
(
const std::vector<cv::Point3f> &world_pts,
const std::vector<cv::Point2f> &image_pts,
const cv::Mat &cam_matrix,
const int &max_iters,
cv::Mat &rot_matrix,
cv::Mat &trl_matrix
)
{
/// Homogeneous world points
const unsigned int num_landmarks = static_cast<unsigned int>(image_pts.size());
cv::Mat A(num_landmarks,4,CV_64F);
for (int i=0; i < num_landmarks; i++)
{
A.at<double>(i,0) = static_cast<double>(world_pts[i].x);
A.at<double>(i,1) = static_cast<double>(world_pts[i].y);
A.at<double>(i,2) = static_cast<double>(world_pts[i].z);
A.at<double>(i,3) = 1.0;
}
cv::Mat B = A.inv(cv::DECOMP_SVD);
/// Normalize image points
float focal_length = cam_matrix.at<float>(0,0);
cv::Point2f face_center = cv::Point2f(cam_matrix.at<float>(0,2),cam_matrix.at<float>(1,2));
std::vector<cv::Point2f> centered_pts;
for (const cv::Point2f &pt : image_pts)
centered_pts.push_back(cv::Point2f(pt - face_center) * (1.0f/focal_length));
cv::Mat Ui(num_landmarks,1,CV_64F), Vi(num_landmarks,1,CV_64F);
for (int i=0; i < num_landmarks; i++)
{
Ui.at<double>(i,0) = centered_pts[i].x;
Vi.at<double>(i,0) = centered_pts[i].y;
}
/// POSIT loop
double Tx = 0.0, Ty = 0.0, Tz = 0.0;
std::vector<double> r1(4), r2(4), r3(4);
std::vector<double> oldUi(num_landmarks), oldVi(num_landmarks), deltaUi(num_landmarks), deltaVi(num_landmarks);
for (unsigned int iter=0; iter < max_iters; iter++)
{
cv::Mat I = B * Ui;
cv::Mat J = B * Vi;
/// Estimate translation vector and rotation matrix
double normI = 1.0/std::sqrt(cv::sum(I.rowRange(0,3).mul(I.rowRange(0,3)))[0]);
double normJ = 1.0/std::sqrt(cv::sum(J.rowRange(0,3).mul(J.rowRange(0,3)))[0]);
Tz = std::sqrt(normI*normJ); // geometric average instead of arithmetic average of classicPosit
for (int j=0; j < 4; j++)
{
r1[j] = I.at<double>(j,0)*Tz;
r2[j] = J.at<double>(j,0)*Tz;
}
for (int j=0; j < 3; j++)
{
if ((r1[j] > 1.0) or (r1[j] < -1.0))
r1[j] = std::max(-1.0,std::min(1.0,r1[j]));
if ((r2[j] > 1.0) or (r2[j] < -1.0))
r2[j] = std::max(-1.0,std::min(1.0,r2[j]));
}
r3[0] = r1[1]*r2[2] - r1[2]*r2[1];
r3[1] = r1[2]*r2[0] - r1[0]*r2[2];
r3[2] = r1[0]*r2[1] - r1[1]*r2[0];
r3[3] = Tz;
Tx = r1[3];
Ty = r2[3];
/// Compute epsilon, update Ui and Vi and check convergence
std::vector<double> eps(num_landmarks,0.0);
for (int i=0; i < num_landmarks; i++)
for (int j=0; j < 4; j++)
eps[i] += A.at<double>(i,j) * r3[j] / Tz;
for (int i=0; i < num_landmarks; i++)
{
oldUi[i] = Ui.at<double>(i,0);
oldVi[i] = Vi.at<double>(i,0);
Ui.at<double>(i,0) = eps[i] * centered_pts[i].x;
Vi.at<double>(i,0) = eps[i] * centered_pts[i].y;
deltaUi[i] = Ui.at<double>(i,0) - oldUi[i];
deltaVi[i] = Vi.at<double>(i,0) - oldVi[i];
}
double delta = 0.0;
for (int i=0; i < num_landmarks; i++)
delta += deltaUi[i] * deltaUi[i] + deltaVi[i] * deltaVi[i];
delta = delta*focal_length*focal_length;
if ((iter > 0) and (delta < 0.01)) // converged
break;
}
/// Return rotation and translation matrices
rot_matrix = (cv::Mat_<float>(3,3) << static_cast<float>(r1[0]),static_cast<float>(r1[1]),static_cast<float>(r1[2]),
static_cast<float>(r2[0]),static_cast<float>(r2[1]),static_cast<float>(r2[2]),
static_cast<float>(r3[0]),static_cast<float>(r3[1]),static_cast<float>(r3[2]));
trl_matrix = (cv::Mat_<float>(3,1) << static_cast<float>(Tx), static_cast<float>(Ty), static_cast<float>(Tz));
/// Convert to nearest orthogonal rotation matrix
cv::Mat w, u, vt;
cv::SVD::compute(rot_matrix, w, u, vt); /// R = U*D*Vt
rot_matrix = u*cv::Mat::eye(3,3,CV_32F)*vt;
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
cv::Point3f
ModernPosit::rotationMatrixToEuler
(
const cv::Mat &rot_matrix
)
{
/// This conversion is better avoided, since it has singularities at pitch + & - 90 degrees, so if already working
/// in terms of matrices its better to continue using matrices if possible.
/// http://euclideanspace.com/maths/geometry/rotations/conversions/matrixToEuler/index.htm
const double a00 = rot_matrix.at<float>(0,0), a01 = rot_matrix.at<float>(0,1), a02 = rot_matrix.at<float>(0,2);
const double a10 = rot_matrix.at<float>(1,0), a11 = rot_matrix.at<float>(1,1), a12 = rot_matrix.at<float>(1,2);
const double a20 = rot_matrix.at<float>(2,0), a21 = rot_matrix.at<float>(2,1), a22 = rot_matrix.at<float>(2,2);
double yaw, pitch, roll;
if (fabs(1.0 - a10) <= DBL_EPSILON) // singularity at north pole / special case a10 == +1
{
UPM_PRINT("Gimbal lock case a10 == " << a10);
yaw = atan2(a02,a22);
pitch = M_PI_2;
roll = 0;
}
else if (fabs(-1.0 - a10) <= DBL_EPSILON) // singularity at south pole / special case a10 == -1
{
UPM_PRINT("Gimbal lock case a10 == " << a10);
yaw = atan2(a02,a22);
pitch = -M_PI_2;
roll = 0;
}
else // standard case a10 != +-1
{
yaw = atan2(-a20,a00);
pitch = asin(a10);
roll = atan2(-a12,a11);
}
/// Convert to degrees
cv::Point3f euler = cv::Point3d(yaw, pitch, roll) * (180.0/M_PI);
/// Change coordinates system
euler = cv::Point3f((-euler.x)+90, -euler.y, (-euler.z)-90);
if (euler.x > 180) euler.x -= 360; else if (euler.x < -180) euler.x += 360;
if (euler.y > 180) euler.y -= 360; else if (euler.y < -180) euler.y += 360;
if (euler.z > 180) euler.z -= 360; else if (euler.z < -180) euler.z += 360;
return euler;
};
// -----------------------------------------------------------------------------
//
// Purpose and Method:
// Inputs:
// Outputs:
// Dependencies:
// Restrictions and Caveats:
//
// -----------------------------------------------------------------------------
cv::Mat
ModernPosit::eulerToRotationMatrix
(
const cv::Point3f &headpose
)
{
/// It is much easier to convert in this direction than to convert back from the matrix to euler angles.
/// Therefore once we convert to matrices it is best to continue to work in matrices.
/// http://euclideanspace.com/maths/geometry/rotations/conversions/eulerToMatrix/index.htm
/// Change coordinates system
cv::Point3f euler = cv::Point3f(-(headpose.x-90), -headpose.y, -(headpose.z+90));
/// Convert to radians
cv::Point3f rad = euler * (M_PI/180.0f);
float cy = cosf(rad.x);
float sy = sinf(rad.x);
float cp = cosf(rad.y);
float sp = sinf(rad.y);
float cr = cosf(rad.z);
float sr = sinf(rad.z);
cv::Mat Ry, Rp, Rr;
Ry = (cv::Mat_<float>(3,3) << cy, 0.0f, sy, 0.0f, 1.0f, 0.0f, -sy, 0.0f, cy);
Rp = (cv::Mat_<float>(3,3) << cp, -sp, 0.0f, sp, cp, 0.0f, 0.0f, 0.0f, 1.0f);
Rr = (cv::Mat_<float>(3,3) << 1.0f, 0.0f, 0.0f, 0.0f, cr, -sr, 0.0f, sr, cr);
return Ry*Rp*Rr;
};
| 35.956044 | 121 | 0.560513 | [
"geometry",
"vector",
"3d"
] |
aaeb6180654a744398b6c9974c94ca047e963aa2 | 6,546 | cpp | C++ | src/mongo/db/s/resharding/document_source_resharding_ownership_match.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/resharding/document_source_resharding_ownership_match.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/resharding/document_source_resharding_ownership_match.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2021-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/s/resharding/document_source_resharding_ownership_match.h"
#include "mongo/db/s/resharding/resharding_util.h"
#include "mongo/db/transaction_history_iterator.h"
#include "mongo/s/catalog_cache.h"
#include "mongo/s/grid.h"
#include "mongo/s/resharding/common_types_gen.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand
namespace mongo {
REGISTER_INTERNAL_DOCUMENT_SOURCE(_internalReshardingOwnershipMatch,
LiteParsedDocumentSourceDefault::parse,
DocumentSourceReshardingOwnershipMatch::createFromBson,
true);
boost::intrusive_ptr<DocumentSourceReshardingOwnershipMatch>
DocumentSourceReshardingOwnershipMatch::create(
ShardId recipientShardId,
ShardKeyPattern reshardingKey,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
return new DocumentSourceReshardingOwnershipMatch(
std::move(recipientShardId), std::move(reshardingKey), expCtx);
}
boost::intrusive_ptr<DocumentSourceReshardingOwnershipMatch>
DocumentSourceReshardingOwnershipMatch::createFromBson(
BSONElement elem, const boost::intrusive_ptr<ExpressionContext>& expCtx) {
uassert(8423307,
str::stream() << "Argument to " << kStageName << " must be an object",
elem.type() == Object);
auto parsed = DocumentSourceReshardingOwnershipMatchSpec::parse(
{"DocumentSourceReshardingOwnershipMatchSpec"}, elem.embeddedObject());
return new DocumentSourceReshardingOwnershipMatch(
parsed.getRecipientShardId(), ShardKeyPattern(parsed.getReshardingKey()), expCtx);
}
DocumentSourceReshardingOwnershipMatch::DocumentSourceReshardingOwnershipMatch(
ShardId recipientShardId,
ShardKeyPattern reshardingKey,
const boost::intrusive_ptr<ExpressionContext>& expCtx)
: DocumentSource(kStageName, expCtx),
_recipientShardId{std::move(recipientShardId)},
_reshardingKey{std::move(reshardingKey)} {}
StageConstraints DocumentSourceReshardingOwnershipMatch::constraints(
Pipeline::SplitState pipeState) const {
return StageConstraints(StreamType::kStreaming,
PositionRequirement::kNone,
HostTypeRequirement::kAnyShard,
DiskUseRequirement::kNoDiskUse,
FacetRequirement::kNotAllowed,
TransactionRequirement::kNotAllowed,
LookupRequirement::kNotAllowed,
UnionRequirement::kNotAllowed,
ChangeStreamRequirement::kDenylist);
}
Value DocumentSourceReshardingOwnershipMatch::serialize(
boost::optional<ExplainOptions::Verbosity> explain) const {
return Value{Document{{kStageName,
DocumentSourceReshardingOwnershipMatchSpec(
_recipientShardId, _reshardingKey.getKeyPattern())
.toBSON()}}};
}
DepsTracker::State DocumentSourceReshardingOwnershipMatch::getDependencies(
DepsTracker* deps) const {
for (const auto& skElem : _reshardingKey.toBSON()) {
deps->fields.insert(skElem.fieldNameStringData().toString());
}
return DepsTracker::State::SEE_NEXT;
}
DocumentSource::GetModPathsReturn DocumentSourceReshardingOwnershipMatch::getModifiedPaths() const {
// This stage does not modify or rename any paths.
return {DocumentSource::GetModPathsReturn::Type::kFiniteSet, std::set<std::string>{}, {}};
}
DocumentSource::GetNextResult DocumentSourceReshardingOwnershipMatch::doGetNext() {
if (!_tempReshardingChunkMgr) {
// TODO: Actually propagate the temporary resharding namespace from the recipient.
auto tempReshardingNss = constructTemporaryReshardingNss(pExpCtx->ns.db(), *pExpCtx->uuid);
auto* catalogCache = Grid::get(pExpCtx->opCtx)->catalogCache();
_tempReshardingChunkMgr =
uassertStatusOK(catalogCache->getShardedCollectionRoutingInfoWithRefresh(
pExpCtx->opCtx, tempReshardingNss));
}
auto nextInput = pSource->getNext();
for (; nextInput.isAdvanced(); nextInput = pSource->getNext()) {
auto shardKey =
_reshardingKey.extractShardKeyFromDocThrows(nextInput.getDocument().toBson());
if (_tempReshardingChunkMgr->keyBelongsToShard(shardKey, _recipientShardId)) {
return nextInput;
}
// For performance reasons, a streaming stage must not keep references to documents across
// calls to getNext(). Such stages must retrieve a result from their child and then release
// it (or return it) before asking for another result. Failing to do so can result in extra
// work, since the Document/Value library must copy data on write when that data has a
// refcount above one.
nextInput.releaseDocument();
}
return nextInput;
}
} // namespace mongo
| 43.932886 | 100 | 0.7044 | [
"object"
] |
aaf91a5c71adc3839117d16bbd4b83811c6e1af3 | 7,539 | cpp | C++ | torch/csrc/jit/serialization/onnx.cpp | stungkit/pytorch | 0f05e398705bf15406bce79f7ee57d3935ad2abd | [
"Intel"
] | 2 | 2020-03-13T06:57:49.000Z | 2020-05-17T04:18:14.000Z | torch/csrc/jit/serialization/onnx.cpp | stungkit/pytorch | 0f05e398705bf15406bce79f7ee57d3935ad2abd | [
"Intel"
] | 1 | 2022-01-10T18:39:28.000Z | 2022-01-10T19:15:57.000Z | torch/csrc/jit/serialization/onnx.cpp | stungkit/pytorch | 0f05e398705bf15406bce79f7ee57d3935ad2abd | [
"Intel"
] | 1 | 2022-03-26T14:42:50.000Z | 2022-03-26T14:42:50.000Z | #include <c10/util/irange.h>
#include <torch/csrc/jit/serialization/onnx.h>
#include <torch/csrc/onnx/onnx.h>
#include <sstream>
#include <string>
namespace torch {
namespace jit {
namespace {
namespace onnx_torch = ::torch::onnx;
namespace onnx = ::ONNX_NAMESPACE;
// Pretty printing for ONNX
constexpr char indent_char = ' ';
constexpr size_t indent_multiplier = 2;
std::string idt(size_t indent) {
return std::string(indent * indent_multiplier, indent_char);
}
std::string nlidt(size_t indent) {
return std::string("\n") + idt(indent);
}
void dump(const onnx::TensorProto& tensor, std::ostream& stream) {
stream << "TensorProto shape: [";
for (const auto i : c10::irange(tensor.dims_size())) {
stream << tensor.dims(i) << (i == tensor.dims_size() - 1 ? "" : " ");
}
stream << "]";
}
void dump(const onnx::TensorShapeProto& shape, std::ostream& stream) {
for (const auto i : c10::irange(shape.dim_size())) {
auto& dim = shape.dim(i);
if (dim.has_dim_value()) {
stream << dim.dim_value();
} else {
stream << "?";
}
stream << (i == shape.dim_size() - 1 ? "" : " ");
}
}
void dump(const onnx::TypeProto_Tensor& tensor_type, std::ostream& stream) {
stream << "Tensor dtype: ";
if (tensor_type.has_elem_type()) {
stream << tensor_type.elem_type();
} else {
stream << "None.";
}
stream << ", ";
stream << "Tensor dims: ";
if (tensor_type.has_shape()) {
dump(tensor_type.shape(), stream);
} else {
stream << "None.";
}
}
void dump(const onnx::TypeProto& type, std::ostream& stream);
void dump(const onnx::TypeProto_Optional& optional_type, std::ostream& stream) {
stream << "Optional<";
if (optional_type.has_elem_type()) {
dump(optional_type.elem_type(), stream);
} else {
stream << "None";
}
stream << ">";
}
void dump(const onnx::TypeProto_Sequence& sequence_type, std::ostream& stream) {
stream << "Sequence<";
if (sequence_type.has_elem_type()) {
dump(sequence_type.elem_type(), stream);
} else {
stream << "None";
}
stream << ">";
}
void dump(const onnx::TypeProto& type, std::ostream& stream) {
if (type.has_tensor_type()) {
dump(type.tensor_type(), stream);
} else if (type.has_sequence_type()) {
dump(type.sequence_type(), stream);
} else if (type.has_optional_type()) {
dump(type.optional_type(), stream);
} else {
stream << "None";
}
}
void dump(const onnx::ValueInfoProto& value_info, std::ostream& stream) {
stream << "{name: \"" << value_info.name() << "\", type:";
dump(value_info.type(), stream);
stream << "}";
}
void dump(const onnx::GraphProto& graph, std::ostream& stream, size_t indent);
void dump(
const onnx::AttributeProto& attr,
std::ostream& stream,
size_t indent) {
stream << "{ name: '" << attr.name() << "', type: ";
if (attr.has_f()) {
stream << "float, value: " << attr.f();
} else if (attr.has_i()) {
stream << "int, value: " << attr.i();
} else if (attr.has_s()) {
stream << "string, value: '" << attr.s() << "'";
} else if (attr.has_g()) {
stream << "graph, value:\n";
dump(attr.g(), stream, indent + 1);
stream << nlidt(indent);
} else if (attr.has_t()) {
stream << "tensor, value:";
dump(attr.t(), stream);
} else if (attr.floats_size()) {
stream << "floats, values: [";
for (const auto i : c10::irange(attr.floats_size())) {
stream << attr.floats(i) << (i == attr.floats_size() - 1 ? "" : " ");
}
stream << "]";
} else if (attr.ints_size()) {
stream << "ints, values: [";
for (const auto i : c10::irange(attr.ints_size())) {
stream << attr.ints(i) << (i == attr.ints_size() - 1 ? "" : " ");
}
stream << "]";
} else if (attr.strings_size()) {
stream << "strings, values: [";
for (const auto i : c10::irange(attr.strings_size())) {
stream << "'" << attr.strings(i) << "'"
<< (i == attr.strings_size() - 1 ? "" : " ");
}
stream << "]";
} else if (attr.tensors_size()) {
stream << "tensors, values: [";
for (auto& t : attr.tensors()) {
dump(t, stream);
}
stream << "]";
} else if (attr.graphs_size()) {
stream << "graphs, values: [";
for (auto& g : attr.graphs()) {
dump(g, stream, indent + 1);
}
stream << "]";
} else {
stream << "UNKNOWN";
}
stream << "}";
}
void dump(const onnx::NodeProto& node, std::ostream& stream, size_t indent) {
stream << "Node {type: \"" << node.op_type() << "\", inputs: [";
for (const auto i : c10::irange(node.input_size())) {
stream << node.input(i) << (i == node.input_size() - 1 ? "" : ",");
}
stream << "], outputs: [";
for (const auto i : c10::irange(node.output_size())) {
stream << node.output(i) << (i == node.output_size() - 1 ? "" : ",");
}
stream << "], attributes: [";
for (const auto i : c10::irange(node.attribute_size())) {
dump(node.attribute(i), stream, indent + 1);
stream << (i == node.attribute_size() - 1 ? "" : ",");
}
stream << "]}";
}
void dump(const onnx::GraphProto& graph, std::ostream& stream, size_t indent) {
stream << idt(indent) << "GraphProto {" << nlidt(indent + 1) << "name: \""
<< graph.name() << "\"" << nlidt(indent + 1) << "inputs: [";
for (const auto i : c10::irange(graph.input_size())) {
dump(graph.input(i), stream);
stream << (i == graph.input_size() - 1 ? "" : ",");
}
stream << "]" << nlidt(indent + 1) << "outputs: [";
for (const auto i : c10::irange(graph.output_size())) {
dump(graph.output(i), stream);
stream << (i == graph.output_size() - 1 ? "" : ",");
}
stream << "]" << nlidt(indent + 1) << "value_infos: [";
for (const auto i : c10::irange(graph.value_info_size())) {
dump(graph.value_info(i), stream);
stream << (i == graph.value_info_size() - 1 ? "" : ",");
}
stream << "]" << nlidt(indent + 1) << "initializers: [";
for (const auto i : c10::irange(graph.initializer_size())) {
dump(graph.initializer(i), stream);
stream << (i == graph.initializer_size() - 1 ? "" : ",");
}
stream << "]" << nlidt(indent + 1) << "nodes: [" << nlidt(indent + 2);
for (const auto i : c10::irange(graph.node_size())) {
dump(graph.node(i), stream, indent + 2);
if (i != graph.node_size() - 1) {
stream << "," << nlidt(indent + 2);
}
}
stream << nlidt(indent + 1) << "]\n" << idt(indent) << "}\n";
}
void dump(
const onnx::OperatorSetIdProto& operator_set_id,
std::ostream& stream) {
stream << "OperatorSetIdProto { domain: " << operator_set_id.domain()
<< ", version: " << operator_set_id.version() << "}";
}
void dump(const onnx::ModelProto& model, std::ostream& stream, size_t indent) {
stream << idt(indent) << "ModelProto {" << nlidt(indent + 1)
<< "producer_name: \"" << model.producer_name() << "\""
<< nlidt(indent + 1) << "domain: \"" << model.domain() << "\""
<< nlidt(indent + 1) << "doc_string: \"" << model.doc_string() << "\"";
if (model.has_graph()) {
stream << nlidt(indent + 1) << "graph:\n";
dump(model.graph(), stream, indent + 2);
}
if (model.opset_import_size()) {
stream << idt(indent + 1) << "opset_import: [";
for (auto& opset_imp : model.opset_import()) {
dump(opset_imp, stream);
}
stream << "],\n";
}
stream << idt(indent) << "}\n";
}
} // namespace
std::string prettyPrint(const ::ONNX_NAMESPACE::ModelProto& model) {
std::ostringstream ss;
dump(model, ss, 0);
return ss.str();
}
} // namespace jit
} // namespace torch
| 30.897541 | 80 | 0.569041 | [
"shape",
"model"
] |
aaffa02c9f2d0a1348cf84b5cfea3899f77a478d | 2,786 | cpp | C++ | eagle_mpc_rviz_plugins/src/LineVisual.cpp | PepMS/eagle_mpc_ros | 6f4caa559eb786c40834175b49749c2a2599bcee | [
"BSD-3-Clause"
] | null | null | null | eagle_mpc_rviz_plugins/src/LineVisual.cpp | PepMS/eagle_mpc_ros | 6f4caa559eb786c40834175b49749c2a2599bcee | [
"BSD-3-Clause"
] | 2 | 2020-06-13T04:20:15.000Z | 2020-06-13T04:20:31.000Z | eagle_mpc_rviz_plugins/src/LineVisual.cpp | PepMS/multicopter-mpc-ros | 6f4caa559eb786c40834175b49749c2a2599bcee | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2020-2021, University of Edinburgh, Istituto Italiano di Tecnologia
// Copyright (c) 2021, Institut de Robotica i Informatica Industrial (CSIC-UPC)
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
#include <OgreVector3.h>
#include "whole_body_state_rviz_plugin/LineVisual.h"
#include <rviz/ogre_helpers/arrow.h>
namespace whole_body_state_rviz_plugin {
LineVisual::LineVisual(Ogre::SceneManager *scene_manager,
Ogre::SceneNode *parent_node)
: distance_(0.) {
scene_manager_ = scene_manager;
// Ogre::SceneNode s form a tree, with each node storing the transform
// (position and orientation) of itself relative to its parent. Ogre does
// the math of combining those transforms when it is time to render.
// Here we create a node to store the pose of the Point's header frame
// relative to the RViz fixed frame.
frame_node_ = parent_node->createChildSceneNode();
// We create the arrow object within the frame node so that we can set its
// position and direction relative to its header frame.
arrow_ = new rviz::Arrow(scene_manager_, frame_node_);
}
LineVisual::~LineVisual() {
// Delete the arrow to make it disappear.
delete arrow_;
// Destroy the frame node since we don't need it anymore.
scene_manager_->destroySceneNode(frame_node_);
}
void LineVisual::setArrow(const Ogre::Vector3 &initial_point,
const Ogre::Vector3 &final_point) {
arrow_->setPosition(initial_point);
Eigen::Vector3d ref_dir = -Eigen::Vector3d::UnitZ();
Eigen::Vector3d arrow_dir(final_point.x - initial_point.x,
final_point.y - initial_point.y,
final_point.z - initial_point.z);
Eigen::Quaterniond arrow_q;
arrow_q.setFromTwoVectors(ref_dir, arrow_dir);
Ogre::Quaternion orientation(arrow_q.w(), arrow_q.x(), arrow_q.y(),
arrow_q.z());
arrow_->setOrientation(orientation);
distance_ = arrow_dir.norm();
}
void LineVisual::setFramePosition(const Ogre::Vector3 &position) {
frame_node_->setPosition(position);
}
void LineVisual::setFrameOrientation(const Ogre::Quaternion &orientation) {
frame_node_->setOrientation(orientation);
}
void LineVisual::setColor(float r, float g, float b, float a) {
arrow_->setColor(r, g, b, a);
}
void LineVisual::setProperties(float shaft_diameter, float head_length,
float head_diameter) {
arrow_->set(distance_, shaft_diameter, head_length, head_diameter);
}
} // namespace whole_body_state_rviz_plugin
| 36.657895 | 84 | 0.66906 | [
"render",
"object",
"transform"
] |
c9084c145b0145efe7dc06c2a06176d417a49c92 | 2,226 | cpp | C++ | src/App/IMGUI/ui-styler.cpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | src/App/IMGUI/ui-styler.cpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | src/App/IMGUI/ui-styler.cpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | #include "core.hpp"
#include "ui-styler.hpp"
#include "ui-core.hpp"
#include "ui-items.hpp"
#include "ui-panel.hpp"
#include "ui-rendered.hpp"
void Styler::render(Panel& panel) {
// panel.m_background.color = 0x10101010;
if(panel.m_background.color)
m_renderedUiItems.put<RenderedUIItems::Background>(panel.m_background);
if(panel.m_blured)
m_renderedUiItems.put<RenderedUIItems::ToBlur>(
RenderedUIItems::ToBlur {panel.m_background.box, panel.m_background.depth});
}
void Styler::render(Item& item) {
u32 itemColor = 0xf0f0f040;
if(item.m_action > PointerActions::Hover and item.m_action <= PointerActions::RmbHold)
itemColor = 0xf0f0f0a0;
else if(item.m_action == PointerActions::Hover)
itemColor = 0xf0f0f080;
itemColor = item.m_color.value_or(itemColor);
if(itemColor)
m_renderedUiItems.put<RenderedUIItems::ColoredBox>({item.m_size, item.m_depth, itemColor});
}
void Styler::renderSlider(Item& item, float ratio) {
auto size = item.m_size;
float heightCorrection = size[3] * 0.8f;
size[1] += heightCorrection;
size[3] -= 2.f * heightCorrection;
m_renderedUiItems.put<RenderedUIItems::ColoredBox>({size, item.m_depth, 0xa0a0a050});
size[2] *= ratio;
m_renderedUiItems.put<RenderedUIItems::ColoredBox>({size, item.m_depth, 0xf0f0f0f0});
}
void Styler::renderText(Item& item, const std::string& text) {
item.m_text->formatting = item.m_formatting.value_or(Text::Left);
item.m_text->color = item.m_textColor.value_or(0xf0f0f0d0);
item.m_text->font = item.m_font.value_or("ui_20");
item.m_text->depth = item.m_depth;
item.m_text->bounds = item.m_size + glm::vec4(5, 5, -10, -10);
item.m_text->renderTo(m_renderedUiItems.get<Text::Rendered>(), text);
}
void Styler::renderSymbol(Item& item, const std::u16string& text, const std::string& font) {
Text textItem;
textItem.formatting = item.m_formatting.value_or(Text::Left);
textItem.color = item.m_textColor.value_or(0xf0f0f0d0);
textItem.font = font;
textItem.depth = item.m_depth;
textItem.bounds = item.m_size + glm::vec4(5, 5, -10, -10);
textItem.renderTo(m_renderedUiItems.get<Text::Rendered>(), text);
}
| 40.472727 | 99 | 0.703953 | [
"render"
] |
c908d4f43e94c3fc467595a1e9ac16fe3c5d173e | 384 | hpp | C++ | apal_cxx/include/gaussian_white_noise.hpp | davidkleiven/APAL | f3d549498d312b98f55aad5db7c4ad061785ecbf | [
"MIT"
] | null | null | null | apal_cxx/include/gaussian_white_noise.hpp | davidkleiven/APAL | f3d549498d312b98f55aad5db7c4ad061785ecbf | [
"MIT"
] | 15 | 2019-05-23T07:18:19.000Z | 2019-12-17T08:01:10.000Z | apal_cxx/include/gaussian_white_noise.hpp | davidkleiven/APAL | f3d549498d312b98f55aad5db7c4ad061785ecbf | [
"MIT"
] | null | null | null | #ifndef GAUSSIAN_WHITE_NOISE_H
#define GAUSSIAN_WHITE_NOISE_H
#include "thermal_noise_generator.hpp"
class GaussianWhiteNoise: public ThermalNoiseGenerator{
public:
GaussianWhiteNoise(double dt, double amplitude): ThermalNoiseGenerator(dt), amplitude(amplitude){};
virtual void create(std::vector<double> &noise) const override;
private:
double amplitude{1.0};
};
#endif | 29.538462 | 103 | 0.796875 | [
"vector"
] |
c90e3f820a0159f3faee21cb7921143497c60c1a | 1,240 | cpp | C++ | arc075/e.cpp | nel215/atcoder-grand-contest | a13ce146516c03881f50b7ac284be23d16d29ffe | [
"MIT"
] | null | null | null | arc075/e.cpp | nel215/atcoder-grand-contest | a13ce146516c03881f50b7ac284be23d16d29ffe | [
"MIT"
] | null | null | null | arc075/e.cpp | nel215/atcoder-grand-contest | a13ce146516c03881f50b7ac284be23d16d29ffe | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <deque>
#include <complex>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#define REP(i,x) for(int i=0 ; i<(int)(x) ; i++)
#define ALL(x) (x).begin(),(x).end()
#define LL long long
using namespace std;
struct BIT{
int N;
vector<LL> data;
BIT(int N){
this->N = N;
data.assign(N+1, 0);
}
void add(int i, LL v){
while(i<=N){
data[i] += v;
i += i&-i;
}
}
LL sum(int i){
LL res = 0;
while(i>0){
res += data[i];
i -= i&-i;
}
return res;
}
};
int main(){
int N, K;
cin >> N >> K;
vector<int> A(N);
REP(i, N)cin >> A[i];
vector<LL> B(N+1);
REP(i, N){
B[i+1] = B[i] + A[i] - K;
}
sort(ALL(B));
BIT bit(N+1);
LL res = 0;
LL thres = 0;
REP(i, N+1){
int p = lower_bound(ALL(B), thres) - B.begin() + 1;
res += bit.sum(p);
bit.add(p, 1);
thres += A[i] - K;
}
cout << res << endl;
return 0;
}
| 17.222222 | 59 | 0.466935 | [
"vector"
] |
c9110147975532987bd5737d440e2de6b8c78439 | 14,990 | cpp | C++ | framework/decode/custom_vulkan_struct_decoders.cpp | davidd-lunarg/gfxreconstruct | 3aa9f032982ac5fbb926d3d8cd043940f152cdba | [
"BSD-2-Clause",
"MIT"
] | 1 | 2021-03-04T03:33:45.000Z | 2021-03-04T03:33:45.000Z | framework/decode/custom_vulkan_struct_decoders.cpp | davidd-lunarg/gfxreconstruct | 3aa9f032982ac5fbb926d3d8cd043940f152cdba | [
"BSD-2-Clause",
"MIT"
] | 1 | 2021-12-07T11:44:18.000Z | 2021-12-07T11:44:18.000Z | framework/decode/custom_vulkan_struct_decoders.cpp | davidd-lunarg/gfxreconstruct | 3aa9f032982ac5fbb926d3d8cd043940f152cdba | [
"BSD-2-Clause",
"MIT"
] | null | null | null | /*
** Copyright (c) 2018-2020 Valve Corporation
** Copyright (c) 2018-2020 LunarG, Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
*/
#include "decode/custom_vulkan_struct_decoders.h"
#include "decode/decode_allocator.h"
#include "decode/value_decoder.h"
#include "generated/generated_vulkan_struct_decoders.h"
#include "util/defines.h"
#include "util/logging.h"
#include <cassert>
GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(decode)
size_t DecodePNextStruct(const uint8_t* buffer, size_t buffer_size, PNextNode** pNext);
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkClearColorValue* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkClearColorValue* value = wrapper->decoded_value;
wrapper->uint32.SetExternalMemory(value->uint32, 4);
bytes_read += wrapper->uint32.DecodeUInt32((buffer + bytes_read), (buffer_size - bytes_read));
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkClearValue* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkClearValue* value = wrapper->decoded_value;
wrapper->color = DecodeAllocator::Allocate<Decoded_VkClearColorValue>();
wrapper->color->decoded_value = &(value->color);
bytes_read += DecodeStruct((buffer + bytes_read), (buffer_size - bytes_read), wrapper->color);
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkPipelineExecutableStatisticValueKHR* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkPipelineExecutableStatisticValueKHR* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeUInt64Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->u64));
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkDeviceOrHostAddressKHR* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkDeviceOrHostAddressKHR* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeVkDeviceSizeValue(
(buffer + bytes_read), (buffer_size - bytes_read), &(value->deviceAddress));
wrapper->hostAddress = value->deviceAddress;
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkDeviceOrHostAddressConstKHR* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkDeviceOrHostAddressConstKHR* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeVkDeviceSizeValue(
(buffer + bytes_read), (buffer_size - bytes_read), &(value->deviceAddress));
wrapper->hostAddress = value->deviceAddress;
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkAccelerationStructureGeometryDataKHR* wrapper)
{
// TODO
GFXRECON_LOG_ERROR("VkAccelerationStructureGeometryDataKHR is not supported");
return 0;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkDescriptorImageInfo* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkDescriptorImageInfo* value = wrapper->decoded_value;
bytes_read +=
ValueDecoder::DecodeHandleIdValue((buffer + bytes_read), (buffer_size - bytes_read), &(wrapper->sampler));
value->sampler = VK_NULL_HANDLE;
bytes_read +=
ValueDecoder::DecodeHandleIdValue((buffer + bytes_read), (buffer_size - bytes_read), &(wrapper->imageView));
value->imageView = VK_NULL_HANDLE;
bytes_read +=
ValueDecoder::DecodeEnumValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->imageLayout));
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkWriteDescriptorSet* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkWriteDescriptorSet* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeEnumValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->sType));
bytes_read += DecodePNextStruct((buffer + bytes_read), (buffer_size - bytes_read), &(wrapper->pNext));
value->pNext = wrapper->pNext ? wrapper->pNext->GetPointer() : nullptr;
bytes_read +=
ValueDecoder::DecodeHandleIdValue((buffer + bytes_read), (buffer_size - bytes_read), &(wrapper->dstSet));
value->dstSet = VK_NULL_HANDLE;
bytes_read +=
ValueDecoder::DecodeUInt32Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->dstBinding));
bytes_read +=
ValueDecoder::DecodeUInt32Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->dstArrayElement));
bytes_read +=
ValueDecoder::DecodeUInt32Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->descriptorCount));
bytes_read +=
ValueDecoder::DecodeEnumValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->descriptorType));
wrapper->pImageInfo = DecodeAllocator::Allocate<StructPointerDecoder<Decoded_VkDescriptorImageInfo>>();
bytes_read += wrapper->pImageInfo->Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->pImageInfo = wrapper->pImageInfo->GetPointer();
wrapper->pBufferInfo = DecodeAllocator::Allocate<StructPointerDecoder<Decoded_VkDescriptorBufferInfo>>();
bytes_read += wrapper->pBufferInfo->Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->pBufferInfo = wrapper->pBufferInfo->GetPointer();
bytes_read += wrapper->pTexelBufferView.Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->pTexelBufferView = wrapper->pTexelBufferView.GetHandlePointer();
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkPerformanceValueINTEL* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkPerformanceValueINTEL* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeEnumValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->type));
wrapper->data = DecodeAllocator::Allocate<Decoded_VkPerformanceValueDataINTEL>();
wrapper->data->decoded_value = &(value->data);
if (value->type == VK_PERFORMANCE_VALUE_TYPE_STRING_INTEL)
{
bytes_read += wrapper->data->valueString.Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->data.valueString = wrapper->data->valueString.GetPointer();
}
else
{
bytes_read +=
ValueDecoder::DecodeUInt64Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->data.value64));
}
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_VkAccelerationStructureGeometryKHR* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
VkAccelerationStructureGeometryKHR* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeEnumValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->sType));
bytes_read += DecodePNextStruct((buffer + bytes_read), (buffer_size - bytes_read), &(wrapper->pNext));
value->pNext = wrapper->pNext ? wrapper->pNext->GetPointer() : nullptr;
bytes_read +=
ValueDecoder::DecodeEnumValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->geometryType));
wrapper->geometry = DecodeAllocator::Allocate<Decoded_VkAccelerationStructureGeometryDataKHR>();
switch (value->geometryType)
{
case VK_GEOMETRY_TYPE_TRIANGLES_KHR:
wrapper->geometry->triangles =
DecodeAllocator::Allocate<Decoded_VkAccelerationStructureGeometryTrianglesDataKHR>();
wrapper->geometry->triangles->decoded_value = &(value->geometry.triangles);
bytes_read += DecodeStruct((buffer + bytes_read), (buffer_size - bytes_read), wrapper->geometry->triangles);
break;
case VK_GEOMETRY_TYPE_AABBS_KHR:
wrapper->geometry->aabbs = DecodeAllocator::Allocate<Decoded_VkAccelerationStructureGeometryAabbsDataKHR>();
wrapper->geometry->aabbs->decoded_value = &(value->geometry.aabbs);
bytes_read += DecodeStruct((buffer + bytes_read), (buffer_size - bytes_read), wrapper->geometry->aabbs);
break;
case VK_GEOMETRY_TYPE_INSTANCES_KHR:
wrapper->geometry->instances =
DecodeAllocator::Allocate<Decoded_VkAccelerationStructureGeometryInstancesDataKHR>();
wrapper->geometry->instances->decoded_value = &(value->geometry.instances);
bytes_read += DecodeStruct((buffer + bytes_read), (buffer_size - bytes_read), wrapper->geometry->instances);
break;
default:
break;
}
bytes_read += ValueDecoder::DecodeFlagsValue((buffer + bytes_read), (buffer_size - bytes_read), &(value->flags));
return bytes_read;
}
// The WIN32 SID structure has a variable size, so was encoded as an array of bytes instead of a struct.
static uint8_t* unpack_sid_struct(const PointerDecoder<uint8_t>& packed_value)
{
const uint8_t* bytes = packed_value.GetPointer();
// Allocate memory for variable length SID struct, to use for unpacking.
// SidAuthorityCount is the second byte of the packed array.
size_t sid_authority_size = bytes[1] * sizeof(uint32_t);
// sizeof(SID) already includes the size of one of the SidAuthority elements,
// so we can subtract 4 bytes from sid_authority_size.
size_t allocation_size = sizeof(SID) + (sid_authority_size - sizeof(uint32_t));
uint8_t* unpacked_memory = DecodeAllocator::Allocate<uint8_t>(allocation_size);
SID* sid = reinterpret_cast<SID*>(unpacked_memory);
sid->Revision = bytes[0];
sid->SubAuthorityCount = bytes[1];
memcpy(sid->IdentifierAuthority.Value, &bytes[2], 6);
memcpy(sid->SubAuthority, &bytes[8], sid_authority_size);
return unpacked_memory;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_ACL* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
ACL* value = wrapper->decoded_value;
bytes_read +=
ValueDecoder::DecodeUInt8Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->AclRevision));
bytes_read += ValueDecoder::DecodeUInt8Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->Sbz1));
bytes_read += ValueDecoder::DecodeUInt16Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->AclSize));
bytes_read +=
ValueDecoder::DecodeUInt16Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->AceCount));
bytes_read += ValueDecoder::DecodeUInt16Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->Sbz2));
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_SECURITY_DESCRIPTOR* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
SECURITY_DESCRIPTOR* value = wrapper->decoded_value;
bytes_read += ValueDecoder::DecodeUInt8Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->Revision));
bytes_read += ValueDecoder::DecodeUInt8Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->Sbz1));
bytes_read += ValueDecoder::DecodeUInt16Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->Control));
// The SID structure has a variable size, so has been packed into an array of bytes.
bytes_read += wrapper->PackedOwner.DecodeUInt8((buffer + bytes_read), (buffer_size - bytes_read));
wrapper->Owner = unpack_sid_struct(wrapper->PackedOwner);
value->Owner = wrapper->Owner;
bytes_read += wrapper->PackedGroup.DecodeUInt8((buffer + bytes_read), (buffer_size - bytes_read));
wrapper->Group = unpack_sid_struct(wrapper->PackedOwner);
value->Group = wrapper->Group;
wrapper->Sacl = DecodeAllocator::Allocate<StructPointerDecoder<Decoded_ACL>>();
bytes_read += wrapper->Sacl->Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->Sacl = wrapper->Sacl->GetPointer();
wrapper->Dacl = DecodeAllocator::Allocate<StructPointerDecoder<Decoded_ACL>>();
bytes_read += wrapper->Dacl->Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->Dacl = wrapper->Dacl->GetPointer();
return bytes_read;
}
size_t DecodeStruct(const uint8_t* buffer, size_t buffer_size, Decoded_SECURITY_ATTRIBUTES* wrapper)
{
assert((wrapper != nullptr) && (wrapper->decoded_value != nullptr));
size_t bytes_read = 0;
SECURITY_ATTRIBUTES* value = wrapper->decoded_value;
uint32_t nLength = 0;
bytes_read += ValueDecoder::DecodeUInt32Value((buffer + bytes_read), (buffer_size - bytes_read), &nLength);
value->nLength = nLength;
wrapper->lpSecurityDescriptor = DecodeAllocator::Allocate<StructPointerDecoder<Decoded_SECURITY_DESCRIPTOR>>();
bytes_read += wrapper->lpSecurityDescriptor->Decode((buffer + bytes_read), (buffer_size - bytes_read));
value->lpSecurityDescriptor = wrapper->lpSecurityDescriptor->GetPointer();
bytes_read +=
ValueDecoder::DecodeInt32Value((buffer + bytes_read), (buffer_size - bytes_read), &(value->bInheritHandle));
return bytes_read;
}
GFXRECON_END_NAMESPACE(decode)
GFXRECON_END_NAMESPACE(gfxrecon)
| 44.88024 | 120 | 0.709606 | [
"geometry"
] |
c917a91f53ab2a717e0409550e7be0aa2c15161b | 721 | cpp | C++ | .LHP/.Lop12/.PreHSG/.T.Van/D2/DELNUM/DELNUM/DELNUM.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | .LHP/.Lop12/.PreHSG/.T.Van/D2/DELNUM/DELNUM/DELNUM.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | .LHP/.Lop12/.PreHSG/.T.Van/D2/DELNUM/DELNUM/DELNUM.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#define maxN 400001
typedef long maxn;
typedef long long maxa;
maxn n, res;
maxa a[maxN];
std::vector <maxa> st;
void Prepare() {
std::cin >> n;
for (maxn i = 0; i < n; i++) std::cin >> a[i];
}
void Process() {
for (maxn i = 0; i < n; i++) {
while (!st.empty() && ((st.size() == 1) || (st.size() >= 2 && st.back() != st[st.size() - 2])) && st.back() < a[i]) {
st.pop_back();
if (!st.empty()) ++res;
}
st.push_back(a[i]);
}
std::cout << n - res;
}
int main() {
//freopen("delnum.inp", "r", stdin);
//freopen("delnum.out", "w", stdout);
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
Process();
} | 16.767442 | 119 | 0.552011 | [
"vector"
] |
c918a1c5313e0357a5a7e4d6d62065b4cb9af0c9 | 60,187 | cpp | C++ | examples/Chapter-09/Chapter-9.cpp | kamarianakis/glGA-edu | 17f0b33c3ea8efcfa8be01d41343862ea4e6fae0 | [
"BSD-4-Clause-UC"
] | 4 | 2018-08-22T03:43:30.000Z | 2021-03-11T18:20:27.000Z | examples/Chapter-09/Chapter-9.cpp | kamarianakis/glGA-edu | 17f0b33c3ea8efcfa8be01d41343862ea4e6fae0 | [
"BSD-4-Clause-UC"
] | 7 | 2020-10-06T16:34:12.000Z | 2020-12-06T17:29:22.000Z | examples/Chapter-09/Chapter-9.cpp | kamarianakis/glGA-edu | 17f0b33c3ea8efcfa8be01d41343862ea4e6fae0 | [
"BSD-4-Clause-UC"
] | 71 | 2015-03-26T10:28:04.000Z | 2021-11-07T10:09:12.000Z | //shadow map not working in MacOSX
// basic STL streams
#include <iostream>
// GLEW lib
// http://glew.sourceforge.net/basic.html
#include <GL/glew.h>
//Update 04/08/16
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <ImGUI/imgui.h>
#include <ImGUI/imgui_impl_sdl.h>
#include <ImGUI/imgui_impl_opengl3.h>
// Here we decide which of the two versions we want to use
// If your systems supports both, choose to uncomment USE_OPENGL32
// otherwise choose to uncomment USE_OPENGL21
// GLView cna also help you decide before running this program:
//
// FOR MACOSX only, please use OPENGL32 for AntTweakBar to work properly
//
#define USE_OPENGL32
#include <glGA/glGARigMesh.h>
// GLM lib
// http://glm.g-truc.net/api/modules.html
#define GLM_SWIZZLE
#define GLM_FORCE_INLINE
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/random.hpp>
#include <fstream>
//local
#include "glGA/glGAHelper.h"
#include "glGA/glGAMesh.h"
// number of Squares for Plane
#define NumOfSQ 50
// global variables
int windowWidth=1024, windowHeight=768;
//color
float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f };
GLuint programX, programY, programZ, programPlane, program3Dmodel, programPyramid;
GLuint vao, vaoX, vaoY, vaoZ, vaoPlane, vao3Dmodel, vaoPyramid;
GLuint bufferX, bufferY, bufferZ, bufferPlane, buffer3Dmodel, bufferPyramid;
GLuint eyes_uniform;
GLuint MV_uniformX , MVP_uniformX;
GLuint MV_uniformY , MVP_uniformY;
GLuint MV_uniformZ , MVP_uniformZ;
GLuint MV_uniformPlane , MVP_uniformPlane , Normal_uniformPlane, V_uniformPlane;
GLuint MV_uniform3D , MVP_uniform3D , Normal_uniform3D , V_uniform3D;
GLuint MV_uniformPyramid , MVP_uniform_Pyramid;
GLuint MVlight;
GLuint TextureMatrix_Uniform;
int timesc = 0;
GLuint gSampler1,gSampler;
Texture *pTexture = NULL;
Mesh *m = NULL;
const int NumVerticesl = 2;
const int NumVerticesSQ = ( (NumOfSQ) * (NumOfSQ)) * (2) * (3);
bool wireFrame = false;
bool camera = false;
typedef glm::vec4 color4;
typedef glm::vec4 point4;
int IndexSQ = 0;
int IndexPyramid = 0;
//Modelling arrays
point4 pointPyramid[18];
color4 colorPyramid[18];
point4 pointsq[NumVerticesSQ];
color4 colorsq[NumVerticesSQ];
glm::vec3 normalsq[NumVerticesSQ];
glm::vec4 tex_coords[NumVerticesSQ];
glm::vec3 pos = glm::vec3( 3.0f, 4.0f , 10.0f );
float horizAngle = 3.14f;
float verticAngle = 0.0f;
int divideFactor = 2;
float speedo = 9.0f;
float mouseSpeedo = 0.005f;
int xpos = 0,ypos = 0;
struct Lights
{
GLint activeLight;
GLfloat ambient[4];
GLfloat diffuse[4];
GLfloat specular[4];
GLfloat position[4];
glm::vec3 spotDirection;
GLfloat spotExponent;
GLfloat spotCutoff;
// (range: [0.0,90.0], 180.0)
GLfloat spotCosCutoff; // Derived: cos(Crli)
// (range: [1.0,0.0],-1.0)
GLfloat constantAttenuation;
GLfloat linearAttenuation;
GLfloat quadraticAttenuation;
};
struct MaterialProperties
{
GLfloat emission[4];
GLfloat ambient[4];
GLfloat diffuse[4];
GLfloat specular[4];
GLfloat shininess;
};
struct MaterialProperties *frontMaterial,*backMaterial;
struct FogProperties
{
int enable;
float density;
float start;
float end;
glm::vec4 color;
enum equation{FOG_EQUATION_LINEAR , FOG_EQUATION_EXP, FOG_EQUATION_EXP2};
equation pick;
float scale;
};
struct FogProperties *Fog;
int maxLights = 0; // maximum number of dynamic lights allowed by the graphic card
Lights *lights = NULL; // array of lights
MaterialProperties *materials = NULL;
//Plane
point4 planeVertices[NumVerticesSQ];
color4 planeColor[NumVerticesSQ];
//update 04/08/16
SDL_Window *gWindow = NULL;
SDL_GLContext gContext;
//Vertices of a XYZ axis
// X - axis
point4 Xvertices[2] = {
point4( 0.0, 0.0 , 0.0 , 1.0),
point4( 5.0, 0.0 , 0.0 , 1.0)
};
color4 Xvertex_color[2] = {
color4( 1.0, 0.0, 0.0, 1.0),
color4( 1.0, 0.0, 0.0, 1.0)
};
// Y - axis
point4 Yvertices[2] = {
point4( 0.0, 0.0, 0.0, 1.0),
point4( 0.0, 5.0, 0.0, 1.0)
};
color4 Yvertex_color[2] = {
color4( 0.0, 1.0, 0.0, 1.0),
color4( 0.0, 1.0, 0.0, 1.0)
};
// Z - axis
point4 Zvertices[2] = {
point4( 0.0, 0.0, 0.0, 1.0),
point4( 0.0, 0.0, 5.0, 1.0)
};
color4 Zvertex_color[2] = {
color4( 0.0, 0.0, 1.0, 1.0),
color4( 0.0, 0.0, 1.0, 1.0)
};
point4 Pyramid[5] = {
point4(-1.0, 6.0, 1.0, 1.0),
point4(-1.0, 6.0,-1.0, 1.0),
point4( 1.0, 6.0,-1.0, 1.0),
point4( 1.0, 6.0, 1.0, 1.0),
point4( 0.0, 9.0, 0.0, 1.0)
};
color4 PyramidsColor[5] = {
color4(0.1, 1.0, 0.1, 1.0),
color4(0.1, 1.0, 0.1, 1.0),
color4(0.1, 1.0, 0.1, 1.0),
color4(0.1, 1.0, 0.1, 1.0),
color4(0.1, 1.0, 0.1, 1.0)
};
// Update function prototypes
bool initSDL();
bool event_handler(SDL_Event* event);
void close();
void resize_window(int width, int height);
bool initImGui();
void displayGui();
// Update functions 04/08/16
bool initSDL()
{
//Init flag
bool success = true;
//Basic Setup
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl;
success = false;
}
else
{
std::cout << std::endl << "Yay! Initialized SDL succesfully!" << std::endl;
//Use OpenGL Core 3.2
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
//SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
#ifdef __APPLE__
SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
#endif
//Create Window
SDL_DisplayMode current;
SDL_GetCurrentDisplayMode(0, ¤t);
#ifdef __APPLE__
gWindow = SDL_CreateWindow("Chapter-9", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI );
divideFactor = 4;
#else
gWindow = SDL_CreateWindow("Chapter-9", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
#endif
if (gWindow == NULL)
{
std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl;
success = false;
}
else
{
std::cout << std::endl << "Yay! Created window sucessfully!" << std::endl << std::endl;
//Create context
gContext = SDL_GL_CreateContext(gWindow);
if (gContext == NULL)
{
std::cout << "OpenGL context could not be created! SDL Error: " << SDL_GetError() << std::endl;
success = false;
}
else
{
//Initialize GLEW
glewExperimental = GL_TRUE;
GLenum glewError = glewInit();
if (glewError != GLEW_OK)
{
std::cout << "Error initializing GLEW! " << glewGetErrorString(glewError) << std::endl;
}
//Use Vsync
if (SDL_GL_SetSwapInterval(1) < 0)
{
std::cout << "Warning: Unable to set Vsync! SDL Error: " << SDL_GetError() << std::endl;
}
//Initializes ImGui
if (!initImGui())
{
std::cout << "Error initializing ImGui! " << std::endl;
success = false;
}
//Init glViewport first time;
resize_window(windowWidth, windowHeight);
}
}
}
return success;
}
bool event_handler(SDL_Event* event)
{
switch (event->type)
{
case SDL_WINDOWEVENT:
{
if (event->window.event == SDL_WINDOWEVENT_RESIZED)
{
resize_window(event->window.data1, event->window.data2);
}
}
case SDL_MOUSEWHEEL:
{
return true;
}
case SDL_MOUSEBUTTONDOWN:
{
if (event->button.button == SDL_BUTTON_LEFT)
if (event->button.button == SDL_BUTTON_RIGHT)
if (event->button.button == SDL_BUTTON_MIDDLE)
return true;
}
case SDL_TEXTINPUT:
{
return true;
}
case SDL_KEYDOWN:
{
if (event->key.keysym.sym == SDLK_w)
{
if (wireFrame)
{
wireFrame = false;
}
else
{
wireFrame = true;
}
return true;
}
if (event->key.keysym.sym == SDLK_SPACE)
{
if (camera == false)
{
camera = true;
SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor);
SDL_GetMouseState(&xpos, &ypos);
}
else
{
camera = false;
SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor);
SDL_GetMouseState(&xpos, &ypos);
}
return true;
}
return true;
}
case SDL_KEYUP:
{
return true;
}
case SDL_MOUSEMOTION:
{
return true;
}
}
return false;
}
void close()
{
//Cleanup
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
SDL_GL_DeleteContext(gContext);
SDL_DestroyWindow(gWindow);
SDL_Quit();
}
void resize_window(int width, int height)
{
// Set OpenGL viewport and default camera
glViewport(0, 0, width, height);
//float aspect = (GLfloat)width / (GLfloat)height;
windowWidth = width;
windowHeight = height;
}
bool initImGui()
{
// Setup ImGui binding
IMGUI_CHECKVERSION();
ImGui::SetCurrentContext(ImGui::CreateContext());
// Setup ImGui binding
if (!ImGui_ImplOpenGL3_Init("#version 150"))
{
return false;
}
if (!ImGui_ImplSDL2_InitForOpenGL(gWindow, gContext))
{
return false;
}
// Load Fonts
// (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
// Marios -> in order to use custom Fonts,
//there is a file named extra_fonts inside /_thirdPartyLibs/include/ImGUI/extra_fonts
//Uncomment the next line -> ImGui::GetIO() and one of the others -> io.Fonts->AddFontFromFileTTF("", 15.0f).
//Important : Make sure to check the first parameter is the correct file path of the .ttf or you get an assertion.
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("../../_thirdPartyLibs/include/ImGUI/extra_fonts/Karla-Regular.ttf", 14.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
//io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
return true;
}
void displayGui()
{
//ImGui::SetNextWindowSize(ImVec2(200, 200));
//ImGui::SetWindowPos(ImVec2(10, 10));
ImGui::Begin("Main");
ImGui::SetWindowSize(ImVec2(200, 200), ImGuiSetCond_Once);
ImGui::SetWindowPos(ImVec2(0, 0), ImGuiSetCond_Once);
static bool checkbox = false;
if (ImGui::Checkbox("Wireframe", &checkbox))
{
if (checkbox == false)
wireFrame = false;
else
wireFrame = true;
}
ImGui::Separator();
ImGui::ColorEdit3("Background Color", bgColor);
ImGui::Separator();
if (ImGui::TreeNode("Fog properties"))
{
ImGui::SliderInt("Fog Enable", &Fog->enable, 0, 1);
ImGui::InputFloat("Fog Start", &Fog->start, (1.0F), (5.0F), 2);
ImGui::InputFloat("Fog End", &Fog->end, (1.0F), (5.0F), 2);
ImGui::InputFloat("Fog Density", &Fog->density, (0.01F), (0.02F), 2);
if (Fog->start > 100.0f)
Fog->start = 100.0f;
if (Fog->start < 0.0f)
Fog->start = 0.0f;
if (Fog->end > 100.0f)
Fog->end = 100.0f;
if (Fog->end < 0.0f)
Fog->end = 0.0f;
if (Fog->density < 0.01f)
Fog->density = 0.01f;
const char* items[] = { "Linear Equation", "Exp Equation", "Exp2 Equation" };
static int current_item = 0;
ImGui::Combo("Fog Equation", ¤t_item, items, 3);
if (current_item == 0)
Fog->pick = FogProperties::FOG_EQUATION_LINEAR;
else if (current_item == 1)
Fog->pick = FogProperties::FOG_EQUATION_EXP;
else
Fog->pick = FogProperties::FOG_EQUATION_EXP2;
ImGui::ColorEdit3("Fog Color", (float*)&Fog->color);
ImGui::TreePop();
}
ImGui::End();
ImGui::Begin("Lights-Materials");
ImGui::SetWindowPos(ImVec2(10, 220), ImGuiSetCond_Once);
ImGui::SetWindowSize(ImVec2(200, 200), ImGuiSetCond_Once);
if (ImGui::TreeNode("Edit Lights"))
{
if (ImGui::TreeNode("Light #1"))
{
ImGui::SliderInt("activeLight", &lights[0].activeLight, 0, 1);
ImGui::ColorEdit3("Ambient", lights[0].ambient);
ImGui::ColorEdit3("Diffuse", lights[0].diffuse);
ImGui::ColorEdit3("Specular", lights[0].specular);
if (ImGui::TreeNode("Position"))
{
ImGui::SliderFloat3("Position", lights[0].position, -100.0f, 100.0f, "%.2f");
ImGui::InputFloat("X", &lights[0].position[0], 0.5F, 0.1F, 2);
ImGui::InputFloat("Y", &lights[0].position[1], 0.5F, 0.1F, 2);
ImGui::InputFloat("Z", &lights[0].position[2], 0.5F, 0.1F, 2);
ImGui::TreePop();
}
ImGui::InputFloat("spotCutoff", &lights[0].spotCutoff, 1.0F, 5.0F, 2);
ImGui::InputFloat("spotCosCutoff", &lights[0].spotCosCutoff, 1.0F, 5.0F, 2);
ImGui::TreePop();
}
ImGui::Separator();
if (ImGui::TreeNode("Light #2"))
{
ImGui::SliderInt("activeLight", &lights[1].activeLight, 0, 1);
ImGui::ColorEdit3("Ambient", lights[1].ambient);
ImGui::ColorEdit3("Diffuse", lights[1].diffuse);
ImGui::ColorEdit3("Specular", lights[1].specular);
if (ImGui::TreeNode("Position"))
{
ImGui::SliderFloat3("Position", lights[1].position, -100.0f, 100.0f, "%.2f");
ImGui::InputFloat("X", &lights[1].position[0], 0.5F, 0.1F, 2);
ImGui::InputFloat("Y", &lights[1].position[1], 0.5F, 0.1F, 2);
ImGui::InputFloat("Z", &lights[1].position[2], 0.5F, 0.1F, 2);
ImGui::TreePop();
}
ImGui::InputFloat("spotCutoff", &lights[1].spotCutoff, 1.0F, 5.0F, 2);
ImGui::InputFloat("spotCosCutoff", &lights[1].spotCosCutoff, 1.0F, 5.0F, 2);
ImGui::TreePop();
}
ImGui::Separator();
if (ImGui::TreeNode("Light #3"))
{
ImGui::SliderInt("activeLight", &lights[2].activeLight, 0, 1);
ImGui::ColorEdit3("Ambient", lights[2].ambient);
ImGui::ColorEdit3("Diffuse", lights[2].diffuse);
ImGui::ColorEdit3("Specular", lights[2].specular);
if (ImGui::TreeNode("Position"))
{
ImGui::SliderFloat3("Position", lights[2].position, -100.0f, 100.0f, "%.2f");
ImGui::InputFloat("X", &lights[2].position[0], 0.5F, 0.1F, 2);
ImGui::InputFloat("Y", &lights[2].position[1], 0.5F, 0.1F, 2);
ImGui::InputFloat("Z", &lights[2].position[2], 0.5F, 0.1F, 2);
ImGui::TreePop();
}
ImGui::InputFloat("spotCutoff", &lights[2].spotCutoff, 1.0F, 5.0F, 2);
ImGui::InputFloat("spotCosCutoff", &lights[2].spotCosCutoff, 1.0F, 5.0F, 2);
ImGui::TreePop();
}
ImGui::Separator();
if (ImGui::TreeNode("Light #4"))
{
ImGui::SliderInt("activeLight", &lights[3].activeLight, 0, 1);
ImGui::ColorEdit3("Ambient", lights[3].ambient);
ImGui::ColorEdit3("Diffuse", lights[3].diffuse);
ImGui::ColorEdit3("Specular", lights[3].specular);
if (ImGui::TreeNode("Position"))
{
ImGui::SliderFloat3("Position", lights[3].position, -100.0f, 100.0f, "%.2f");
ImGui::InputFloat("X", &lights[3].position[0], 0.5F, 0.1F, 2);
ImGui::InputFloat("Y", &lights[3].position[1], 0.5F, 0.1F, 2);
ImGui::InputFloat("Z", &lights[3].position[2], 0.5F, 0.1F, 2);
ImGui::TreePop();
}
ImGui::InputFloat("spotCutoff", &lights[3].spotCutoff, 1.0F, 5.0F, 2);
ImGui::InputFloat("spotCosCutoff", &lights[3].spotCosCutoff, 1.0F, 5.0F, 2);
ImGui::TreePop();
}
ImGui::Separator();
if (ImGui::TreeNode("Light #5"))
{
ImGui::SliderInt("activeLight", &lights[4].activeLight, 0, 1);
ImGui::ColorEdit3("Ambient", lights[4].ambient);
ImGui::ColorEdit3("Diffuse", lights[4].diffuse);
ImGui::ColorEdit3("Specular", lights[4].specular);
if (ImGui::TreeNode("Position"))
{
ImGui::SliderFloat3("Position", lights[4].position, -100.0f, 100.0f, "%.2f");
ImGui::InputFloat("X", &lights[4].position[0], 0.5F, 0.1F, 2);
ImGui::InputFloat("Y", &lights[4].position[1], 0.5F, 0.1F, 2);
ImGui::InputFloat("Z", &lights[4].position[2], 0.5F, 0.1F, 2);
ImGui::TreePop();
}
ImGui::InputFloat("spotCutoff", &lights[4].spotCutoff, 1.0F, 5.0F, 2);
ImGui::InputFloat("spotCosCutoff", &lights[4].spotCosCutoff, 1.0F, 5.0F, 2);
ImGui::TreePop();
}
ImGui::TreePop();
}
ImGui::Separator();
if (ImGui::TreeNode("Materials"))
{
if (ImGui::TreeNode("FrontMaterial"))
{
ImGui::ColorEdit4("Ambient", frontMaterial->ambient);
ImGui::ColorEdit4("Diffuse", frontMaterial->diffuse);
ImGui::ColorEdit4("Specular", frontMaterial->specular);
ImGui::ColorEdit4("Emission", frontMaterial->emission);
ImGui::SliderFloat("Shininess", &frontMaterial->shininess, 0.0f, 100.0f, "%.2f");
ImGui::TreePop();
}
ImGui::Separator();
if (ImGui::TreeNode("BackMaterial"))
{
ImGui::ColorEdit4("Ambient", backMaterial->ambient);
ImGui::ColorEdit4("Diffuse", backMaterial->diffuse);
ImGui::ColorEdit4("Specular", backMaterial->specular);
ImGui::ColorEdit4("Emission", backMaterial->emission);
ImGui::SliderFloat("Shininess", &backMaterial->shininess, 0.0f, 100.0f, "%.2f");
ImGui::TreePop();
}
ImGui::TreePop();
}
ImGui::End();
}
int getActiveLights(Lights *ptr)
{
int activeLight = 0;
if(ptr == NULL)
{
return activeLight;
}
else
{
for(int i=0;i<maxLights;i++)
{
if(ptr[i].activeLight == 1)
{
activeLight++;
}
}
return activeLight;
}
}
void initLights()
{
// Get the max number of lights allowed by the graphic card
glGetIntegerv(GL_MAX_LIGHTS, &maxLights);
if(maxLights > 8)
{
maxLights = 5;
}
maxLights = 5;
lights = new Lights[maxLights];
for(int i=0;i<maxLights;i++)
{
lights[i].activeLight = 0;
}
//#Light-1- Directional Light
lights[0].activeLight = 0;
lights[0].ambient[0] = 0.3f;lights[0].ambient[1] = 0.3f;lights[0].ambient[2] = 0.3f;lights[0].ambient[3] = 1.0f;
lights[0].diffuse[0] = 1.0f;lights[0].diffuse[1] = 1.0f;lights[0].diffuse[2] = 1.0f;lights[0].diffuse[3] = 1.0f;
lights[0].specular[0] = 1.0f;lights[0].specular[1] = 1.0f;lights[0].specular[2] = 1.0f;lights[0].specular[3] = 1.0f;
lights[0].position[0] = 10.0f;lights[0].position[1] = 1.0f;lights[0].position[2] = 0.0f;lights[0].position[3] = 0.0f;
//#Light-2- Point Light
lights[1].activeLight = 0;
lights[1].ambient[0] = 0.3f;lights[1].ambient[1] = 0.3f;lights[1].ambient[2] = 0.3f;lights[1].ambient[3] = 1.0f;
lights[1].diffuse[0] = 1.0f;lights[1].diffuse[1] = 1.0f;lights[1].diffuse[2] = 1.0f;lights[1].diffuse[3] = 1.0f;
lights[1].specular[0] = 1.0f;lights[1].specular[1] = 1.0f;lights[1].specular[2] = 1.0f;lights[1].specular[3] = 1.0f;
lights[1].position[0] = -4.5f;lights[1].position[1] = 1.0f;lights[1].position[2] = 4.0f;lights[1].position[3] = 1.0f;
lights[1].constantAttenuation = 1.0f;lights[1].linearAttenuation = 0.0f;lights[1].quadraticAttenuation = 0.0f;
lights[1].spotCutoff = 180.0f;
//#lights-2- Point Light
lights[2].activeLight = 0;
lights[2].ambient[0] = 0.3f;lights[2].ambient[1] = 0.3f;lights[2].ambient[2] = 0.3f;lights[2].ambient[3] = 1.0f;
lights[2].diffuse[0] = 1.0f;lights[2].diffuse[1] = 1.0f;lights[2].diffuse[2] = 1.0f;lights[2].diffuse[3] = 1.0f;
lights[2].specular[0] = 1.0f;lights[2].specular[1] = 1.0f;lights[2].specular[2] = 1.0f;lights[2].specular[3] = 1.0f;
lights[2].position[0] = -4.5f;lights[2].position[1] = 1.0f;lights[2].position[2] = -4.0f;lights[2].position[3] = 1.0f;
lights[2].constantAttenuation = 1.0f;lights[2].linearAttenuation = 0.0f;lights[2].quadraticAttenuation = 0.0f;
lights[2].spotCutoff = 180.0f;
//#lights-3- Spot Light
lights[3].activeLight = 0;
lights[3].ambient[0] = 0.3f;lights[3].ambient[1] = 0.3f;lights[3].ambient[2] = 0.3f;lights[3].ambient[3] = 1.0f;
lights[3].diffuse[0] = 1.0f;lights[3].diffuse[1] = 1.0f;lights[3].diffuse[2] = 1.0f;lights[3].diffuse[3] = 1.0f;
lights[3].specular[0] = 1.0f;lights[3].specular[1] = 1.0f;lights[3].specular[2] = 1.0f;lights[3].specular[3] = 1.0f;
lights[3].position[0] = -4.5f;lights[3].position[1] = 1.0f;lights[3].position[2] = 4.0f;lights[3].position[3] = 1.0f;
lights[3].constantAttenuation = 1.0f;lights[3].linearAttenuation = 0.0f;lights[3].quadraticAttenuation = 0.0f;
lights[3].spotCutoff = 45.0f;
lights[3].spotDirection = glm::vec3(-1.0f,-1.0f,1.0f);
lights[3].spotExponent = 15.0f;
lights[3].spotCosCutoff = glm::cos(glm::radians(glm::clamp(lights[3].spotCutoff,0.0f,90.0f)));
//#lights-4- Spot Light
lights[4].activeLight = 0;
lights[4].ambient[0] = 0.3f;lights[4].ambient[1] = 0.3f;lights[4].ambient[2] = 0.3f;lights[4].ambient[3] = 1.0f;
lights[4].diffuse[0] = 1.0f;lights[4].diffuse[1] = 1.0f;lights[4].diffuse[2] = 1.0f;lights[4].diffuse[3] = 1.0f;
lights[4].specular[0] = 1.0f;lights[4].specular[1] = 1.0f;lights[4].specular[2] = 1.0f;lights[4].specular[3] = 1.0f;
lights[4].position[0] = -4.5f;lights[4].position[1] = 1.0f;lights[4].position[2] = -4.0f;lights[4].position[3] = 1.0f;
lights[4].constantAttenuation = 1.0f;lights[4].linearAttenuation = 0.0f;lights[4].quadraticAttenuation = 0.0f;
lights[4].spotCutoff = 45.0f;
lights[4].spotDirection = glm::vec3(-1.0f,-1.0f,1.0f);
lights[4].spotExponent = 40.0f;
lights[4].spotCosCutoff = glm::cos(glm::radians(glm::clamp(lights[4].spotCutoff,0.0f,90.0f)));
}
void initMaterials()
{
frontMaterial = new MaterialProperties;
frontMaterial->ambient[0] = 0.2f;frontMaterial->ambient[1] = 0.2f;frontMaterial->ambient[2] = 0.2f;frontMaterial->ambient[3] = 1.0f;
frontMaterial->diffuse[0] = 1.0f;frontMaterial->diffuse[1] = 0.8f;frontMaterial->diffuse[2] = 0.8f;frontMaterial->diffuse[3] = 1.0f;
frontMaterial->specular[0] = 1.0f;frontMaterial->specular[1] = 1.0f;frontMaterial->specular[2] = 1.0f;frontMaterial->specular[3] = 1.0f;
frontMaterial->emission[0] = 0.0f;frontMaterial->emission[1] = 0.0f;frontMaterial->emission[2] = 0.0f;frontMaterial->emission[3] = 1.0f;
frontMaterial->shininess = 5.0f;
backMaterial = new MaterialProperties;
backMaterial->ambient[0] = 0.2f;backMaterial->ambient[1] = 0.2f;backMaterial->ambient[2] = 0.2f;backMaterial->ambient[3] = 1.0f;
backMaterial->diffuse[0] = 0.0f;backMaterial->diffuse[1] = 0.0f;backMaterial->diffuse[2] = 1.0f;backMaterial->diffuse[3] = 1.0f;
backMaterial->specular[0] = 1.0f;backMaterial->specular[1] = 1.0f;backMaterial->specular[2] = 1.0f;backMaterial->specular[3] = 1.0f;
backMaterial->emission[0] = 0.0f;backMaterial->emission[1] = 0.0f;backMaterial->emission[2] = 0.0f;backMaterial->emission[3] = 1.0f;
backMaterial->shininess = 5.0f;
}
void initFog()
{
Fog = new FogProperties;
Fog->enable = 1;
Fog->density = 0.1f;
Fog->start = 0.0f;
Fog->end = 20.0f;
Fog->color = glm::vec4(0.7f, 0.7f, 0.7f, 1.0f);
Fog->pick = (FogProperties::equation)(FogProperties::FOG_EQUATION_LINEAR);
Fog->scale = 1.0f / (Fog->end - Fog->start);
}
void LoadUniforms(GLuint program)
{
//Load Lights
//Directional Light -1-
glUniform1iv( glGetUniformLocation(program, "lights[0].activeLight"),1,&(lights[0].activeLight));
glUniform4fv( glGetUniformLocation(program, "lights[0].ambient"),1,lights[0].ambient);
glUniform4fv( glGetUniformLocation(program, "lights[0].diffuse"),1,lights[0].diffuse);
glUniform4fv( glGetUniformLocation(program, "lights[0].specular"),1,lights[0].specular);
glUniform4fv( glGetUniformLocation(program, "lights[0].position"),1,lights[0].position);
//Point Light -2-
glUniform1iv( glGetUniformLocation(program, "lights[1].activeLight"),1,&(lights[1].activeLight));
glUniform4fv( glGetUniformLocation(program, "lights[1].ambient"),1,lights[1].ambient);
glUniform4fv( glGetUniformLocation(program, "lights[1].diffuse"),1,lights[1].diffuse);
glUniform4fv( glGetUniformLocation(program, "lights[1].specular"),1,lights[1].specular);
glUniform4fv( glGetUniformLocation(program, "lights[1].position"),1,lights[1].position);
glUniform1fv( glGetUniformLocation(program, "lights[1].constantAttenuation"),1,&(lights[1].constantAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[1].linearAttenuation"),1,&(lights[1].linearAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[1].quadraticAttenuation"),1,&(lights[1].quadraticAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[1].spotCutoff"),1,&(lights[1].spotCutoff));
//Point Light -3-
glUniform1iv( glGetUniformLocation(program, "lights[2].activeLight"),1,&(lights[2].activeLight));
glUniform4fv( glGetUniformLocation(program, "lights[2].ambient"),1,lights[2].ambient);
glUniform4fv( glGetUniformLocation(program, "lights[2].diffuse"),1,lights[2].diffuse);
glUniform4fv( glGetUniformLocation(program, "lights[2].specular"),1,lights[2].specular);
glUniform4fv( glGetUniformLocation(program, "lights[2].position"),1,lights[2].position);
glUniform1fv( glGetUniformLocation(program, "lights[2].constantAttenuation"),1,&(lights[2].constantAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[2].linearAttenuation"),1,&(lights[2].linearAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[2].quadraticAttenuation"),1,&(lights[2].quadraticAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[2].spotCutoff"),1,&(lights[2].spotCutoff));
//Spot Light -4-
glUniform1iv( glGetUniformLocation(program, "lights[3].activeLight"),1,&(lights[3].activeLight));
glUniform4fv( glGetUniformLocation(program, "lights[3].ambient"),1,lights[3].ambient);
glUniform4fv( glGetUniformLocation(program, "lights[3].diffuse"),1,lights[3].diffuse);
glUniform4fv( glGetUniformLocation(program, "lights[3].specular"),1,lights[3].specular);
glUniform4fv( glGetUniformLocation(program, "lights[3].position"),1,lights[3].position);
glUniform1fv( glGetUniformLocation(program, "lights[3].constantAttenuation"),1,&(lights[3].constantAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[3].linearAttenuation"),1,&(lights[3].linearAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[3].quadraticAttenuation"),1,&(lights[3].quadraticAttenuation));
glUniform1fv( glGetUniformLocation(program, "lights[3].spotCutoff"),1,&(lights[3].spotCutoff));
glUniform3fv( glGetUniformLocation(program, "lights[3].spotDirection"),1,glm::value_ptr(lights[3].spotDirection));
glUniform1fv( glGetUniformLocation(program, "lights[3].spotExponent"),1,&(lights[3].spotExponent));
lights[3].spotCosCutoff = glm::cos(glm::radians(glm::clamp(lights[3].spotCutoff,0.0f,90.0f)));
glUniform1fv( glGetUniformLocation(program, "lights[3].spotCosCutoff"),1,&(lights[3].spotCosCutoff));
//Spot Light -5-
//glUniform1iv( glGetUniformLocation(program, "lights[4].activeLight"),1,&(lights[4].activeLight));
//glUniform4fv( glGetUniformLocation(program, "lights[4].ambient"),1,lights[4].ambient);
//glUniform4fv( glGetUniformLocation(program, "lights[4].diffuse"),1,lights[4].diffuse);
//glUniform4fv( glGetUniformLocation(program, "lights[4].specular"),1,lights[4].specular);
//glUniform4fv( glGetUniformLocation(program, "lights[4].position"),1,lights[4].position);
//glUniform1fv( glGetUniformLocation(program, "lights[4].constantAttenuation"),1,&(lights[4].constantAttenuation));
//glUniform1fv( glGetUniformLocation(program, "lights[4].linearAttenuation"),1,&(lights[4].linearAttenuation));
//glUniform1fv( glGetUniformLocation(program, "lights[4].quadraticAttenuation"),1,&(lights[4].quadraticAttenuation));
//glUniform1fv( glGetUniformLocation(program, "lights[4].spotCutoff"),1,&(lights[4].spotCutoff));
//glUniform3fv( glGetUniformLocation(program, "lights[4].spotDirection"),1,glm::value_ptr(lights[4].spotDirection));
//glUniform1fv( glGetUniformLocation(program, "lights[4].spotExponent"),1,&(lights[4].spotExponent));
//glUniform1fv( glGetUniformLocation(program, "lights[4].spotCosCutoff"),1,&(lights[4].spotCosCutoff));
//Load Material Properties
glUniform4fv( glGetUniformLocation(program, "frontMaterial.ambient"),1,frontMaterial->ambient);
glUniform4fv( glGetUniformLocation(program, "frontMaterial.diffuse"),1,frontMaterial->diffuse);
glUniform4fv( glGetUniformLocation(program, "frontMaterial.specular"),1,frontMaterial->specular);
glUniform4fv( glGetUniformLocation(program, "frontMaterial.emission"),1,frontMaterial->emission);
glUniform1fv( glGetUniformLocation(program, "frontMaterial.shininess"),1,&(frontMaterial->shininess));
glUniform4fv( glGetUniformLocation(program, "backMaterial.ambient"),1,backMaterial->ambient);
glUniform4fv( glGetUniformLocation(program, "backMaterial.diffuse"),1,backMaterial->diffuse);
glUniform4fv( glGetUniformLocation(program, "backMaterial.specular"),1,backMaterial->specular);
glUniform4fv( glGetUniformLocation(program, "backMaterial.emission"),1,backMaterial->emission);
glUniform1fv( glGetUniformLocation(program, "backMaterial.shininess"),1,&(backMaterial->shininess));
glUniform1iv( glGetUniformLocation(program, "Fog.enable"),1,&(Fog->enable));
glUniform1fv( glGetUniformLocation(program, "Fog.density"),1,&(Fog->density));
glUniform1fv( glGetUniformLocation(program, "Fog.end"),1,&(Fog->end));
glUniform4fv( glGetUniformLocation(program, "Fog.color"),1,glm::value_ptr(Fog->color));
if(Fog->pick == (FogProperties::equation)(FogProperties::FOG_EQUATION_LINEAR))
{
int x = 0;
glUniform1iv( glGetUniformLocation(program, "Fog.equation"),1,&(x));
}
else if(Fog->pick == (FogProperties::equation)(FogProperties::FOG_EQUATION_EXP))
{
int x = 1;
glUniform1iv( glGetUniformLocation(program, "Fog.equation"),1,&(x));
}
else
{
int x = 2;
glUniform1iv( glGetUniformLocation(program, "Fog.equation"),1,&(x));
}
Fog->scale = 1.0f / (Fog->end - Fog->start);
glUniform1fv( glGetUniformLocation(program, "Fog.scale"),1,&(Fog->scale));
}
void quadSQ( int a, int b, int c, int d )
{
//specify temporary vectors along each quad's edge in order to compute the face
// normal using the cross product rule
glm::vec3 u = (planeVertices[b]-planeVertices[a]).xyz();
glm::vec3 v = (planeVertices[c]-planeVertices[b]).xyz();
glm::vec3 norm = glm::cross(u, v);
glm::vec3 normal= glm::normalize(norm);
normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a]; tex_coords[IndexSQ] = glm::vec4(0.0,1.0,0.0,0.0);IndexSQ++;
normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[b]; pointsq[IndexSQ] = planeVertices[b]; tex_coords[IndexSQ] = glm::vec4(1.0,1.0,0.0,0.0);IndexSQ++;
normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c]; tex_coords[IndexSQ] = glm::vec4(1.0,0.0,0.0,0.0);IndexSQ++;
normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[a]; pointsq[IndexSQ] = planeVertices[a]; tex_coords[IndexSQ] = glm::vec4(0.0,1.0,0.0,0.0);IndexSQ++;
normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[c]; pointsq[IndexSQ] = planeVertices[c]; tex_coords[IndexSQ] = glm::vec4(1.0,0.0,0.0,0.0);IndexSQ++;
normalsq[IndexSQ]=normal;colorsq[IndexSQ] = planeColor[d]; pointsq[IndexSQ] = planeVertices[d]; tex_coords[IndexSQ] = glm::vec4(0.0,0.0,0.0,0.0);IndexSQ++;
}
void init3Dmodel()
{
GLuint m_Buffers[4];
m = new Mesh();
m->loadMesh("./Models/box1/models/CargoCube01.dae");
//m->loadMesh("../../_glGA-data/data/models/sphere.dae");
glGenVertexArrays(1, &vao3Dmodel);
glBindVertexArray(vao3Dmodel);
//create the VBO
glGenBuffers(ARRAY_SIZE_IN_ELEMENTS(m_Buffers), m_Buffers);
//Load shaders and use the resulting shader program
program3Dmodel = LoadShaders("vshader3D.vert", "fshader3D.frag");
glUseProgram(program3Dmodel);
std::cout << "this is Position size : " << m->Positions.size() << " and this is Normal size : " << m->Normals.size() << " and this is TexCoords size : " << m->TexCoords.size() << std::endl;
std::cout << "this is numVertices " << m->numVertices << std::endl;
std::cout << "this is numSamplers " << m->m_TextureSamplers.size() << std::endl;
std::cout << "this is numTextures " << m->m_Textures.size() << std::endl;
// Vertex VBO
glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[POS_VB]);
glBufferData(GL_ARRAY_BUFFER, sizeof(m->Positions[0]) * m->Positions.size(), &m->Positions[0], GL_STATIC_DRAW);
// Connect vertex arrays to the the shader attributes: vPosition, vNormal, vTexCoord
GLuint vPositionMesh = glGetAttribLocation(program3Dmodel, "vPosition");
glEnableVertexAttribArray(vPositionMesh);
glVertexAttribPointer(vPositionMesh, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
//stop using previous VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);
// TEXCOORD VBO
glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[TEXCOORD_VB]);
glBufferData(GL_ARRAY_BUFFER, sizeof(m->TexCoords[0]) * m->TexCoords.size(), &m->TexCoords[0], GL_STATIC_DRAW);
GLuint vTexCoordMesh = glGetAttribLocation(program3Dmodel, "vTexCoord");
glEnableVertexAttribArray(vTexCoordMesh);
glVertexAttribPointer(vTexCoordMesh, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
//stop using previous VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Normal VBO
glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[NORMAL_VB]);
glBufferData(GL_ARRAY_BUFFER, sizeof(m->Normals[0]) * m->Normals.size(), &m->Normals[0], GL_STATIC_DRAW);
GLuint vNormalMesh = glGetAttribLocation(program3Dmodel, "vNormal");
glEnableVertexAttribArray(vNormalMesh);
glVertexAttribPointer(vNormalMesh, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
//stop using previous VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Index VBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Buffers[INDEX_BUFFER]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m->Indices[0]) * m->Indices.size(), &m->Indices[0], GL_STATIC_DRAW);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0, 0.0, 0.0, 1.0);
glBindVertexArray(0);
}
void initPyramid()
{
pointPyramid[0] = Pyramid[0]; pointPyramid[1] = Pyramid[1]; pointPyramid[2] = Pyramid[2];
pointPyramid[3] = Pyramid[0]; pointPyramid[4] = Pyramid[3]; pointPyramid[5] = Pyramid[2];
pointPyramid[6] = Pyramid[0]; pointPyramid[7] = Pyramid[4]; pointPyramid[8] = Pyramid[3];
pointPyramid[9] = Pyramid[0]; pointPyramid[10] = Pyramid[4]; pointPyramid[11] = Pyramid[1];
pointPyramid[12] = Pyramid[1]; pointPyramid[13] = Pyramid[4]; pointPyramid[14] = Pyramid[2];
pointPyramid[15] = Pyramid[2]; pointPyramid[16] = Pyramid[4]; pointPyramid[17] = Pyramid[3];
for(int i = 0;i < 18; i++)
{
colorPyramid[i] = PyramidsColor[0];
}
//generate and bind a VAO for the 3D axes
glGenVertexArrays(1, &vaoPyramid);
glBindVertexArray(vaoPyramid);
// Load shaders and use the resulting shader program
programPyramid = LoadShaders( "vPyramidShader.vert", "fPyramidShader.frag" );
glUseProgram( programPyramid );
// Create and initialize a buffer object on the server side (GPU)
//GLuint buffer;
glGenBuffers( 1, &bufferPyramid);
glBindBuffer( GL_ARRAY_BUFFER, bufferPyramid );
glBufferData( GL_ARRAY_BUFFER, sizeof(pointPyramid) + sizeof(colorPyramid),NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(pointPyramid), pointPyramid );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointPyramid), sizeof(colorPyramid), colorPyramid );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( programPyramid, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( programPyramid, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointPyramid)) );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.0, 0.0, 0.0, 1.0 );
// only one VAO can be bound at a time, so disable it to avoid altering it accidentally
//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void initX()
{
//generate and bind a VAO for the 3D axes
glGenVertexArrays(1, &vaoX);
glBindVertexArray(vaoX);
// Load shaders and use the resulting shader program
programX = LoadShaders( "vAxisShader.vert", "fAxisShader.frag" );
glUseProgram( programX );
// Create and initialize a buffer object on the server side (GPU)
//GLuint buffer;
glGenBuffers( 1, &bufferX );
glBindBuffer( GL_ARRAY_BUFFER, bufferX );
glBufferData( GL_ARRAY_BUFFER, sizeof(Xvertices) + sizeof(Xvertex_color),NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(Xvertices), Xvertices );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(Xvertices), sizeof(Xvertex_color), Xvertex_color );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( programX, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( programX, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(Xvertices)) );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.0, 0.0, 0.0, 1.0 );
// only one VAO can be bound at a time, so disable it to avoid altering it accidentally
//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void initY()
{
//generate and bind a VAO for the 3D axes
glGenVertexArrays(1, &vaoY);
glBindVertexArray(vaoY);
// Load shaders and use the resulting shader program
programY = LoadShaders("vAxisShader.vert", "fAxisShader.frag" );
glUseProgram( programY );
// Create and initialize a buffer object on the server side (GPU)
//GLuint buffer;
glGenBuffers( 1, &bufferY );
glBindBuffer( GL_ARRAY_BUFFER, bufferY );
glBufferData( GL_ARRAY_BUFFER, sizeof(Yvertices) + sizeof(Yvertex_color),NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(Yvertices), Yvertices );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(Yvertices), sizeof(Yvertex_color), Yvertex_color );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( programY, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( programY, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(Yvertices)) );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.0, 0.0, 0.0, 1.0 );
// only one VAO can be bound at a time, so disable it to avoid altering it accidentally
//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void initZ()
{
//generate and bind a VAO for the 3D axes
glGenVertexArrays(1, &vaoZ);
glBindVertexArray(vaoZ);
// Load shaders and use the resulting shader program
programZ = LoadShaders( "vAxisShader.vert", "fAxisShader.frag" );
glUseProgram( programZ );
// Create and initialize a buffer object on the server side (GPU)
//GLuint buffer;
glGenBuffers( 1, &bufferZ );
glBindBuffer( GL_ARRAY_BUFFER, bufferZ );
glBufferData( GL_ARRAY_BUFFER, sizeof(Zvertices) + sizeof(Zvertex_color),NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(Zvertices), Zvertices );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(Zvertices), sizeof(Zvertex_color), Zvertex_color );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( programZ, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( programZ, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(Zvertices)) );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.0, 0.0, 0.0, 1.0 );
// only one VAO can be bound at a time, so disable it to avoid altering it accidentally
//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void initPlane()
{
float numX =-10.0f,numX1 = -10.5f;
float numZ = -9.5f,numZ1 = -10.0f;
planeVertices[0] = point4 ( numX, 0.0, numZ1, 1.0); planeColor[0] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[1] = point4 ( numX, 0.0, numZ, 1.0); planeColor[1] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[2] = point4 ( numX1, 0.0, numZ, 1.0); planeColor[2] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[3] = point4 ( numX1, 0.0, numZ1, 1.0); planeColor[3] = color4 (0.603922, 0.803922, 0.196078, 1.0);
int k = 4;
int counter = 0;
for(k=4;k<NumVerticesSQ-4;k=k+4)
{
numX+=0.5f; numX1+=0.5f; counter++;
planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0);
if( counter == (NumOfSQ - 1) )
{
numX = -10.0f;numX1 = -10.5f;k+=4;
counter = 0;
numZ+=0.5f;numZ1+=0.5f;
planeVertices[k] = point4 (numX, 0.0, numZ1, 1.0); planeColor[k] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[k+1] = point4 (numX, 0.0, numZ, 1.0); planeColor[k+1] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[k+2] = point4 (numX1, 0.0, numZ, 1.0); planeColor[k+2] = color4 (0.603922, 0.803922, 0.196078, 1.0);
planeVertices[k+3] = point4 (numX1, 0.0, numZ1, 1.0); planeColor[k+3] = color4 (0.603922, 0.803922, 0.196078, 1.0);
cout << (k+3) << endl;
cout << NumVerticesSQ << endl;
}
}
//generate and bind a VAO for the 3D axes
glGenVertexArrays(1, &vaoPlane);
glBindVertexArray(vaoPlane);
pTexture = new Texture(GL_TEXTURE_2D,"./Textures/nvidia_logo.jpg");
//pTexture = new Texture(GL_TEXTURE_2D,"./Textures/NVIDIA.jpg");
if (!pTexture->loadTexture()) {
exit(EXIT_FAILURE);
}
int lp = 0,a=1,b=0,c=3,d=2;
for(lp = 0;lp < (NumOfSQ * NumOfSQ);lp++)
{
quadSQ(a,b,c,d);
a+=4;b+=4;c+=4;d+=4;
}
// Load shaders and use the resulting shader program
programPlane = LoadShaders( "vPlaneShader.vert", "fPlaneShader.frag" );
glUseProgram( programPlane );
// Create and initialize a buffer object on the server side (GPU)
//GLuint buffer;
glGenBuffers( 1, &bufferPlane );
glBindBuffer( GL_ARRAY_BUFFER, bufferPlane );
glBufferData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) + sizeof(tex_coords),NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(pointsq), pointsq );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq), sizeof(colorsq), colorsq );
glBufferSubData( GL_ARRAY_BUFFER,sizeof(pointsq) + sizeof(colorsq),sizeof(normalsq),normalsq );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq) ,sizeof(tex_coords) , tex_coords );
// set up vertex arrays
GLuint vPosition = glGetAttribLocation( programPlane, "MCvertex" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) );
GLuint vColor = glGetAttribLocation( programPlane, "vColor" );
glEnableVertexAttribArray( vColor );
glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq)) );
GLuint vNormal = glGetAttribLocation( programPlane, "vNormal" );
glEnableVertexAttribArray( vNormal );
glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq)) );
GLuint vText = glGetAttribLocation( programPlane, "MultiTexCoord0" );
glEnableVertexAttribArray( vText );
glVertexAttribPointer( vText, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(sizeof(pointsq) + sizeof(colorsq) + sizeof(normalsq)) );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.0, 0.0, 0.0, 1.0 );
// only one VAO can be bound at a time, so disable it to avoid altering it accidentally
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void checkActiveUniforms()
{
GLint nUniforms, maxLen;
glGetProgramiv( program3Dmodel, GL_ACTIVE_UNIFORM_MAX_LENGTH,&maxLen);
glGetProgramiv( program3Dmodel, GL_ACTIVE_UNIFORMS,&nUniforms);
GLchar * name = (GLchar *) malloc( maxLen );
GLint size, location;
GLsizei written;
GLenum type;
printf(" Location | Name\n");
printf("------------------------------------------------\n");
for( int i = 0; i < nUniforms; ++i ) {
glGetActiveUniform( program3Dmodel, i, maxLen, &written,&size, &type, name );
location = glGetUniformLocation(program3Dmodel, name);
printf(" %-8d | %s\n", location, name);
}
free(name);
}
void display3Dmodel(glm::mat4 &tsl,glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv)
{
glUseProgram(program3Dmodel);
glBindVertexArray(vao3Dmodel);
glDisable(GL_CULL_FACE);
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (wireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
MV_uniform3D = glGetUniformLocation(program3Dmodel, "MV_mat");
MVP_uniform3D = glGetUniformLocation(program3Dmodel, "MVP_mat");
Normal_uniform3D = glGetUniformLocation(program3Dmodel, "Normal_mat");
MVlight = glGetUniformLocation(program3Dmodel, "MVl_mat");
eyes_uniform = glGetUniformLocation(program3Dmodel, "eyes");
//Calculation of ModelView Matrix
glm::mat4 model_mat = tsl;
glm::mat4 view_mat = glm::lookAt(positionv,positionv + directionv,upv);
glm::mat4 Model = glm::mat4();
glm::mat4 ModelView = view_mat * Model;
glUniformMatrix4fv(MVlight,1, GL_FALSE, glm::value_ptr(ModelView));
glUniformMatrix4fv(V_uniform3D,1,GL_FALSE,glm::value_ptr(view_mat));
glm::mat4 MV_mat = view_mat * model_mat;
glUniformMatrix4fv(MV_uniform3D,1, GL_FALSE, glm::value_ptr(MV_mat));
//Calculation of Normal Matrix
glm::mat3 Normal_mat = glm::transpose(glm::inverse(glm::mat3(MV_mat)));
glUniformMatrix3fv(Normal_uniform3D,1, GL_FALSE, glm::value_ptr(Normal_mat));
//Calculation of ModelViewProjection Matrix
float aspect = (GLfloat)windowWidth / (GLfloat)windowHeight;
glm::mat4 projection_mat = glm::perspective(45.0f, aspect,0.1f,100.0f);
glm::mat4 MVP_mat = projection_mat * MV_mat;
glUniformMatrix4fv(MVP_uniform3D, 1, GL_FALSE, glm::value_ptr(MVP_mat));
glm::mat4 InView = glm::inverse(view_mat);
float eyse[] = {InView[3][0],InView[3][1],InView[3][2],InView[3][3]};
glm::vec4 eye = glm::vec4(positionv,1.0);
glUniform4fv(eyes_uniform,1,glm::value_ptr(eye));
gSampler1 = glGetUniformLocationARB(program3Dmodel, "gSampler1");
glUniform1iARB(gSampler1, 0);
LoadUniforms(program3Dmodel);
m->render();
if(timesc < 1)
checkActiveUniforms();
timesc++;
glPopAttrib();
glBindVertexArray(0);
//glUseProgram(0);
}
void displayPyramid(glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv)
{
glUseProgram(programPyramid);
glBindVertexArray(vaoPyramid);
glDisable(GL_CULL_FACE);
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (wireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
MV_uniformPyramid = glGetUniformLocation(programPyramid, "MV_mat");
MVP_uniform_Pyramid = glGetUniformLocation(programPyramid, "MVP_mat");
glUniform1fv( glGetUniformLocation(programPyramid, "Fog.density"),1,&(Fog->density));
glUniform1fv( glGetUniformLocation(programPyramid, "Fog.start"),1,&(Fog->start));
glUniform1fv( glGetUniformLocation(programPyramid, "Fog.end"),1,&(Fog->end));
glUniform4fv( glGetUniformLocation(programPyramid, "Fog.color"),1,glm::value_ptr(Fog->color));
// glUniform1iv( glGetUniformLocation(programPyramid, "Fog.equation"),1,&(Fog->equation));
glUniform1fv( glGetUniformLocation(programPyramid, "Fog.scale"),1,&(Fog->scale));
glUniform1iv( glGetUniformLocation(programPyramid, "Fog.enable"),1,&(Fog->enable));
// Calculation of ModelView Matrix
glm::mat4 model_mat_Pyramid = glm::mat4();
glm::mat4 view_mat_Pyramid = glm::lookAt(positionv,positionv + directionv,upv);
glm::mat4 MV_mat_Pyramid = view_mat_Pyramid * model_mat_Pyramid;
glUniformMatrix4fv(MV_uniformPyramid,1, GL_FALSE, glm::value_ptr(MV_mat_Pyramid));
// Calculation of ModelViewProjection Matrix
float aspect_Pyramid = (GLfloat)windowWidth / (GLfloat)windowHeight;
glm::mat4 projection_mat_Pyramid = glm::perspective(45.0f, aspect_Pyramid,0.1f,100.0f);
glm::mat4 MVP_mat_Pyramid = projection_mat_Pyramid * MV_mat_Pyramid;
glUniformMatrix4fv(MVP_uniform_Pyramid, 1, GL_FALSE, glm::value_ptr(MVP_mat_Pyramid));
glDrawArrays( GL_TRIANGLES, 0, 18);
glPopAttrib();
glBindVertexArray(0);
//glUseProgram(0);
}
void displayX(glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv)
{
glUseProgram(programX);
glBindVertexArray(vaoX);
glDisable(GL_CULL_FACE);
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (wireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
MV_uniformX = glGetUniformLocation(programX, "MV_mat");
MVP_uniformX = glGetUniformLocation(programX, "MVP_mat");
// Calculation of ModelView Matrix
glm::mat4 model_matx = glm::mat4();
glm::mat4 view_matx = glm::lookAt(positionv,positionv + directionv,upv);
glm::mat4 MV_matx = view_matx * model_matx;
glUniformMatrix4fv(MV_uniformX,1, GL_FALSE, glm::value_ptr(MV_matx));
// Calculation of ModelViewProjection Matrix
float aspectx = (GLfloat)windowWidth / (GLfloat)windowHeight;
glm::mat4 projection_matx = glm::perspective(45.0f, aspectx,0.1f,100.0f);
glm::mat4 MVP_matx = projection_matx * MV_matx;
glUniformMatrix4fv(MVP_uniformX, 1, GL_FALSE, glm::value_ptr(MVP_matx));
glDrawArrays( GL_LINES, 0, NumVerticesl );
glPopAttrib();
glBindVertexArray(0);
//glUseProgram(0);
}
void displayY(glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv)
{
glUseProgram(programY);
glBindVertexArray(vaoY);
glDisable(GL_CULL_FACE);
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (wireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
MV_uniformY = glGetUniformLocation(programY, "MV_mat");
MVP_uniformY = glGetUniformLocation(programY, "MVP_mat");
// Calculation of ModelView Matrix
glm::mat4 model_maty = glm::mat4();
glm::mat4 view_maty = glm::lookAt(positionv,positionv + directionv,upv);
glm::mat4 MV_maty = view_maty * model_maty;
glUniformMatrix4fv(MV_uniformY,1, GL_FALSE, glm::value_ptr(MV_maty));
// Calculation of ModelViewProjection Matrix
float aspecty = (GLfloat)windowWidth / (GLfloat)windowHeight;
glm::mat4 projection_maty = glm::perspective(45.0f, aspecty,0.1f,100.0f);
glm::mat4 MVP_maty = projection_maty * MV_maty;
glUniformMatrix4fv(MVP_uniformY, 1, GL_FALSE, glm::value_ptr(MVP_maty));
glDrawArrays( GL_LINES, 0, NumVerticesl );
glPopAttrib();
glBindVertexArray(0);
//glUseProgram(0);
}
void displayZ(glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv)
{
glUseProgram(programZ);
glBindVertexArray(vaoZ);
glDisable(GL_CULL_FACE);
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (wireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
MV_uniformZ = glGetUniformLocation(programZ, "MV_mat");
MVP_uniformZ = glGetUniformLocation(programZ, "MVP_mat");
// Calculation of ModelView Matrix
glm::mat4 model_matz = glm::mat4();
glm::mat4 view_matz = glm::lookAt(positionv,positionv + directionv,upv);
glm::mat4 MV_matz = view_matz * model_matz;
glUniformMatrix4fv(MV_uniformZ,1, GL_FALSE, glm::value_ptr(MV_matz));
// Calculation of ModelViewProjection Matrix
float aspect = (GLfloat)windowWidth / (GLfloat)windowHeight;
glm::mat4 projection_matz = glm::perspective(45.0f, aspect,0.1f,100.0f);
glm::mat4 MVP_matz = projection_matz * MV_matz;
glUniformMatrix4fv(MVP_uniformZ, 1, GL_FALSE, glm::value_ptr(MVP_matz));
glDrawArrays( GL_LINES, 0, NumVerticesl );
glPopAttrib();
glBindVertexArray(0);
//glUseProgram(0);
}
void displayPlane(glm::vec3 positionv,glm::vec3 directionv,glm::vec3 upv)
{
glUseProgram(programPlane);
glBindVertexArray(vaoPlane);
glDisable(GL_CULL_FACE);
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (wireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
V_uniformPlane = glGetUniformLocation(programPlane, "V_mat" );
MV_uniformPlane = glGetUniformLocation(programPlane, "MV_mat");
MVP_uniformPlane = glGetUniformLocation(programPlane, "MVP_mat");
Normal_uniformPlane = glGetUniformLocation(programPlane, "Normal_mat");
GLuint eyes_uniformPlane = glGetUniformLocation(programPlane, "eyes");
TextureMatrix_Uniform = glGetUniformLocation(programPlane, "TextureMatrix");
glm::mat4 TexMat = glm::mat4();
//TexMat = glm::scale(glm::mat4(1.0),glm::vec3(-2.0,-2.0,-2.0));
glUniformMatrix4fv(TextureMatrix_Uniform,1,GL_FALSE,glm::value_ptr(TexMat));
// Calculation of ModelView Matrix
glm::mat4 model_mat_plane = glm::mat4();
glm::mat4 view_mat_plane = glm::lookAt(positionv,positionv + directionv,upv);
glUniformMatrix4fv(V_uniformPlane,1,GL_FALSE, glm::value_ptr(view_mat_plane));
glm::mat4 MV_mat_plane = view_mat_plane * model_mat_plane;
glUniformMatrix4fv(MV_uniformPlane,1, GL_FALSE, glm::value_ptr(MV_mat_plane));
// Calculation of Normal Matrix
glm::mat3 Normal_mat_plane = glm::transpose(glm::inverse(glm::mat3(MV_mat_plane)));
glUniformMatrix3fv(Normal_uniformPlane,1, GL_FALSE, glm::value_ptr(Normal_mat_plane));
glm::mat4 InView = glm::inverse(view_mat_plane);
float eye[] = {InView[3][0],InView[3][1],InView[3][2],InView[3][3]};
glUniformMatrix4fv(eyes_uniformPlane,1,GL_FALSE,eye);
// Calculation of ModelViewProjection Matrix
float aspect_plane = (GLfloat)windowWidth / (GLfloat)windowHeight;
glm::mat4 projection_mat_plane = glm::perspective(45.0f, aspect_plane,0.1f,100.0f);
glm::mat4 MVP_mat_plane = projection_mat_plane * MV_mat_plane;
glUniformMatrix4fv(MVP_uniformPlane, 1, GL_FALSE, glm::value_ptr(MVP_mat_plane));
LoadUniforms(programPlane);
gSampler = glGetUniformLocationARB(programPlane, "gSampler");
glUniform1iARB(gSampler, 0);
pTexture->bindTexture(GL_TEXTURE0);
glDrawArrays( GL_TRIANGLES, 0, NumVerticesSQ );
//GLExitIfError();
//GLCheckError();
glPopAttrib();
glBindVertexArray(0);
//glUseProgram(0);
}
int main (int argc, char * argv[])
{
// Current time
double time = 0;
// initialise GLFW
int running = GL_TRUE;
if (!initSDL())
{
exit(EXIT_FAILURE);
}
glEnable(GL_TEXTURE_2D);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
initX(); // initialize X axis
initY(); // initialize Y axis
initZ(); // initialize Z axis
initPlane(); //initialize Plane
init3Dmodel(); // initialize 3D model
//initPyramid();
initLights(); // initialize Lighting of the Scene
initMaterials(); // initialize Material properties of the Objects and the Scene
initFog(); // initialize Fog Properties
// Initialize time
time = SDL_GetTicks();
uint32 currentTime;
uint32 lastTime = 0U;
#ifdef __APPLE__
int *w = (int*)malloc(sizeof(int));
int *h = (int*)malloc(sizeof(int));
#endif
while (running) {
glm::vec3 direction(cos(verticAngle) * sin(horizAngle), sin(verticAngle), cos(verticAngle) * cos(horizAngle));
glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f / 2.0f), 0, cos(horizAngle - 3.14f / 2.0f));
glm::vec3 up = glm::cross(right, direction);
currentTime = SDL_GetTicks();
float dTime = float(currentTime - lastTime) / 1000.0f;
lastTime = currentTime;
SDL_Event event;
while (SDL_PollEvent(&event))
{
ImGui_ImplSDL2_ProcessEvent(&event);
event_handler(&event);
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_UP)
pos += direction * dTime * speedo;
if (event.key.keysym.sym == SDLK_DOWN)
pos -= direction * dTime * speedo;
if (event.key.keysym.sym == SDLK_RIGHT)
pos += right * dTime * speedo;
if (event.key.keysym.sym == SDLK_LEFT)
pos -= right * dTime * speedo;
}
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)
{
running = GL_FALSE;
}
if (event.type == SDL_QUIT)
running = GL_FALSE;
}
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(gWindow);
ImGui::NewFrame();
glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );
glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color
if(camera == true)
{
SDL_GetMouseState(&xpos, &ypos);
SDL_WarpMouseInWindow(gWindow, windowWidth / divideFactor, windowHeight / divideFactor);
//glfwGetMousePos(&xpos,&ypos);
//glfwSetMousePos(windowWidth/2, windowHeight/2);
horizAngle += mouseSpeedo * float(windowWidth/divideFactor - xpos );
verticAngle += mouseSpeedo * float( windowHeight/divideFactor - ypos );
}
glm::mat4 cube1 = glm::mat4();
cube1 = glm::translate(cube1,glm::vec3(-4.0,1.0,4.0));
glm::mat4 cube2 = glm::mat4();
cube2 = glm::translate(cube2,glm::vec3(-4.0,1.0,-4.0));
glm::mat4 cube3 = glm::mat4();
cube3 = glm::translate(cube3,glm::vec3(4.0,1.0,-4.0));
glm::mat4 cube4 = glm::mat4();
cube4 = glm::translate(cube4,glm::vec3(4.0,1.0,4.0));
displayX(pos,direction,up);
displayY(pos,direction,up);
displayZ(pos,direction,up);
displayPlane(pos,direction,up);
//displayPyramid(pos,direction,up);
display3Dmodel(cube1,pos,direction,up);
display3Dmodel(cube2,pos,direction,up);
display3Dmodel(cube3,pos,direction,up);
display3Dmodel(cube4,pos,direction,up);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
displayGui();
ImGui::Render();
SDL_GL_MakeCurrent(gWindow, gContext);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(gWindow);
#ifdef __APPLE__
if(w!=NULL && h!=NULL){
SDL_GL_GetDrawableSize(gWindow, w, h);
resize_window(*w, *h);
}
#endif
}
//close OpenGL window and terminate ImGui and SDL2
close();
exit(EXIT_SUCCESS);
}
| 36.565614 | 195 | 0.678236 | [
"mesh",
"render",
"object",
"model",
"3d"
] |
c919001b16c19d9ec13cd4cbabb4d9aea37d04f3 | 1,491 | cpp | C++ | C-plus-plus/cpp_exercise/Chapter17/exercise7.cpp | dqhplhzz2008/Study-notes | 0df739d22add100e0f5976226abce34242fae57b | [
"MIT"
] | 11 | 2018-10-09T03:45:27.000Z | 2020-12-25T11:39:51.000Z | C-plus-plus/cpp_exercise/Chapter17/exercise7.cpp | dqhplhzz2008/Study-notes | 0df739d22add100e0f5976226abce34242fae57b | [
"MIT"
] | 2 | 2019-03-07T02:45:49.000Z | 2019-03-07T03:55:08.000Z | C-plus-plus/cpp_exercise/Chapter17/exercise7.cpp | dqhplhzz2008/Study-notes | 0df739d22add100e0f5976226abce34242fae57b | [
"MIT"
] | 7 | 2019-03-07T02:46:14.000Z | 2022-03-19T03:30:22.000Z | //C++ Primer Plus(5th Edition)
//Chapter 17 Exercise 7
//Modified by Yushuai Zhang
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
void ShowStr(const std::string & str)
{
std::cout << str << std::endl;
}
class Store
{
std::ofstream & of;
public:
Store(std::ofstream &out) :of(out) {}
void operator()(const std::string &str)
{
size_t len = str.size();
of.write((char*)&len, sizeof(std::size_t));
of.write(str.data(), len);
}
};
void GetStrs(std::ifstream &is, std::vector<std::string> &vec)
{
size_t len;
while (is.read((char *)&len, sizeof(size_t)))
{
char *st = new char[len];
is.read(st, len);
st[len + 1] = '\0';
vec.push_back(st);
}
}
int main()
{
using namespace std;
vector<string> vostr;
string temp;
cout << "Enter strings (empty line to quit):\n";
while (getline(cin, temp) && temp[0] != '\0')
vostr.push_back(temp);
cout << "Here is your input.\n";
for_each(vostr.begin(), vostr.end(), ShowStr);
ofstream fout("strings.txt", ios_base::out | ios_base::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));
fout.close();
vector<string> vistr;
ifstream fin("strings.txt", ios_base::in | ios_base::binary);
if (!fin.is_open())
{
cerr << "Could not open file for input.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the strings read form the file:\n";
for_each(vistr.begin(), vistr.end(), ShowStr);
system("pause");
return 0;
} | 22.253731 | 64 | 0.643863 | [
"vector"
] |
c924fd2dd6e3506ffe9e9800f61342f03e6aa454 | 110,480 | cc | C++ | content/browser/cache_storage/cache_storage_cache_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2022-02-10T00:36:35.000Z | 2022-02-10T00:36:35.000Z | content/browser/cache_storage/cache_storage_cache_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/cache_storage/cache_storage_cache_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <memory>
#include <set>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/notreached.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "components/services/storage/public/mojom/cache_storage_control.mojom.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/cache_storage/cache_storage_cache.h"
#include "content/browser/cache_storage/cache_storage_cache_handle.h"
#include "content/browser/cache_storage/cache_storage_histogram_utils.h"
#include "content/browser/cache_storage/cache_storage_manager.h"
#include "content/browser/cache_storage/legacy/legacy_cache_storage.h"
#include "content/browser/cache_storage/legacy/legacy_cache_storage_cache.h"
#include "content/common/background_fetch/background_fetch_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_utils.h"
#include "crypto/symmetric_key.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/data_pipe_drainer.h"
#include "net/base/test_completion_callback.h"
#include "net/base/url_util.h"
#include "net/disk_cache/disk_cache.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/browser/test/blob_test_utils.h"
#include "storage/browser/test/fake_blob.h"
#include "storage/browser/test/mock_quota_manager_proxy.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "storage/common/quota/padding_key.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h"
#include "url/origin.h"
using blink::FetchAPIRequestHeadersMap;
using blink::mojom::CacheStorageError;
using blink::mojom::CacheStorageVerboseErrorPtr;
namespace content {
namespace cache_storage_cache_unittest {
const char kTestData[] = "Hello World";
const char kCacheName[] = "test_cache";
const FetchAPIRequestHeadersMap kHeaders({{"a", "a"}, {"b", "b"}});
void SizeCallback(base::RunLoop* run_loop,
bool* callback_called,
int64_t* out_size,
int64_t size) {
*callback_called = true;
*out_size = size;
if (run_loop)
run_loop->Quit();
}
// A blob that never finishes writing to its pipe.
class SlowBlob : public storage::FakeBlob {
public:
explicit SlowBlob(base::OnceClosure quit_closure)
: FakeBlob("foo"), quit_closure_(std::move(quit_closure)) {}
void ReadAll(
mojo::ScopedDataPipeProducerHandle producer_handle,
mojo::PendingRemote<blink::mojom::BlobReaderClient> client) override {
// Don't respond, forcing the consumer to wait forever.
std::move(quit_closure_).Run();
}
private:
base::OnceClosure quit_closure_;
};
// A disk_cache::Backend wrapper that can delay operations.
class DelayableBackend : public disk_cache::Backend {
public:
explicit DelayableBackend(std::unique_ptr<disk_cache::Backend> backend)
: Backend(backend->GetCacheType()),
backend_(std::move(backend)),
delay_open_entry_(false) {}
// disk_cache::Backend overrides
int32_t GetEntryCount() const override { return backend_->GetEntryCount(); }
EntryResult OpenEntry(const std::string& key,
net::RequestPriority request_priority,
EntryResultCallback callback) override {
if (delay_open_entry_ && open_entry_callback_.is_null()) {
open_entry_callback_ =
base::BindOnce(&DelayableBackend::OpenEntryDelayedImpl,
base::Unretained(this), key, std::move(callback));
if (open_entry_started_callback_)
std::move(open_entry_started_callback_).Run();
return EntryResult::MakeError(net::ERR_IO_PENDING);
}
return backend_->OpenEntry(key, request_priority, std::move(callback));
}
EntryResult CreateEntry(const std::string& key,
net::RequestPriority request_priority,
EntryResultCallback callback) override {
return backend_->CreateEntry(key, request_priority, std::move(callback));
}
EntryResult OpenOrCreateEntry(const std::string& key,
net::RequestPriority request_priority,
EntryResultCallback callback) override {
return backend_->OpenOrCreateEntry(key, request_priority,
std::move(callback));
}
net::Error DoomEntry(const std::string& key,
net::RequestPriority request_priority,
CompletionOnceCallback callback) override {
return backend_->DoomEntry(key, request_priority, std::move(callback));
}
net::Error DoomAllEntries(CompletionOnceCallback callback) override {
return backend_->DoomAllEntries(std::move(callback));
}
net::Error DoomEntriesBetween(base::Time initial_time,
base::Time end_time,
CompletionOnceCallback callback) override {
return backend_->DoomEntriesBetween(initial_time, end_time,
std::move(callback));
}
net::Error DoomEntriesSince(base::Time initial_time,
CompletionOnceCallback callback) override {
return backend_->DoomEntriesSince(initial_time, std::move(callback));
}
int64_t CalculateSizeOfAllEntries(
Int64CompletionOnceCallback callback) override {
return backend_->CalculateSizeOfAllEntries(std::move(callback));
}
std::unique_ptr<Iterator> CreateIterator() override {
return backend_->CreateIterator();
}
void GetStats(base::StringPairs* stats) override {
return backend_->GetStats(stats);
}
void OnExternalCacheHit(const std::string& key) override {
return backend_->OnExternalCacheHit(key);
}
int64_t MaxFileSize() const override { return backend_->MaxFileSize(); }
// Call to continue a delayed call to OpenEntry.
bool OpenEntryContinue() {
if (open_entry_callback_.is_null())
return false;
std::move(open_entry_callback_).Run();
return true;
}
void set_delay_open_entry(bool value) { delay_open_entry_ = value; }
void set_open_entry_started_callback(
base::OnceClosure open_entry_started_callback) {
open_entry_started_callback_ = std::move(open_entry_started_callback);
}
private:
void OpenEntryDelayedImpl(const std::string& key,
EntryResultCallback callback) {
auto split_callback = base::SplitOnceCallback(std::move(callback));
EntryResult result =
backend_->OpenEntry(key, net::HIGHEST, std::move(split_callback.first));
if (result.net_error() != net::ERR_IO_PENDING)
std::move(split_callback.second).Run(std::move(result));
}
std::unique_ptr<disk_cache::Backend> backend_;
bool delay_open_entry_;
base::OnceClosure open_entry_callback_;
base::OnceClosure open_entry_started_callback_;
};
class FailableCacheEntry : public disk_cache::Entry {
public:
explicit FailableCacheEntry(disk_cache::Entry* entry) : entry_(entry) {}
void Doom() override { entry_->Doom(); }
void Close() override { entry_->Close(); }
std::string GetKey() const override { return entry_->GetKey(); }
base::Time GetLastUsed() const override { return entry_->GetLastUsed(); }
base::Time GetLastModified() const override {
return entry_->GetLastModified();
}
int32_t GetDataSize(int index) const override {
return entry_->GetDataSize(index);
}
int ReadData(int index,
int offset,
IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override {
return entry_->ReadData(index, offset, buf, buf_len, std::move(callback));
}
int WriteData(int index,
int offset,
IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback,
bool truncate) override {
std::move(callback).Run(net::ERR_FAILED);
return net::ERR_IO_PENDING;
}
int ReadSparseData(int64_t offset,
IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override {
return entry_->ReadSparseData(offset, buf, buf_len, std::move(callback));
}
int WriteSparseData(int64_t offset,
IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) override {
return entry_->WriteSparseData(offset, buf, buf_len, std::move(callback));
}
disk_cache::RangeResult GetAvailableRange(
int64_t offset,
int len,
disk_cache::RangeResultCallback callback) override {
return entry_->GetAvailableRange(offset, len, std::move(callback));
}
bool CouldBeSparse() const override { return entry_->CouldBeSparse(); }
void CancelSparseIO() override { entry_->CancelSparseIO(); }
net::Error ReadyForSparseIO(CompletionOnceCallback callback) override {
return entry_->ReadyForSparseIO(std::move(callback));
}
void SetLastUsedTimeForTest(base::Time time) override {
entry_->SetLastUsedTimeForTest(time);
}
private:
disk_cache::Entry* const entry_;
};
class FailableBackend : public disk_cache::Backend {
public:
enum class FailureStage { CREATE_ENTRY = 0, WRITE_HEADERS = 1 };
explicit FailableBackend(std::unique_ptr<disk_cache::Backend> backend,
FailureStage stage)
: Backend(backend->GetCacheType()),
backend_(std::move(backend)),
stage_(stage) {}
// disk_cache::Backend overrides
int32_t GetEntryCount() const override { return backend_->GetEntryCount(); }
EntryResult OpenOrCreateEntry(const std::string& key,
net::RequestPriority request_priority,
EntryResultCallback callback) override {
if (stage_ == FailureStage::CREATE_ENTRY) {
return EntryResult::MakeError(net::ERR_FILE_NO_SPACE);
} else if (stage_ == FailureStage::WRITE_HEADERS) {
return backend_->OpenOrCreateEntry(
key, request_priority,
base::BindOnce(
[](EntryResultCallback callback, disk_cache::EntryResult result) {
FailableCacheEntry failable_entry(result.ReleaseEntry());
EntryResult failable_result =
EntryResult::MakeCreated(&failable_entry);
std::move(callback).Run(std::move(failable_result));
},
std::move(callback)));
} else {
return backend_->OpenOrCreateEntry(key, request_priority,
std::move(callback));
}
}
EntryResult OpenEntry(const std::string& key,
net::RequestPriority request_priority,
EntryResultCallback callback) override {
return backend_->OpenEntry(key, request_priority, std::move(callback));
}
EntryResult CreateEntry(const std::string& key,
net::RequestPriority request_priority,
EntryResultCallback callback) override {
return backend_->CreateEntry(key, request_priority, std::move(callback));
}
net::Error DoomEntry(const std::string& key,
net::RequestPriority request_priority,
CompletionOnceCallback callback) override {
return backend_->DoomEntry(key, request_priority, std::move(callback));
}
net::Error DoomAllEntries(CompletionOnceCallback callback) override {
return backend_->DoomAllEntries(std::move(callback));
}
net::Error DoomEntriesBetween(base::Time initial_time,
base::Time end_time,
CompletionOnceCallback callback) override {
return backend_->DoomEntriesBetween(initial_time, end_time,
std::move(callback));
}
net::Error DoomEntriesSince(base::Time initial_time,
CompletionOnceCallback callback) override {
return backend_->DoomEntriesSince(initial_time, std::move(callback));
}
int64_t CalculateSizeOfAllEntries(
Int64CompletionOnceCallback callback) override {
return backend_->CalculateSizeOfAllEntries(std::move(callback));
}
std::unique_ptr<Iterator> CreateIterator() override {
return backend_->CreateIterator();
}
void GetStats(base::StringPairs* stats) override {
return backend_->GetStats(stats);
}
void OnExternalCacheHit(const std::string& key) override {
return backend_->OnExternalCacheHit(key);
}
int64_t MaxFileSize() const override { return backend_->MaxFileSize(); }
private:
std::unique_ptr<disk_cache::Backend> backend_;
FailureStage stage_;
};
std::string CopySideData(blink::mojom::Blob* actual_blob) {
std::string output;
base::RunLoop loop;
actual_blob->ReadSideData(base::BindLambdaForTesting(
[&](const absl::optional<mojo_base::BigBuffer> data) {
if (data)
output.append(data->data(), data->data() + data->size());
loop.Quit();
}));
loop.Run();
return output;
}
bool ResponseMetadataEqual(const blink::mojom::FetchAPIResponse& expected,
const blink::mojom::FetchAPIResponse& actual) {
EXPECT_EQ(expected.status_code, actual.status_code);
if (expected.status_code != actual.status_code)
return false;
EXPECT_EQ(expected.status_text, actual.status_text);
if (expected.status_text != actual.status_text)
return false;
EXPECT_EQ(expected.url_list.size(), actual.url_list.size());
if (expected.url_list.size() != actual.url_list.size())
return false;
for (size_t i = 0; i < expected.url_list.size(); ++i) {
EXPECT_EQ(expected.url_list[i], actual.url_list[i]);
if (expected.url_list[i] != actual.url_list[i])
return false;
}
EXPECT_EQ(!expected.blob, !actual.blob);
if (!expected.blob != !actual.blob)
return false;
if (expected.blob) {
if (expected.blob->size == 0) {
EXPECT_STREQ("", actual.blob->uuid.c_str());
if (!actual.blob->uuid.empty())
return false;
} else {
EXPECT_STRNE("", actual.blob->uuid.c_str());
if (actual.blob->uuid.empty())
return false;
}
}
EXPECT_EQ(expected.response_time, actual.response_time);
if (expected.response_time != actual.response_time)
return false;
EXPECT_EQ(expected.cache_storage_cache_name, actual.cache_storage_cache_name);
if (expected.cache_storage_cache_name != actual.cache_storage_cache_name)
return false;
EXPECT_EQ(expected.cors_exposed_header_names,
actual.cors_exposed_header_names);
if (expected.cors_exposed_header_names != actual.cors_exposed_header_names)
return false;
return true;
}
blink::mojom::FetchAPIResponsePtr SetCacheName(
blink::mojom::FetchAPIResponsePtr response) {
response->response_source =
network::mojom::FetchResponseSource::kCacheStorage;
response->cache_storage_cache_name = kCacheName;
return response;
}
void OnBadMessage(std::string* result) {
*result = "CSDH_UNEXPECTED_OPERATION";
}
// A CacheStorageCache that can optionally delay during backend creation.
class TestCacheStorageCache : public LegacyCacheStorageCache {
public:
TestCacheStorageCache(
const blink::StorageKey& storage_key,
const std::string& cache_name,
const base::FilePath& path,
LegacyCacheStorage* cache_storage,
const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy,
scoped_refptr<BlobStorageContextWrapper> blob_storage_context)
: LegacyCacheStorageCache(storage_key,
storage::mojom::CacheStorageOwner::kCacheAPI,
cache_name,
path,
cache_storage,
base::ThreadTaskRunnerHandle::Get(),
quota_manager_proxy,
std::move(blob_storage_context),
0 /* cache_size */,
0 /* cache_padding */),
delay_backend_creation_(false) {}
TestCacheStorageCache(const TestCacheStorageCache&) = delete;
TestCacheStorageCache& operator=(const TestCacheStorageCache&) = delete;
~TestCacheStorageCache() override { base::RunLoop().RunUntilIdle(); }
void CreateBackend(ErrorCallback callback) override {
backend_creation_callback_ = std::move(callback);
if (delay_backend_creation_)
return;
ContinueCreateBackend();
}
void ContinueCreateBackend() {
LegacyCacheStorageCache::CreateBackend(
std::move(backend_creation_callback_));
}
void set_delay_backend_creation(bool delay) {
delay_backend_creation_ = delay;
}
// Swap the existing backend with a delayable one. The backend must have been
// created before calling this.
DelayableBackend* UseDelayableBackend() {
EXPECT_TRUE(backend_);
DelayableBackend* delayable_backend =
new DelayableBackend(std::move(backend_));
backend_.reset(delayable_backend);
return delayable_backend;
}
void UseFailableBackend(FailableBackend::FailureStage stage) {
EXPECT_TRUE(backend_);
auto failable_backend =
std::make_unique<FailableBackend>(std::move(backend_), stage);
backend_ = std::move(failable_backend);
}
void Init() { InitBackend(); }
base::CheckedNumeric<uint64_t> GetRequiredSafeSpaceForRequest(
const blink::mojom::FetchAPIRequestPtr& request) {
return CalculateRequiredSafeSpaceForRequest(request);
}
base::CheckedNumeric<uint64_t> GetRequiredSafeSpaceForResponse(
const blink::mojom::FetchAPIResponsePtr& response) {
return CalculateRequiredSafeSpaceForResponse(response);
}
private:
bool delay_backend_creation_;
ErrorCallback backend_creation_callback_;
};
class MockLegacyCacheStorage : public LegacyCacheStorage {
public:
MockLegacyCacheStorage(
const base::FilePath& origin_path,
bool memory_only,
base::SequencedTaskRunner* cache_task_runner,
scoped_refptr<base::SequencedTaskRunner> scheduler_task_runner,
scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy,
scoped_refptr<BlobStorageContextWrapper> blob_storage_context,
LegacyCacheStorageManager* cache_storage_manager,
const blink::StorageKey& storage_key,
storage::mojom::CacheStorageOwner owner)
: LegacyCacheStorage(origin_path,
memory_only,
cache_task_runner,
std::move(scheduler_task_runner),
std::move(quota_manager_proxy),
std::move(blob_storage_context),
cache_storage_manager,
storage_key,
owner) {}
void CacheUnreferenced(LegacyCacheStorageCache* cache) override {
// Normally the LegacyCacheStorage will attempt to delete the cache
// from its map when the cache has become unreferenced. Since we are
// using detached cache objects we instead override to do nothing here.
}
};
class CacheStorageCacheTest : public testing::Test {
public:
CacheStorageCacheTest()
: task_environment_(BrowserTaskEnvironment::IO_MAINLOOP) {}
void SetUp() override {
ChromeBlobStorageContext* blob_storage_context =
ChromeBlobStorageContext::GetFor(&browser_context_);
// Wait for chrome_blob_storage_context to finish initializing.
base::RunLoop().RunUntilIdle();
mojo::PendingRemote<storage::mojom::BlobStorageContext> remote;
blob_storage_context->BindMojoContext(
remote.InitWithNewPipeAndPassReceiver());
blob_storage_context_ =
base::MakeRefCounted<BlobStorageContextWrapper>(std::move(remote));
const bool is_incognito = MemoryOnly();
if (!is_incognito) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
temp_dir_path_ = temp_dir_.GetPath();
}
quota_policy_ = base::MakeRefCounted<storage::MockSpecialStoragePolicy>();
mock_quota_manager_ = base::MakeRefCounted<storage::MockQuotaManager>(
is_incognito, temp_dir_path_, base::ThreadTaskRunnerHandle::Get(),
quota_policy_);
SetQuota(1024 * 1024 * 100);
quota_manager_proxy_ = base::MakeRefCounted<storage::MockQuotaManagerProxy>(
mock_quota_manager_.get(), base::ThreadTaskRunnerHandle::Get());
CreateRequests(blob_storage_context);
response_time_ = base::Time::Now();
for (int i = 0; i < 100; ++i)
expected_blob_data_ += kTestData;
blob_storage_context_->context()->RegisterFromMemory(
blob_remote_.BindNewPipeAndPassReceiver(), expected_blob_uuid_,
std::vector<uint8_t>(expected_blob_data_.begin(),
expected_blob_data_.end()));
// Use a mock LegacyCacheStorage object so we can use real
// CacheStorageCacheHandle reference counting. A LegacyCacheStorage
// must be present to be notified when a cache becomes unreferenced.
mock_cache_storage_ = std::make_unique<MockLegacyCacheStorage>(
temp_dir_path_, MemoryOnly(), base::ThreadTaskRunnerHandle::Get().get(),
base::ThreadTaskRunnerHandle::Get(), quota_manager_proxy_,
blob_storage_context_, /* cache_storage_manager = */ nullptr,
blink::StorageKey(url::Origin::Create(kTestUrl)),
storage::mojom::CacheStorageOwner::kCacheAPI);
InitCache(mock_cache_storage_.get());
}
void TearDown() override {
disk_cache::FlushCacheThreadForTesting();
content::RunAllTasksUntilIdle();
}
GURL BodyUrl() const {
GURL::Replacements replacements;
replacements.SetPathStr("/body.html");
return kTestUrl.ReplaceComponents(replacements);
}
GURL BodyUrlWithQuery() const {
return net::AppendQueryParameter(BodyUrl(), "query", "test");
}
GURL NoBodyUrl() const {
GURL::Replacements replacements;
replacements.SetPathStr("/no_body.html");
return kTestUrl.ReplaceComponents(replacements);
}
void InitCache(LegacyCacheStorage* cache_storage) {
cache_ = std::make_unique<TestCacheStorageCache>(
blink::StorageKey(url::Origin::Create(kTestUrl)), kCacheName,
temp_dir_path_, cache_storage, quota_manager_proxy_,
blob_storage_context_);
cache_->Init();
}
void CreateRequests(ChromeBlobStorageContext* blob_storage_context) {
body_request_ = CreateFetchAPIRequest(BodyUrl(), "GET", kHeaders,
blink::mojom::Referrer::New(), false);
body_request_with_query_ =
CreateFetchAPIRequest(BodyUrlWithQuery(), "GET", kHeaders,
blink::mojom::Referrer::New(), false);
no_body_request_ = CreateFetchAPIRequest(
NoBodyUrl(), "GET", kHeaders, blink::mojom::Referrer::New(), false);
body_head_request_ = CreateFetchAPIRequest(
BodyUrl(), "HEAD", kHeaders, blink::mojom::Referrer::New(), false);
}
blink::mojom::FetchAPIResponsePtr CreateBlobBodyResponse() {
auto blob = blink::mojom::SerializedBlob::New();
blob->uuid = expected_blob_uuid_;
blob->size = expected_blob_data_.size();
// Use cloned blob remote for all responses with blob body.
blob_remote_->Clone(blob->blob.InitWithNewPipeAndPassReceiver());
blink::mojom::FetchAPIResponsePtr response = CreateNoBodyResponse();
response->url_list = {BodyUrl()};
response->blob = std::move(blob);
return response;
}
blink::mojom::FetchAPIResponsePtr CreateOpaqueResponse() {
auto response = CreateBlobBodyResponse();
response->response_type = network::mojom::FetchResponseType::kOpaque;
response->response_time = base::Time::Now();
// CacheStorage depends on fetch to provide the opaque response padding
// value now. We prepolute a padding value here to simulate that.
response->padding = 10;
return response;
}
blink::mojom::FetchAPIResponsePtr CreateBlobBodyResponseWithQuery() {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
response->url_list = {BodyUrlWithQuery()};
response->cors_exposed_header_names = {"a"};
return response;
}
blink::mojom::FetchAPIResponsePtr CreateNoBodyResponse() {
return blink::mojom::FetchAPIResponse::New(
std::vector<GURL>({NoBodyUrl()}), 200, "OK",
network::mojom::FetchResponseType::kDefault, /*padding=*/0,
network::mojom::FetchResponseSource::kUnspecified,
base::flat_map<std::string, std::string>(kHeaders.cbegin(),
kHeaders.cend()),
/*mime_type=*/absl::nullopt, net::HttpRequestHeaders::kGetMethod,
/*blob=*/nullptr, blink::mojom::ServiceWorkerResponseError::kUnknown,
response_time_, /*cache_storage_cache_name=*/std::string(),
/*cors_exposed_header_names=*/std::vector<std::string>(),
/*side_data_blob=*/nullptr,
/*side_data_blob_cache_put=*/nullptr,
network::mojom::ParsedHeaders::New(),
net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN,
/*alpn_negotiated_protocol=*/"unknown",
/*was_fetched_via_spdy=*/false, /*has_range_requested=*/false,
/*auth_challenge_info=*/absl::nullopt,
/*request_include_credentials=*/true);
}
void CopySideDataToResponse(const std::string& uuid,
const std::string& data,
blink::mojom::FetchAPIResponse* response) {
auto& blob = response->side_data_blob_for_cache_put;
blob = blink::mojom::SerializedBlob::New();
blob->uuid = uuid;
blob->size = data.size();
blob_storage_context_->context()->RegisterFromMemory(
blob->blob.InitWithNewPipeAndPassReceiver(), uuid,
std::vector<uint8_t>(data.begin(), data.end()));
}
blink::mojom::FetchAPIRequestPtr CopyFetchRequest(
const blink::mojom::FetchAPIRequestPtr& request) {
return CreateFetchAPIRequest(request->url, request->method,
request->headers, request->referrer.Clone(),
request->is_reload);
}
CacheStorageError BatchOperation(
std::vector<blink::mojom::BatchOperationPtr> operations) {
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->BatchOperation(
std::move(operations), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::VerboseErrorTypeCallback,
base::Unretained(this), base::Unretained(loop.get())),
base::BindOnce(&OnBadMessage, base::Unretained(&bad_message_reason_)));
// TODO(jkarlin): These functions should use base::RunLoop().RunUntilIdle()
// once the cache uses a passed in task runner instead of the CACHE thread.
loop->Run();
return callback_error_;
}
void CheckOpHistograms(base::HistogramTester& histogram_tester,
const char* op_name) {
std::string base("ServiceWorkerCache.Cache.Scheduler.");
histogram_tester.ExpectTotalCount(base + "OperationDuration2." + op_name,
1);
histogram_tester.ExpectTotalCount(base + "QueueDuration2." + op_name, 1);
histogram_tester.ExpectTotalCount(base + "QueueLength." + op_name, 1);
}
bool Put(const blink::mojom::FetchAPIRequestPtr& request,
blink::mojom::FetchAPIResponsePtr response) {
base::HistogramTester histogram_tester;
blink::mojom::BatchOperationPtr operation =
blink::mojom::BatchOperation::New();
operation->operation_type = blink::mojom::OperationType::kPut;
operation->request = BackgroundFetchSettledFetch::CloneRequest(request);
operation->response = std::move(response);
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.emplace_back(std::move(operation));
CacheStorageError error = BatchOperation(std::move(operations));
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "Put");
return error == CacheStorageError::kSuccess;
}
bool Match(const blink::mojom::FetchAPIRequestPtr& request,
blink::mojom::CacheQueryOptionsPtr match_options = nullptr) {
base::HistogramTester histogram_tester;
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->Match(
CopyFetchRequest(request), std::move(match_options),
CacheStorageSchedulerPriority::kNormal, /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::ResponseAndErrorCallback,
base::Unretained(this), base::Unretained(loop.get())));
loop->Run();
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "Match");
return callback_error_ == CacheStorageError::kSuccess;
}
bool MatchAll(const blink::mojom::FetchAPIRequestPtr& request,
blink::mojom::CacheQueryOptionsPtr match_options,
std::vector<blink::mojom::FetchAPIResponsePtr>* responses) {
base::HistogramTester histogram_tester;
base::RunLoop loop;
cache_->MatchAll(
CopyFetchRequest(request), std::move(match_options),
/* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::ResponsesAndErrorCallback,
base::Unretained(this), loop.QuitClosure(), responses));
loop.Run();
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "MatchAll");
return callback_error_ == CacheStorageError::kSuccess;
}
bool GetAllMatchedEntries(
std::vector<blink::mojom::CacheEntryPtr>* cache_entries) {
base::RunLoop loop;
cache_->GetAllMatchedEntries(
nullptr /* request */, nullptr /* options */,
/* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::CacheEntriesAndErrorCallback,
base::Unretained(this), loop.QuitClosure(),
cache_entries));
loop.Run();
return callback_error_ == CacheStorageError::kSuccess;
}
bool MatchAll(std::vector<blink::mojom::FetchAPIResponsePtr>* responses) {
return MatchAll(blink::mojom::FetchAPIRequest::New(), nullptr, responses);
}
bool Delete(const blink::mojom::FetchAPIRequestPtr& request,
blink::mojom::CacheQueryOptionsPtr match_options = nullptr) {
base::HistogramTester histogram_tester;
blink::mojom::BatchOperationPtr operation =
blink::mojom::BatchOperation::New();
operation->operation_type = blink::mojom::OperationType::kDelete;
operation->request = BackgroundFetchSettledFetch::CloneRequest(request);
operation->match_options = std::move(match_options);
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.emplace_back(std::move(operation));
CacheStorageError error = BatchOperation(std::move(operations));
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "Delete");
return error == CacheStorageError::kSuccess;
}
bool Keys(const blink::mojom::FetchAPIRequestPtr& request =
blink::mojom::FetchAPIRequest::New(),
blink::mojom::CacheQueryOptionsPtr match_options = nullptr) {
base::HistogramTester histogram_tester;
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->Keys(
CopyFetchRequest(request), std::move(match_options),
/* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::RequestsCallback,
base::Unretained(this), base::Unretained(loop.get())));
loop->Run();
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "Keys");
return callback_error_ == CacheStorageError::kSuccess;
}
bool Close() {
base::HistogramTester histogram_tester;
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->Close(base::BindOnce(&CacheStorageCacheTest::CloseCallback,
base::Unretained(this),
base::Unretained(loop.get())));
loop->Run();
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "Close");
return callback_closed_;
}
bool WriteSideData(const GURL& url,
base::Time expected_response_time,
scoped_refptr<net::IOBuffer> buffer,
int buf_len) {
base::HistogramTester histogram_tester;
base::RunLoop run_loop;
cache_->WriteSideData(
base::BindOnce(&CacheStorageCacheTest::ErrorTypeCallback,
base::Unretained(this), base::Unretained(&run_loop)),
url, expected_response_time, /* trace_id = */ 0, buffer, buf_len);
run_loop.Run();
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "WriteSideData");
return callback_error_ == CacheStorageError::kSuccess;
}
int64_t Size() {
base::HistogramTester histogram_tester;
// Storage notification happens after an operation completes. Let the any
// notifications complete before calling Size.
base::RunLoop().RunUntilIdle();
base::RunLoop run_loop;
bool callback_called = false;
int64_t result = 0;
cache_->Size(
base::BindOnce(&SizeCallback, &run_loop, &callback_called, &result));
run_loop.Run();
EXPECT_TRUE(callback_called);
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "Size");
return result;
}
int64_t GetSizeThenClose() {
base::HistogramTester histogram_tester;
base::RunLoop run_loop;
bool callback_called = false;
int64_t result = 0;
cache_->GetSizeThenClose(
base::BindOnce(&SizeCallback, &run_loop, &callback_called, &result));
run_loop.Run();
EXPECT_TRUE(callback_called);
if (callback_error_ == CacheStorageError::kSuccess)
CheckOpHistograms(histogram_tester, "SizeThenClose");
return result;
}
void RequestsCallback(base::RunLoop* run_loop,
CacheStorageError error,
std::unique_ptr<CacheStorageCache::Requests> requests) {
callback_error_ = error;
callback_strings_.clear();
if (requests) {
for (const blink::mojom::FetchAPIRequestPtr& request : *requests)
callback_strings_.push_back(request->url.spec());
}
if (run_loop)
run_loop->Quit();
}
void VerboseErrorTypeCallback(base::RunLoop* run_loop,
CacheStorageVerboseErrorPtr error) {
ErrorTypeCallback(run_loop, error->value);
callback_message_ = error->message;
}
void ErrorTypeCallback(base::RunLoop* run_loop, CacheStorageError error) {
callback_message_ = absl::nullopt;
callback_error_ = error;
if (run_loop)
run_loop->Quit();
}
void SequenceCallback(int sequence,
int* sequence_out,
base::RunLoop* run_loop,
CacheStorageVerboseErrorPtr error) {
*sequence_out = sequence;
callback_error_ = error->value;
if (run_loop)
run_loop->Quit();
}
void ResponseAndErrorCallback(base::RunLoop* run_loop,
CacheStorageError error,
blink::mojom::FetchAPIResponsePtr response) {
callback_error_ = error;
callback_response_ = std::move(response);
if (run_loop)
run_loop->Quit();
}
void ResponsesAndErrorCallback(
base::OnceClosure quit_closure,
std::vector<blink::mojom::FetchAPIResponsePtr>* responses_out,
CacheStorageError error,
std::vector<blink::mojom::FetchAPIResponsePtr> responses) {
callback_error_ = error;
*responses_out = std::move(responses);
std::move(quit_closure).Run();
}
void CacheEntriesAndErrorCallback(
base::OnceClosure quit_closure,
std::vector<blink::mojom::CacheEntryPtr>* cache_entries_out,
CacheStorageError error,
std::vector<blink::mojom::CacheEntryPtr> cache_entries) {
callback_error_ = error;
*cache_entries_out = std::move(cache_entries);
std::move(quit_closure).Run();
}
void CloseCallback(base::RunLoop* run_loop) {
EXPECT_FALSE(callback_closed_);
callback_closed_ = true;
if (run_loop)
run_loop->Quit();
}
bool TestResponseType(network::mojom::FetchResponseType response_type) {
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->response_type = response_type;
if (storage::ShouldPadResponseType(response_type))
body_response->padding = 10;
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Match(body_request_));
EXPECT_TRUE(Delete(body_request_));
return response_type == callback_response_->response_type;
}
void VerifyAllOpsFail() {
EXPECT_FALSE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_FALSE(Match(no_body_request_));
EXPECT_FALSE(Delete(body_request_));
EXPECT_FALSE(Keys());
}
virtual bool MemoryOnly() { return false; }
void SetQuota(uint64_t quota) {
mock_quota_manager_->SetQuota(
blink::StorageKey(url::Origin::Create(kTestUrl)),
blink::mojom::StorageType::kTemporary, quota);
}
void SetMaxQuerySizeBytes(size_t max_bytes) {
cache_->max_query_size_bytes_ = max_bytes;
}
size_t EstimatedResponseSizeWithoutBlob(
const blink::mojom::FetchAPIResponse& response) {
return LegacyCacheStorageCache::EstimatedResponseSizeWithoutBlob(response);
}
protected:
base::ScopedTempDir temp_dir_;
BrowserTaskEnvironment task_environment_;
TestBrowserContext browser_context_;
scoped_refptr<storage::MockSpecialStoragePolicy> quota_policy_;
scoped_refptr<storage::MockQuotaManager> mock_quota_manager_;
scoped_refptr<storage::MockQuotaManagerProxy> quota_manager_proxy_;
scoped_refptr<BlobStorageContextWrapper> blob_storage_context_;
std::unique_ptr<MockLegacyCacheStorage> mock_cache_storage_;
base::FilePath temp_dir_path_;
std::unique_ptr<TestCacheStorageCache> cache_;
blink::mojom::FetchAPIRequestPtr body_request_;
blink::mojom::FetchAPIRequestPtr body_request_with_query_;
blink::mojom::FetchAPIRequestPtr no_body_request_;
blink::mojom::FetchAPIRequestPtr body_head_request_;
std::string expected_blob_uuid_ = "blob-id:myblob";
// Holds a Mojo connection to the BlobImpl with uuid |expected_blob_uuid_|.
mojo::Remote<blink::mojom::Blob> blob_remote_;
base::Time response_time_;
std::string expected_blob_data_;
CacheStorageError callback_error_ = CacheStorageError::kSuccess;
absl::optional<std::string> callback_message_ = absl::nullopt;
blink::mojom::FetchAPIResponsePtr callback_response_;
std::vector<std::string> callback_strings_;
std::string bad_message_reason_;
bool callback_closed_ = false;
const GURL kTestUrl{"http://example.com"};
};
class CacheStorageCacheTestP : public CacheStorageCacheTest,
public testing::WithParamInterface<bool> {
public:
bool MemoryOnly() override { return !GetParam(); }
};
TEST_P(CacheStorageCacheTestP, PutNoBody) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
}
TEST_P(CacheStorageCacheTestP, PutBody) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
}
TEST_P(CacheStorageCacheTestP, PutBody_Multiple) {
blink::mojom::BatchOperationPtr operation1 =
blink::mojom::BatchOperation::New();
operation1->operation_type = blink::mojom::OperationType::kPut;
operation1->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation1->request->url = GURL("http://example.com/1");
operation1->response = CreateBlobBodyResponse();
operation1->response->url_list.emplace_back("http://example.com/1");
blink::mojom::FetchAPIRequestPtr request1 =
BackgroundFetchSettledFetch::CloneRequest(operation1->request);
blink::mojom::BatchOperationPtr operation2 =
blink::mojom::BatchOperation::New();
operation2->operation_type = blink::mojom::OperationType::kPut;
operation2->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation2->request->url = GURL("http://example.com/2");
operation2->response = CreateBlobBodyResponse();
operation2->response->url_list.emplace_back("http://example.com/2");
blink::mojom::FetchAPIRequestPtr request2 =
BackgroundFetchSettledFetch::CloneRequest(operation2->request);
blink::mojom::BatchOperationPtr operation3 =
blink::mojom::BatchOperation::New();
operation3->operation_type = blink::mojom::OperationType::kPut;
operation3->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation3->request->url = GURL("http://example.com/3");
operation3->response = CreateBlobBodyResponse();
operation3->response->url_list.emplace_back("http://example.com/3");
blink::mojom::FetchAPIRequestPtr request3 =
BackgroundFetchSettledFetch::CloneRequest(operation3->request);
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.push_back(std::move(operation1));
operations.push_back(std::move(operation2));
operations.push_back(std::move(operation3));
EXPECT_EQ(CacheStorageError::kSuccess, BatchOperation(std::move(operations)));
EXPECT_TRUE(Match(request1));
EXPECT_TRUE(Match(request2));
EXPECT_TRUE(Match(request3));
}
TEST_P(CacheStorageCacheTestP, MatchLimit) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(no_body_request_));
size_t max_size =
LegacyCacheStorageCache::EstimatedStructSize(no_body_request_) +
EstimatedResponseSizeWithoutBlob(*callback_response_);
SetMaxQuerySizeBytes(max_size);
EXPECT_TRUE(Match(no_body_request_));
SetMaxQuerySizeBytes(max_size - 1);
EXPECT_FALSE(Match(no_body_request_));
EXPECT_EQ(CacheStorageError::kErrorQueryTooLarge, callback_error_);
}
TEST_P(CacheStorageCacheTestP, MatchAllLimit) {
EXPECT_TRUE(Put(body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_with_query_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(body_request_));
size_t body_request_size =
LegacyCacheStorageCache::EstimatedStructSize(body_request_) +
EstimatedResponseSizeWithoutBlob(*callback_response_);
size_t query_request_size =
LegacyCacheStorageCache::EstimatedStructSize(body_request_with_query_) +
EstimatedResponseSizeWithoutBlob(*callback_response_);
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
// There is enough room for both requests and responses
SetMaxQuerySizeBytes(body_request_size + query_request_size);
EXPECT_TRUE(MatchAll(body_request_, match_options->Clone(), &responses));
EXPECT_EQ(1u, responses.size());
match_options->ignore_search = true;
EXPECT_TRUE(MatchAll(body_request_, match_options->Clone(), &responses));
EXPECT_EQ(2u, responses.size());
// There is not enough room for both requests and responses
SetMaxQuerySizeBytes(body_request_size);
match_options->ignore_search = false;
EXPECT_TRUE(MatchAll(body_request_, match_options->Clone(), &responses));
EXPECT_EQ(1u, responses.size());
match_options->ignore_search = true;
EXPECT_FALSE(MatchAll(body_request_, match_options->Clone(), &responses));
EXPECT_EQ(CacheStorageError::kErrorQueryTooLarge, callback_error_);
}
TEST_P(CacheStorageCacheTestP, KeysLimit) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
size_t max_size =
LegacyCacheStorageCache::EstimatedStructSize(no_body_request_) +
LegacyCacheStorageCache::EstimatedStructSize(body_request_);
SetMaxQuerySizeBytes(max_size);
EXPECT_TRUE(Keys());
SetMaxQuerySizeBytes(
LegacyCacheStorageCache::EstimatedStructSize(no_body_request_));
EXPECT_FALSE(Keys());
EXPECT_EQ(CacheStorageError::kErrorQueryTooLarge, callback_error_);
}
// TODO(nhiroki): Add a test for the case where one of PUT operations fails.
// Currently there is no handy way to fail only one operation in a batch.
// This could be easily achieved after adding some security checks in the
// browser side (http://crbug.com/425505).
TEST_P(CacheStorageCacheTestP, ResponseURLDiffersFromRequestURL) {
blink::mojom::FetchAPIResponsePtr no_body_response = CreateNoBodyResponse();
no_body_response->url_list.clear();
no_body_response->url_list.emplace_back("http://example.com/foobar");
EXPECT_STRNE("http://example.com/foobar",
no_body_request_->url.spec().c_str());
EXPECT_TRUE(Put(no_body_request_, std::move(no_body_response)));
EXPECT_TRUE(Match(no_body_request_));
ASSERT_EQ(1u, callback_response_->url_list.size());
EXPECT_STREQ("http://example.com/foobar",
callback_response_->url_list[0].spec().c_str());
}
TEST_P(CacheStorageCacheTestP, ResponseURLEmpty) {
blink::mojom::FetchAPIResponsePtr no_body_response = CreateNoBodyResponse();
no_body_response->url_list.clear();
EXPECT_STRNE("", no_body_request_->url.spec().c_str());
EXPECT_TRUE(Put(no_body_request_, std::move(no_body_response)));
EXPECT_TRUE(Match(no_body_request_));
EXPECT_EQ(0u, callback_response_->url_list.size());
}
TEST_P(CacheStorageCacheTestP, PutBodyDropBlobRef) {
blink::mojom::BatchOperationPtr operation =
blink::mojom::BatchOperation::New();
operation->operation_type = blink::mojom::OperationType::kPut;
operation->request = BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation->response = CreateBlobBodyResponse();
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.emplace_back(std::move(operation));
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->BatchOperation(
std::move(operations), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTestP::VerboseErrorTypeCallback,
base::Unretained(this), base::Unretained(loop.get())),
CacheStorageCache::BadMessageCallback());
// The handle should be held by the cache now so the deref here should be
// okay.
blob_remote_.reset();
loop->Run();
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutBadMessage) {
base::HistogramTester histogram_tester;
// Two unique puts that will collectively overflow unit64_t size of the
// batch operation.
blink::mojom::BatchOperationPtr operation1 =
blink::mojom::BatchOperation::New(
blink::mojom::OperationType::kPut,
BackgroundFetchSettledFetch::CloneRequest(body_request_),
CreateBlobBodyResponse(), nullptr /* match_options */);
operation1->response->blob->size = std::numeric_limits<uint64_t>::max();
blink::mojom::BatchOperationPtr operation2 =
blink::mojom::BatchOperation::New(
blink::mojom::OperationType::kPut,
BackgroundFetchSettledFetch::CloneRequest(body_request_with_query_),
CreateBlobBodyResponse(), nullptr /* match_options */);
operation2->response->blob->size = std::numeric_limits<uint64_t>::max();
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.push_back(std::move(operation1));
operations.push_back(std::move(operation2));
EXPECT_EQ(CacheStorageError::kErrorStorage,
BatchOperation(std::move(operations)));
histogram_tester.ExpectBucketCount("ServiceWorkerCache.ErrorStorageType",
ErrorStorageType::kBatchInvalidSpace, 1);
EXPECT_EQ("CSDH_UNEXPECTED_OPERATION", bad_message_reason_);
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, PutReplace) {
EXPECT_TRUE(Put(body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(body_request_));
EXPECT_FALSE(callback_response_->blob);
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Match(body_request_));
EXPECT_TRUE(callback_response_->blob);
EXPECT_TRUE(Put(body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(body_request_));
EXPECT_FALSE(callback_response_->blob);
}
TEST_P(CacheStorageCacheTestP, PutReplaceInBatchFails) {
blink::mojom::BatchOperationPtr operation1 =
blink::mojom::BatchOperation::New();
operation1->operation_type = blink::mojom::OperationType::kPut;
operation1->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation1->response = CreateNoBodyResponse();
blink::mojom::BatchOperationPtr operation2 =
blink::mojom::BatchOperation::New();
operation2->operation_type = blink::mojom::OperationType::kPut;
operation2->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation2->response = CreateBlobBodyResponse();
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.push_back(std::move(operation1));
operations.push_back(std::move(operation2));
EXPECT_EQ(CacheStorageError::kErrorDuplicateOperation,
BatchOperation(std::move(operations)));
// A duplicate operation error should provide an informative message
// containing the URL of the duplicate request.
ASSERT_TRUE(callback_message_);
EXPECT_NE(std::string::npos,
callback_message_.value().find(BodyUrl().spec()));
// Neither operation should have completed.
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, MatchNoBody) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(no_body_request_));
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateNoBodyResponse()),
*callback_response_));
EXPECT_FALSE(callback_response_->blob);
}
TEST_P(CacheStorageCacheTestP, MatchBody) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Match(body_request_));
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()),
*callback_response_));
mojo::Remote<blink::mojom::Blob> blob(
std::move(callback_response_->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
}
TEST_P(CacheStorageCacheTestP, MatchBodyHead) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_FALSE(Match(body_head_request_));
}
TEST_P(CacheStorageCacheTestP, MatchAll_Empty) {
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
EXPECT_TRUE(MatchAll(&responses));
EXPECT_TRUE(responses.empty());
}
TEST_P(CacheStorageCacheTestP, MatchAll_NoBody) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(1u, responses.size());
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateNoBodyResponse()),
*responses[0]));
EXPECT_FALSE(responses[0]->blob);
}
TEST_P(CacheStorageCacheTestP, MatchAll_Body) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(1u, responses.size());
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()),
*responses[0]));
mojo::Remote<blink::mojom::Blob> blob(std::move(responses[0]->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
}
TEST_P(CacheStorageCacheTestP, MatchAll_TwoResponsesThenOne) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(2u, responses.size());
EXPECT_TRUE(responses[1]->blob);
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateNoBodyResponse()),
*responses[0]));
EXPECT_FALSE(responses[0]->blob);
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()),
*responses[1]));
mojo::Remote<blink::mojom::Blob> blob(std::move(responses[1]->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
responses.clear();
EXPECT_TRUE(Delete(body_request_));
EXPECT_TRUE(MatchAll(&responses));
ASSERT_EQ(1u, responses.size());
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateNoBodyResponse()),
*responses[0]));
EXPECT_FALSE(responses[0]->blob);
}
TEST_P(CacheStorageCacheTestP, Match_IgnoreSearch) {
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
EXPECT_FALSE(Match(body_request_));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(Match(body_request_, std::move(match_options)));
}
TEST_P(CacheStorageCacheTestP, Match_IgnoreMethod) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
blink::mojom::FetchAPIRequestPtr post_request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
post_request->method = "POST";
EXPECT_FALSE(Match(post_request));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_method = true;
EXPECT_TRUE(Match(post_request, std::move(match_options)));
}
TEST_P(CacheStorageCacheTestP, Match_IgnoreVary) {
body_request_->headers["vary_foo"] = "foo";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "vary_foo";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Match(body_request_));
body_request_->headers["vary_foo"] = "bar";
EXPECT_FALSE(Match(body_request_));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_vary = true;
EXPECT_TRUE(Match(body_request_, std::move(match_options)));
}
TEST_P(CacheStorageCacheTestP, GetAllMatchedEntries_RequestsIncluded) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
std::vector<blink::mojom::CacheEntryPtr> cache_entries;
EXPECT_TRUE(GetAllMatchedEntries(&cache_entries));
ASSERT_EQ(1u, cache_entries.size());
const auto& request = cache_entries[0]->request;
EXPECT_EQ(request->url, body_request_->url);
EXPECT_EQ(request->headers, body_request_->headers);
EXPECT_EQ(request->method, body_request_->method);
auto& response = cache_entries[0]->response;
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()),
*response));
mojo::Remote<blink::mojom::Blob> blob(std::move(response->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
}
TEST_P(CacheStorageCacheTestP, Keys_IgnoreSearch) {
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
EXPECT_TRUE(Keys(body_request_));
EXPECT_EQ(0u, callback_strings_.size());
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(Keys(body_request_, std::move(match_options)));
EXPECT_EQ(1u, callback_strings_.size());
}
TEST_P(CacheStorageCacheTestP, Keys_IgnoreMethod) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
blink::mojom::FetchAPIRequestPtr post_request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
post_request->method = "POST";
EXPECT_TRUE(Keys(post_request));
EXPECT_EQ(0u, callback_strings_.size());
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_method = true;
EXPECT_TRUE(Keys(post_request, std::move(match_options)));
EXPECT_EQ(1u, callback_strings_.size());
}
TEST_P(CacheStorageCacheTestP, Keys_IgnoreVary) {
body_request_->headers["vary_foo"] = "foo";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "vary_foo";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Keys(body_request_));
EXPECT_EQ(1u, callback_strings_.size());
body_request_->headers["vary_foo"] = "bar";
EXPECT_TRUE(Keys(body_request_));
EXPECT_EQ(0u, callback_strings_.size());
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_vary = true;
EXPECT_TRUE(Keys(body_request_, std::move(match_options)));
EXPECT_EQ(1u, callback_strings_.size());
}
TEST_P(CacheStorageCacheTestP, Delete_IgnoreSearch) {
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
EXPECT_FALSE(Delete(body_request_));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(Delete(body_request_, std::move(match_options)));
}
TEST_P(CacheStorageCacheTestP, Delete_IgnoreMethod) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
blink::mojom::FetchAPIRequestPtr post_request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
post_request->method = "POST";
EXPECT_FALSE(Delete(post_request));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_method = true;
EXPECT_TRUE(Delete(post_request, std::move(match_options)));
}
TEST_P(CacheStorageCacheTestP, Delete_IgnoreVary) {
body_request_->headers["vary_foo"] = "foo";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "vary_foo";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
body_request_->headers["vary_foo"] = "bar";
EXPECT_FALSE(Delete(body_request_));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_vary = true;
EXPECT_TRUE(Delete(body_request_, std::move(match_options)));
}
TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreMethod) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
blink::mojom::FetchAPIRequestPtr post_request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
post_request->method = "POST";
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
EXPECT_TRUE(MatchAll(post_request, nullptr, &responses));
EXPECT_EQ(0u, responses.size());
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_method = true;
EXPECT_TRUE(MatchAll(post_request, std::move(match_options), &responses));
EXPECT_EQ(1u, responses.size());
}
TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreVary) {
body_request_->headers["vary_foo"] = "foo";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "vary_foo";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
EXPECT_TRUE(MatchAll(body_request_, nullptr, &responses));
EXPECT_EQ(1u, responses.size());
body_request_->headers["vary_foo"] = "bar";
EXPECT_TRUE(MatchAll(body_request_, nullptr, &responses));
EXPECT_EQ(0u, responses.size());
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_vary = true;
EXPECT_TRUE(MatchAll(body_request_, std::move(match_options), &responses));
EXPECT_EQ(1u, responses.size());
}
TEST_P(CacheStorageCacheTestP, MatchAll_IgnoreSearch) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(MatchAll(body_request_, std::move(match_options), &responses));
ASSERT_EQ(2u, responses.size());
// Order of returned responses is not guaranteed.
std::set<std::string> matched_set;
for (const blink::mojom::FetchAPIResponsePtr& response : responses) {
ASSERT_EQ(1u, response->url_list.size());
if (response->url_list[0] == BodyUrlWithQuery()) {
EXPECT_TRUE(ResponseMetadataEqual(
*SetCacheName(CreateBlobBodyResponseWithQuery()), *response));
matched_set.insert(response->url_list[0].spec());
} else if (response->url_list[0] == BodyUrl()) {
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()),
*response));
matched_set.insert(response->url_list[0].spec());
}
}
EXPECT_EQ(2u, matched_set.size());
}
TEST_P(CacheStorageCacheTestP, MatchAll_Head) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(MatchAll(body_head_request_, match_options->Clone(), &responses));
EXPECT_TRUE(responses.empty());
match_options->ignore_method = true;
EXPECT_TRUE(MatchAll(body_head_request_, match_options->Clone(), &responses));
ASSERT_EQ(1u, responses.size());
EXPECT_TRUE(ResponseMetadataEqual(*SetCacheName(CreateBlobBodyResponse()),
*responses[0]));
mojo::Remote<blink::mojom::Blob> blob(std::move(responses[0]->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
}
TEST_P(CacheStorageCacheTestP, Vary) {
body_request_->headers["vary_foo"] = "foo";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "vary_foo";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Match(body_request_));
body_request_->headers["vary_foo"] = "bar";
EXPECT_FALSE(Match(body_request_));
body_request_->headers.erase(std::string("vary_foo"));
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, EmptyVary) {
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Match(body_request_));
body_request_->headers["zoo"] = "zoo";
EXPECT_TRUE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, NoVaryButDiffHeaders) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Match(body_request_));
body_request_->headers["zoo"] = "zoo";
EXPECT_TRUE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, VaryMultiple) {
body_request_->headers["vary_foo"] = "foo";
body_request_->headers["vary_bar"] = "bar";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = " vary_foo , vary_bar";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Match(body_request_));
body_request_->headers["vary_bar"] = "foo";
EXPECT_FALSE(Match(body_request_));
body_request_->headers.erase(std::string("vary_bar"));
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, VaryNewHeader) {
body_request_->headers["vary_foo"] = "foo";
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = " vary_foo, vary_bar";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_TRUE(Match(body_request_));
body_request_->headers["vary_bar"] = "bar";
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, VaryStar) {
blink::mojom::FetchAPIResponsePtr body_response = CreateBlobBodyResponse();
body_response->headers["vary"] = "*";
EXPECT_TRUE(Put(body_request_, std::move(body_response)));
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, EmptyKeys) {
EXPECT_TRUE(Keys());
EXPECT_EQ(0u, callback_strings_.size());
}
TEST_P(CacheStorageCacheTestP, TwoKeys) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Keys());
std::vector<std::string> expected_keys{no_body_request_->url.spec(),
body_request_->url.spec()};
EXPECT_EQ(expected_keys, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, TwoKeysThenOne) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Keys());
std::vector<std::string> expected_keys{no_body_request_->url.spec(),
body_request_->url.spec()};
EXPECT_EQ(expected_keys, callback_strings_);
EXPECT_TRUE(Delete(body_request_));
EXPECT_TRUE(Keys());
std::vector<std::string> expected_keys2{no_body_request_->url.spec()};
EXPECT_EQ(expected_keys2, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, KeysWithIgnoreSearchTrue) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(Keys(body_request_with_query_, std::move(match_options)));
std::vector<std::string> expected_keys = {
body_request_->url.spec(), body_request_with_query_->url.spec()};
EXPECT_EQ(expected_keys, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, KeysWithIgnoreSearchFalse) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
// Default value of ignore_search is false.
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
EXPECT_EQ(match_options->ignore_search, false);
EXPECT_TRUE(Keys(body_request_with_query_, std::move(match_options)));
std::vector<std::string> expected_keys = {
body_request_with_query_->url.spec()};
EXPECT_EQ(expected_keys, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, DeleteNoBody) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(no_body_request_));
EXPECT_TRUE(Delete(no_body_request_));
EXPECT_FALSE(Match(no_body_request_));
EXPECT_FALSE(Delete(no_body_request_));
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(no_body_request_));
EXPECT_TRUE(Delete(no_body_request_));
}
TEST_P(CacheStorageCacheTestP, DeleteBody) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Match(body_request_));
EXPECT_TRUE(Delete(body_request_));
EXPECT_FALSE(Match(body_request_));
EXPECT_FALSE(Delete(body_request_));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Match(body_request_));
EXPECT_TRUE(Delete(body_request_));
}
TEST_P(CacheStorageCacheTestP, DeleteWithIgnoreSearchTrue) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
EXPECT_TRUE(Keys());
std::vector<std::string> expected_keys{no_body_request_->url.spec(),
body_request_->url.spec(),
body_request_with_query_->url.spec()};
EXPECT_EQ(expected_keys, callback_strings_);
// The following delete operation will remove both of body_request_ and
// body_request_with_query_ from cache storage.
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
match_options->ignore_search = true;
EXPECT_TRUE(Delete(body_request_with_query_, std::move(match_options)));
EXPECT_TRUE(Keys());
expected_keys.clear();
std::vector<std::string> expected_keys2{no_body_request_->url.spec()};
EXPECT_EQ(expected_keys2, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, DeleteWithIgnoreSearchFalse) {
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Put(body_request_with_query_, CreateBlobBodyResponseWithQuery()));
EXPECT_TRUE(Keys());
std::vector<std::string> expected_keys{no_body_request_->url.spec(),
body_request_->url.spec(),
body_request_with_query_->url.spec()};
EXPECT_EQ(expected_keys, callback_strings_);
// Default value of ignore_search is false.
blink::mojom::CacheQueryOptionsPtr match_options =
blink::mojom::CacheQueryOptions::New();
EXPECT_EQ(match_options->ignore_search, false);
EXPECT_TRUE(Delete(body_request_with_query_, std::move(match_options)));
EXPECT_TRUE(Keys());
std::vector<std::string> expected_keys2{no_body_request_->url.spec(),
body_request_->url.spec()};
EXPECT_EQ(expected_keys2, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, QuickStressNoBody) {
for (int i = 0; i < 100; ++i) {
EXPECT_FALSE(Match(no_body_request_));
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_TRUE(Match(no_body_request_));
EXPECT_TRUE(Delete(no_body_request_));
}
}
TEST_P(CacheStorageCacheTestP, QuickStressBody) {
for (int i = 0; i < 100; ++i) {
ASSERT_FALSE(Match(body_request_));
ASSERT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
ASSERT_TRUE(Match(body_request_));
ASSERT_TRUE(Delete(body_request_));
}
}
TEST_P(CacheStorageCacheTestP, PutResponseType) {
EXPECT_TRUE(TestResponseType(network::mojom::FetchResponseType::kBasic));
EXPECT_TRUE(TestResponseType(network::mojom::FetchResponseType::kCors));
EXPECT_TRUE(TestResponseType(network::mojom::FetchResponseType::kDefault));
EXPECT_TRUE(TestResponseType(network::mojom::FetchResponseType::kError));
EXPECT_TRUE(TestResponseType(network::mojom::FetchResponseType::kOpaque));
EXPECT_TRUE(
TestResponseType(network::mojom::FetchResponseType::kOpaqueRedirect));
}
TEST_P(CacheStorageCacheTestP, PutWithSideData) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
const std::string expected_side_data = "SideData";
CopySideDataToResponse("blob-id:mysideblob", expected_side_data,
response.get());
EXPECT_TRUE(Put(body_request_, std::move(response)));
EXPECT_TRUE(Match(body_request_));
ASSERT_TRUE(callback_response_->blob);
mojo::Remote<blink::mojom::Blob> blob(
std::move(callback_response_->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
EXPECT_EQ(expected_side_data, CopySideData(blob.get()));
}
TEST_P(CacheStorageCacheTestP, PutWithSideData_QuotaExceeded) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(uint64_t{safe_expected_entry_size.ValueOrDie()} - 1);
const std::string expected_side_data = "SideData";
CopySideDataToResponse("blob-id:mysideblob", expected_side_data,
response.get());
// When the available space is not enough for the body, Put operation must
// fail.
EXPECT_FALSE(Put(body_request_, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutWithSideData_QuotaExceededSkipSideData) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
const std::string expected_side_data = "SideData";
CopySideDataToResponse("blob-id:mysideblob", expected_side_data,
response.get());
// When the available space is enough for the body but not enough for the side
// data, Put operation must succeed.
EXPECT_TRUE(Put(body_request_, std::move(response)));
EXPECT_TRUE(Match(body_request_));
ASSERT_TRUE(callback_response_->blob);
mojo::Remote<blink::mojom::Blob> blob(
std::move(callback_response_->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
// The side data should not be written.
EXPECT_EQ("", CopySideData(blob.get()));
}
TEST_P(CacheStorageCacheTestP, PutWithSideData_BadMessage) {
base::HistogramTester histogram_tester;
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
const std::string expected_side_data = "SideData";
CopySideDataToResponse("blob-id:mysideblob", expected_side_data,
response.get());
blink::mojom::BatchOperationPtr operation =
blink::mojom::BatchOperation::New();
operation->operation_type = blink::mojom::OperationType::kPut;
operation->request = BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation->response = std::move(response);
operation->response->side_data_blob_for_cache_put->size =
std::numeric_limits<uint64_t>::max();
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.emplace_back(std::move(operation));
EXPECT_EQ(CacheStorageError::kErrorStorage,
BatchOperation(std::move(operations)));
histogram_tester.ExpectBucketCount(
"ServiceWorkerCache.ErrorStorageType",
ErrorStorageType::kBatchDidGetUsageAndQuotaInvalidSpace, 1);
EXPECT_EQ("CSDH_UNEXPECTED_OPERATION", bad_message_reason_);
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, WriteSideData) {
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
response->response_time = response_time;
EXPECT_TRUE(Put(body_request_, std::move(response)));
const std::string expected_side_data1 = "SideDataSample";
scoped_refptr<net::IOBuffer> buffer1 =
base::MakeRefCounted<net::StringIOBuffer>(expected_side_data1);
EXPECT_TRUE(WriteSideData(body_request_->url, response_time, buffer1,
expected_side_data1.length()));
EXPECT_TRUE(Match(body_request_));
ASSERT_TRUE(callback_response_->blob);
mojo::Remote<blink::mojom::Blob> blob1(
std::move(callback_response_->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob1.get()));
EXPECT_EQ(expected_side_data1, CopySideData(blob1.get()));
const std::string expected_side_data2 = "New data";
scoped_refptr<net::IOBuffer> buffer2 =
base::MakeRefCounted<net::StringIOBuffer>(expected_side_data2);
EXPECT_TRUE(WriteSideData(body_request_->url, response_time, buffer2,
expected_side_data2.length()));
EXPECT_TRUE(Match(body_request_));
ASSERT_TRUE(callback_response_->blob);
mojo::Remote<blink::mojom::Blob> blob2(
std::move(callback_response_->blob->blob));
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob2.get()));
EXPECT_EQ(expected_side_data2, CopySideData(blob2.get()));
ASSERT_TRUE(Delete(body_request_));
}
TEST_P(CacheStorageCacheTestP, WriteSideData_QuotaExceeded) {
SetQuota(1024 * 1023);
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIResponsePtr response(CreateNoBodyResponse());
response->response_time = response_time;
EXPECT_TRUE(Put(no_body_request_, std::move(response)));
const size_t kSize = 1024 * 1024;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kSize);
memset(buffer->data(), 0, kSize);
EXPECT_FALSE(
WriteSideData(no_body_request_->url, response_time, buffer, kSize));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
ASSERT_TRUE(Delete(no_body_request_));
}
TEST_P(CacheStorageCacheTestP, WriteSideData_QuotaManagerModified) {
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIResponsePtr response(CreateNoBodyResponse());
response->response_time = response_time;
EXPECT_EQ(0, quota_manager_proxy_->notify_storage_modified_count());
EXPECT_TRUE(Put(no_body_request_, std::move(response)));
// Storage notification happens after the operation returns, so continue the
// event loop.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, quota_manager_proxy_->notify_storage_modified_count());
const size_t kSize = 10;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kSize);
memset(buffer->data(), 0, kSize);
EXPECT_TRUE(
WriteSideData(no_body_request_->url, response_time, buffer, kSize));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, quota_manager_proxy_->notify_storage_modified_count());
ASSERT_TRUE(Delete(no_body_request_));
}
TEST_P(CacheStorageCacheTestP, WriteSideData_DifferentTimeStamp) {
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIResponsePtr response(CreateNoBodyResponse());
response->response_time = response_time;
EXPECT_TRUE(Put(no_body_request_, std::move(response)));
const size_t kSize = 10;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kSize);
memset(buffer->data(), 0, kSize);
EXPECT_FALSE(WriteSideData(no_body_request_->url,
response_time + base::Seconds(1), buffer, kSize));
EXPECT_EQ(CacheStorageError::kErrorNotFound, callback_error_);
ASSERT_TRUE(Delete(no_body_request_));
}
TEST_P(CacheStorageCacheTestP, WriteSideData_NotFound) {
const size_t kSize = 10;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kSize);
memset(buffer->data(), 0, kSize);
EXPECT_FALSE(WriteSideData(GURL("http://www.example.com/not_exist"),
base::Time::Now(), buffer, kSize));
EXPECT_EQ(CacheStorageError::kErrorNotFound, callback_error_);
}
TEST_F(CacheStorageCacheTest, CaselessServiceWorkerFetchRequestHeaders) {
// CacheStorageCache depends on blink::mojom::FetchAPIRequest having caseless
// headers so that it can quickly lookup vary headers.
auto request = blink::mojom::FetchAPIRequest::New();
request->url = GURL("http://www.example.com");
request->method = "GET";
request->referrer = blink::mojom::Referrer::New();
request->is_reload = false;
request->headers["content-type"] = "foo";
request->headers["Content-Type"] = "bar";
EXPECT_EQ("bar", request->headers["content-type"]);
}
TEST_P(CacheStorageCacheTestP, QuotaManagerModified) {
EXPECT_EQ(0, quota_manager_proxy_->notify_storage_modified_count());
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
// Storage notification happens after the operation returns, so continue the
// event loop.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, quota_manager_proxy_->notify_storage_modified_count());
EXPECT_LT(0, quota_manager_proxy_->last_notified_delta());
int64_t sum_delta = quota_manager_proxy_->last_notified_delta();
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, quota_manager_proxy_->notify_storage_modified_count());
EXPECT_LT(sum_delta, quota_manager_proxy_->last_notified_delta());
sum_delta += quota_manager_proxy_->last_notified_delta();
EXPECT_TRUE(Delete(body_request_));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(3, quota_manager_proxy_->notify_storage_modified_count());
sum_delta += quota_manager_proxy_->last_notified_delta();
EXPECT_TRUE(Delete(no_body_request_));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(4, quota_manager_proxy_->notify_storage_modified_count());
sum_delta += quota_manager_proxy_->last_notified_delta();
EXPECT_EQ(0, sum_delta);
}
TEST_P(CacheStorageCacheTestP, PutObeysQuotaLimits) {
SetQuota(0);
EXPECT_FALSE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutObeysQuotaLimitsWithEmptyResponse) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
// The first Put will completely fill the quota, leaving no space for the
// second operation, which will fail even with empty response, due to the size
// of the headers.
EXPECT_TRUE(Put(body_request_, std::move(response)));
EXPECT_FALSE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutSafeSpaceIsEnough) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
EXPECT_TRUE(Put(body_request_, std::move(response)));
}
TEST_P(CacheStorageCacheTestP, PutRequestUrlObeysQuotaLimits) {
const GURL url("http://example.com/body.html");
const GURL longerUrl("http://example.com/longer-body.html");
blink::mojom::FetchAPIRequestPtr request = CreateFetchAPIRequest(
url, "GET", kHeaders, blink::mojom::Referrer::New(), false);
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(request) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
request->url = longerUrl;
EXPECT_FALSE(Put(request, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutRequestMethodObeysQuotaLimits) {
blink::mojom::FetchAPIRequestPtr request = CreateFetchAPIRequest(
BodyUrl(), "GET", kHeaders, blink::mojom::Referrer::New(), false);
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(request) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
request->method = "LongerMethodThanGet";
EXPECT_FALSE(Put(request, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutRequestHeadersObeyQuotaLimits) {
blink::mojom::FetchAPIRequestPtr request = CreateFetchAPIRequest(
BodyUrl(), "GET", kHeaders, blink::mojom::Referrer::New(), false);
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(request) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
request->headers["New-Header"] = "foo";
EXPECT_FALSE(Put(request, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutResponseStatusObeysQuotaLimits) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
response->status_text = "LongerThanOK";
EXPECT_FALSE(Put(body_request_, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutResponseBlobObeysQuotaLimits) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
response->blob->size += 1;
EXPECT_FALSE(Put(body_request_, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutResponseHeadersObeyQuotaLimits) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
response->headers["New-Header"] = "foo";
EXPECT_FALSE(Put(body_request_, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutResponseCorsHeadersObeyQuotaLimits) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
response->cors_exposed_header_names.push_back("AnotherOne");
EXPECT_FALSE(Put(body_request_, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutResponseUrlListObeysQuotaLimits) {
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
base::CheckedNumeric<uint64_t> safe_expected_entry_size =
cache_->GetRequiredSafeSpaceForRequest(body_request_) +
cache_->GetRequiredSafeSpaceForResponse(response);
SetQuota(safe_expected_entry_size.ValueOrDie());
response->url_list.emplace_back("http://example.com/another-url");
EXPECT_FALSE(Put(body_request_, std::move(response)));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutObeysQuotaLimitsWithEmptyResponseZeroQuota) {
SetQuota(0);
EXPECT_FALSE(Put(body_request_, CreateNoBodyResponse()));
EXPECT_EQ(CacheStorageError::kErrorQuotaExceeded, callback_error_);
}
TEST_P(CacheStorageCacheTestP, Size) {
EXPECT_EQ(0, Size());
EXPECT_TRUE(Put(no_body_request_, CreateNoBodyResponse()));
EXPECT_LT(0, Size());
int64_t no_body_size = Size();
EXPECT_TRUE(Delete(no_body_request_));
EXPECT_EQ(0, Size());
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_LT(no_body_size, Size());
EXPECT_TRUE(Delete(body_request_));
EXPECT_EQ(0, Size());
}
TEST_F(CacheStorageCacheTest, VerifyOpaqueSizePadding) {
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIRequestPtr non_opaque_request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
non_opaque_request->url = GURL("http://example.com/no-pad.html");
blink::mojom::FetchAPIResponsePtr non_opaque_response =
CreateBlobBodyResponse();
non_opaque_response->response_time = response_time;
EXPECT_TRUE(Put(non_opaque_request, std::move(non_opaque_response)));
int64_t unpadded_no_data_cache_size = Size();
// Now write some side data to that cache.
const std::string expected_side_data(2048, 'X');
scoped_refptr<net::IOBuffer> side_data_buffer =
base::MakeRefCounted<net::StringIOBuffer>(expected_side_data);
EXPECT_TRUE(WriteSideData(non_opaque_request->url, response_time,
side_data_buffer, expected_side_data.length()));
int64_t unpadded_total_resource_size = Size();
int64_t unpadded_side_data_size =
unpadded_total_resource_size - unpadded_no_data_cache_size;
EXPECT_EQ(expected_side_data.size(),
static_cast<size_t>(unpadded_side_data_size));
blink::mojom::FetchAPIResponsePtr non_opaque_response_clone =
CreateBlobBodyResponse();
non_opaque_response_clone->response_time = response_time;
// Now write an identically sized opaque response.
blink::mojom::FetchAPIRequestPtr opaque_request =
BackgroundFetchSettledFetch::CloneRequest(non_opaque_request);
opaque_request->url = GURL("http://example.com/opaque.html");
// Same URL length means same cache sizes (ignoring padding).
EXPECT_EQ(opaque_request->url.spec().length(),
non_opaque_request->url.spec().length());
blink::mojom::FetchAPIResponsePtr opaque_response(CreateOpaqueResponse());
opaque_response->response_time = response_time;
EXPECT_TRUE(Put(opaque_request, std::move(opaque_response)));
int64_t size_after_opaque_put = Size();
int64_t opaque_padding = size_after_opaque_put -
2 * unpadded_no_data_cache_size -
unpadded_side_data_size;
ASSERT_GT(opaque_padding, 0);
// Now write side data and expect to see the padding change.
EXPECT_TRUE(WriteSideData(opaque_request->url, response_time,
side_data_buffer, expected_side_data.length()));
int64_t current_padding = Size() - 2 * unpadded_total_resource_size;
EXPECT_NE(opaque_padding, current_padding);
// Now reset opaque side data back to zero.
const std::string expected_side_data2;
scoped_refptr<net::IOBuffer> buffer2 =
base::MakeRefCounted<net::StringIOBuffer>(expected_side_data2);
EXPECT_TRUE(WriteSideData(opaque_request->url, response_time, buffer2,
expected_side_data2.length()));
EXPECT_EQ(size_after_opaque_put, Size());
// And delete the opaque response entirely.
EXPECT_TRUE(Delete(opaque_request));
EXPECT_EQ(unpadded_total_resource_size, Size());
}
TEST_F(CacheStorageCacheTest, TestDifferentOpaqueSideDataSizes) {
blink::mojom::FetchAPIRequestPtr request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
blink::mojom::FetchAPIResponsePtr response(CreateOpaqueResponse());
auto response_time = response->response_time;
EXPECT_TRUE(Put(request, std::move(response)));
int64_t opaque_cache_size_no_side_data = Size();
const std::string small_side_data(1024, 'X');
scoped_refptr<net::IOBuffer> buffer1 =
base::MakeRefCounted<net::StringIOBuffer>(small_side_data);
EXPECT_TRUE(WriteSideData(request->url, response_time, buffer1,
small_side_data.length()));
int64_t opaque_cache_size_with_side_data = Size();
EXPECT_NE(opaque_cache_size_with_side_data, opaque_cache_size_no_side_data);
// Write side data of a different size. The padding should change.
const std::string large_side_data(2048, 'X');
EXPECT_NE(large_side_data.length(), small_side_data.length());
scoped_refptr<net::IOBuffer> buffer2 =
base::MakeRefCounted<net::StringIOBuffer>(large_side_data);
EXPECT_TRUE(WriteSideData(request->url, response_time, buffer2,
large_side_data.length()));
int side_data_delta = large_side_data.length() - small_side_data.length();
EXPECT_NE(opaque_cache_size_with_side_data + side_data_delta, Size());
}
TEST_F(CacheStorageCacheTest, TestDoubleOpaquePut) {
blink::mojom::FetchAPIRequestPtr request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIResponsePtr response(CreateOpaqueResponse());
response->response_time = response_time;
EXPECT_TRUE(Put(request, std::move(response)));
int64_t size_after_first_put = Size();
blink::mojom::FetchAPIRequestPtr request2 =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
blink::mojom::FetchAPIResponsePtr response2(CreateOpaqueResponse());
response2->response_time = response_time;
EXPECT_TRUE(Put(request2, std::move(response2)));
EXPECT_EQ(size_after_first_put, Size());
}
TEST_P(CacheStorageCacheTestP, GetSizeThenClose) {
// Create the backend and put something in it.
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
// Get a reference to the response in the cache.
EXPECT_TRUE(Match(body_request_));
mojo::Remote<blink::mojom::Blob> blob(
std::move(callback_response_->blob->blob));
callback_response_ = nullptr;
int64_t cache_size = Size();
EXPECT_EQ(cache_size, GetSizeThenClose());
VerifyAllOpsFail();
// Reading blob should fail.
EXPECT_EQ("", storage::BlobToString(blob.get()));
}
TEST_P(CacheStorageCacheTestP, OpsFailOnClosedBackend) {
// Create the backend and put something in it.
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
EXPECT_TRUE(Close());
VerifyAllOpsFail();
}
// Shutdown the cache in the middle of its writing the response body. Upon
// restarting, that response shouldn't be available. See crbug.com/617683.
TEST_P(CacheStorageCacheTestP, UnfinishedPutsShouldNotBeReusable) {
// Create a response with a blob that takes forever to write its bytes to the
// mojo pipe. Guaranteeing that the response isn't finished writing by the
// time we close the backend.
base::RunLoop run_loop;
auto blob = blink::mojom::SerializedBlob::New();
blob->uuid = "mock blob";
blob->size = 100;
mojo::MakeSelfOwnedReceiver(
std::make_unique<SlowBlob>(run_loop.QuitClosure()),
blob->blob.InitWithNewPipeAndPassReceiver());
blink::mojom::FetchAPIResponsePtr response = CreateNoBodyResponse();
response->url_list = {BodyUrl()};
response->blob = std::move(blob);
blink::mojom::BatchOperationPtr operation =
blink::mojom::BatchOperation::New();
operation->operation_type = blink::mojom::OperationType::kPut;
operation->request = BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation->response = std::move(response);
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.emplace_back(std::move(operation));
// Start the put operation and let it run until the blob is supposed to write
// to its pipe.
cache_->BatchOperation(std::move(operations), /* trace_id = */ 0,
base::DoNothing(), base::DoNothing());
run_loop.Run();
// Shut down the cache. Doing so causes the write to cease, and the entry
// should be erased.
cache_ = nullptr;
base::RunLoop().RunUntilIdle();
// Create a new Cache in the same space.
InitCache(nullptr);
// Now attempt to read the same response from the cache. It should fail.
EXPECT_FALSE(Match(body_request_));
}
TEST_P(CacheStorageCacheTestP, BlobReferenceDelaysClose) {
// Create the backend and put something in it.
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
// Get a reference to the response in the cache.
EXPECT_TRUE(Match(body_request_));
mojo::Remote<blink::mojom::Blob> blob(
std::move(callback_response_->blob->blob));
callback_response_ = nullptr;
base::RunLoop loop;
cache_->Close(base::BindOnce(&CacheStorageCacheTest::CloseCallback,
base::Unretained(this),
base::Unretained(&loop)));
task_environment_.RunUntilIdle();
// If MemoryOnly closing does succeed right away.
EXPECT_EQ(MemoryOnly(), callback_closed_);
// Reading blob should succeed.
EXPECT_EQ(expected_blob_data_, storage::BlobToString(blob.get()));
blob.reset();
loop.Run();
EXPECT_TRUE(callback_closed_);
}
TEST_P(CacheStorageCacheTestP, VerifySerialScheduling) {
// Start two operations, the first one is delayed but the second isn't. The
// second should wait for the first.
EXPECT_TRUE(Keys()); // Opens the backend.
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
base::RunLoop open_started_loop;
delayable_backend->set_open_entry_started_callback(
open_started_loop.QuitClosure());
int sequence_out = -1;
blink::mojom::BatchOperationPtr operation1 =
blink::mojom::BatchOperation::New();
operation1->operation_type = blink::mojom::OperationType::kPut;
operation1->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation1->response = CreateBlobBodyResponse();
std::unique_ptr<base::RunLoop> close_loop1(new base::RunLoop());
std::vector<blink::mojom::BatchOperationPtr> operations1;
operations1.emplace_back(std::move(operation1));
cache_->BatchOperation(
std::move(operations1), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::SequenceCallback,
base::Unretained(this), 1, &sequence_out,
close_loop1.get()),
CacheStorageCache::BadMessageCallback());
// Wait until the first operation attempts to open the entry and becomes
// delayed.
open_started_loop.Run();
blink::mojom::BatchOperationPtr operation2 =
blink::mojom::BatchOperation::New();
operation2->operation_type = blink::mojom::OperationType::kPut;
operation2->request =
BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation2->response = CreateBlobBodyResponse();
delayable_backend->set_delay_open_entry(false);
std::unique_ptr<base::RunLoop> close_loop2(new base::RunLoop());
std::vector<blink::mojom::BatchOperationPtr> operations2;
operations2.emplace_back(std::move(operation2));
cache_->BatchOperation(
std::move(operations2), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::SequenceCallback,
base::Unretained(this), 2, &sequence_out,
close_loop2.get()),
CacheStorageCache::BadMessageCallback());
// The second put operation should wait for the first to complete.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(-1, sequence_out);
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
close_loop1->Run();
EXPECT_EQ(1, sequence_out);
close_loop2->Run();
EXPECT_EQ(2, sequence_out);
}
#if defined(OS_WIN)
// TODO(crbug.com/936129): Flaky on Windows.
#define MAYBE_KeysWithManyCacheEntries DISABLED_KeysWithManyCacheEntries
#else
#define MAYBE_KeysWithManyCacheEntries KeysWithManyCacheEntries
#endif
TEST_P(CacheStorageCacheTestP, MAYBE_KeysWithManyCacheEntries) {
// Use a smaller list in disk mode to reduce test runtime.
const int kNumEntries = MemoryOnly() ? 1000 : 250;
std::vector<std::string> expected_keys;
for (int i = 0; i < kNumEntries; ++i) {
GURL url =
net::AppendQueryParameter(NoBodyUrl(), "n", base::NumberToString(i));
expected_keys.push_back(url.spec());
blink::mojom::FetchAPIRequestPtr request = CreateFetchAPIRequest(
url, "GET", kHeaders, blink::mojom::Referrer::New(), false);
EXPECT_TRUE(Put(request, CreateNoBodyResponse()));
}
EXPECT_TRUE(Keys());
EXPECT_EQ(expected_keys.size(), callback_strings_.size());
EXPECT_EQ(expected_keys, callback_strings_);
}
TEST_P(CacheStorageCacheTestP, SelfRefsDuringMatch) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
// When there are no operations outstanding and we're not holding an
// explicit reference the cache should consider itself unreferenced.
EXPECT_TRUE(cache_->IsUnreferenced());
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->Match(CopyFetchRequest(body_request_), /* match_options = */ nullptr,
CacheStorageSchedulerPriority::kNormal, /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::ResponseAndErrorCallback,
base::Unretained(this), loop.get()));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// Since an operation is outstanding the cache should consider itself
// referenced.
EXPECT_FALSE(cache_->IsUnreferenced());
// Allow the operation to continue.
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
loop->Run();
// The operation should succeed.
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
}
TEST_P(CacheStorageCacheTestP, SelfRefsDuringMatchAll) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
// When there are no operations outstanding and we're not holding an
// explicit reference the cache should consider itself unreferenced.
EXPECT_TRUE(cache_->IsUnreferenced());
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
std::vector<blink::mojom::FetchAPIResponsePtr> responses;
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->MatchAll(
CopyFetchRequest(body_request_), /* match_options = */ nullptr,
/* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::ResponsesAndErrorCallback,
base::Unretained(this), loop->QuitClosure(), &responses));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// Since an operation is outstanding the cache should consider itself
// referenced.
EXPECT_FALSE(cache_->IsUnreferenced());
// Allow the operation to continue.
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
loop->Run();
// The operation should succeed.
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
EXPECT_EQ(1u, responses.size());
}
TEST_P(CacheStorageCacheTestP, SelfRefsDuringWriteSideData) {
base::Time response_time(base::Time::Now());
blink::mojom::FetchAPIResponsePtr response = CreateBlobBodyResponse();
response->response_time = response_time;
EXPECT_TRUE(Put(body_request_, std::move(response)));
// When there are no operations outstanding and we're not holding an
// explicit reference the cache should consider itself unreferenced.
EXPECT_TRUE(cache_->IsUnreferenced());
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
const std::string expected_side_data = "SideDataSample";
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::StringIOBuffer>(expected_side_data);
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->WriteSideData(
base::BindOnce(&CacheStorageCacheTest::ErrorTypeCallback,
base::Unretained(this), base::Unretained(loop.get())),
BodyUrl(), response_time, /* trace_id = */ 0, buffer,
expected_side_data.length());
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// Since an operation is outstanding the cache should consider itself
// referenced.
EXPECT_FALSE(cache_->IsUnreferenced());
// Allow the operation to continue.
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
loop->Run();
// The operation should succeed.
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
}
TEST_P(CacheStorageCacheTestP, SelfRefsDuringBatchOperation) {
// Open the backend
EXPECT_TRUE(Keys());
blink::mojom::BatchOperationPtr operation =
blink::mojom::BatchOperation::New();
operation->operation_type = blink::mojom::OperationType::kPut;
operation->request = BackgroundFetchSettledFetch::CloneRequest(body_request_);
operation->request->url = GURL("http://example.com/1");
operation->response = CreateBlobBodyResponse();
operation->response->url_list.emplace_back("http://example.com/1");
std::vector<blink::mojom::BatchOperationPtr> operations;
operations.push_back(std::move(operation));
// When there are no operations outstanding and we're not holding an
// explicit reference the cache should consider itself unreferenced.
EXPECT_TRUE(cache_->IsUnreferenced());
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->BatchOperation(
std::move(operations), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::VerboseErrorTypeCallback,
base::Unretained(this), base::Unretained(loop.get())),
base::BindOnce(&OnBadMessage, base::Unretained(&bad_message_reason_)));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// Since an operation is outstanding the cache should consider itself
// referenced.
EXPECT_FALSE(cache_->IsUnreferenced());
// Allow the operation to continue.
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
loop->Run();
// The operation should succeed.
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
}
TEST_P(CacheStorageCacheTestP, SelfRefsDuringKeys) {
EXPECT_TRUE(Put(body_request_, CreateBlobBodyResponse()));
// When there are no operations outstanding and we're not holding an
// explicit reference the cache should consider itself unreferenced.
EXPECT_TRUE(cache_->IsUnreferenced());
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->Keys(
BackgroundFetchSettledFetch::CloneRequest(body_request_),
/* match_options = */ nullptr,
/* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::RequestsCallback,
base::Unretained(this), base::Unretained(loop.get())));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// Since an operation is outstanding the cache should consider itself
// referenced.
EXPECT_FALSE(cache_->IsUnreferenced());
// Allow the operation to continue.
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
loop->Run();
// The operation should succeed.
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
}
TEST_P(CacheStorageCacheTestP, SelfRefsDuringPut) {
// Open the backend
EXPECT_TRUE(Keys());
// When there are no operations outstanding and we're not holding an
// explicit reference the cache should consider itself unreferenced.
EXPECT_TRUE(cache_->IsUnreferenced());
DelayableBackend* delayable_backend = cache_->UseDelayableBackend();
delayable_backend->set_delay_open_entry(true);
std::unique_ptr<base::RunLoop> loop(new base::RunLoop());
cache_->Put(
BackgroundFetchSettledFetch::CloneRequest(body_request_),
CreateBlobBodyResponse(), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::ErrorTypeCallback,
base::Unretained(this), base::Unretained(loop.get())));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// Since an operation is outstanding the cache should consider itself
// referenced.
EXPECT_FALSE(cache_->IsUnreferenced());
// Allow the operation to continue.
EXPECT_TRUE(delayable_backend->OpenEntryContinue());
loop->Run();
// The operation should succeed.
EXPECT_EQ(CacheStorageError::kSuccess, callback_error_);
}
TEST_P(CacheStorageCacheTestP, PutFailCreateEntry) {
// Open the backend.
EXPECT_TRUE(Keys());
std::unique_ptr<base::RunLoop> run_loop;
cache_->UseFailableBackend(FailableBackend::FailureStage::CREATE_ENTRY);
cache_->Put(
BackgroundFetchSettledFetch::CloneRequest(body_request_),
CreateBlobBodyResponse(), /* trace_id = */ 0,
base::BindOnce(&CacheStorageCacheTest::ErrorTypeCallback,
base::Unretained(this), base::Unretained(run_loop.get())));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// The operation should fail.
EXPECT_EQ(CacheStorageError::kErrorExists, callback_error_);
// QuotaManager should have been notified of write failures.
ASSERT_EQ(1U, mock_quota_manager_->write_error_tracker().size());
EXPECT_EQ(1,
/*error_count*/ mock_quota_manager_->write_error_tracker()
.begin()
->second);
EXPECT_FALSE(Put(body_request_, CreateBlobBodyResponse()));
ASSERT_EQ(1U, mock_quota_manager_->write_error_tracker().size());
EXPECT_EQ(2,
/*error_count*/ mock_quota_manager_->write_error_tracker()
.begin()
->second);
}
TEST_P(CacheStorageCacheTestP, PutFailWriteHeaders) {
// Only interested in quota being notified for disk write errors
// as opposed to errors from a memory only scenario.
if (MemoryOnly()) {
return;
}
// Open the backend.
EXPECT_TRUE(Keys());
std::unique_ptr<base::RunLoop> run_loop;
cache_->UseFailableBackend(FailableBackend::FailureStage::WRITE_HEADERS);
EXPECT_FALSE(Put(body_request_, CreateBlobBodyResponse()));
// Blocks on opening the cache entry.
base::RunLoop().RunUntilIdle();
// The operation should fail.
EXPECT_EQ(CacheStorageError::kErrorStorage, callback_error_);
// QuotaManager should have been notified of write failures.
ASSERT_EQ(1U, mock_quota_manager_->write_error_tracker().size());
EXPECT_EQ(1,
/*error_count*/ mock_quota_manager_->write_error_tracker()
.begin()
->second);
EXPECT_FALSE(Put(body_request_, CreateBlobBodyResponse()));
ASSERT_EQ(1U, mock_quota_manager_->write_error_tracker().size());
EXPECT_EQ(2,
/*error_count*/ mock_quota_manager_->write_error_tracker()
.begin()
->second);
}
INSTANTIATE_TEST_SUITE_P(CacheStorageCacheTest,
CacheStorageCacheTestP,
::testing::Values(false, true));
} // namespace cache_storage_cache_unittest
} // namespace content
| 39.8557 | 81 | 0.72548 | [
"object",
"vector"
] |
c9337b819d228ef17e9806b9d58a0c0a2fe3def8 | 9,050 | cc | C++ | PYTHIA8/pythia8243/examples/main113.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | PYTHIA8/pythia8243/examples/main113.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | PYTHIA8/pythia8243/examples/main113.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | // main113.cc is a part of the PYTHIA event generator.
// Copyright (C) 2019 Torbjorn Sjostrand.
// PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details.
// Please respect the MCnet Guidelines, see GUIDELINES for details.
// This test program will generate Pb-Pb collisions at
// sqrt(S_NN)=2.76TeV using the Angantyr model for Heavy Ion
// collisions. The analysis will divide the event in centrality
// classes using the same observable as was used for p-Pb in the ATLAS
// analysis in arXiv:1508.00848 [hep-ex] (see main112.cc). The
// centrality classes are same as in the ALICE analysis in
// arXiv:1012.1657 [nucl-ex] although the actual observable used is
// not the same. Histograms of multiplicity distributions are measured
// for each centrality percentile.
// Note that heavy ion collisions are computationally quite CPU
// intensive and generating a single event will take around a second
// on a reasonable desktop. To get reasonable statistics, this program
// will take a couple of hours to run.
#include "Pythia8/Pythia.h"
// You need to include this to get access to the HIInfo object for
// HeavyIons.
#include "Pythia8/HeavyIons.h"
using namespace Pythia8;
int main() {
Pythia pythia;
// Setup the beams.
pythia.readString("Beams:idA = 1000822080");
pythia.readString("Beams:idB = 1000822080"); // The lead ion.
pythia.readString("Beams:eCM = 2760.0");
pythia.readString("Beams:frameType = 1");
// Initialize the Angantyr model to fit the total and semi-includive
// cross sections in Pythia within some tolerance.
pythia.readString("HeavyIon:SigFitErr = "
"0.02,0.02,0.1,0.05,0.05,0.0,0.1,0.0");
// These parameters are typicall suitable for sqrt(S_NN)=5TeV
pythia.readString("HeavyIon:SigFitDefPar = "
"17.24,2.15,0.33,0.0,0.0,0.0,0.0,0.0");
// A simple genetic algorithm is run for 20 generations to fit the
// parameters.
pythia.readString("HeavyIon:SigFitNGen = 20");
// There will be nine centrality bins based on the sum transverse
// emergy in a rapidity interval between 3.2 and 4.9 obtained from
// the borders from the generated transverse energy spectrum. The
// default settings should give approximately the following:
double genlim[] = {2979.4, 2400.1, 1587.5, 1028.8, 669.9,
397.4, 220.3, 116.3, 54.5};
// If you change any parameters these should also be changed.
// The upper edge of the correponding percentiles:
double pclim[] = {0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
// Book the pseudorapidity and multiplicity histograms and get
// counters for number of events and sum of event weights:
typedef map<double,int,std::greater<double> > MapIdx;
MapIdx genetaidx;
vector<Hist*> etadist(9), lmult(9), hmult(9);
string etaname("EtadistC"), mname("MultC");
vector<double> gensumw(9, 0.0), gensumn(9, 0.0);
for ( int i = 0; i < 9; ++i ) {
genetaidx[genlim[i]] = i;
etadist[i] = new Hist(etaname + char('0' + i), 54, -2.7, 2.7);
hmult[i] = new Hist(mname + 'H' + char('0' + i),
75, -0.5, 2999.5);
lmult[i] = new Hist(mname + 'L' + char('0' + i),
75, -0.5, 299.5);
}
// Book histogram for the centrality measure.
Hist sumet("SumETfwd", 200, 0.0, 4000.0);
// Also make a map of all weight to check the generated centrality
// classes.
multimap<double,double> gencent;
// Book a histogram for the distribution of number of wounded
// nucleons.
Hist wounded("Nwounded", 209, -0.5, 417.5);
// Profile for average central multiplicity and number of wounded
// nucleons as a function of centrality (with errors).
vector<double> cmult(9, 0.0), cmult2(9, 0.0);
vector<double> wound(9, 0.0), wound2(9, 0.0);
// Sum up the weights of all generated events.
double sumw = 0.0;
// Initialise Pythia.
pythia.init();
// Loop over events.
int nEvents = 10000;
for ( int iEvent = 0; iEvent < nEvents; ++iEvent ) {
if ( !pythia.next() ) continue;
// First sum up transverse energy for centrality measure and also
// check that the trigger requiring ar least one charged particle
// forward and backward.
double etfwd = 0.0;
bool trigfwd = false;
bool trigbwd = false;
int nc = 0;
for (int i = 0; i < pythia.event.size(); ++i) {
Particle & p = pythia.event[i];
if ( p.isFinal() ) {
double eta = p.eta();
if ( p.isCharged() && p.pT() > 0.1 && eta < -2.09 && eta > -3.84 )
trigfwd = true;
if ( p.isCharged() && p.pT() > 0.1 && eta > 2.09 && eta < 3.84 )
trigbwd = true;
if ( p.pT() > 0.1 && abs(eta) > 3.2 && abs(eta) < 4.9 )
etfwd += p.eT();
if ( p.isCharged() && p.pT() > 0.1 && abs(eta) < 0.5 ) ++nc;
}
}
// Skip if not triggered
if ( !(trigfwd && trigbwd) ) continue;
// Keep track of the sum of waights
double weight = pythia.info.weight();
sumw += weight;
// Histogram and save the summed Et.
sumet.fill(etfwd, weight);
gencent.insert(make_pair(etfwd, weight));
// Also fill the number of (absorptively and diffractively)
// wounded nucleaons.
int nw = pythia.info.hiinfo->nAbsTarg() +
pythia.info.hiinfo->nDiffTarg() +
pythia.info.hiinfo->nAbsProj() +
pythia.info.hiinfo->nDiffProj();
wounded.fill(nw, weight);
// Find the correct centrality histograms.
MapIdx::iterator genit = genetaidx.upper_bound(etfwd);
int genidx = genit== genetaidx.end()? -1: genit->second;
// Sum the weights in the centrality classes, skip if not in a class.
if ( genidx < 0 ) continue;
gensumw[genidx] += weight;
hmult[genidx]->fill(nc, weight);
lmult[genidx]->fill(nc, weight);
gensumn[genidx] += 1.0;
cmult[genidx] += nc*weight;
cmult2[genidx] += nc*nc*weight;
wound[genidx] += nw*weight;
wound2[genidx] += nw*nw*weight;
// Go through the event again and fill the eta distributions.
for (int i = 0; i < pythia.event.size(); ++i) {
Particle & p = pythia.event[i];
if ( p.isFinal() && p.isCharged() &&
abs(p.eta()) < 2.7 && p.pT() > 0.1 ) {
etadist[genidx]->fill(p.eta(), weight);
}
}
}
// The run is over, so we write out some statistics.
// Now, we just have to normalize and prtint out the histograms. We
// choose to print the histograms to a file that can be read by
// eg. gnuplot.
ofstream ofs("main113.dat");
sumet /= sumw*2.0;
ofs << "# " << sumet.getTitle() << endl;
sumet.table(ofs);
wounded /= sumw*2.0;
ofs << "\n# " << wounded.getTitle() << endl;
wounded.table(ofs);
// Print out the centrality binned eta distributions and delete the
// heap-allocate histograms.
for ( int idx = 0; idx < 9; ++idx ) {
*hmult[idx] /= gensumw[idx]*40.0;
ofs << "\n# " << hmult[idx]->getTitle() << endl;
hmult[idx]->table(ofs);
delete hmult[idx];
*lmult[idx] /= gensumw[idx]*4.0;
ofs << "\n# " << lmult[idx]->getTitle() << endl;
lmult[idx]->table(ofs);
delete lmult[idx];
*etadist[idx] /= gensumw[idx]*0.1;
ofs << "\n# " << etadist[idx]->getTitle() << endl;
etadist[idx]->table(ofs);
delete etadist[idx];
}
// Print out average central charged multiplicity as a function of
// centrality.
ofs << "\n# Nch0\n";
for ( int idx = 0; idx < 9; ++idx ) {
double Nch = cmult[idx]/gensumw[idx];
cmult2[idx] = (cmult2[idx]/gensumw[idx] - pow2(Nch))/gensumn[idx];
ofs << setprecision(2) << setw(4) << int(pclim[idx]*100.0 + 0.5)
<< setw(10) << Nch << setw(10) << sqrt(cmult2[idx]) <<endl;
}
ofs << "\n# Nwc\n";
for ( int idx = 0; idx < 9; ++idx ) {
double Nw = wound[idx]/gensumw[idx];
wound2[idx] = (wound2[idx]/gensumw[idx] - pow2(Nw))/gensumn[idx];
ofs << setprecision(2) << setw(4) << int(pclim[idx]*100.0 + 0.5)
<< setw(10) << Nw << setw(10) << sqrt(wound2[idx]) <<endl;
}
// Befor we end we print out some statistics. Also, we want to check
// that our generated centrality classes were the same as we
// guessed.
pythia.stat();
double curr = 0.0;
double prev = 0.0;
double acc = 0.0;
int idxa = 8;
double lim = sumw*(1.0 - pclim[idxa]);
vector<double> newlim(9);
for ( multimap<double, double>::iterator it = gencent.begin();
it != gencent.end(); ++it ) {
prev = curr;
curr = it->first;
double w = it->second;
if ( acc < lim && acc + w >= lim ) {
newlim[idxa--] = prev + (curr - prev)*(lim - acc)/w;
if ( idxa < 0 ) break;
lim = sumw*(1.0 - pclim[idxa]);
}
acc += w;
}
cout << "The generated limits between centrality classes in this run:\n"
<< " % assumed actual\n";
for ( int idx = 0; idx < 9; ++idx )
cout << setw(4) << int(pclim[idx]*100.0 + 0.5)
<< setw(10) << fixed << setprecision(1) << genlim[idx]
<< setw(10) << fixed << setprecision(1) << newlim[idx] << endl;
// And we're done!
return 0;
}
| 36.055777 | 77 | 0.612818 | [
"object",
"vector",
"model"
] |
c938715a16960f6604da3c7492bdf49dec024a4d | 20,668 | cpp | C++ | admin/admt/workobj/chdom.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/admt/workobj/chdom.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/admt/workobj/chdom.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*---------------------------------------------------------------------------
File: ChangeDomain.cpp
Comments: Implementation of COM object that changes the domain affiliation on
a computer.
(c) Copyright 1999, Mission Critical Software, Inc., All Rights Reserved
Proprietary and confidential to Mission Critical Software, Inc.
REVISION LOG ENTRY
Revision By: Christy Boles
Revised on 02/15/99 11:21:07
---------------------------------------------------------------------------
*/
// ChangeDomain.cpp : Implementation of CChangeDomain
#include "stdafx.h"
#include "WorkObj.h"
#include "ChDom.h"
#include "Common.hpp"
#include "UString.hpp"
#include "EaLen.hpp"
#include "ResStr.h"
#include "ErrDct.hpp"
#include "TxtSid.h"
#include "TReg.hpp"
/////////////////////////////////////////////////////////////////////////////
// CChangeDomain
#include "LSAUtils.h"
#import "NetEnum.tlb" no_namespace
#import "VarSet.tlb" no_namespace rename("property", "aproperty")
#include <lm.h> // for NetXxx API
#include <winbase.h>
TErrorDct errLocal;
typedef NET_API_STATUS (NET_API_FUNCTION* PNETJOINDOMAIN)
(
IN LPCWSTR lpServer OPTIONAL,
IN LPCWSTR lpDomain,
IN LPCWSTR lpAccountOU, OPTIONAL
IN LPCWSTR lpAccount OPTIONAL,
IN LPCWSTR lpPassword OPTIONAL,
IN DWORD fJoinOptions
);
HINSTANCE hDll = NULL;
PNETJOINDOMAIN pNetJoinDomain = NULL;
BOOL GetNetJoinDomainFunction()
{
BOOL bSuccess = FALSE;
hDll = LoadLibrary(L"NetApi32.dll");
if ( hDll )
{
pNetJoinDomain = (PNETJOINDOMAIN)GetProcAddress(hDll,"NetJoinDomain");
if ( pNetJoinDomain )
{
bSuccess = TRUE;
}
}
return bSuccess;
}
typedef HRESULT (CALLBACK * ADSGETOBJECT)(LPWSTR, REFIID, void**);
extern ADSGETOBJECT ADsGetObject;
STDMETHODIMP
CChangeDomain::ChangeToDomain(
BSTR activeComputerName, // in - computer name currently being used (old name if simultaneously renaming and changing domain)
BSTR domain, // in - domain to move computer to
BSTR newComputerName, // in - computer name the computer will join the new domain as (the name that will be in effect on reboot, if simultaneously renaming and changing domain)
BSTR * errReturn // out- string describing any errors that occurred
)
{
HRESULT hr = S_OK;
return hr;
}
STDMETHODIMP
CChangeDomain::ChangeToDomainWithSid(
BSTR activeComputerName, // in - computer name currently being used (old name if simultaneously renaming and changing domain)
BSTR domain, // in - domain to move computer to
BSTR domainSid, // in - sid of domain, as string
BSTR domainController, // in - domain controller to use
BSTR newComputerName, // in - computer name the computer will join the new domain as (the name that will be in effect on reboot, if simultaneously renaming and changing domain)
BSTR srcPath, // in - source account original LDAP path
BSTR * errReturn // out- string describing any errors that occurred
)
{
USES_CONVERSION;
HRESULT hr = S_OK;
// initialize output parameters
(*errReturn) = NULL;
//
// Use NetJoinDomain API if available (Windows 2000 and later)
// otherwise must use LSA APIs (Windows NT 4 and earlier).
//
if (GetNetJoinDomainFunction())
{
DWORD dwError = ERROR_SUCCESS;
//
// If a preferred domain controller is specified then use it.
//
_bstr_t strNewDomain = domain;
if (SysStringLen(domainController) > 0)
{
//
// The preferred domain controller may only be specified for uplevel
// (W2K or later) domains. During undo of a computer migration the
// target domain may be a downlevel (NT4) domain. If unable to obtain
// operating system version information from the specified domain
// controller or the operating system is downlevel then don't specify
// a preferred domain controller.
//
PWKSTA_INFO_100 pInfo = NULL;
NET_API_STATUS nasStatus = NetWkstaGetInfo(domainController, 100, (LPBYTE*)&pInfo);
if ((nasStatus == NERR_Success) && pInfo)
{
if (pInfo->wki100_ver_major >= 5)
{
NetApiBufferFree(pInfo);
strNewDomain += L"\\";
strNewDomain += domainController;
}
}
}
//
// Join Options
//
const DWORD JOIN_OPTIONS = NETSETUP_JOIN_DOMAIN | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_UNSECURE;
//
// Check whether a new computer name has been specified.
//
if (SysStringLen(newComputerName) == 0)
{
//
// A new name has not been specified therefore simply
// join the new domain with the current computer name.
//
dwError = pNetJoinDomain(NULL, strNewDomain, NULL, NULL, NULL, JOIN_OPTIONS);
}
else
{
//
// A new name has been specified therefore computer must be re-named during join.
//
// The current APIs only support joining a domain with the current name and then
// re-naming the computer in the domain after the join. Unfortunately the re-name
// in the domain requires the credentials of a security principal with the rights
// to change the name of the computer in the domain or that this process be running
// under the security context of a security principal with the rights to change the
// name of the computer in the domain. Since these requirements cannot be met with
// ADMT the following trick (read hack) must be used.
//
// Set the active computer name in the registry to the new name during the duration
// of the NetJoinDomain call so that the computer is joined to the new domain with
// the new name without requiring a subsequent re-name in the new domain.
//
TRegKey key;
static WCHAR c_szKey[] = L"System\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName";
dwError = key.Open(c_szKey, HKEY_LOCAL_MACHINE);
if (dwError == ERROR_SUCCESS)
{
static WCHAR c_szKeyValue[] = L"ComputerName";
WCHAR szOldComputerName[MAX_PATH];
dwError = key.ValueGetStr(c_szKeyValue, szOldComputerName, MAX_PATH - 1);
if (dwError == ERROR_SUCCESS)
{
dwError = key.ValueSetStr(c_szKeyValue, OLE2CW(newComputerName));
if (dwError == ERROR_SUCCESS)
{
dwError = pNetJoinDomain(NULL, strNewDomain, NULL, NULL, NULL, JOIN_OPTIONS);
key.ValueSetStr(c_szKeyValue, szOldComputerName);
key.Close();
}
}
}
}
hr = HRESULT_FROM_WIN32(dwError);
}
else
{
do // once
{
LSA_HANDLE PolicyHandle = NULL;
LPWSTR Workstation; // target machine of policy update
WCHAR Password[LEN_Password];
PSID DomainSid=NULL; // Sid representing domain to trust
PSERVER_INFO_101 si101 = NULL;
DWORD Type;
NET_API_STATUS nas;
NTSTATUS Status;
WCHAR errMsg[1000];
WCHAR TrustedDomainName[LEN_Domain];
WCHAR LocalMachine[MAX_PATH] = L"";
DWORD lenLocalMachine = DIM(LocalMachine);
LPWSTR activeWorkstation = L"";
// use the target name, if provided
if ( newComputerName && UStrLen((WCHAR*)newComputerName) )
{
Workstation = (WCHAR*)newComputerName;
if ( ! activeComputerName || ! UStrLen((WCHAR*)activeComputerName) )
{
activeWorkstation = LocalMachine;
}
else
{
activeWorkstation = (WCHAR*)activeComputerName;
}
}
else
{
if (! activeComputerName || ! UStrLen((WCHAR*)activeComputerName) )
{
GetComputerName(LocalMachine,&lenLocalMachine);
Workstation = LocalMachine;
activeWorkstation = L"";
}
else
{
Workstation = (WCHAR*)activeComputerName;
activeWorkstation = Workstation;
}
}
wcscpy(TrustedDomainName,(WCHAR*)domain);
if ( Workstation[0] == L'\\' )
Workstation += 2;
// Use a default password
for ( UINT p = 0 ; p < wcslen(Workstation) ; p++ )
Password[p] = towlower(Workstation[p]);
Password[wcslen(Workstation)] = 0;
// ensure that the password is truncated at 14 characters
Password[14] = 0;
//
// insure the target machine is NOT a DC, as this operation is
// only appropriate against a workstation.
//
nas = NetServerGetInfo(activeWorkstation, 101, (LPBYTE *)&si101);
if(nas != NERR_Success)
{
hr = HRESULT_FROM_WIN32(nas);
break;
}
// Use LSA APIs
Type = si101->sv101_type;
if( (Type & SV_TYPE_DOMAIN_CTRL) ||
(Type & SV_TYPE_DOMAIN_BAKCTRL) )
{
swprintf(errMsg,GET_STRING(IDS_NotAllowedOnDomainController));
hr = E_NOTIMPL;
break;
}
//
// do not allow a workstation to trust itself
//
if(lstrcmpiW(TrustedDomainName, Workstation) == 0)
{
swprintf(errMsg,GET_STRING(IDS_CannotTrustSelf),
TrustedDomainName);
hr = E_INVALIDARG;
break;
}
if( lstrlenW(TrustedDomainName ) > MAX_COMPUTERNAME_LENGTH )
{
TrustedDomainName[MAX_COMPUTERNAME_LENGTH] = L'\0'; // truncate
}
if ( ! m_bNoChange )
{
//
// build the DomainSid of the domain to trust
//
DomainSid = SidFromString(domainSid);
if(!DomainSid )
{
hr = HRESULT_FROM_WIN32(GetLastError());
break;
}
}
if ( (!m_bNoChange) && (si101->sv101_version_major < 4) )
{
// For NT 3.51 machines, we must move the computer to a workgroup, and
// then move it into the new domain
hr = ChangeToWorkgroup(SysAllocString(activeWorkstation),SysAllocString(L"WORKGROUP"),errReturn);
if (FAILED(hr)) {
break;
}
Status = QueryWorkstationTrustedDomainInfo(PolicyHandle,DomainSid,m_bNoChange);
if ( Status != STATUS_SUCCESS )
{
hr = HRESULT_FROM_WIN32(LsaNtStatusToWinError(Status));
break;
}
}
//
// see if the computer account exists on the domain
//
//
// open the policy on this computer
//
Status = OpenPolicy(
activeWorkstation,
DELETE | // to remove a trust
POLICY_VIEW_LOCAL_INFORMATION | // to view trusts
POLICY_CREATE_SECRET | // for password set operation
POLICY_TRUST_ADMIN, // for trust creation
&PolicyHandle
);
if( Status != STATUS_SUCCESS )
{
hr = HRESULT_FROM_WIN32(LsaNtStatusToWinError(Status));
break;
}
if ( ! m_bNoChange )
{
Status = QueryWorkstationTrustedDomainInfo(PolicyHandle,DomainSid,m_bNoChange);
if (Status == STATUS_SUCCESS) {
Status = SetWorkstationTrustedDomainInfo(
PolicyHandle,
DomainSid,
TrustedDomainName,
Password,
errMsg
);
}
}
if( Status != STATUS_SUCCESS )
{
hr = HRESULT_FROM_WIN32(LsaNtStatusToWinError(Status));
break;
}
//
// Update the primary domain to match the specified trusted domain
//
if (! m_bNoChange )
{
Status = SetPrimaryDomain(PolicyHandle, DomainSid, TrustedDomainName);
if(Status != STATUS_SUCCESS)
{
// DisplayNtStatus(errMsg,"SetPrimaryDomain", Status,NULL);
hr = HRESULT_FROM_WIN32(LsaNtStatusToWinError(Status));
break;
}
}
NetApiBufferFree(si101);
// Cleanup
//LocalFree(Workstation);
//
// free the Sid which was allocated for the TrustedDomain Sid
//
if(DomainSid)
{
FreeSid(DomainSid);
}
//
// close the policy handle
//
if ( PolicyHandle )
{
LsaClose(PolicyHandle);
}
} while (false); // do once
if (FAILED(hr))
{
(*errReturn) = NULL;
}
}
return hr;
}
STDMETHODIMP
CChangeDomain::ChangeToWorkgroup(
BSTR Computer, // in - name of computer to update
BSTR Workgroup, // in - name of workgroup to join
BSTR * errReturn // out- text describing error if failure
)
{
HRESULT hr = S_OK;
LSA_HANDLE PolicyHandle = NULL;
LPWSTR Workstation; // target machine of policy update
LPWSTR TrustedDomainName; // domain to join
PSERVER_INFO_101 si101;
DWORD Type;
NET_API_STATUS nas;
NTSTATUS Status;
WCHAR errMsg[1000] = L"";
// BOOL bSessionEstablished = FALSE;
// initialize output parameters
(*errReturn) = NULL;
Workstation = (WCHAR*)Computer;
TrustedDomainName = (WCHAR*)Workgroup;
errLocal.DbgMsgWrite(0,L"Changing to workgroup...");
//
// insure the target machine is NOT a DC, as this operation is
// only appropriate against a workstation.
//
do // once
{
/*if ( m_account.length() )
{
// Establish our credentials to the target machine
if (! EstablishSession(Workstation,m_domain,m_account,m_password, TRUE) )
{
// DisplayError(errMsg,"EstablishSession",GetLastError(),NULL);
hr = GetLastError();
}
else
{
bSessionEstablished = TRUE;
}
}
*/
nas = NetServerGetInfo(Workstation, 101, (LPBYTE *)&si101);
if(nas != NERR_Success)
{
//DisplayError(errMsg, "NetServerGetInfo", nas,NULL);
hr = E_FAIL;
break;
}
Type = si101->sv101_type;
NetApiBufferFree(si101);
if( (Type & SV_TYPE_DOMAIN_CTRL) ||
(Type & SV_TYPE_DOMAIN_BAKCTRL) )
{
swprintf(errMsg,L"Operation is not valid on a domain controller.\n");
hr = E_FAIL;
break;
}
//
// do not allow a workstation to trust itself
//
if(lstrcmpiW(TrustedDomainName, Workstation) == 0)
{
swprintf(errMsg,L"Error: Domain %ls cannot be a member of itself.\n",
TrustedDomainName);
hr = E_FAIL;
break;
}
if( lstrlenW(TrustedDomainName ) > MAX_COMPUTERNAME_LENGTH )
{
TrustedDomainName[MAX_COMPUTERNAME_LENGTH] = L'\0'; // truncate
}
//
// open the policy on this computer
//
Status = OpenPolicy(
Workstation,
DELETE | // to remove a trust
POLICY_VIEW_LOCAL_INFORMATION | // to view trusts
POLICY_CREATE_SECRET | // for password set operation
POLICY_TRUST_ADMIN, // for trust creation
&PolicyHandle
);
if( Status != STATUS_SUCCESS )
{
//DisplayNtStatus(errMsg,"OpenPolicy", Status,NULL);
hr = LsaNtStatusToWinError(Status);
break;
}
if( Status != STATUS_SUCCESS )
{
hr = E_FAIL;
break;
}
//
// Update the primary domain to match the specified trusted domain
//
if (! m_bNoChange )
{
Status = SetPrimaryDomain(PolicyHandle, NULL, TrustedDomainName);
if(Status != STATUS_SUCCESS)
{
//DisplayNtStatus(errMsg,"SetPrimaryDomain", Status,NULL);
hr = LsaNtStatusToWinError(Status);
break;
}
}
} while (false); // do once
// Cleanup
//
// close the policy handle
//
if(PolicyHandle)
{
LsaClose(PolicyHandle);
}
/*if ( bSessionEstablished )
{
EstablishSession(Workstation,m_domain,m_account,m_password,FALSE);
}
*/
if ( FAILED(hr) )
{
hr = S_FALSE;
(*errReturn) = SysAllocString(errMsg);
}
return hr;
}
STDMETHODIMP
CChangeDomain::ConnectAs(
BSTR domain, // in - domain name to use for credentials
BSTR user, // in - account name to use for credentials
BSTR password // in - password to use for credentials
)
{
m_domain = domain;
m_account = user;
m_password = password;
m_domainAccount = domain;
m_domainAccount += L"\\";
m_domainAccount += user;
return S_OK;
}
STDMETHODIMP
CChangeDomain::get_NoChange(
BOOL * pVal // out- flag, whether to write changes
)
{
(*pVal) = m_bNoChange;
return S_OK;
}
STDMETHODIMP
CChangeDomain::put_NoChange(
BOOL newVal // in - flag, whether to write changes
)
{
m_bNoChange = newVal;
return S_OK;
}
// ChangeDomain worknode: Changes the domain affiliation of a workstation or server
// (This operation cannot be performed on domain controllers)
//
// VarSet syntax:
//
// Input:
// ChangeDomain.Computer: <ComputerName>
// ChangeDomain.TargetDomain: <Domain>
// ChangeDomain.DomainIsWorkgroup: <Yes|No> default is No
// ChangeDomain.ConnectAs.Domain: <Domain> optional credentials to use
// ChangeDomain.ConnectAs.User : <Username>
// ChangeDomain.ConnectAs.Password : <Password>
//
// Output:
// ChangeDomain.ErrorText : <string-error message>
// This function is not currently used by the domain migration tool.
// The actual implementation is removed from the source.
STDMETHODIMP
CChangeDomain::Process(
IUnknown * pWorkItem
)
{
return E_NOTIMPL;
}
| 31.74808 | 206 | 0.514031 | [
"object"
] |
c93d540444a6d08d7391b2fbe17c2ab338389154 | 722 | cc | C++ | uva/chapter_5/382.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | uva/chapter_5/382.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | uva/chapter_5/382.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using ll = long long;
using llu = unsigned long long;
const int INF = numeric_limits<int>::max();
int main() {
printf("PERFECTION OUTPUT\n");
int n;
while (cin >> n, n) {
int sum = 0;
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum += i;
}
}
printf("%5d ", n);
if (n < sum) {
printf("ABUNDANT\n");
} else if (n == sum) {
printf("PERFECT\n");
} else {
printf("DEFICIENT\n");
}
}
// 15 DEFICIENT
// 28 PERFECT
// 6 PERFECT
// 56 ABUNDANT
// 60000 ABUNDANT
// 22 DEFICIENT
// 496 PERFECT"
printf("END OF OUTPUT\n");
}
| 19 | 43 | 0.51385 | [
"vector"
] |
c942c2366d27878abd3a2c4afabffd8e7d5e6753 | 2,696 | cpp | C++ | src/python/cupoch_pybind/planning/planning.cpp | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 522 | 2020-01-19T05:59:00.000Z | 2022-03-25T04:36:52.000Z | src/python/cupoch_pybind/planning/planning.cpp | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 87 | 2020-02-23T09:56:48.000Z | 2022-03-25T13:35:15.000Z | src/python/cupoch_pybind/planning/planning.cpp | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 74 | 2020-01-27T15:33:30.000Z | 2022-03-27T11:58:22.000Z | /**
* Copyright (c) 2020 Neka-Nat
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
#include "cupoch_pybind/planning/planning.h"
#include "cupoch/planning/planner.h"
#include "cupoch/geometry/graph.h"
using namespace cupoch;
void pybind_planning_classes(py::module &m) {
// cupoch.registration.ICPConvergenceCriteria
py::class_<planning::Pos3DPlanner> pos3d_planner(
m, "Pos3DPlanner",
"Planner implements position-based 3d path planner.");
py::detail::bind_copy_functions<planning::Pos3DPlanner>(pos3d_planner);
pos3d_planner
.def(py::init([](const geometry::Graph<3>& graph,
float object_radius,
float max_edge_distance) {
return new planning::Pos3DPlanner(graph, object_radius, max_edge_distance);
}),
"graph"_a, "object_radius"_a = 0.1, "max_edge_distance"_a = 1.0)
.def("update_graph", &planning::Pos3DPlanner::UpdateGraph)
.def("add_obstacle", &planning::Pos3DPlanner::AddObstacle)
.def("find_path", [] (planning::Pos3DPlanner& self,
const Eigen::Vector3f& start,
const Eigen::Vector3f& goal) {
return *self.FindPath(start, goal);
})
.def("get_graph", &planning::Pos3DPlanner::GetGraph)
.def_readwrite("object_radius", &planning::Pos3DPlanner::object_radius_)
.def_readwrite("max_edge_distance", &planning::Pos3DPlanner::max_edge_distance_);
}
void pybind_planning(py::module &m) {
py::module m_submodule = m.def_submodule("planning");
pybind_planning_classes(m_submodule);
} | 48.142857 | 91 | 0.68954 | [
"geometry",
"3d"
] |
c94721e1c762990db03df575cc01bad81c27e20d | 17,657 | cpp | C++ | BXRtrain/src/CommandLine.cpp | eugene-yang/bxr-bayesian-regression | 0ec28783ab3e3ad67e2d608a47be66edf67ab8b8 | [
"MIT"
] | null | null | null | BXRtrain/src/CommandLine.cpp | eugene-yang/bxr-bayesian-regression | 0ec28783ab3e3ad67e2d608a47be66edf67ab8b8 | [
"MIT"
] | null | null | null | BXRtrain/src/CommandLine.cpp | eugene-yang/bxr-bayesian-regression | 0ec28783ab3e3ad67e2d608a47be66edf67ab8b8 | [
"MIT"
] | null | null | null | /*
3.03 -R option fix; (-R is only a switcharg)
3.04 sparse topicFeats output;
3.05 -R changed to valueArg
3.06 bbrformat fix.
3.07 modelname.
3.08 inf as a value for -V
3.09 allow comment line in ind prior file
3.10 warning if ind prior file has no content
3.11 -R classid bug (if classid not existing, or not the final one)
3.12 0 in ind prior file
3.13 -R class info; add -R classid into DataFactory; overwrite the ver3.11 changes.
3.14 --bbrtrainformat error check
3.15 add try catch block
3.16 skip reference class when reading ind prior file setting.
3.17 modify train data reading;
3.18 linux 64 bit change
3.19 -bmrtrainformat
3.20 -I class
3.21 remove standardization code: commandline option -s; avgsqunorm calc in tuneModel; standardization in train; WriteModel.
3.22 nonzero mode features;
4.0 read ind prior file with ABS; put ind prior file reading into train() instead of in Commandline.cpp
4.1 symbolic feature reading;
todo list:
1. consider +1 and 1 different; (should be solved after the symbolic modification)
2. -R 1 and -b 1 generates different results for penalty.data; (waiting for Dave's notes)
*/
#ifdef _MSC_VER
#define VERSION "3.21 Windows Executable"
#endif
#ifdef USE_GCC
#define VERSION "3.21 Linux Executable"
#endif
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <stdexcept>
#define _USE_MATH_DEFINES
#include <math.h>
#include <sys/resource.h>
using namespace std;
#include "Compiler.h"
#include "logging.h"
#include "FeatSelectParamManager.h"
#include "BayesParamManager.h"
#include "ModelTypeParam.h"
#include "Data.h"
#include "PolyZO.h"
#include "IndividualPriors.h"
#include "Design.h"
#include "DataFactory.h"
#include "ModelFile.h"
#include <tclap/CmdLine.h>
using namespace TCLAP;
// TODO: These should be "somewhere" but maybe not here.
logging Log(15);
bool readFromStdin(const char* fname) {
return 0==stricmp( "-", fname ) || 0==stricmp( "=", fname );
}
//
struct Config {
HyperParamPlan* m_hyperParamPlan;
// IndividualPriorsHolder m_individualPriorsHolder; // ver 4.0
DesignParameter m_designParameter;
// bool m_standardize; // v3.21
double m_convergenceLimit;
int m_iterationLimit;
ModelType::optimizer m_optimizerType;
ModelType::zoStoppingRule m_stopType;
bool m_highAccuracy;
double m_probabilityThreshold;
string m_stringArg;
string m_trainPlainFile;
string m_testPlainFile;
string m_modelWriteFileName;
string m_modelReadFileName;
string m_resultFileName;
string m_indpriorFile;
string m_initFile;
int m_logLevel;
string m_referenceClassId; // ver 3.05
bool m_allZeroes;
double m_stopThreshold;
double m_stopRatio;
bool m_computeLogLikelihood;
bool m_legacyWriteModel;
bool m_binary;
int m_format; // ver 3.06
string m_modelname; // ver 3.07
bool m_symbolic; // ver 4.1
public:
Config() : m_hyperParamPlan(0), // m_standardize(false), // v3.21
m_convergenceLimit(-1), m_iterationLimit(-1), m_optimizerType(ModelType::ZO),
m_stopType(ModelType::zoStoppingRule_linearScores),
m_highAccuracy(false),
m_logLevel(0),
m_legacyWriteModel(false),
m_binary(false),
m_symbolic(false)
{}
};
// Obsolete args:
static ValueArg<int> nclassesArg("y","yvalues","OBSOLETE: Number of classes",false,2,"[2..]");
// Args for stopping criteria:
static ValueArg<double> stopRatioArg("", "stopCountRatio", "Ratio above stopping criterion threshold", false, 0.01, "");
static ValueArg<double> stopThresholdArg("", "stopCountThreshold", "Prob of change stopping criterion threshold", false, 0.1, "");
static ValueArg<int> stopTypeArg("", "stopcriterion", "Stopping criterion, 1=linear scores, 2=prob of change", false, 1, "[1,2]");
static ValueArg<unsigned> iterLimitArg("","iter","Max number of iterations",false,iterDefault,"integer");
static ValueArg<double> convergeArg("e","eps","Convergence threshold",false,convergeDefault,"float");
// Args for logging:
static ValueArg<int> computeLogLikelihoodArg("", "loglikelihood", "Display log likelihood, 1=yes, 0=no", false, 0, "");
static ValueArg <int> logArg("l","log","Log verbosity level",false,0, "[0..2]");
// Args for data standardization and normalization:
static SwitchArg cosnormArg("c","cosnorm","Cosine normalization",false);
// static SwitchArg standardizeArg("s","standardize","Standardize variables",false); // v3.21
// Args for parameter searching
//back-compatibility only -->
static ValueArg <string> searchArg("S","search",
"DEPRECATED Search for hyperparameter value",false,"","list of floats, comma-separated, no spaces");
static ValueArg <double> hypArg("H","hyperparameter",
"DEPRECATED Hyperparameter, depends on the type of prior", false,0,"float");
//<--back-compatibility only
// Args configuring output file:
static SwitchArg resScoreArg("","rscore","Scores, not probabilities, in the result file", false);
static ValueArg<string> resfileArg("r","resultfile","Results file",false,"","resultfile");
static ValueArg<int> formatArg("","outputformat",
"format: \n\t 1-bbr \n\t 2-bmr \n\t 3-sparse", false, 2, "[1,3]");
static ValueArg<string> modelnameArg("","modelname","name of the model",false,"","model name"); // ver 3.07
static SwitchArg symbolicArg("","symbolic","string feature or class labels",false); // ver 4.1
// Args configuring optimizer:
static ValueArg <int> optArg("o","opt",
"Optimizer: \n\t 1-ZO \n\t 2-quasi-Newton, smoothed penalty \n\t 3-quasi-Newton, double coordinate",
false,1,"[1,3]");
static SwitchArg highAccuracyArg("","accurate","High accuracy mode",false);
// Binary versus non:
static ValueArg<int> binaryArg("b", "binary","1=Binary, 0=Poly", false, 0, "[0,1]");
// Bayes args:
static ValueArg <int> priorArg("p","prior","Type of prior, 1-Laplace 2-Gaussian",false,2,"[1,2]");
static ValueArg<string> indPriorsArg("I", "individualPriorsFile", "Individual Priors file", false, "", "indPriorsFile");
static ValueArg<string> initArg("", "init", "init file", false, "", "initfile");
static SwitchArg allZeroArg("z","zerovars","Exclude all-zero per class", false);
//static SwitchArg refClassArg("R","refClass","Use Reference Class", false);
static ValueArg <string> refClassArg("R","refClass","Use Reference Class", false, "", "reference class"); // ver 3.05
static SwitchArg pvarSearchArg("","autosearch","Auto search for prior variance, no grid required", false);
static SwitchArg negOnlyArg("","neg","Negative only model coefficients", false);
static SwitchArg posOnlyArg("","pos","Positive only model coefficients", false);
// Args for cross validation:
static SwitchArg errBarArg("","errbar","Error bar rule for cross-validation", false);
static ValueArg <string> cvArg("C","cv","Cross-validation",false,"10,10","#folds[,#runs]");
static ValueArg <string> priorVarArg("V","variance",
"Prior variance values; if more than one, cross-validation will be used",false,"",
"number[,number]*");
// Args specifying test data file, train data file, and model data file:
static ValueArg<string> testfileArg("", "testfile", "Test file", false, "", "");
static UnlabeledValueArg<string> datafileArg("x","Data file; '-' signifies standard input","","data file");
static UnlabeledValueArg<string> modelfileArg("modelfile","Model file","","model file");
//
static ValueArg<double> probThrArg("","probthres","Probability threshold",false,0.5,"0<=p<=1");
static ValueArg<int> legacyWriteModelArg("", "legacywm", "Legacy write model", false, 0, "[0,1]");
static Arg* args[] = {&nclassesArg,
&legacyWriteModelArg,
&negOnlyArg,
&posOnlyArg,
&probThrArg,
&highAccuracyArg,
&pvarSearchArg,
&stopRatioArg,
&stopThresholdArg,
&stopTypeArg,
&iterLimitArg,
&convergeArg,
&computeLogLikelihoodArg,
&logArg,
&cosnormArg,
// &standardizeArg, // v3.21
&searchArg,
&hypArg,
&resScoreArg,
&resfileArg,
&formatArg, // ver 3.06
&modelnameArg, // ver 3.07
&symbolicArg, // ver 4.1
&optArg,
&priorArg,
&indPriorsArg,
&initArg,
&allZeroArg,
&refClassArg,
&errBarArg,
&cvArg,
&priorVarArg,
&testfileArg,
&datafileArg,
&modelfileArg,
&binaryArg,
0
};
static bool parseArgs(int argc, char** argv) {
// try {
CmdLine cmd( "Bayesian Multinomial Logistic Regression - Training", ' ', VERSION );
for (Arg** a = args; *a; a++) {
cmd.add(*a);
}
// Parse the args.
cmd.parse( argc, argv );
/* } catch( std::exception& e){
Log(0)<<std::endl<<"Exception parsing parameters: "<<e.what();
cerr<<std::endl<<"Exception parsing parameters: "<<e.what();
return false;
} catch(...){
Log(0)<<std::endl<<"***Unrecognized exception";
cerr<<std::endl<<"***Unrecognized exception";
return false;
}
*/
return true;
}
static ModelType::optimizer getOptimizerType() {
if (optArg.getValue() == 2) {
return ModelType::QuasiNewtonSmooth;
} else if (optArg.getValue() == 3) {
return ModelType::QuasiNewtonDoubleCoord;
} else {
return ModelType::ZO;
}
}
static HyperParamPlan getHyperParamPlan() {
HyperParamPlan plan;
enum PriorType prior = PriorType(priorArg.getValue());
if( prior!=1 && prior!=2 )
throw runtime_error("Illegal prior type; should be 1-Laplace or 2-Gaussian");
int skew = posOnlyArg.getValue() ? 1 : negOnlyArg.getValue() ? -1 : 0;
if( priorVarArg.isSet() ) { // new mode
if( pvarSearchArg.isSet() ) throw runtime_error("Incompatible arguments: auto search and grid");
plan = HyperParamPlan( prior, skew, priorVarArg.getValue(), cvArg.getValue(),
HyperParamPlan::AsVar, errBarArg.getValue() );
} else if( searchArg.isSet() ) { //back-compatibility
plan = HyperParamPlan( prior, skew, searchArg.getValue(), cvArg.getValue(),
HyperParamPlan::Native, errBarArg.getValue() );
} else if( hypArg.isSet() ) { //fixed hyperpar - back-compatibility
plan = HyperParamPlan( prior, hypArg.getValue(), skew );
} else if( pvarSearchArg.isSet() ) { // auto search, no grid
plan = HyperParamPlan( prior, skew, cvArg.getValue() );
}
else //auto-select hyperpar
plan = HyperParamPlan( prior, skew );
return plan;
}
static ModelType* createModelType(Config* config) {
ModelType* modelType = new ModelType(ModelType::logistic,
config->m_optimizerType,
config->m_probabilityThreshold,
config->m_convergenceLimit,
config->m_iterationLimit,
config->m_highAccuracy,
config->m_referenceClassId, // ver 3.05
config->m_allZeroes,
config->m_modelname, // ver 3.07
config->m_stringArg,
config->m_stopType,
config->m_stopThreshold,
config->m_stopRatio,
config->m_computeLogLikelihood,
config->m_binary
);
Log(2)<<endl<<*modelType;
return modelType;
}
static DataFactory* createDataFactory(Config* config) {
DataFactory* dataFactory = new DataFactory(config->m_symbolic);
dataFactory->setTestAndTrainFileSpec(
config->m_trainPlainFile,
config->m_testPlainFile,
config->m_indpriorFile,
config->m_referenceClassId
);
dataFactory->readFiles();
// ver 3.14; --bbrtrainformat error check
if(config->m_format == 1) {
// --bbrtrainformat only allow with two classes
const RowSetMetadata& metadata = dataFactory->getRowSetMetadata();
if (metadata.getClassCount()!=2)
throw logic_error("--bbrtrainformat is allowed only with two classes.\n");
// the two classes could only be -1 and +1
#ifdef SYMBOLIC
if (metadata.getClassId(0)!="-1" || (metadata.getClassId(1)!="1"&&metadata.getClassId(1)!="+1") )
#else
if (metadata.getClassId(0)!=-1 || metadata.getClassId(1)!=1)
#endif
throw logic_error("--bbrtrainformat is allowed only when the two classes are -1 and +1.\n");
}
return dataFactory;
}
static WriteModel* createWriteModel(Config* config, const RowSetMetadata& rowSetMeta) {
ofstream* resultFileStream = new ofstream(config->m_resultFileName.c_str());
WriteModel* writeModel = new WriteModel(config->m_modelWriteFileName, config->m_format, // ver 3.06
rowSetMeta,
resultFileStream, config->m_legacyWriteModel);
return writeModel;
}
static void run(DataFactory& dataFactory, ModelType& modelType, WriteModel& writeModel, Config *config) {
LRModel model(*config->m_hyperParamPlan,
dataFactory.getIndPriorHolder(), // ver 4.0
config->m_designParameter,
modelType,
dataFactory.getRowSetMetadata(),
config->m_initFile );
model.train(*dataFactory.getTrainData(), writeModel, dataFactory.getTestData());
bool test = (dataFactory.getTestData() != 0);
if (test) {
model.test(*dataFactory.getTestData(), writeModel);
}
writeModel.closeResultsFile();
}
static void logHeader(int argc, char** argv) {
Log(0)<<endl<<"Bayesian Multinomial Logistic Regression - Training \tVer. "<<VERSION;
Log(2)<<"\nCommand line: ";
for( int i=0; i<argc; i++ ) {
Log(2)<<" "<<argv[i];
}
Log(2)<<"\nLog Level: "<<Log.level()-5;
}
static Config* configureLogger() {
Config* config = new Config();
config->m_logLevel = logArg.getValue()+5;
Log.setLevel(config->m_logLevel);
return config;
}
static void readConfig(Config* config) {
config->m_hyperParamPlan = new HyperParamPlan(getHyperParamPlan());
// config->m_standardize = standardizeArg.getValue(); // v3.21
config->m_convergenceLimit = convergeArg.isSet() ? convergeArg.getValue() : convergeDefault;
config->m_iterationLimit = iterLimitArg.isSet() ? iterLimitArg.getValue() : iterDefault;
config->m_optimizerType = getOptimizerType();
config->m_stopType = stopTypeArg.getValue() == 1 ? ModelType::zoStoppingRule_linearScores : ModelType::zoStoppingRule_changeProb;
config->m_stopRatio = stopRatioArg.getValue();
config->m_stopThreshold = stopThresholdArg.getValue();
config->m_referenceClassId = refClassArg.isSet() ? refClassArg.getValue() : "" ; // ver 3.05
config->m_modelname = modelnameArg.isSet() ? modelnameArg.getValue() : datafileArg.getValue()+".model"; // ver 3.07
config->m_symbolic = symbolicArg.isSet() ? true : false; // ver 4.1
config->m_allZeroes = allZeroArg.getValue();
config->m_trainPlainFile = datafileArg.getValue();
config->m_testPlainFile = testfileArg.getValue();
config->m_modelWriteFileName = modelfileArg.getValue();
config->m_modelReadFileName = ""; // TODO This should be "" when training, set when testing to: modelfileArg.getValue();
config->m_resultFileName = resfileArg.getValue();
config->m_designParameter = DesignParameter((enum DesignType)designPlain);
config->m_indpriorFile = indPriorsArg.isSet() ? indPriorsArg.getValue() : "";
config->m_initFile = initArg.isSet() ? initArg.getValue() : "";
/* // ver 4.0
if( indPriorsArg.isSet() ) {
config->m_individualPriorsHolder = IndividualPriorsHolder( indPriorsArg.getValue(), IND_PRIORS_MODE_RELATIVE );
}
*/
config->m_binary = binaryArg.getValue() == 1 ? true : false;
config->m_highAccuracy = highAccuracyArg.getValue();
config->m_probabilityThreshold = probThrArg.getValue();
config->m_legacyWriteModel = legacyWriteModelArg.getValue() == 1 ? true : false;
// Does this do anything?
config->m_stringArg = string("");
config->m_format = formatArg.getValue(); // ver 3.06
}
void logConfig(Config* config) {
Log(2)<<"\nData file for training: "
<<( readFromStdin(config->m_trainPlainFile.c_str()) ? "stdin" : config->m_trainPlainFile);
Log(2)<<"\nData file for testing: "<<config->m_testPlainFile.c_str();
Log(2)<<"\nWrite Model file: "<<config->m_modelWriteFileName;
Log(2)<<endl; // <<config->m_individualPriorsHolder; // ver 4.0
}
void postSanityCheck(Config* config){
// ver 3.14; if --bbrtrainformat specified, and -R is only allowed with value +1;
if(config->m_format == 1){
if(config->m_referenceClassId!="1")
throw logic_error("--bbrtrainformat is allowed only when '-R -1' is specified, i.e. class -1 is forced to be the reference class.\n");
}
}
int main(int argc, char** argv) {
try{
bool ok = parseArgs(argc, argv);
if (!ok) {
exit(1);
}
Config* config = configureLogger();
logHeader(argc, argv);
readConfig(config);
logConfig(config);
postSanityCheck(config); // ver 3.14
// ver 3.13; add referenceclassid into Y vector;
DataFactory* dataFactory = createDataFactory(config);
ModelType* modelType = createModelType(config);
WriteModel* writeModel = createWriteModel(config, dataFactory->getRowSetMetadata());
run(*dataFactory, *modelType, *writeModel, config);
struct rusage rsg;
if(getrusage(RUSAGE_SELF, &rsg)==0)
cout<<"max memory used:"<<rsg.ru_maxrss<<endl;
delete modelType;
delete writeModel;
delete dataFactory;
}
catch (ArgException e) {
cerr << "***Command line error: " << e.error()
<< " for arg " << e.argId() << endl;
return 1;
}
catch(std::exception& e){
cerr<<std::endl<<"***Exception: "<<e.what();
return 1;
}
catch(...){
cerr<<std::endl<<"***Unrecognized exception";
return 1;
}
}
| 33.252354 | 139 | 0.677125 | [
"vector",
"model"
] |
c94793caf1743b73ebc2752e5c1db7de3d6597f4 | 2,961 | hpp | C++ | include/fsm/statemachine.hpp | mikedevnull/minifsm | 496ebba259d6ad5e9d5b7deb74c243b4375f70c5 | [
"MIT"
] | null | null | null | include/fsm/statemachine.hpp | mikedevnull/minifsm | 496ebba259d6ad5e9d5b7deb74c243b4375f70c5 | [
"MIT"
] | null | null | null | include/fsm/statemachine.hpp | mikedevnull/minifsm | 496ebba259d6ad5e9d5b7deb74c243b4375f70c5 | [
"MIT"
] | null | null | null | #pragma once
#include <fsm/detail/transition_table.hpp>
namespace fsm {
template <typename SMConfig>
class StateMachine {
using TransitionTable = detail::transition_table_from_config<SMConfig>;
using StateList = detail::extractStates_t<TransitionTable>;
using States = detail::rebind<StateList, detail::Tuple>;
using InitialState = detail::extract_initial_state<TransitionTable>;
using ContextList = detail::extract_contexts<TransitionTable>;
using ContextHoldingTypes =
detail::transform<ContextList, utils::add_pointer_t>;
using Contexts = detail::rebind<ContextHoldingTypes, detail::Tuple>;
public:
template <typename... Ts>
constexpr explicit StateMachine(Ts &&...deps)
: contexts_(utils::forward<Ts>(deps)...),
states_{},
tt_{SMConfig::transition_table()} {
static_assert(sizeof...(Ts) == ContextList::size);
}
template <typename Event>
void processEvent(const Event &event) {
detail::visit(
states_, currentStateIndex_, [this, event](auto ¤tState) {
using Transitions = decltype(tt_.transitions);
using Source = utils::remove_cvref_t<decltype(currentState)>;
using Match = detail::matchTransition_t<typename Transitions::TL,
Source, Event>;
if constexpr (utils::is_same_v<Match, detail::NoMatch>) {
return;
} else {
constexpr auto matchTransitionIndex =
detail::index_of<typename Transitions::TL, Match>;
static_assert(matchTransitionIndex > -1);
using Target = typename Match::Target;
constexpr auto targetIndex =
detail::index_of<typename States::TL, Target>;
static_assert(targetIndex > -1);
using Context = typename Match::Context;
if constexpr (utils::is_same_v<Context, detail::NoContext>) {
detail::get<matchTransitionIndex>(tt_.transitions)
.execute(currentState, event,
detail::get<targetIndex>(states_));
} else {
constexpr auto contextIndex =
detail::index_of<typename Contexts::TL,
utils::add_pointer_t<Context>>;
static_assert(contextIndex > -1);
detail::get<matchTransitionIndex>(tt_.transitions)
.execute(detail::get<contextIndex>(contexts_), currentState,
event, detail::get<targetIndex>(states_));
}
currentStateIndex_ = targetIndex;
}
});
}
template <typename State>
constexpr bool isState() {
return currentStateIndex_ == detail::index_of<typename States::TL, State>;
}
private:
States states_;
TransitionTable tt_;
Contexts contexts_;
unsigned int currentStateIndex_ =
detail::index_of<typename States::TL, InitialState>;
};
} // namespace fsm | 38.454545 | 78 | 0.628504 | [
"transform"
] |
c9526f90bbeb8ccaa3955d6be8995e7b72f9729a | 10,098 | cc | C++ | src/pass/copy_propagation.cc | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | 1 | 2020-08-31T02:43:43.000Z | 2020-08-31T02:43:43.000Z | src/pass/copy_propagation.cc | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | null | null | null | src/pass/copy_propagation.cc | laekov/akg | 5316b8cb2340bbf71bdc724dc9d81513a67b3104 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Huawei Technologies 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 <tvm/ir_pass.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_visitor.h>
#include <tvm.h>
#include <pass/utils.h>
#include "build_module.h"
namespace akg {
namespace ir {
inline bool IsArgsSame(const Array<Expr> &args1, const Array<Expr> &args2, bool can_remove_broadcast = false) {
if (args1.size() != args2.size()) {
return false;
}
auto size = args1.size();
for (size_t i = 0; i < size; i++) {
if (args1[i].as<Variable>() && args2[i].as<Variable>()) {
auto var1 = args1[i].as<Variable>();
auto var2 = args2[i].as<Variable>();
CHECK(var1);
CHECK(var2);
if (var1->name_hint != var2->name_hint) {
return false;
}
} else if (args1[i].as<IntImm>() && args2[i].as<IntImm>()) {
auto var1 = args1[i].as<IntImm>();
auto var2 = args2[i].as<IntImm>();
CHECK(var1);
CHECK(var2);
if (var1->value != var2->value) {
return false;
}
} else if (can_remove_broadcast && args1[i].as<Variable>() && args2[i].as<IntImm>()) {
// broadcast case
return is_zero(args2[i]);
} else {
return false;
}
}
return true;
}
inline bool IsAttrValueSame(const Expr &value1, const Expr &value2) {
if (value1.as<StringImm>() && value2.as<StringImm>()) {
auto v1 = value1.as<StringImm>();
auto v2 = value2.as<StringImm>();
CHECK(v1);
CHECK(v2);
return (v1->value == v2->value);
}
return false;
}
struct CopyInfo {
FunctionRef func_ref_;
std::unordered_set<size_t> broadcast_indexes_;
};
class DetectCanEliminatedCopy : public IRVisitor {
public:
explicit DetectCanEliminatedCopy(const Map<Tensor, Buffer> &extern_buffers) : extern_buffers_(extern_buffers) {}
~DetectCanEliminatedCopy() override = default;
void Visit_(const AttrStmt *op) final {
auto func = Downcast<FunctionRef>(op->node);
attr_[func] = op->value;
IRVisitor::Visit(op->body);
attr_.erase(func);
}
void Visit_(const Realize *op) final {
auto func = op->func;
realize_[func] = op;
IRVisitor::Visit(op->body);
realize_.erase(func);
}
void Visit_(const ProducerConsumer *op) final {
auto func = op->func;
producers_.insert(func);
IRVisitor::Visit(op->body);
producers_.erase(func);
}
void Visit_(const Provide *op) final {
std::vector<const Call *> src_call;
auto GetSrcCall = [&, this](const NodeRef &op) {
if (const auto call = op.as<Call>()) {
src_call.emplace_back(call);
}
};
air::ir::PostOrderVisit(op->value, GetSrcCall);
for (size_t i = 0; i < src_call.size(); ++i) {
auto func = src_call[i]->func;
if (copy_stmts_.count(func) != 0) {
auto substitute_func = copy_stmts_[func].func_ref_;
if (realize_.count(substitute_func) == 0) {
// Do not elimate the copy if out of realize scope.
copy_stmts_.erase(func);
not_copy_.insert(func);
}
}
}
auto call_op = op->value.as<Call>();
if (call_op == nullptr) {
if (enable_compute_in_place_ && (op->value.as<Add>() || op->value.as<Sub>() || op->value.as<Mul>())) {
// A(i0, i1, i2) = B(i0, i1, i2) * C(i0, i1), here A can be replaced by B to remove redundant buffer
// if B is not used later.
std::vector<const Call *> target_call;
for (const auto &ele : src_call) {
if (ele->func != op->func && IsArgsSame(op->args, ele->args, false)) {
target_call.emplace_back(ele);
}
}
if (target_call.size() == 1) {
FunctionRef f;
for (const auto &it : copy_stmts_) {
if (it.second.func_ref_ == target_call[0]->func) {
f = it.first;
}
}
if (!f.defined()) {
call_op = target_call[0];
} else {
// Do not eliminate the copy if detect B used again.
copy_stmts_.erase(f);
not_copy_.insert(f);
}
}
}
if (call_op == nullptr) {
if (copy_stmts_.count(op->func) != 0) {
copy_stmts_.erase(op->func);
}
not_copy_.insert(op->func);
return;
}
}
auto dst_args = op->args;
auto src_args = call_op->args;
auto op_func = op->func;
auto call_op_func = call_op->func;
if (!copy_stmts_.empty()) {
for (auto &it : copy_stmts_) {
if (op_func == it.first) {
if (call_op_func != it.second.func_ref_) {
// Do not eliminate the copy if detect any modification to the target buffer after the copy.
copy_stmts_.erase(op_func);
not_copy_.insert(op_func);
return;
}
}
}
}
// detect copy, eg. compute_1(i0, i1) = compute_2(i0, i1), in which compute_1 is not bound
// only detect complete copy: the number of args must be the same with the size of bounds in realize
if (not_copy_.count(op_func) == 0 && copy_stmts_.count(call_op_func) == 0 &&
IsArgsSame(dst_args, src_args, can_remove_broadcast_) && realize_.count(op_func) != 0 &&
realize_.count(call_op_func) != 0 && attr_.count(op_func) != 0 && attr_.count(call_op_func) != 0 &&
IsAttrValueSame(attr_[op_func], attr_[call_op_func])) {
if (dst_args.size() == realize_[op_func]->bounds.size()) {
if (std::any_of(extern_buffers_.begin(), extern_buffers_.end(), [=](const std::pair<Tensor, Buffer> &it) {
return (op_func->func_name() == it.first->op->name);
})) {
return;
}
}
std::unordered_set<size_t> broadcast_indexes;
if (can_remove_broadcast_) {
for (size_t i = 0; i < src_args.size(); ++i) {
if (is_zero(src_args[i])) {
broadcast_indexes.insert(i);
}
}
}
copy_stmts_[op_func] = CopyInfo{call_op_func, broadcast_indexes};
} else {
// Do not eliminate the copy.
if (copy_stmts_.count(op_func) != 0) {
copy_stmts_.erase(op_func);
}
not_copy_.insert(op_func);
}
}
std::unordered_map<FunctionRef /*copy_dst*/, CopyInfo /*copy_src*/, NodeHash, NodeEqual> copy_stmts_;
private:
std::unordered_map<FunctionRef, Expr, NodeHash, NodeEqual> attr_;
std::unordered_map<FunctionRef, const Realize *, NodeHash, NodeEqual> realize_;
std::unordered_set<FunctionRef, NodeHash, NodeEqual> producers_;
std::unordered_set<FunctionRef, NodeHash, NodeEqual> not_copy_;
const Map<Tensor, Buffer> &extern_buffers_;
bool can_remove_broadcast_ = global_attrs.GetBoolAttr(kEnableRemoveBroadcastCopy, false);
bool enable_compute_in_place_ = global_attrs.GetBoolAttr(kEnableComputeInPlace, false);
};
class EliminateCopyAndRealize : public IRMutator {
public:
explicit EliminateCopyAndRealize(const std::unordered_map<FunctionRef, CopyInfo, NodeHash, NodeEqual> ©_stmts)
: copy_stmts_(copy_stmts) {}
~EliminateCopyAndRealize() override = default;
Stmt Mutate_(const AttrStmt *op, const Stmt &s) final {
auto body = this->Mutate(op->body);
if (op->attr_key == air::ir::attr::realize_scope) {
auto node = op->node.as<OperationNode>();
if (node) {
for (auto &it : copy_stmts_) {
if (node->name == it.first->func_name() && op->node.get() == it.first.get()) {
return body;
}
}
}
}
return AttrStmt::make(op->node, op->attr_key, op->value, body);
}
Stmt Mutate_(const ProducerConsumer *op, const Stmt &s) final {
if (op->is_producer && copy_stmts_.count(op->func) != 0) {
return this->Mutate(op->body);
}
return IRMutator::Mutate_(op, s);
}
Stmt Mutate_(const Realize *op, const Stmt &s) final {
if (copy_stmts_.count(op->func) == 0) {
return IRMutator::Mutate_(op, s);
}
return this->Mutate(op->body);
}
Stmt Mutate_(const Provide *op, const Stmt &s) final {
if (copy_stmts_.count(op->func) != 0) {
if (op->value.as<Call>() == nullptr) {
return Provide::make(copy_stmts_[op->func].func_ref_, op->value_index, op->value, op->args);
}
return Evaluate::make(0);
}
return IRMutator::Mutate_(op, s);
}
Expr Mutate_(const Call *op, const Expr &s) final {
auto it = copy_stmts_.find(op->func);
if (it != copy_stmts_.end()) {
auto new_func_ref = it->second.func_ref_;
Array<Expr> new_args;
for (size_t i = 0; i < op->args.size(); ++i) {
if (it->second.broadcast_indexes_.count(i) == 0) {
new_args.push_back(op->args[i]);
} else {
new_args.push_back(make_zero(op->args[i].type()));
}
}
auto new_call =
Call::make(op->type, new_func_ref->func_name(), new_args, op->call_type, new_func_ref, op->value_index);
return new_call;
}
return IRMutator::Mutate_(op, s);
}
private:
// copy_stmts_ is of std::unordered_map<copy_dst, copy_src, NodeHash, NodeEqual>
std::unordered_map<FunctionRef, CopyInfo, NodeHash, NodeEqual> copy_stmts_;
};
/* Eliminate useless copy, e.g.
* x = y
* z = x * w + b
* In this case 'x = y' will be eliminated and x will be replaced by y
*/
Stmt CopyPropagation(const Stmt stmt, const Map<Tensor, Buffer> &extern_buffer) {
DetectCanEliminatedCopy detect_visitor(extern_buffer);
detect_visitor.Visit(stmt);
EliminateCopyAndRealize eliminator(detect_visitor.copy_stmts_);
return RemoveNoOp(eliminator.Mutate(stmt));
}
} // namespace ir
} // namespace akg
| 32.469453 | 116 | 0.615567 | [
"vector"
] |
e92038f469eb46e99b3dcc610309bd6e82a442bd | 2,920 | hpp | C++ | src/core/storage/fileio/buffered_writer.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/core/storage/fileio/buffered_writer.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/core/storage/fileio/buffered_writer.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include<vector>
#include<core/parallel/mutex.hpp>
#include<core/storage/sframe_data/sframe_constants.hpp>
namespace turi {
/**
* \ingroup fileio
* Provide buffered write abstraction.
* The class manages buffered concurrent write to an output iterator.
*
* Example:
*
* Suppose there are M data sources randomly flow to N sinks. We can use
* buffered_writer to achieve efficient concurrent write.
*
* \code
*
* std::vector<input_iterator> sources; // size M
* std::vector<output_iterator> sinks; // size N
* std::vector<turi::mutex> sink_mutex; // size N
*
* parallel_for_each(s : sources) {
* std::vector<buffered_writer> writers;
* for (i = 1...N) {
* writers.push_back(buffered_writer(sinks[i], sink_mutex[i]));
* }
* while (s.has_next()) {
* size_t destination = random.randint(N);
* writers[destination].write(s.next());
* }
* for (i = 1...N) {
* writers[i].flush();
* }
* }
* \endcode
*
* Two parameters "soft_limit" and "hard_limit" are used to control the buffer
* size. When soft_limit is met, the writer will try to flush the buffer
* content to the sink. When hard_limit is met, the writer will force the flush.
*/
template<typename ValueType, typename OutIterator>
class buffered_writer {
public:
buffered_writer(OutIterator& out, turi::mutex& out_lock,
size_t soft_limit = SFRAME_WRITER_BUFFER_SOFT_LIMIT,
size_t hard_limit = SFRAME_WRITER_BUFFER_HARD_LIMIT) :
out(out), out_lock(out_lock),
soft_limit(soft_limit),
hard_limit(hard_limit) {
ASSERT_GT(hard_limit, soft_limit);
}
/**
* Write the value to the buffer.
* Try flush when buffer exceeds soft limit and force
* flush when buffer exceeds hard limit.
*/
void write(const ValueType& val) {
buffer.push_back(val);
if (buffer.size() >= soft_limit) {
bool locked = out_lock.try_lock();
if (locked || buffer.size() >= hard_limit) {
flush(locked);
}
}
}
void write(ValueType&& val) {
buffer.push_back(val);
if (buffer.size() >= soft_limit) {
bool locked = out_lock.try_lock();
if (locked || buffer.size() >= hard_limit) {
flush(locked);
}
}
}
/**
* Flush the buffer to the output sink. Clear the buffer when finished.
*/
void flush(bool is_locked = false) {
if (!is_locked) {
out_lock.lock();
}
std::lock_guard<turi::mutex> guard(out_lock, std::adopt_lock);
for (auto& val : buffer) {
*out++ = std::move(val);
}
buffer.clear();
}
private:
OutIterator& out;
turi::mutex& out_lock;
size_t soft_limit;
size_t hard_limit;
std::vector<ValueType> buffer;
};
}
| 27.54717 | 86 | 0.652397 | [
"vector"
] |
e922d5b01fd9e79cfc37b67b080db8e8921cb576 | 2,169 | cpp | C++ | src/ui/widgets/carousel.cpp | CommitteeOfZero/impacto | 87e0aa27d59d8f350849dfb20048679b2a3db1e3 | [
"0BSD"
] | 45 | 2020-02-01T19:10:13.000Z | 2022-03-11T01:45:52.000Z | src/ui/widgets/carousel.cpp | Enorovan/impacto | 807c5247dca2720e3e1205fca4724ad1fafb1ab4 | [
"0BSD"
] | 7 | 2020-01-26T17:30:00.000Z | 2021-09-26T10:00:46.000Z | src/ui/widgets/carousel.cpp | Enorovan/impacto | 807c5247dca2720e3e1205fca4724ad1fafb1ab4 | [
"0BSD"
] | 11 | 2020-02-01T23:01:50.000Z | 2021-12-15T14:39:27.000Z | #include "carousel.h"
#include "../../vm/interface/input.h"
#include "../../profile/scriptinput.h"
#include "../../inputsystem.h"
namespace Impacto {
namespace UI {
namespace Widgets {
using namespace Impacto::Profile::ScriptInput;
using namespace Impacto::Vm::Interface;
Carousel::Carousel(CarouselDirection dir) {
Direction = dir;
OnAdvanceHandler = std::bind(&Carousel::OnChange, this, std::placeholders::_1,
std::placeholders::_2);
OnBackHandler = std::bind(&Carousel::OnChange, this, std::placeholders::_1,
std::placeholders::_2);
}
Carousel::Carousel(CarouselDirection dir,
std::function<void(Widget*, Widget*)> onAdvanceHandler,
std::function<void(Widget*, Widget*)> onBackHandler) {
Direction = dir;
OnAdvanceHandler = onAdvanceHandler;
OnBackHandler = onBackHandler;
}
void Carousel::Update(float dt) {
for (const auto& el : Children) {
el->Update(dt);
}
}
void Carousel::UpdateInput() {
if (!Children.empty()) {
auto buttonAdvance = Direction == CDIR_HORIZONTAL ? PAD1RIGHT : PAD1DOWN;
auto buttonBack = Direction == CDIR_HORIZONTAL ? PAD1LEFT : PAD1UP;
if (PADinputButtonWentDown & buttonBack) {
Previous();
}
if (PADinputButtonWentDown & buttonAdvance) {
Next();
}
}
}
void Carousel::Render() {
for (const auto& el : Children) {
auto tint = el->Tint;
el->Tint *= Tint;
el->Render();
el->Tint = tint;
}
}
void Carousel::Add(Widget* widget) {
Children.push_back(widget);
Iterator = Children.begin();
}
void Carousel::Next() {
auto current = *Iterator;
Iterator++;
if (Iterator == Children.end()) {
Iterator = Children.begin();
}
auto next = *Iterator;
OnAdvanceHandler(current, next);
}
void Carousel::Previous() {
auto current = *Iterator;
if (Iterator == Children.begin()) {
Iterator = Children.end();
}
Iterator--;
auto next = *Iterator;
OnBackHandler(current, next);
}
void Carousel::OnChange(Widget* current, Widget* next) {
current->Hide();
next->Show();
}
} // namespace Widgets
} // namespace UI
} // namespace Impacto | 24.1 | 80 | 0.640848 | [
"render"
] |
e92c865501e96123e9eadae99f92048d57295830 | 7,177 | cpp | C++ | src/tests/test_graphvisitor_generic.cpp | JoshuaSBrown/GraphCluster | d9c28204b276165cf59137c9668c4dfcfa397089 | [
"MIT"
] | null | null | null | src/tests/test_graphvisitor_generic.cpp | JoshuaSBrown/GraphCluster | d9c28204b276165cf59137c9668c4dfcfa397089 | [
"MIT"
] | null | null | null | src/tests/test_graphvisitor_generic.cpp | JoshuaSBrown/GraphCluster | d9c28204b276165cf59137c9668c4dfcfa397089 | [
"MIT"
] | null | null | null |
#include <cassert>
#include <cmath>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include "../../include/ugly/edge_directed.hpp"
#include "../../include/ugly/edge_undirected.hpp"
#include "../../include/ugly/edge_weighted.hpp"
#include "../../include/ugly/graphvisitor/graphvisitor_generic.hpp"
#include "../libugly/weak_pointer_supplement.hpp"
using namespace ugly;
using namespace std;
int main(void) {
cout << "Testing: Constructor " << endl;
{ GraphVisitorGeneric graphvisitorgeneric; }
cout << "Testing: addEdge" << endl;
{
shared_ptr<EdgeWeighted> ed1(new EdgeWeighted(1, 2));
shared_ptr<EdgeWeighted> ed2(new EdgeWeighted(2, 3));
shared_ptr<EdgeWeighted> ed3(new EdgeWeighted(2, 1));
GraphVisitorGeneric graphvisitorgeneric;
bool throwError = false;
try {
graphvisitorgeneric.addEdge(ed1);
} catch (...) {
throwError = true;
}
assert(throwError);
graphvisitorgeneric.setStartingVertex(1);
graphvisitorgeneric.addEdge(ed1);
// Cannot add the same edge twice
throwError = false;
try {
graphvisitorgeneric.addEdge(ed1);
} catch (...) {
throwError = true;
}
assert(throwError);
// Cannot add an edge that is not associated with a vertex that has been
// explored, currently the starting vertex is the only one that satisfies
// that criteria
throwError = false;
try {
graphvisitorgeneric.addEdge(ed2);
} catch (...) {
throwError = true;
}
assert(throwError);
// The generic graph visitor allows mixing of edges
shared_ptr<Edge> ed4(new EdgeUndirected(4, 1));
graphvisitorgeneric.addEdge(ed4);
}
cout << "Testing: addEdges" << endl;
{
shared_ptr<Edge> ed1(new EdgeWeighted(1, 2));
shared_ptr<Edge> ed2(new EdgeWeighted(2, 3));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitorGeneric graphvisitorgeneric;
bool throwError = false;
try {
graphvisitorgeneric.addEdges(eds);
} catch (...) {
throwError = true;
}
assert(throwError);
graphvisitorgeneric.setStartingVertex(1);
// Because edge 2 is not connected to vertex 1 this will throw an error
throwError = false;
try {
graphvisitorgeneric.addEdges(eds);
} catch (...) {
throwError = true;
}
assert(throwError);
shared_ptr<Edge> ed11(new EdgeUndirected(1, 2));
shared_ptr<Edge> ed22(new EdgeDirected(2, 3));
vector<weak_ptr<Edge>> eds2 = {ed11, ed22};
cout << "ed11 directional? " << ed11->directional() << endl;
GraphVisitorGeneric graphvisitorgeneric2;
graphvisitorgeneric2.setStartingVertex(2);
// Generic visitor allows mixing of edges
graphvisitorgeneric2.addEdges(eds2);
}
cout << "Testing: exploreEdge" << endl;
{
shared_ptr<Edge> ed1(new EdgeWeighted(1, 2));
shared_ptr<Edge> ed2(new EdgeWeighted(2, 3));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitorGeneric graphvisitorgeneric;
bool throwError = false;
try {
graphvisitorgeneric.exploreEdge(ed1);
} catch (...) {
throwError = true;
}
assert(throwError);
graphvisitorgeneric.setStartingVertex(2);
graphvisitorgeneric.addEdges(eds);
graphvisitorgeneric.exploreEdge(ed1);
// Should now throw an error because ed1 has now been explored
throwError = false;
try {
graphvisitorgeneric.exploreEdge(ed1);
} catch (...) {
throwError = true;
}
assert(throwError);
graphvisitorgeneric.exploreEdge(ed2);
}
cout << "Testing: exploreEdge" << endl;
{
shared_ptr<Edge> ed1(new Edge(1, 2));
shared_ptr<Edge> ed2(new Edge(2, 3));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitor graphvisitor;
bool throwError = false;
try {
graphvisitor.exploreEdge(ed1);
} catch (...) {
throwError = true;
}
assert(throwError);
}
cout << "Testing: getUnexploredVertex" << endl;
{
shared_ptr<Edge> ed1(new EdgeWeighted(1, 2));
shared_ptr<Edge> ed2(new EdgeWeighted(2, 3));
shared_ptr<Edge> ed3(new EdgeWeighted(2, 4));
shared_ptr<Edge> ed4(new EdgeWeighted(3, 4));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitorGeneric graphvisitorgeneric;
graphvisitorgeneric.setStartingVertex(2);
graphvisitorgeneric.addEdges(eds);
auto unexploredvertex = graphvisitorgeneric.getUnexploredVertex(ed1);
assert(unexploredvertex == 1);
unexploredvertex = graphvisitorgeneric.getUnexploredVertex(ed3);
assert(unexploredvertex == 4);
// Neither vertex of edge 4 is listed as explored so it will
// throw an error
bool throwError = false;
try {
graphvisitorgeneric.getUnexploredVertex(ed4);
} catch (...) {
throwError = true;
}
assert(throwError);
}
cout << "Testing: getExploredVertex" << endl;
{
shared_ptr<Edge> ed1(new EdgeWeighted(1, 2));
shared_ptr<Edge> ed2(new EdgeWeighted(2, 3));
shared_ptr<Edge> ed3(new EdgeWeighted(4, 3));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitorGeneric graphvisitorgeneric;
graphvisitorgeneric.setStartingVertex(2);
graphvisitorgeneric.addEdges(eds);
bool throwError = false;
try {
graphvisitorgeneric.getExploredVertex(ed3);
} catch (...) {
throwError = true;
}
assert(throwError);
auto exploredvertex = graphvisitorgeneric.getExploredVertex(ed1);
assert(exploredvertex == 2);
}
cout << "Testing: allEdgesExplored" << endl;
{
shared_ptr<Edge> ed1(new EdgeWeighted(1, 2));
shared_ptr<Edge> ed2(new EdgeWeighted(2, 3));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitorGeneric graphvisitorgeneric;
graphvisitorgeneric.setStartingVertex(2);
graphvisitorgeneric.addEdges(eds);
bool complete = graphvisitorgeneric.allEdgesExplored();
assert(complete == false);
graphvisitorgeneric.exploreEdge(ed1);
complete = graphvisitorgeneric.allEdgesExplored();
assert(complete == false);
graphvisitorgeneric.exploreEdge(ed2);
complete = graphvisitorgeneric.allEdgesExplored();
assert(complete == true);
}
cout << "Testing: getNextEdge" << endl;
{
shared_ptr<EdgeWeighted> ed1(new EdgeWeighted(1, 2, 0.5));
shared_ptr<EdgeWeighted> ed2(new EdgeWeighted(2, 3, 2.3));
vector<weak_ptr<Edge>> eds = {ed1, ed2};
GraphVisitorGeneric graphvisitorgeneric;
graphvisitorgeneric.setStartingVertex(2);
graphvisitorgeneric.addEdges(eds);
vector<weak_ptr<EdgeWeighted>> edges;
auto ed11 = graphvisitorgeneric.getNextEdge<EdgeWeighted>();
edges.push_back(ed11);
graphvisitorgeneric.exploreEdge(ed11);
auto ed22 = graphvisitorgeneric.getNextEdge<EdgeWeighted>();
edges.push_back(ed22);
graphvisitorgeneric.exploreEdge(ed22);
bool ed1_found = false;
bool ed2_found = false;
for (auto ed : edges) {
if (ed == ed1) ed1_found = true;
if (ed == ed2) ed2_found = true;
}
assert(ed1_found);
assert(ed2_found);
}
return 0;
}
| 28.145098 | 77 | 0.65905 | [
"vector"
] |
e92dd923c61719e199375299a53acbeb58c643df | 6,620 | cpp | C++ | tione/src/v20191022/model/CodeRepoSummary.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | tione/src/v20191022/model/CodeRepoSummary.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | tione/src/v20191022/model/CodeRepoSummary.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tione/v20191022/model/CodeRepoSummary.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tione::V20191022::Model;
using namespace std;
CodeRepoSummary::CodeRepoSummary() :
m_creationTimeHasBeenSet(false),
m_lastModifiedTimeHasBeenSet(false),
m_codeRepositoryNameHasBeenSet(false),
m_gitConfigHasBeenSet(false),
m_noSecretHasBeenSet(false)
{
}
CoreInternalOutcome CodeRepoSummary::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("CreationTime") && !value["CreationTime"].IsNull())
{
if (!value["CreationTime"].IsString())
{
return CoreInternalOutcome(Error("response `CodeRepoSummary.CreationTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_creationTime = string(value["CreationTime"].GetString());
m_creationTimeHasBeenSet = true;
}
if (value.HasMember("LastModifiedTime") && !value["LastModifiedTime"].IsNull())
{
if (!value["LastModifiedTime"].IsString())
{
return CoreInternalOutcome(Error("response `CodeRepoSummary.LastModifiedTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_lastModifiedTime = string(value["LastModifiedTime"].GetString());
m_lastModifiedTimeHasBeenSet = true;
}
if (value.HasMember("CodeRepositoryName") && !value["CodeRepositoryName"].IsNull())
{
if (!value["CodeRepositoryName"].IsString())
{
return CoreInternalOutcome(Error("response `CodeRepoSummary.CodeRepositoryName` IsString=false incorrectly").SetRequestId(requestId));
}
m_codeRepositoryName = string(value["CodeRepositoryName"].GetString());
m_codeRepositoryNameHasBeenSet = true;
}
if (value.HasMember("GitConfig") && !value["GitConfig"].IsNull())
{
if (!value["GitConfig"].IsObject())
{
return CoreInternalOutcome(Error("response `CodeRepoSummary.GitConfig` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_gitConfig.Deserialize(value["GitConfig"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_gitConfigHasBeenSet = true;
}
if (value.HasMember("NoSecret") && !value["NoSecret"].IsNull())
{
if (!value["NoSecret"].IsBool())
{
return CoreInternalOutcome(Error("response `CodeRepoSummary.NoSecret` IsBool=false incorrectly").SetRequestId(requestId));
}
m_noSecret = value["NoSecret"].GetBool();
m_noSecretHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void CodeRepoSummary::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_creationTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreationTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_creationTime.c_str(), allocator).Move(), allocator);
}
if (m_lastModifiedTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LastModifiedTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_lastModifiedTime.c_str(), allocator).Move(), allocator);
}
if (m_codeRepositoryNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CodeRepositoryName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_codeRepositoryName.c_str(), allocator).Move(), allocator);
}
if (m_gitConfigHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "GitConfig";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_gitConfig.ToJsonObject(value[key.c_str()], allocator);
}
if (m_noSecretHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NoSecret";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_noSecret, allocator);
}
}
string CodeRepoSummary::GetCreationTime() const
{
return m_creationTime;
}
void CodeRepoSummary::SetCreationTime(const string& _creationTime)
{
m_creationTime = _creationTime;
m_creationTimeHasBeenSet = true;
}
bool CodeRepoSummary::CreationTimeHasBeenSet() const
{
return m_creationTimeHasBeenSet;
}
string CodeRepoSummary::GetLastModifiedTime() const
{
return m_lastModifiedTime;
}
void CodeRepoSummary::SetLastModifiedTime(const string& _lastModifiedTime)
{
m_lastModifiedTime = _lastModifiedTime;
m_lastModifiedTimeHasBeenSet = true;
}
bool CodeRepoSummary::LastModifiedTimeHasBeenSet() const
{
return m_lastModifiedTimeHasBeenSet;
}
string CodeRepoSummary::GetCodeRepositoryName() const
{
return m_codeRepositoryName;
}
void CodeRepoSummary::SetCodeRepositoryName(const string& _codeRepositoryName)
{
m_codeRepositoryName = _codeRepositoryName;
m_codeRepositoryNameHasBeenSet = true;
}
bool CodeRepoSummary::CodeRepositoryNameHasBeenSet() const
{
return m_codeRepositoryNameHasBeenSet;
}
GitConfig CodeRepoSummary::GetGitConfig() const
{
return m_gitConfig;
}
void CodeRepoSummary::SetGitConfig(const GitConfig& _gitConfig)
{
m_gitConfig = _gitConfig;
m_gitConfigHasBeenSet = true;
}
bool CodeRepoSummary::GitConfigHasBeenSet() const
{
return m_gitConfigHasBeenSet;
}
bool CodeRepoSummary::GetNoSecret() const
{
return m_noSecret;
}
void CodeRepoSummary::SetNoSecret(const bool& _noSecret)
{
m_noSecret = _noSecret;
m_noSecretHasBeenSet = true;
}
bool CodeRepoSummary::NoSecretHasBeenSet() const
{
return m_noSecretHasBeenSet;
}
| 29.422222 | 146 | 0.702568 | [
"object",
"model"
] |
e92fcf5c8178a0a121e7cb720d074c722e68bc19 | 4,015 | cpp | C++ | 453-skeleton/Window.cpp | JeremyKimotho/Space_Orrery | 27271a9777d8603004d1301d4481febda070b597 | [
"Unlicense"
] | null | null | null | 453-skeleton/Window.cpp | JeremyKimotho/Space_Orrery | 27271a9777d8603004d1301d4481febda070b597 | [
"Unlicense"
] | null | null | null | 453-skeleton/Window.cpp | JeremyKimotho/Space_Orrery | 27271a9777d8603004d1301d4481febda070b597 | [
"Unlicense"
] | null | null | null | #include "Window.h"
#include "Log.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <iostream>
// ---------------------------
// static function definitions
// ---------------------------
void Window::keyMetaCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
CallbackInterface* callbacks = static_cast<CallbackInterface*>(glfwGetWindowUserPointer(window));
callbacks->keyCallback(key, scancode, action, mods);
}
void Window::mouseButtonMetaCallback(GLFWwindow* window, int button, int action, int mods) {
CallbackInterface* callbacks = static_cast<CallbackInterface*>(glfwGetWindowUserPointer(window));
callbacks->mouseButtonCallback(button, action, mods);
}
void Window::cursorPosMetaCallback(GLFWwindow* window, double xpos, double ypos) {
CallbackInterface* callbacks = static_cast<CallbackInterface*>(glfwGetWindowUserPointer(window));
callbacks->cursorPosCallback(xpos, ypos);
}
void Window::scrollMetaCallback(GLFWwindow* window, double xoffset, double yoffset) {
CallbackInterface* callbacks = static_cast<CallbackInterface*>(glfwGetWindowUserPointer(window));
callbacks->scrollCallback(xoffset, yoffset);
}
void Window::windowSizeMetaCallback(GLFWwindow* window, int width, int height) {
CallbackInterface* callbacks = static_cast<CallbackInterface*>(glfwGetWindowUserPointer(window));
callbacks->windowSizeCallback(width, height);
}
// ----------------------
// non-static definitions
// ----------------------
Window::Window(
std::shared_ptr<CallbackInterface> callbacks, int width, int height,
const char* title, GLFWmonitor* monitor, GLFWwindow* share
)
: window(nullptr)
, callbacks(callbacks)
{
// specify OpenGL version
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // needed for mac?
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
// create window
window = std::unique_ptr<GLFWwindow, WindowDeleter>(glfwCreateWindow(width, height, title, monitor, share));
if (window == nullptr) {
Log::error("WINDOW failed to create GLFW window");
throw std::runtime_error("Failed to create GLFW window.");
}
glfwMakeContextCurrent(window.get());
// initialize OpenGL extensions for the current context (this window)
GLenum err = glewInit();
if (err != GLEW_OK) {
Log::error("WINDOW glewInit error:{}", glewGetErrorString(err));
throw std::runtime_error("Failed to initialize GLEW");
}
glfwSetWindowSizeCallback(window.get(), defaultWindowSizeCallback);
if (callbacks != nullptr) {
connectCallbacks();
}
// Standard ImGui/GLFW middleware
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window.get(), true);
ImGui_ImplOpenGL3_Init("#version 330 core");
}
Window::Window(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share)
: Window(nullptr, width, height, title, monitor, share)
{}
void Window::connectCallbacks() {
// set userdata of window to point to the object that carries out the callbacks
glfwSetWindowUserPointer(window.get(), callbacks.get());
// bind meta callbacks to actual callbacks
glfwSetKeyCallback(window.get(), keyMetaCallback);
glfwSetMouseButtonCallback(window.get(), mouseButtonMetaCallback);
glfwSetCursorPosCallback(window.get(), cursorPosMetaCallback);
glfwSetScrollCallback(window.get(), scrollMetaCallback);
glfwSetWindowSizeCallback(window.get(), windowSizeMetaCallback);
}
void Window::setCallbacks(std::shared_ptr<CallbackInterface> callbacks_) {
callbacks = callbacks_;
connectCallbacks();
}
glm::ivec2 Window::getPos() const {
int x, y;
glfwGetWindowPos(window.get(), &x, &y);
return glm::ivec2(x, y);
}
glm::ivec2 Window::getSize() const {
int w, h;
glfwGetWindowSize(window.get(), &w, &h);
return glm::ivec2(w, h);
}
| 30.884615 | 109 | 0.746949 | [
"object"
] |
e9347df79eb1c60d547d6936486e71c7aa94e290 | 2,182 | cpp | C++ | src/worker/ListMarketBook.cpp | captain-igloo/greenthumb | 39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72 | [
"MIT"
] | 3 | 2019-04-08T19:17:51.000Z | 2019-05-21T01:01:29.000Z | src/worker/ListMarketBook.cpp | captain-igloo/greenthumb | 39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72 | [
"MIT"
] | 1 | 2019-04-30T23:39:06.000Z | 2019-07-27T00:07:20.000Z | src/worker/ListMarketBook.cpp | captain-igloo/greenthumb | 39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72 | [
"MIT"
] | 1 | 2019-02-28T09:22:18.000Z | 2019-02-28T09:22:18.000Z | /**
* Copyright 2020 Colin Doig. Distributed under the MIT license.
*/
#include <set>
#include <wx/log.h>
#include "worker/ListMarketBook.h"
#include "GreenThumb.h"
namespace greenthumb {
namespace worker {
wxDEFINE_EVENT(LIST_MARKET_BOOK, wxThreadEvent);
ListMarketBook::ListMarketBook(wxEvtHandler* eventHandler,
const entity::Market& market) :
Worker(eventHandler), market(market) {
}
wxThread::ExitCode ListMarketBook::Entry() {
wxLogStatus("List market book ...");
try {
if (DoListMarketBook()) {
wxLogStatus("List market book ... Success");
} else {
wxLogStatus("List market book ... Failed");
}
} catch (const std::exception& e) {
wxLogStatus("List market book ... Failed: " + _(e.what()));
}
wxThreadEvent* event = new wxThreadEvent(LIST_MARKET_BOOK);
event->SetPayload<greentop::sport::MarketBook>(betfairMarketBook);
QueueEvent(event);
return (wxThread::ExitCode) 0;
}
bool ListMarketBook::DoListMarketBook() {
std::vector<std::string> marketIds;
marketIds.push_back(market.GetMarketCatalogue().getMarketId());
std::set<greentop::sport::PriceData> priceData;
priceData.insert(greentop::sport::PriceData(greentop::sport::PriceData::EX_BEST_OFFERS));
greentop::sport::PriceProjection priceProjection(priceData);
// show "virtual" bets
priceProjection.setVirtualise(true);
greentop::sport::OrderProjection orderProjection(greentop::sport::OrderProjection::EXECUTABLE);
greentop::sport::MatchProjection matchProjection(greentop::sport::MatchProjection::ROLLED_UP_BY_AVG_PRICE);
greentop::sport::ListMarketBookRequest listMarketBookRequest(marketIds, priceProjection, orderProjection, matchProjection);
greentop::sport::ListMarketBookResponse lmbResp = GreenThumb::GetBetfairApi().listMarketBook(listMarketBookRequest);
if (TestDestroy()) {
return false;
}
if (lmbResp.isSuccess()) {
for (unsigned i = 0; i < lmbResp.getMarketBooks().size(); ++i) {
betfairMarketBook = lmbResp.getMarketBooks()[i];
break;
}
return true;
}
return false;
}
}
}
| 29.890411 | 127 | 0.690192 | [
"vector"
] |
e93947f72e0a15381377f40fdf83af1d7cdb5456 | 2,391 | cpp | C++ | Recursion.cpp | FaheemAKamal/Cstuff | a13243ad8de753e3c7d9b0ee541278f0049b59a2 | [
"MIT"
] | null | null | null | Recursion.cpp | FaheemAKamal/Cstuff | a13243ad8de753e3c7d9b0ee541278f0049b59a2 | [
"MIT"
] | null | null | null | Recursion.cpp | FaheemAKamal/Cstuff | a13243ad8de753e3c7d9b0ee541278f0049b59a2 | [
"MIT"
] | null | null | null | #include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <algorithm>
using std::sort;
#include <vector>
using std::vector;
#if 0 /* Basic Recursion Problem */
void f(int n){
if(n==0){
cout << 0 <<endl;
return;
}
cout<<n<<endl;
f(n-1);
cout<<n<<endl;
}
int main(){
f(4);
return 0;
}
#endif
#if 0
/* TODO: write a recursive function to compute x^n (x to the n power)
* where n is an integer. */
int f(int x, int n){
if (n == 0) return 1;
if (n == 1) return x;
if (n > 1) return (f(x,n-1)*x);
}
int main(){
int y;
int b;
cout << "Value of Base? \n";
cin >> y;
cout << "Value of Power? \n";
cin >> b;
cout<<f(y,b)<<endl;
}
#endif
#if 0
/* TODO: write a function that recursively computes terms of the
* fibonacci sequence. */
int fibonacci(int n){
if(n==1) return 0;
if(n==2 ||n == 3) return 1;
if(n > 3) return (fibonacci(n-1)+fibonacci(n-2));
}
int main(){
int y;
cout << "What fibonacci term you want? \n";
cin >> y;
cout << "Fibonacci Term: " << fibonacci(y) << endl;
return 0;
}
#endif
#if 0 /* Online Version */
int fib(int n)
{
int a = 0, b = 1, c, i;
if( n == 0)
return a;
for(i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
int main()
{
int n;
cin >> n;
cout << fib(n);
return 0;
}
#endif
#if 0
/* TODO: try to implement the idea for recursive sorting from the lecture.
* IDEA: sort the left and right halves recursively, then combine them
* together with some kind of "merge" operation. */
vector <int> sort(vector<int> &v){
if(v.size()<2){
return v;
}
else{
vector<int> vleft;
vector<int> vright;
for(size_t i = 0; i < v.size(); i++){
if(i<v.size()/2){
vleft.push_back(v[i]);
}else{
vright.push_back(v[i]);
}
}
sort(vleft);
sort(vright);
}
}
#endif
#if 0
/* TODO: write code to compute the greatest common divisor of two integers
* Do this with recursion -- no loops! */
int gcd(int a, int b){
if (b==0) {
return a;
}
else
return gcd (b, a%b);
}
#endif | 17.580882 | 75 | 0.488499 | [
"vector"
] |
e93df49edade03420d176cd55120a0e6575b74d6 | 345 | cpp | C++ | src/TMB/bicopula_TMBExports.cpp | ellessenne/bicopula | b56323f7284a0312569822e19632d27c270bc6c9 | [
"MIT"
] | null | null | null | src/TMB/bicopula_TMBExports.cpp | ellessenne/bicopula | b56323f7284a0312569822e19632d27c270bc6c9 | [
"MIT"
] | null | null | null | src/TMB/bicopula_TMBExports.cpp | ellessenne/bicopula | b56323f7284a0312569822e19632d27c270bc6c9 | [
"MIT"
] | null | null | null | // Generated by TMBtools: do not edit by hand
#define TMB_LIB_INIT R_init_bicopula_TMBExports
#include <TMB.hpp>
#include "bisurvreg.hpp"
template<class Type>
Type objective_function<Type>::operator() () {
DATA_STRING(model);
if(model == "bisurvreg") {
return bisurvreg(this);
} else {
error("Unknown model.");
}
return 0;
}
| 20.294118 | 47 | 0.695652 | [
"model"
] |
e94118edebe18044464af9fe722e1f85574b00e3 | 2,358 | cpp | C++ | test_driven/IntersectionData.cpp | colinw7/CRayTrace | bee666d42128666fbb1968812e9d2e3630a7827f | [
"MIT"
] | null | null | null | test_driven/IntersectionData.cpp | colinw7/CRayTrace | bee666d42128666fbb1968812e9d2e3630a7827f | [
"MIT"
] | null | null | null | test_driven/IntersectionData.cpp | colinw7/CRayTrace | bee666d42128666fbb1968812e9d2e3630a7827f | [
"MIT"
] | null | null | null | #include <IntersectionData.h>
#include <Intersection.h>
#include <Ray.h>
#include <Object.h>
#include <RayTrace.h>
#include <set>
namespace RayTrace {
IntersectionData::
IntersectionData(const Intersection &intersection, const Ray &ray,
const Intersections &intersections)
{
assert(intersection.object());
t_ = intersection.t();
object_ = intersection.object();
point_ = ray.position(t_);
eye_ = -ray.direction();
normal_ = object_->pointNormal(point_, intersection);
if (normal_.dotProduct(eye_) < 0) {
inside_ = true;
normal_ = -normal_;
}
else {
inside_ = false;
}
overPoint_ = point_ + normal_*EPSILON();
underPoint_ = point_ - normal_*EPSILON();
reflect_ = ray.direction().reflect(normal_);
//-----
std::vector<const Object *> containers;
//---
auto containersFind = [&](const Object *object) {
for (const auto &container : containers)
if (container == object)
return true;
return false;
};
//---
auto containersRemove = [&](const Object *object) {
std::size_t i = 0;
for ( ; i < containers.size(); ++i) {
if (containers[i] == object)
break;
}
assert(i < containers.size());
++i;
for ( ; i < containers.size(); ++i)
containers[i - 1] = containers[i];
containers.pop_back();
};
//---
for (const auto &intersection1 : intersections) {
if (intersection1 == intersection) {
if (containers.empty())
n1_ = 1.0;
else
n1_ = containers.back()->material().refractiveIndex();
}
if (containersFind(intersection1.object())) {
containersRemove(intersection1.object());
}
else {
containers.push_back(intersection1.object());
}
if (intersection1 == intersection) {
if (containers.empty())
n2_ = 1.0;
else
n2_ = containers.back()->material().refractiveIndex();
break;
}
}
}
double
IntersectionData::
schlick() const
{
double cos = eye().dotProduct(normal());
if (n1() > n2()) {
double n = n1()/n2();
double sin2t = n*n*(1 - cos*cos);
if (sin2t > 1.0)
return 1.0;
double cost = std::sqrt(1 - sin2t);
cos = cost;
}
double n1_n2_f = (n1() - n2())/(n1() + n2());
double r0 = n1_n2_f*n1_n2_f;
return r0 + (1 - r0)*std::pow(1 - cos, 5);
}
}
| 18.864 | 66 | 0.583545 | [
"object",
"vector"
] |
e9418d86fbf6c361ecc3073f49ba1e4cb9df2a03 | 1,056 | hpp | C++ | source/data_model/hdf5/include/lue/hdf5/error_stack.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/data_model/hdf5/include/lue/hdf5/error_stack.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/data_model/hdf5/include/lue/hdf5/error_stack.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include "lue/hdf5/identifier.hpp"
#include <vector>
namespace lue {
namespace hdf5 {
/*!
@brief This class provides a view on the HDF5 error stack
*/
class ErrorStack
{
public:
ErrorStack ();
explicit ErrorStack (Identifier const& id);
ErrorStack (ErrorStack const&)=default;
ErrorStack (ErrorStack&&)=default;
~ErrorStack ();
ErrorStack& operator= (ErrorStack const&)=default;
ErrorStack& operator= (ErrorStack&&)=default;
bool empty () const;
void clear () const;
// void add_message (std::string const& message);
std::vector<std::string>
messages () const;
private:
Identifier _id;
::herr_t (*_original_error_handler)(::hid_t, void*);
void* _original_client_data;
};
} // namespace hdf5
} // namespace lue
| 20.307692 | 71 | 0.505682 | [
"vector"
] |
e943160b1524d5e3865529b591b15f56826bd1bc | 28,446 | cpp | C++ | Source/tests/functional/crypto/hash/md5_tests.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 5 | 2019-10-30T06:10:10.000Z | 2020-04-25T16:52:06.000Z | Source/tests/functional/crypto/hash/md5_tests.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | null | null | null | Source/tests/functional/crypto/hash/md5_tests.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 2 | 2019-11-27T23:47:54.000Z | 2020-01-13T16:36:03.000Z | //
// md5_test.cpp
// OpenPGP
//
// Created by Yanfeng Zhang on 10/28/16.
//
// The MIT License
//
// Copyright (c) 2019 Proton Technologies AG
//
// 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.
#import "utils_test.h"
#include <hash/MD5.h>
namespace tests {
namespace hash_tests {
// Test vectors from <http://www.nsrl.nist.gov/testdata/NSRLvectors.zip>
const std::vector<std::string> MD5_BYTES = {
"",
"24",
"70f0",
"0e1ef0",
"0838788f",
"103e08fc0f",
"e7c71e07ef03",
"e0fb71f8f9c1fc",
"ff7c603c1f80e207",
"f03fc86081fe01f87f",
"9fc7f81fc1e3c7c73f00",
"007fbfdfc0fe027e00f87f",
"0101c01e03f830080ff3f9ff",
"c403fc0ff801c00ff0061041ff",
"ff078047fc1fc060301fe03c03ff",
"803f843effc03f0f007fc01fe7fc00",
"ffe07f018181ff81ff003e00207f800f",
"003e00701fe00ffaffc83ff3fe00ff80ff",
"7fefc01e7cffe01ffe001ff008ffc07ff000",
"e00f80070c01ffe003f02ff83fef007801fe00",
"e7001000f8180ff0ff00ff803fc3fef00ffc01ff",
"001ff80ffc00fc00ff87c00f807bff000f0201ffc0",
"000ff003c7f83e03ff8003ff8007ff0fff1f83ff801f",
"ffc01f803f9ff8783e7ff8003e20043f807ffc001ffe00",
"3f0780e007e000fc7fc0c00f8ff0800e0e03ffbffc01ffe0",
"fffc11fce00e1fff87801fe0fffdffc003ffc00f0007f001ff",
"f007c1fe00f801e780ff803f1f7f8c001c000ff807fc00fffc00",
"000ff83fc060007ff8ff0003f03c07c07fe03ff801007e03ffc000",
"000ff803001fff000ffe003f0003ffe007c0ff003c7ff001fff83fff",
"0001e0e01ffe0003fc000fffe00fff000e007ffc0ffe0078003fff00ff",
"8041ffc3fe001e000fffe0ff800fe0007ff7ff01fe01ffdfff0001ffe000",
"f80700ffc07fbe000fff0003e3f0fff0001f81ff800fff802003f00380fffc",
"003820007ff001fffecffe07ffc0007ff81f0000c000c00fff3e0fc00fff8000",
"1ff807fff803e001fffc3ff800381f003fdc01c004ffff000ffc08020001f03fff",
"8007860003ffe0003ff8000f800ff80fffe0001f80007ff8c00ffff07c0407ff0000",
"01ff00183e0f0007ffc000f01ffe0780600ff8003ffe381fc0003f81fffc1fe0003fff",
"f03fffc0007ff0003fff0fe0070ffc7e03fff0fc0f9fc03fffcfff0000ffc000e701fff8",
"0001ff8020007fe0007e07fff8c7f8fff00ffe0000e00fe0001fff87ff0001f0007fc1ffff",
"00007fffc001fe7e01fffefff07fffcff807fe000fffc007fffc003e0007fc007fc007800fff",
"ffff03ff07f8ffff80007ffefffe0003fff81fff3ff81fff001fff0fc07ff001ffe0001fff0000",
"ffff0000fffc00030ffff001f8000fe1ffff03e03f1fff80007c0001ffc0017ffe000e07ffe0ffff",
"c0003ffe03fc0c000401ffe1e003ffe03001ff00003c1e018001ff00403ffe003fff807c01ff80007f",
"3fa0000fff81ffc00ff07ff8000fc0007fe001e00004ff001ffe0001ff8007fffe003fffc003ff80003f",
"f01fff01ff80ffc08007f00003ff80001801fffc00fffc03ffff007fc003ffc7ffc003f0ff80003ffe0000",
"07f1bfffe000780007e0008003f03ff700003800fe00f80ffe0000803fffc1fffc00ffff8ff0001ffff00fff",
"001c0007fffc005e3fff00003cffffc03fff81e070001ffc0003ff00007fffc01f8c0ffff0ff8007e01001ffff",
"c00007ff807fff8001803fffcfc0fe00ffc01ffc01fff800fffe0ffff0060000c03fff8078fffc000ffff0000fff",
"ffe007fff8007ff01fff8001fff81ff80103ffe00003e0780fff000ffc1ff8000fffe01f0007fffc001f03fff7ffff",
"c0f80003fe003ffff00003fc0fff8000e3fff83ffe000073e0fffc07ffc3fffe030000700003fff80fffe0001ffff800",
"fff00fc7fffc003ffe00003fff803f80003fffc0007001ffc18003ffff800061fffe03fd803fffe001c1ffff80000ffe00",
"fffc0003fff00ff80007df8ffff80001fffe008000ff801ff000011c00003ff8003fffeffffe01c3808001ffffc00007ffff",
"ffffc001ffc1ffff87ffff003f00001ffc0001ff801fc01fff0000ff801ffff87ff83fffc1ffffe001c03ff7fffefc00003fff",
"00ff81ffe003f80e0000fff81ffffe0000ff800007fff801ffe0000ff001fe003ff07fe0007fffe01ffffc01ffe001800007ffff",
"000ffff00000e00ff80000ffff8003ffe1ffff3ff80fffc7e0001fff003ffe0ffff00300c0001ffffc3fffe03ffff81ff0001fffc0",
"0180001f01ffff830001fc007fe00e7ffe00003800ff00003fff8383ffc0007fff801ffff01ffffc00037fff81c00007ff83ffff0000",
"ff800dffe003fff000fffc00f001f807fff80f800fffff00ffff87ffe1fffc678c7ffe0003ff3ffc0701ffffe00001ffffc00c400fffff",
"00001ffffe001f00001fffff07ffffc007ffe000020000ff00780000e00008001fffff0003f81f00000fffc00001ffffe1f800003f800fff",
"000ff800fc0003ffff00003ff001ffffe07ff800f80fffff80000ffffc0fffe00000ffc3fff007ffff0038f800201ffe3ffe00fe007fffc000",
"003f00e0000ffffc7ffffc00007e0000fffe1ff0001ff0001fff87f0003fc00fff87ff003f81fffff7ffe0ffe03f9fff0007007ffc03fff00000",
"e03ffff0ff803e0003ffe0000ffc0007fff800007f80000ff801ff7ffff0003ffffe7fffe000ffc3ffff0000f000007fff003ffff00001c003ffff",
"0003c001ffdffdff9ffe1fffff003ffffe00007fcffff01ffffe07f000ffffe000010007ff801fe00000fffe03ffff8003f00ffffe00001ffff80000",
"001ffffbfffe0007fff00000ffff00000ff3fffe007800003e00003ffff8001fffff800003ffff0007ffee001ffc007800001fff07fffe03ffffe00000",
"007ffffe00003ffc03fffc1ffff07fd803f000fdfc380008001000e006007ffe00000fff80003f03fffefffff9fff80007fffc01ffc00003ffffe003ffff",
"fff00fffff000600fffff007ffe0040003000003f0ffff0003fffbffc3fff007ffffc7007f800003fff8001fe1fff863fc003fc09ffff800007fff1ffffc00",
"003ffffc000fc7800002001e0000607f03fe00001fff801ff80000ffff800003ffc0007fffc07fe003fc00fff7ffff00001ff00003ffffe1ffff800ff800001f",
"0001fe000383f3ffff8007fffc3ffffc03ff8000060000780007ffff8007fc01f80007ffffc000380007fffe3ffff83fffcf3ffc007fff001fff80003003ffff00",
"f8003800003e3f00003ffff00200000fffff808003ffc00004000fc03ffffe00003ffffe003ffff80030007bff000003fffc3fe1ff8000701fffc007fc001ffff000",
"0003f8180000703ffff80000ffcfffffc003fffe00100000fe03fff800007e00007f8fffc000007fffe0003c07c000007fff01fff801ff80000ffff9e0003fffe00000",
"fffe003fc01ffff07ff80001fff81ffffe0000fffff8007fff803fffff007ffff8000c00000ffe7e003fe0187ffe00003800003ffffe000003fcffe1fe1ffffe000007ff",
"000007fffe000007fe00003fe0007fffc000007ffffc00fe0003ffe0001f0ffc001fff800007fffff000fffff000001ffff801ffe01fffff001f8007f00001fff80001ffff",
"00003fffff03fe000007c000007ffc0ff000001ffffe000007c00000fffe00003ffffc01ff7ffc001ff8001fff07ffffe0007ffffc01fffff00001fff8001e00007ffc003fff",
"fe3fff83fffe0007fffff0003e0000fffffc00403ffe000003f00000703ff80fffffe01f800003c3fffff00001fff00f80000fe0fffffef00001ffc000007ff000007ffee00000",
"000003fff001fc0000ffff00007fffff8007ff8fff80000ffff000003c0003c0fffffe01ffff800c7ffff800001ff000007f800000800000fffff01fffe000fffffe1fff1fc00000",
"fffffe07ffc000063f9ff007fff03ffe1fffff81ffffc0000200fe00040007000001fffffe000007fffe001ffe0000ffffe007f800fffffc003ff3ffffc0007fffe0000ffffc07ffff",
"fff000007e001e03ffff000073fff000000fffdfffffdffc0007fe07fffe00001fdfeffff03ffffc000007fffff000007fe007ff8000007fe003fffff9ffe000003fe3fffffc000003ff",
"0003ff00003fff8001f0000ffe0000060003fffffc03fffff78000007fc00fffe3fe0f00007fff007ff80000ffffee007e01c0001fe00007fffff80000e1fffc3fe7fffff83ffffc001fff",
"00000ffff80000fffffc001fe007ffff0001ffdfff80003ffffc00000ffc07ff0000ff800003fffff00007fffff000fffe1fffffe03ffffe0000600000ffff7ffff00003ffffc0070001ffff",
"0000207ffe0f83ffff8003ff000000ffffe0001fffffe0003ffe7ffff0001fffffe00000ffff87ffc00017fdff9ffffbffffe00003e00007ff9fffff80007fffff0001ffffc0ffffc01000001f",
"000007ffc000ffe00007ff800380000ff800007ffffe00001800fff02001fffe0000600ff0e003fffe003e1ffffc0003ff800000fff8000100000ff3fffc0003ffffe1ffffc1f00000ffffff0000",
"fffff0000007fffc007f87ffff0000007fffc07fff800003f0ff3fff803007ffff1f8e007fffffc001fffc07f800007ffffc003ff000f8000007ff00000e000fff80007fc001ff8ff8000701ffffff",
"ff803fff3ffe0000ffffff9ffff83ffff800000ff8000003fe007fffff000fff01fff00fffe0207ffffcff01f80007ffe0007ff8000fff8000007fe0003ff801fe0007fff000007fffffc00001ffffff",
"007fffe00001fffff800003ffffc007ffe000003fffff003ffe0007f80000fff3ff800007fffff0007801f83f800000ffe3fffc03ffffe1fe00007c003fff00fc00003ffff8000007f800000ffff800000",
"fe0000200004000fffffc001fff83fc00000ffffc000ffffff80003ff8007ffffe7ff8007fff8007ffc0000ffff8007fffc000ffffc03fffffe00fffffe0e01fff8000007fffc071fffffc0001fffff80000",
"ffffe0000ffff000003fffffc000ffff00000fffffe00001ff00001fffe03ffc0003e01ff01ff800003fffffc00ffe0000200000fffc000ffffe3fffff00fff0000080001f03e001fffa003fe000007000000f",
"fdffc0002001fe003ff80003ff000003f8ffcfc3fffffc0003fffffc0000783ffff001ffe00fffff000007fffffcfffff80001ff800007fffffc00001c0001ffff07f800001ffffff00001fe007ffff01ffc0000",
"0000003fff000007fffffc000001e00fff83fc01fffff00fff0000003fffffc01fffffe0002000003fffff0000fffc03fffff0001ffffc000003ffffc07f8000ffffff000f0fffffe00000fff80000fffe00000fff",
"fffe03800003ffffc03fffff0003fffff8000001ffffcffc0000e0eff8000fffe3f8003fffff803fbffe0000fffc000001ff0000cfc001fc00007fffffc000107ffffcfe000007c0ffffff8fff00001f9e000001ffff",
"007fffe00001ffffc3ff800103fc000000fc01fffff87fe7f000007fc03fffffc000001fff800001ffe000007000001c7ffff81ffc000007efe0ffffc1fffc000001ffffffa007ff001e001ffc0000380018c000007fff",
"000ffff8000007ff00fc000003fffc0007ffffe00000fffc0fff00000ffffe0f8007ff03fffff9fffe000003f8000007e00000c0001ffff07fffffc007fffffc00003fffffe000001ffff81ffe00003fffffe03f06000000",
"fff00008000feffffffc00007ffff0007ffff800ffff81ffffe0ffffff000000800003ff803ffffc00001fffc00ffffe00000073f01ffe00ffc03fff003fff83fffe01fffff7ffff8000003f00001fe3fffff0000ffff00000",
"00007ffc007fe0000fffe001f8003fff000078007fe000001f0007fffff8f9f001fff807c00ffff80007f87ffe00000fffe3f00007fffffc031c00007fe000fffffc00000ff3ffe000000ffff9000010003ffffcf87fff000000",
"0003ffffc07fffffc00003ffffff00000ffff01ffff00007ffffefff81f7fffe0007fff000001fffc00f80000ffffc0000ffffffc003ffe3fffffe001fffff0000ffffff0ffff1f8000001ffffff801ffffe000800007fffff8000",
"1fe0007c1fc007ffc007fffffe003c000000ffff800007ffff001ff8ffc000ff81ff01fffe00787ffff000018000001fff00001ffff0001fffffe0003c00001fffff8003ffe001fffff9fff800007c0000fe0000ffffff00000fffff",
"fc0001ff00000c00ffffe3fffff0800e0e00000ffe0003ffc000007fffffe0c0000007e0ffff039fffffc1c00003ffffc3fffffcffffc00001fc000ffc0000007fffff03fffffc0ffffe000003803fffff0000fffff80003ffff800000",
"ffff80fffff80000fc0003fff8000fffff00030000007ffff0003ffff00001fc010003ff801fffe3fffff8001ffffff801ffdffffbffc000003ffff8000080c7fffff80fff00601fffe00001fffffe0ffffffc000000f00603fffffe0000",
"ff000ffffc000ffffffc07fffc0000f0000080007ffe00000ffffffc3f00ffffff001ffffff0001fffffe0001fffffc3ff000001fffff000000fffe007fc000000fe0007fffff800003f00000f80003fffc00011ffef0007007ffffc000000",
"fe00007ff7ffff00000fffffe001ffe0000003ffe000fffe0001fff7fff8000fff000000380007fff807fffc001fffff0fc1ffffc000ffff0ffff001fff80001ffff8000000ff8003ffffe3ffffff00000380fc3ffffff1fffc03fffffe00000",
"fffff0007fc007ffff81ffc00001ffffffc000001ffffe03c0000ffffffc0003ffffff83ffc00007f000001f8000003fffffe7ff0007fffffc00001ffff80003f000fffc001fffffe003fff00001ffffff8000000ffffff810001e03ffffff8000",
"0001fffe0000007ffffff000001fff8007ffffff800001fffc03ffff9ffffe000800000600000081ffffc00007f800ffffff000000fffff8003ffffff83ff80000007fffc07fffffc0fffffe000001fff8000003ffc1fff000000307f801fffe0000",
"f8000001ffff80000fffff8fff001fff0fffc00000fffffc000ffff0007000003fffc000007c00007e000ffc000000ffff8000000ffffffc38000003f00031f01fffffc007ffffe01ffffff3fe000000ffffc0001fe7ffe1ffffdf0000001fff000000",
"3ffffff800000060000fffffe007ffffff00003ffffff01fffff8000700000010000003ffffe0000001ff8fcc00ffff8003fffc0ffff800003fffff8003ffffc00000f81ffc003ffc03fffff8003fffe00fffffe00001c0000003ffffff8007fffc00000",
"0000000ffffe0fffff87ffffff0080000fffc00003f01ff7e00000700001ffffff8001fe07f00001fffc0000040001fffe07fffffe0007c00000ffffff87f003fffc00001ff80001ffffc000003fffc000007f8ffff80000007fffe0060e00000fffff8000",
"03fffffde000001ffff801fffffbffffe001f0f00000ffffff8000007fffffe01ffffff00180ffffffe000007ffff0ffffc0000007fe0000001e001fffffe01fffe001ffc0003fffe000000ff000ffff7fc01ff83fffffc000007fffe0fffc0000ff0fffffff",
"07fffc03ffffffdfffff87ff1800038001ff0000001fff00003fffffc01fe03ffffffc000001fff800003ffffff8000007e00007fff9ffe0003fe0007feff0000781fffc000000ffe00030000000fffff0000003fffc7f07f803ffffff003ffc000001ffc00000",
"007ffc000003fff8000061fe7ffffe00001ffffc3fff8001ffffffe000ffffff801ff8007ffffff8000007ffffe0000007ffffff8000ff800ffffffc00007ffffe0000003000007f800007fffff0000003ffc00fffff803fff8003fffffe03ffffff7ffc1ff00000",
"1ff000007ffffe02000003ffffffd807ffffe001ffff80000007c0000fffc07ff00007ffff800007f000007ffc03ffffffc00001fffff9fffe00001fffc0000003fe3fffff0007fe000003c0003ff8001003fc000fffc0007fffe000fff000007fffe000000fffffff",
"fffffff8000060000000fffffc03fffc00003c003fe07ff80007fff80ff800007ffffffc007fc20003fffffe0001fffffff003fffff01807c0000fffc000007fffff87e0000007001f800407ffe000001fff81ff800003fffc000007ffffffc000001f8001ffff000000",
"000ffc1ff8000ffffff807fff1fc001ffffff0000fffdfffffff000003ffffff0001ffffffc0100ff0000000fc001f00070001f000001fe00000307c3fffe000fffc07fffc003ffffff8ffffc1fc1ffffff80001fffc00000fffffff0000fff80c000007ffff0000007fff",
"ffff80ffff0000007fffff001ffc0006000ff80000018000007fffffe03ffffffc0060000000fe000007fffff07ffffff800008000000fffffffbfffffc007fffe00001c001ffc070001ffff00000080001fff038000003ffffff80007ffffff80001fffffe01fffffc00000",
"fffffff80000007e0000001fff8007ffffff8000000fffffc3fff00000047fc07ff0003fff80007fe00003ffc00007ff00000fff800000078000000fffffff01ffffffc003c0000003ffffe0000fffffc00003fffe0003fff800000fffffc001ffe00000fffffc00001fffffff",
"fff0003ffc0000ffffffe01fc3fe0007fff8000ff001fffff00000ffc00fffff800000fffff3ff80000080083800000ffff0001ffffffc000f800070000031fffffe3ffff80000003c3ff00fffff0003fffbffffff000ffffffe000000f0000000fffffc007ffff00001fffffe00",
"fffff00ff83fffffe00003fffe00003fff80ffffff000000fffff8fffff0000ff1ffff0000000ffffc0000001ff000001ff003ffffffe1ffe000001fffc1fe000007fffc0000001ffe3fc0000001fffc00001fffff0fe00001fc00fe0000007fe0001fffffe07f000ff000fffe0000",
"007fffc007ffffff8007fffffe0000007e0000000fff801ffffe07fffff003c7fffffe0000007ffe00001ffffe000000fffc001fffc000003fff001e000003ffffff8000007ffff803fffc0001fffffe000fff020007fffffe000000fe01fffff7ffff19ffff000007ffc1ff000007ff",
"00000040000007fffff81fffffc0003efffff00000007ffffe000000ff8000003ff1ffffffe0000001ffffff00001ffff80007fffff8001fffc1ffffffe001ffffffe0000007ffffffcfffe0003fe0ffffc00007ffffe001fffc3f0001fffffe0001ff0ffffffc000001ffff8000000fff",
"fffff0ffffffc003800001000003fffffff1ffffffe007fc000003fff00000007e00000007003ffffc000fc7ffff000007ffffc0000003fffc0000ffe00000007ff00000fffffffdff00ffe0ffffe007fffff87ffffe18000001f0001ffffe01c001fffffff80001feffffff80000007ffff",
"fffff0001fffff00003ffff000ffff0007fffff803ffffe7ffffff81000001ff00003ffffff8000000f007ffc00ff0003fffc0007ff800fffc00001fff801ffc000001ffff00007ffffffe00000fff8000000ffffffc000000fffffc000fff80003ffffe00003fe00fffff000001fff0000000",
"ffc0000003fffffc00fffffc0000007fffff0000001fe0000fffc0f000007fffffe000201fffffff0000001f80000007fff1ffffffc000001ffffff0003ffff8003ffffffe01fffffe7f9e001ffffc007fe07fffffe0007ffffe000001fffffff801ffc003000ffff800000ff00fff0000000fff",
"0003ffffffcffff87f8ffffffc01fffffc00001fffffff80000001ffffe1fff0000000fffffff80380003f80000fffffffc00000027ffff803ffc000003fff80000001ffffe0000003800000ffe07ffffffc000001fffffc000000ffff800007fe000007fff000001f8000003e1fffffff9fffffff",
"fffffe0003ffffff8001ffffffa03ffff8007f03ffffc0000fffc3fff80003ffffffc07ff01fe00fffffc0001ffe0fffffe00007fffffc0000fc003ffffff00000003ffc0000000fffc40000ffc00003ffffff800003fc0ffffff0000003ffffc007fffff80c3ffff0001fff80000001fffe00003fff",
"0000001fffc3ffff8000003ffffffe0000000fe0007fffe00ffe00ffffffe003fff80000003fe0000001ffffe7ffffffe0000007ffffc0001fe0000001ffff000003ffffffe000001fe003ffff00000007fff03f8000000ffffffe0000ffffff00003fffff800ffffe01fffffff83fffffc00000ffffff",
"ffffff8000fffffff000001f003ffffe0ff01c00ffffe0000fc01fffc0000001ff80f7fff800003fffc0000001fff00003e3fc0007f800003ffffffe00001f00000018003ffffff80fe0000000600007fffffe0060fffffff800003fff8000003ffffff000000ff000fffff1ff003fffffff01ffe0000000",
"fffffffc000000fffff001fffff80000ffffffe7fff801f87fffff80003ffffc000001ffffe0003fc000007fffff00000fffffffc0000ffff1fffffff8000ffffffc000007ffffff80fffff807f00000001fffffffc000ffffffc0000effffffc0000003fff8000003ff80000000e000000ff800003fffffff",
"3f0003c01f0000000ff00007ffffef00fe007ffe00003ff0003fc0000007fc000003ffffff0fffffffc007f80000f800003f9ffffffc00003fffc00003ffffc00000fffc001fffe0000007ffe0070000007ffffe000000fffffe00000ffc0007fff00000007f8003cfff800001ffffe03c00003fffffff800000",
"30000000fff80000fffc003fffff8000000fcfffcfffffc0ffffff80000001fffffff00000001fff0003fffc00000007ff80007ffffffe0fffc00000007ff0bfffffe00000fff8000001fffff800003e000007ffe00000008000038001fffffff860000000fff0001fffffc7fff040fffffe000007ffdfff800000",
"ffffff83fff81fff1fffff800fffffe00000003fffffc0f8000078001c0000001fe0000000ffffe03ffffffe000003fffffe0000001ffffc007fff0000001fffff000200003ffffc000000fff01ffeffffc001fffffff0000000fffffe0000000fffc000007f7fc0000001fffffe0fffffffc0000f8000003fffffff",
"fffffffe000000fff80ffffff0000007fffffbffc00007fc07e0000001ffffe0007ffffff800003ffff80000000fffff00000fc000003ffff0000001fffffe1ffff80000200000003fffbfff9ffffffc3ffffff0000007800000ffffe7fffffff000003fffffff000007ffffe0ffffffe001fffffff80000007fffffff",
"0000001fffc0000fffc000001fffc0001fc0000003ff80000007ffffffc000000080003ffc00c0000fffff000006003ffc1e001ffffff0003e0ffffff000003ffff00000001fffc00000fffffff800e00000fffffffe00000ffffffe3ffffffc07fe000000c0007ffffffe00fffffffc07ffffe0003fe3ffffc000003fff",
"0000000fffc0000ff8000000fffc00000ffffffe00000003ff00fffc07fff01ffffe0ffffffdfffffff01ffff00007f8fff8000000ffffc03fffffff8000000fffffff000003fffff00007ffff00003ffff001ffffc001ffffff003ffff81ffffffe1fffffffc000007fe00007fffffe00000003e007ffc003fc0007ffffff",
"ffffff000003c0000001fffff80000000fffffff00000f0000fffff88000f8000fc0000000e0000000fffffff80ffffffe00001800007fffffff000003ffffff007ffffffc0003c000000ffffffff00007ffff8001ffffffe0000ffffe07fffff800ffffffc0000003e00007fff00ffff00000fffff87fc003c03fffe0000000",
};
static const std::vector<std::string> MD5_HASHES = {
"d41d8cd98f00b204e9800998ecf8427e",
"c3e97dd6e97fb5125688c97f36720cbe",
"038701ca277a9d4de87bff428dd30a12",
"bc60c6192e361d99b59d47250668a852",
"542c3a0ab6b51bc6a88fa7bb567bca3e",
"e035f9e748a2a09a4fbdcf18c4f58bf1",
"3b4cc9226a236742d72578c5915b6c3c",
"35950208a022baac90056636827158ce",
"84cedff2ed1b78b395cc8651094f4ce3",
"7badf748f4cb700272a72edfea22e9bf",
"a1bb6e142739dbdb0925747d95e0a1ad",
"0cd9b72dfdee8efd2e1515f4c5a62284",
"ef07c13e75d50578d09052aa21a7cffb",
"cf3b261af9344bf83b4dd82b30242c78",
"530710f65fb98fff8eb927e2938cb8c5",
"4e6d73658b27e19d4bb4500625001e39",
"c8e5f2f272b1ef88ec62dd0d9d54e902",
"031cbf1fb05b4ec09f3c93235d0f49ac",
"8c0e1400df02ba8c4809b705e5f5e114",
"57ec48278e19f71f54c570a5ab306df7",
"ecd3dc346a2337b95389a094a031610f",
"f11d91eae492225cbd82ef356aa96f9f",
"26bd8b480216c723ce75da98b9bd430c",
"80999c2d12f623e4f87e0550a8e3523a",
"00945c1bd739ce389ac24bb93f6f9a85",
"7ab55f0bd5dca5b17ecaa7fef73ed87b",
"e3cedd606ad51dd18532abd3079a3e0c",
"df5ecc6732e22cc25836398a10222e97",
"863b6d9962ee3761bbb9cd8a8367589e",
"683c9384e29efe82dd3ac847904c28e8",
"b3d948e72159ddc9c600d75512c5f115",
"ce8633a6cf189b07e022147bbbd0f350",
"8df17372eb32a0afa4fc47837262ff61",
"62c63ca91890ce6f78a59c0bdb1e7bab",
"1eda4bb0259a939548ec4ceb39facde4",
"c4f37a2c450f2a23322513b372e668a5",
"cab8f06436c5ad45f982490215836f4e",
"3a43bc720714a2a42a73a76085542f86",
"03f2f4033b258e6eb1e101f1ed4c24b4",
"2ceb33cec5ecad4a50f6bd3a831ae77c",
"dd808f695d28f93562cfcb164bc3cce4",
"01c6d7a87e94bf685205ec8d7c5196af",
"ef0e93e8928f8bae1b216da8e661fc9b",
"c8da55117d7d4b7ee8ddc8dc4ba73aa6",
"bbfc64583c6d4c2ef4b0358464d4d028",
"3bb5864481f2e66387419dd1a168aadc",
"0d725d3a1d3d97d7b5ea8293bbbf32ba",
"915eb22a15f7673f983672b6c353b6c8",
"13b51da3e8a1422bfd58b79c4e19de64",
"e69d6c03102464f22c395f9fa27108de",
"132fa4cbedaa7bd965b0b5900211be48",
"e37ff5d9f14249f327a19dd5296e6c7e",
"4881a65cf107b1d034ff3ecd64ab9cb4",
"547e92d01c0b699cfdf43f91714cfe2d",
"aa2b3a055b56845f19109f21d3c783f4",
"eb1f01cc647ece73b2192537200bb8b9",
"1db274ef41b1ad71f713df2b05207e1a",
"d8b4ec343b4310345efc6da9cee8a2ec",
"082ee3b2be7910f7350368e395a63d90",
"d247c4070ae1de106bcb438a2dacac23",
"f8cbc4f3af45befc792679f2b113f1cb",
"9031006a437019c5dcd987a31731ebd9",
"a6b62759ee3883258fbdeeb8b56e6283",
"4933898605b4a1b970b674a2dde92292",
"f0684ca20de4607232f3e158e81a37f2",
"c0b3fdecb3bb7b4ff0c936f378ccb027",
"50652123b5e0e51bb5bc3fdde3c6a750",
"ed4526ba8226d969f47edbb27b2f1144",
"80e6f61dff9da8673fa16dbbdb14d03d",
"1d52744bf1450d7c5cfdf1f0bbf967c1",
"3438a953124960bcc44611923a8844ee",
"b2f341296dd7aabbd4fd8e011be68a7d",
"322dba69658a92e9a9ace4d7177fb97d",
"b94a434a98efa493fbbc989360671bb9",
"cd9ce9a01ed810af70999d8ce4c63811",
"4c639abb75a0ae0f22c3384cb9c68441",
"fe31ffcced1717988c854c2f3492466e",
"b56d81337f9bbf0d838df831e9b40216",
"0be9161adfeb2dd1c3f20338bfb3ec4b",
"be7b7c9fa1ab09d6578a3f2a82bfafe3",
"f6bdc04b4611ddf0aa8403bcb04292f7",
"1c7146a10f3c76b0c1dd4af354b14982",
"0d3d987f94aee65f84436696bcf33ea4",
"1a5c9ac3ee859361ad5477ea792506a3",
"e827d60f27e35d8e5b05af748ba897dd",
"5b7899bf7a6267d9b3b8c82f241a1d7b",
"6dc9fe740cf4a4b93cb0953a3c2a6026",
"27adf814806fd4a51c1ffc84122c5c8a",
"f74e94ab992c8f27de264993a09ab429",
"5eee0f1591d10c159763749ec86b9ecb",
"46898964a3889615d9f7c22a81e0a0e7",
"8fb58d6770971b0f12e40b31ad65b4a9",
"eb4ce130268dc13731dcd16ff492d0a9",
"23532a54e8005860ad5e77f4e3392827",
"07fedc4dc4891d1a90c501a781a666f2",
"83e8341035b37dd70a92a6eed5406927",
"6c9f7b3b25734d58f21f5050642874a5",
"ef661042e6624f4052ce86d8f233d780",
"efe794cdfad5cb86656e29854a1f5c92",
"e5f19a0045481443bae165f03598a9ba",
"b8fe8691321edbf308a9d60bb817c6af",
"f31fdd0f1aef106005e6d29b72229fa1",
"239ed45c3cb734db446adfbbe3dab8a1",
"2c2303411c7d25617a54106aca18070d",
"de179c41aca8bcdc388964024948ff8e",
"ca335b74d59bd50832267d3bf28f81df",
"dabda7a1cbaa8ea5104c57c8950b703a",
"076352a22ecea5ebc876812f62c1cb8d",
"ee0a2bdec712a9413623d8a920714b96",
"a927c3a99f2843de4133377c690db9b7",
"1fa98cff485549d49799dc8cf987a8af",
"74013a076a786a26c7e04217bb51031d",
"a44ca9661e967bb2e98af65277dac72f",
"d30897726b635548dbfa5cebffd9cd63",
"4ad04a250b8029c9a7bf6529ee8793c3",
"de41e337d96fd23619121ea709861e1a",
"18e070fd32cf732b9f37a0083320eec2",
"7dd4b27ca8906182f684d0ee4ddb98c4",
"70a440a8bd06ff40f6e9135946eb174d",
"b8d052366e752ce7c803abd24854e934",
"8ab9dfff746ce3e62c6e04feb7b48528",
"ecfca8b371616efe78e9916dbf825f5b",
"5f76da828c37fc4edb4557953539c92a",
"ecad54f76ce3bc233e02fc6fd7f94628",
"e8a1cc06bfec7f677f36a693e1342400",
"9ad0fe040e44a8e7146c3dd8582b6752",
"4e56f978f94cf72158fd4311831b4f9f",
"3b95686fe49f50006607d5978aaa3efc",
"fa354daecc45f14b82b0e7e567d24282",
};
SUITE(md5)
{
TEST(MD5_RFC_1321) {
//MD5 with test vectors from RFC 1321
{
auto md5_hash = MD5("");
auto md5_out = md5_hash.hexdigest();
VERIFY_ARE_EQUAL(md5_out, "d41d8cd98f00b204e9800998ecf8427e");
}
{
auto md5_hash = MD5("abc");
auto md5_out = md5_hash.hexdigest();
VERIFY_ARE_EQUAL((md5_out), "900150983cd24fb0d6963f7d28e17f72");
}
{
auto md5_hash = MD5("message digest");
auto md5_out = md5_hash.hexdigest();
VERIFY_ARE_EQUAL((md5_out), "f96b697d7cb7938d525a2f31aaf161d0");
}
{
auto md5_hash = MD5("abcdefghijklmnopqrstuvwxyz");
auto md5_out = md5_hash.hexdigest();
VERIFY_ARE_EQUAL((md5_out), "c3fcd3d76192e4007dfb496cca67e13b");
}
{
auto md5_hash = MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
auto md5_out = md5_hash.hexdigest();
VERIFY_ARE_EQUAL((md5_out), "d174ab98d277d9f5a5611c2c9f419d9f");
}
{
auto md5_hash = MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890");
auto md5_out = md5_hash.hexdigest();
VERIFY_ARE_EQUAL((md5_out), "57edf4a22be3c955ac49da2e2107b67a");
}
VERIFY_ARE_EQUAL(MD5_BYTES.size(), MD5_HASHES.size());
for ( unsigned int i = 0; i < MD5_BYTES.size(); ++i ) {
auto md5 = MD5(unhexlify(MD5_BYTES[i]));
VERIFY_ARE_EQUAL(md5.hexdigest(), MD5_HASHES[i]);
}
}
}
}
}
| 80.583569 | 271 | 0.798636 | [
"vector"
] |
e9456794d27a0e91e521b41266cabc5f864e0b05 | 8,825 | cpp | C++ | src/test/demultiplexer_node_test.cpp | BrightTux/model_server | cdbeb464c78b161e5706490fc18b0a8cf16138fb | [
"Apache-2.0"
] | 234 | 2020-04-24T22:09:49.000Z | 2022-03-30T10:40:04.000Z | src/test/demultiplexer_node_test.cpp | BrightTux/model_server | cdbeb464c78b161e5706490fc18b0a8cf16138fb | [
"Apache-2.0"
] | 199 | 2020-04-29T08:43:21.000Z | 2022-03-29T09:05:52.000Z | src/test/demultiplexer_node_test.cpp | BrightTux/model_server | cdbeb464c78b161e5706490fc18b0a8cf16138fb | [
"Apache-2.0"
] | 80 | 2020-04-29T14:54:41.000Z | 2022-03-30T14:50:29.000Z | //*****************************************************************************
// Copyright 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "../dl_node.hpp"
#include "../logging.hpp"
#include "../node.hpp"
#include "test_utils.hpp"
using namespace ovms;
using testing::ElementsAre;
static const std::string mockerDemutliplexerNodeOutputName = "mockedDemultiplexerOutputName";
static const std::string mockerDemutliplexerNodeOutputName2 = "mockedDemultiplexerOutputName2";
class DemultiplexerDLNode : public DLNode {
public:
DemultiplexerDLNode(const std::string& nodeName, const std::string& modelName, std::optional<model_version_t> modelVersion, ModelManager& modelManager, std::unordered_map<std::string, std::string> nodeOutputNameAlias, std::optional<uint32_t> demultiplyCount, const NodeSessionMetadata& meta) :
DLNode(nodeName, modelName, modelVersion, modelManager, nodeOutputNameAlias, demultiplyCount.value_or(0)) {
// createSession to have source session for fetchResults()
CollapseDetails collapsingDetails;
std::unique_ptr<NodeSession> nodeSession = createNodeSession(meta, collapsingDetails);
auto emplacePair = nodeSessions.emplace(meta.getSessionKey(), std::move(nodeSession));
EXPECT_TRUE(emplacePair.second);
}
void setFetchResult(InferenceEngine::Blob::Ptr& intermediateResultBlob) {
this->intermediateResultBlob = intermediateResultBlob;
}
using Node::fetchResults;
Status fetchResults(NodeSession& nodeSession, SessionResults& nodeSessionOutputs) {
const auto& sessionMetadata = nodeSession.getNodeSessionMetadata();
const auto sessionKey = sessionMetadata.getSessionKey();
InferenceEngine::Blob::Ptr secondOutput;
EXPECT_EQ(blobClone(secondOutput, intermediateResultBlob), StatusCode::OK);
BlobMap blobs{{mockerDemutliplexerNodeOutputName, intermediateResultBlob},
{mockerDemutliplexerNodeOutputName2, secondOutput}};
std::pair<NodeSessionMetadata, BlobMap> metaBlobsPair{sessionMetadata, std::move(blobs)};
nodeSessionOutputs.emplace(sessionKey, std::move(metaBlobsPair));
return StatusCode::OK;
}
private:
InferenceEngine::Blob::Ptr intermediateResultBlob;
};
using ::testing::AnyOf;
using ::testing::Eq;
TEST(DemultiplexerTest, CheckDemultipliedBlobsMultipleOutputs) {
const uint16_t demultiplyCount = 2;
// prepare pre demultiplexer blob
std::vector<std::vector<float>> blobsData{
{-1, 4, 5, 12, 3, 52, 12, 0.5, 9, 1.67, 0, 8},
{4, 42, 35, -2, 13, 2, -1, 0.9, -0.3, 4.67, 100, 80}};
const std::vector<size_t> shape{demultiplyCount, 1, blobsData[0].size()};
const InferenceEngine::Precision precision{InferenceEngine::Precision::FP32};
const InferenceEngine::Layout layout{InferenceEngine::Layout::CHW};
const InferenceEngine::TensorDesc desc{precision, shape, layout};
std::vector<float> blobDataNonDemultiplexed(blobsData[0].size() * demultiplyCount);
std::copy(blobsData[0].begin(), blobsData[0].end(), blobDataNonDemultiplexed.begin());
std::copy(blobsData[1].begin(), blobsData[1].end(), blobDataNonDemultiplexed.begin() + blobsData[0].size());
InferenceEngine::Blob::Ptr intermediateResultBlob = InferenceEngine::make_shared_blob<float>(desc, blobDataNonDemultiplexed.data());
// construct demultiplexer node
NodeSessionMetadata meta;
ConstructorEnabledModelManager manager;
std::string demultiplexerNodeName("node");
DemultiplexerDLNode demultiplexerNode(demultiplexerNodeName, "model", 1, manager, std::unordered_map<std::string, std::string>{{"NOT_USED", "NOT_USED"}}, demultiplyCount, meta);
demultiplexerNode.setFetchResult(intermediateResultBlob);
SessionResults sessionResults;
session_key_t sessionKey = meta.getSessionKey();
// perform test
auto status = demultiplexerNode.fetchResults(sessionKey, sessionResults);
ASSERT_EQ(status, StatusCode::OK);
ASSERT_EQ(sessionResults.size(), demultiplyCount);
auto demultiplexedMetadata = meta.generateSubsessions(demultiplexerNodeName, demultiplyCount);
ASSERT_EQ(demultiplexedMetadata.size(), demultiplyCount);
for (size_t shardId = 0; shardId < demultiplyCount; ++shardId) {
auto& sessionResult = sessionResults[demultiplexedMetadata[shardId].getSessionKey()];
ASSERT_EQ(sessionResult.first.getSessionKey(), demultiplexedMetadata[shardId].getSessionKey());
for (auto& [blobName, blob] : sessionResult.second) {
EXPECT_THAT(blobName, AnyOf(Eq(mockerDemutliplexerNodeOutputName),
Eq(mockerDemutliplexerNodeOutputName2)));
ASSERT_EQ(blobsData[shardId].size(), blob->size());
ASSERT_THAT(blob->getTensorDesc().getDims(), ElementsAre(1, blobsData[shardId].size()));
EXPECT_EQ(std::memcmp((char*)((const void*)InferenceEngine::as<InferenceEngine::MemoryBlob>(blob)->rmap()), blobsData[shardId].data(), blob->byteSize()), 0) << "Failed comparison for shard: " << shardId << " blobName: " << blobName;
EXPECT_THAT(std::vector<float>((const float*)(const void*)(InferenceEngine::as<InferenceEngine::MemoryBlob>(blob)->rmap()), (const float*)(const void*)InferenceEngine::as<InferenceEngine::MemoryBlob>(blob)->rmap() + blob->size()),
::testing::ElementsAreArray(blobsData[shardId]));
}
}
}
TEST(DemultiplexerTest, DemultiplyShouldReturnErrorWhenWrongOutputDimensions) {
const uint16_t demultiplyCount = 3;
std::vector<float> blobData{-1, 4, 5, 12, 3, 52};
// imitate (1, 2, 3) but shoudl be (1,3,x1, ..., xN)
const std::vector<size_t> shape{1, demultiplyCount - 1, 3};
const InferenceEngine::Precision precision{InferenceEngine::Precision::FP32};
const InferenceEngine::Layout layout{InferenceEngine::Layout::CHW};
const InferenceEngine::TensorDesc desc{precision, shape, layout};
InferenceEngine::Blob::Ptr intermediateResultBlob = InferenceEngine::make_shared_blob<float>(desc, blobData.data());
// construct demultiplexer node
NodeSessionMetadata meta;
ConstructorEnabledModelManager manager;
std::string demultiplexerNodeName("node");
DemultiplexerDLNode demultiplexerNode(demultiplexerNodeName, "model", 1, manager, std::unordered_map<std::string, std::string>{{"NOT_USED", "NOT_USED"}}, demultiplyCount, meta); // demultiplexer expects (1, 3, x1, ..., xN);
demultiplexerNode.setFetchResult(intermediateResultBlob);
SessionResults sessionResults;
session_key_t sessionKey = meta.getSessionKey();
// perform test
auto status = demultiplexerNode.fetchResults(sessionKey, sessionResults);
ASSERT_EQ(status, StatusCode::PIPELINE_WRONG_DIMENSION_SIZE_TO_DEMULTIPLY);
}
TEST(DemultiplexerTest, DemultiplyShouldReturnErrorWhenNotEnoughDimensionsInOutput) {
std::vector<float> blobData{-1, 4, 5, 12, 3, 52};
const uint16_t demultiplyCount = blobData.size();
// imitate (1, 3) but should be at least (1,3,x1, ..., xN) N >= 1
const std::vector<size_t> shape{1, demultiplyCount};
const InferenceEngine::Precision precision{InferenceEngine::Precision::FP32};
const InferenceEngine::Layout layout{InferenceEngine::Layout::NC};
const InferenceEngine::TensorDesc desc{precision, shape, layout};
InferenceEngine::Blob::Ptr intermediateResultBlob = InferenceEngine::make_shared_blob<float>(desc, blobData.data());
// construct demultiplexer node
NodeSessionMetadata meta;
ConstructorEnabledModelManager manager;
std::string demultiplexerNodeName("node");
DemultiplexerDLNode demultiplexerNode(demultiplexerNodeName, "model", 1, manager, std::unordered_map<std::string, std::string>{{"NOT_USED", "NOT_USED"}}, demultiplyCount, meta); // demultiplexer expects (1, 3, x1, ..., xN);
demultiplexerNode.setFetchResult(intermediateResultBlob);
SessionResults sessionResults;
session_key_t sessionKey = meta.getSessionKey();
// perform test
auto status = demultiplexerNode.fetchResults(sessionKey, sessionResults);
ASSERT_EQ(status, StatusCode::PIPELINE_WRONG_NUMBER_OF_DIMENSIONS_TO_DEMULTIPLY);
}
| 58.833333 | 297 | 0.724873 | [
"shape",
"vector",
"model"
] |
e94e54c9ce542ac8a1facfa2e1ce0ef11f7b52af | 1,503 | cpp | C++ | SPOJ/SPOJ/ACPC10D.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | SPOJ/SPOJ/ACPC10D.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | SPOJ/SPOJ/ACPC10D.cpp | aqfaridi/Competitve-Programming-Codes | d055de2f42d3d6bc36e03e67804a1dd6b212241f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
#include <vector>
#include <utility>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#define MAX 1000010
#define MOD 1000000007
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
int main()
{
int n,cases=0;
while(1)
{
scanf("%d",&n);
cases++;
if(n==0)
break;
int arr[n][5];
for(int i=0;i<n;i++)
{
for(int j=1;j<=3;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(int i=0;i<n;i++)
{
arr[i][0] = INT_MAX;
arr[i][4] = INT_MAX;
}
arr[0][3] += arr[0][2];//0th row
//cout<<arr[0][1]<<" "<<arr[0][2]<<" "<<arr[0][3]<<endl;
//1st row
arr[1][1] += arr[0][2];
arr[1][2] += min(arr[0][2],min(arr[1][1],arr[0][3]));
arr[1][3] += min(arr[0][2],min(arr[0][3],arr[1][2]));
//cout<<arr[1][1]<<" "<<arr[1][2]<<" "<<arr[1][3]<<endl;
for(int i=2;i<n;i++)
{
for(int j=1;j<=3;j++)
{
arr[i][j] += min(arr[i-1][j-1],min(arr[i-1][j+1],min(arr[i-1][j],arr[i][j-1])));
//cout<<arr[i][j]<<" ";
}
//cout<<endl;
}
printf("%d. %d\n",cases,arr[n-1][2]);
}
return 0;
}
| 22.772727 | 96 | 0.413839 | [
"vector"
] |
e955be3ed4bbec6f70409fac445df2a2cd831d22 | 277 | cpp | C++ | Cat.cpp | congard/dynlib-test | 3108536e095dc21cb7d36f2a9d43d0d7d7a711b2 | [
"MIT"
] | null | null | null | Cat.cpp | congard/dynlib-test | 3108536e095dc21cb7d36f2a9d43d0d7d7a711b2 | [
"MIT"
] | null | null | null | Cat.cpp | congard/dynlib-test | 3108536e095dc21cb7d36f2a9d43d0d7d7a711b2 | [
"MIT"
] | null | null | null | #include "Cat.h"
#include <iostream>
extern "C" Cat* create_object() {
return new Cat;
}
extern "C" void destroy_object(Cat* object ) {
delete object;
}
Cat::Cat() {
m_voice = "Meow!";
}
void Cat::voice() {
std::cout << "I'm Cat! ";
Animal::voice();
}
| 13.190476 | 46 | 0.574007 | [
"object"
] |
e95c147dd801dafee676fb12ff843442210b85bb | 2,641 | cpp | C++ | aws-cpp-sdk-ssm-incidents/source/SSMIncidentsErrors.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-ssm-incidents/source/SSMIncidentsErrors.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ssm-incidents/source/SSMIncidentsErrors.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/ssm-incidents/SSMIncidentsErrors.h>
#include <aws/ssm-incidents/model/ConflictException.h>
#include <aws/ssm-incidents/model/ServiceQuotaExceededException.h>
#include <aws/ssm-incidents/model/ThrottlingException.h>
#include <aws/ssm-incidents/model/ResourceNotFoundException.h>
using namespace Aws::Client;
using namespace Aws::Utils;
using namespace Aws::SSMIncidents;
using namespace Aws::SSMIncidents::Model;
namespace Aws
{
namespace SSMIncidents
{
template<> AWS_SSMINCIDENTS_API ConflictException SSMIncidentsError::GetModeledError()
{
assert(this->GetErrorType() == SSMIncidentsErrors::CONFLICT);
return ConflictException(this->GetJsonPayload().View());
}
template<> AWS_SSMINCIDENTS_API ServiceQuotaExceededException SSMIncidentsError::GetModeledError()
{
assert(this->GetErrorType() == SSMIncidentsErrors::SERVICE_QUOTA_EXCEEDED);
return ServiceQuotaExceededException(this->GetJsonPayload().View());
}
template<> AWS_SSMINCIDENTS_API ThrottlingException SSMIncidentsError::GetModeledError()
{
assert(this->GetErrorType() == SSMIncidentsErrors::THROTTLING);
return ThrottlingException(this->GetJsonPayload().View());
}
template<> AWS_SSMINCIDENTS_API ResourceNotFoundException SSMIncidentsError::GetModeledError()
{
assert(this->GetErrorType() == SSMIncidentsErrors::RESOURCE_NOT_FOUND);
return ResourceNotFoundException(this->GetJsonPayload().View());
}
namespace SSMIncidentsErrorMapper
{
static const int CONFLICT_HASH = HashingUtils::HashString("ConflictException");
static const int SERVICE_QUOTA_EXCEEDED_HASH = HashingUtils::HashString("ServiceQuotaExceededException");
static const int INTERNAL_SERVER_HASH = HashingUtils::HashString("InternalServerException");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == CONFLICT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SSMIncidentsErrors::CONFLICT), false);
}
else if (hashCode == SERVICE_QUOTA_EXCEEDED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SSMIncidentsErrors::SERVICE_QUOTA_EXCEEDED), false);
}
else if (hashCode == INTERNAL_SERVER_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SSMIncidentsErrors::INTERNAL_SERVER), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace SSMIncidentsErrorMapper
} // namespace SSMIncidents
} // namespace Aws
| 34.298701 | 108 | 0.794017 | [
"model"
] |
e95d6f05b5ad1d181b52ce1ea6b2674306a09c1a | 135 | hpp | C++ | src/libs/base/si_baselogging.hpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | src/libs/base/si_baselogging.hpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | src/libs/base/si_baselogging.hpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | #ifndef __si_baselogging_hpp
#define __si_baselogging_hpp
#define BASE_OBJ_LOG "BAS.Object"
#define BASE_THR_LOG "BAS.Thread"
#endif
| 16.875 | 33 | 0.822222 | [
"object"
] |
e9677e348273495bc553310209d25fea82e82d37 | 8,111 | cpp | C++ | src/ascent/runtimes/flow_filters/ascent_runtime_babelflow_compose.cpp | subhashis-lanl/ascent | 057b95d62d2ad36b9b19f2deb856c09961cb50a0 | [
"BSD-3-Clause"
] | null | null | null | src/ascent/runtimes/flow_filters/ascent_runtime_babelflow_compose.cpp | subhashis-lanl/ascent | 057b95d62d2ad36b9b19f2deb856c09961cb50a0 | [
"BSD-3-Clause"
] | null | null | null | src/ascent/runtimes/flow_filters/ascent_runtime_babelflow_compose.cpp | subhashis-lanl/ascent | 057b95d62d2ad36b9b19f2deb856c09961cb50a0 | [
"BSD-3-Clause"
] | null | null | null | //
// Created by Sergei Shudler on 2020-06-09.
//
#include <vector>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <conduit.hpp>
#include <conduit_relay.hpp>
#include <conduit_blueprint.hpp>
#include <ascent_data_object.hpp>
#include <ascent_logging.hpp>
#include <ascent_runtime_param_check.hpp>
#include <flow_workspace.hpp>
#ifdef ASCENT_MPI_ENABLED
#include <mpi.h>
#else
#include <mpidummy.h>
#define _NOMPI
#endif
#include "BabelFlow/TypeDefinitions.h"
#include "ascent_runtime_babelflow_filters.hpp"
#include "ascent_runtime_babelflow_comp_utils.hpp"
//#define BFLOW_COMP_DEBUG
//-----------------------------------------------------------------------------
///
/// BFlowCompose Filter
///
//-----------------------------------------------------------------------------
void ascent::runtime::filters::BFlowCompose::declare_interface(conduit::Node &i)
{
i["type_name"] = "bflow_comp";
i["port_names"].append() = "in";
i["output_port"] = "false"; // true -- means filter, false -- means extract
}
//-----------------------------------------------------------------------------
bool ascent::runtime::filters::BFlowCompose::verify_params(const conduit::Node ¶ms, conduit::Node &info)
{
info.reset();
bool res = true;
res &= check_string("color_field", params, info, true);
res &= check_string("depth_field", params, info, true);
res &= check_string("image_name", params, info, true);
res &= check_numeric("compositing", params, info, true);
res &= check_numeric("fanin", params, info, false);
return res;
}
//-----------------------------------------------------------------------------
void ascent::runtime::filters::BFlowCompose::execute()
{
if(!input(0).check_type<DataObject>())
{
ASCENT_ERROR("BFlowVolume filter requires a DataObject");
}
// Connect to the input port and get the parameters
DataObject *d_input = input<DataObject>(0);
conduit::Node& data_node = d_input->as_node()->children().next();
conduit::Node& p = params();
// Check if coordset valid, meaning: uniform and with spacing of 1
if( !data_node.has_path("coordsets/coords/type") ||
data_node["coordsets/coords/type"].as_string() != "uniform" )
{
ASCENT_ERROR("BabelFlow comp extract could not find coordsets/coords/type or type is not 'uniform'");
}
if( data_node.has_path("coordsets/coords/spacing/dx") &&
data_node["coordsets/coords/spacing/dx"].as_int32() != 1 )
{
ASCENT_ERROR("BabelFlow comp extract requires spacing of 1 along the X-axis");
}
if( data_node.has_path("coordsets/coords/spacing/dy") &&
data_node["coordsets/coords/spacing/dy"].as_int32() != 1 )
{
ASCENT_ERROR("BabelFlow comp extract requires spacing of 1 along the Y-axis");
}
if( data_node["coordsets/coords/origin/x"].as_int32() != 0 ||
data_node["coordsets/coords/origin/y"].as_int32() != 0 )
{
ASCENT_ERROR("BabelFlow comp extract requires origin (0,0)");
}
// Width and height reduced by 1 because of 'element' association
int32_t img_width = data_node["coordsets/coords/dims/i"].as_int32() - 1;
int32_t img_height = data_node["coordsets/coords/dims/j"].as_int32() - 1;
conduit::Node& fields_root_node = data_node["fields"];
conduit::Node& color_node = fields_root_node[p["color_field"].as_string()];
conduit::Node& depth_node = fields_root_node[p["depth_field"].as_string()];
if( color_node["association"].as_string() != "element" ||
depth_node["association"].as_string() != "element" )
{
ASCENT_ERROR("BabelFlow comp extract requires element association in pixel and zbuf fields");
}
// Convert pixel and zbuf data to unsigned char arrays
conduit::Node converted_pixels;
color_node["values"].to_unsigned_char_array(converted_pixels);
conduit::DataArray<unsigned char> pixels_arr = converted_pixels.as_unsigned_char_array();
conduit::Node converted_zbuf;
depth_node["values"].to_unsigned_char_array(converted_zbuf);
conduit::DataArray<unsigned char> zbuff_arr = converted_zbuf.as_unsigned_char_array();
if( pixels_arr.number_of_elements() != img_width*img_height*bflow_comp::ImageData::sNUM_CHANNELS ||
zbuff_arr.number_of_elements() != img_width*img_height )
{
std::cerr << "BFlowCompose: pixels_arr num elems = " << pixels_arr.number_of_elements() << std::endl;
std::cerr << "BFlowCompose: zbuff_arr num elems = " << zbuff_arr.number_of_elements() << std::endl;
ASCENT_ERROR("BabelFlow comp extract pixel array or zbuf array element count problem");
}
bflow_comp::ImageData input_img;
input_img.image = new unsigned char[img_width*img_height*bflow_comp::ImageData::sNUM_CHANNELS];
input_img.zbuf = new unsigned char[img_width*img_height];
memcpy(input_img.image, pixels_arr.data_ptr(), pixels_arr.number_of_elements());
memcpy(input_img.zbuf, zbuff_arr.data_ptr(), zbuff_arr.number_of_elements());
input_img.bounds = new uint32_t[4];
input_img.rend_bounds = new uint32_t[4];
input_img.bounds[0] = input_img.rend_bounds[0] = 0;
input_img.bounds[1] = input_img.rend_bounds[1] = img_width - 1;
input_img.bounds[2] = input_img.rend_bounds[2] = 0;
input_img.bounds[3] = input_img.rend_bounds[3] = img_height - 1;
MPI_Comm mpi_comm;
int my_rank = 0, n_ranks = 1;
#ifdef ASCENT_MPI_ENABLED
mpi_comm = MPI_Comm_f2c(flow::Workspace::default_mpi_comm());
MPI_Comm_rank(mpi_comm, &my_rank);
MPI_Comm_size(mpi_comm, &n_ranks);
#endif
int64_t fanin = p["fanin"].as_int64();
CompositingType compositing_flag = CompositingType(p["compositing"].as_int64());
std::string image_name = p["image_name"].as_string();
#ifdef BFLOW_COMP_DEBUG
{
std::stringstream img_name;
img_name << "img_data_" << my_rank << "_"
<< input_img.rend_bounds[0] << "_"
<< input_img.rend_bounds[1] << "_"
<< input_img.rend_bounds[2] << "_"
<< input_img.rend_bounds[3] << ".png";
input_img.writeImage(img_name.str().c_str(), input_img.rend_bounds);
}
#endif
switch (compositing_flag)
{
case CompositingType::REDUCE:
{
int32_t n_blocks[3] = {1, 1, 1};
bflow_comp::BabelCompReduce red_graph(input_img,
image_name,
my_rank,
n_ranks,
fanin,
mpi_comm,
n_blocks);
red_graph.Initialize();
red_graph.Execute();
}
break;
case CompositingType::BINSWAP:
{
bflow_comp::BabelCompBinswap binswap_graph(input_img,
image_name,
my_rank,
n_ranks,
fanin,
mpi_comm);
binswap_graph.Initialize();
binswap_graph.Execute();
}
break;
case CompositingType::RADIX_K:
{
std::vector<uint32_t> radix_v(1);
radix_v[0] = n_ranks;
if(p.has_path("radices"))
{
conduit::DataArray<int64_t> radices_arr = p["radices"].as_int64_array();
radix_v.resize(radices_arr.number_of_elements());
for (uint32_t i = 0; i < radix_v.size(); ++i) radix_v[i] = (uint32_t)radices_arr[i];
}
bflow_comp::BabelCompRadixK radixk_graph(input_img,
image_name,
my_rank,
n_ranks,
fanin,
mpi_comm,
radix_v);
radixk_graph.Initialize();
radixk_graph.Execute();
}
break;
}
input_img.delBuffers();
}
| 35.574561 | 109 | 0.594994 | [
"vector"
] |
e96fb3ccae19c11ab42a88650742d9f77d35878f | 6,426 | cpp | C++ | src/SolAROpenCVHelper.cpp | geekyfox90/SolARModuleOpenCV | 4d8d95c904be32e5935b06402de4a9c6e9b271b0 | [
"Apache-2.0"
] | null | null | null | src/SolAROpenCVHelper.cpp | geekyfox90/SolARModuleOpenCV | 4d8d95c904be32e5935b06402de4a9c6e9b271b0 | [
"Apache-2.0"
] | null | null | null | src/SolAROpenCVHelper.cpp | geekyfox90/SolARModuleOpenCV | 4d8d95c904be32e5935b06402de4a9c6e9b271b0 | [
"Apache-2.0"
] | null | null | null | /**
* @copyright Copyright (c) 2017 B-com http://www.b-com.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 "SolAROpenCVHelper.h"
#include <map>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "datastructure/DescriptorBuffer.h"
using namespace org::bcom::xpcf;
namespace SolAR {
using namespace datastructure;
namespace MODULES {
namespace OPENCV {
static std::map<DescriptorBuffer::DataType,uint32_t> solarDescriptor2cvType =
{{ DescriptorBuffer::DataType::TYPE_8U,CV_8U},{DescriptorBuffer::DataType::TYPE_32F,CV_32F}};
static std::map<std::tuple<uint32_t,std::size_t,uint32_t>,int> solar2cvTypeConvertMap = {{std::make_tuple(8,1,3),CV_8UC3},{std::make_tuple(8,1,1),CV_8UC1}};
static std::map<int,std::pair<Image::ImageLayout,Image::DataType>> cv2solarTypeConvertMap = {{CV_8UC3,{Image::ImageLayout::LAYOUT_BGR,Image::DataType::TYPE_8U}},
{CV_8UC1,{Image::ImageLayout::LAYOUT_GREY,Image::DataType::TYPE_8U}}};
uint32_t SolAROpenCVHelper::deduceOpenDescriptorCVType(DescriptorBuffer::DataType querytype){
return solarDescriptor2cvType.at(querytype);
}
int SolAROpenCVHelper::deduceOpenCVType(SRef<Image> img)
{
// TODO : handle safe mode if missing map entry
// is it ok when destLayout != img->ImageLayout ?
return solar2cvTypeConvertMap.at(std::forward_as_tuple(img->getNbBitsPerComponent(),1,img->getNbChannels()));
}
void SolAROpenCVHelper::mapToOpenCV (SRef<Image> imgSrc, cv::Mat& imgDest)
{
cv::Mat imgCV(imgSrc->getHeight(),imgSrc->getWidth(),deduceOpenCVType(imgSrc), imgSrc->data());
imgDest = imgCV;
}
cv::Mat SolAROpenCVHelper::mapToOpenCV (SRef<Image> imgSrc)
{
cv::Mat imgCV(imgSrc->getHeight(),imgSrc->getWidth(),deduceOpenCVType(imgSrc), imgSrc->data());
return imgCV;
}
FrameworkReturnCode SolAROpenCVHelper::convertToSolar (cv::Mat& imgSrc, SRef<Image>& imgDest)
{
if (cv2solarTypeConvertMap.find(imgSrc.type()) == cv2solarTypeConvertMap.end() || imgSrc.empty()) {
return FrameworkReturnCode::_ERROR_LOAD_IMAGE;
}
std::pair<Image::ImageLayout,Image::DataType> type = cv2solarTypeConvertMap.at(imgSrc.type());
imgDest = utils::make_shared<Image>(imgSrc.ptr(), imgSrc.cols, imgSrc.rows, type.first, Image::PixelOrder::INTERLEAVED, type.second);
return FrameworkReturnCode::_SUCCESS;
}
std::vector<cv::Point2i> SolAROpenCVHelper::convertToOpenCV (const Contour2Di &contour)
{
std::vector<cv::Point2i> output;
for (int i = 0; i < contour.size(); i++)
{
output.push_back(cv::Point2i(contour[i]->getX(), contour[i]->getY()));
}
return output;
}
std::vector<cv::Point2f> SolAROpenCVHelper::convertToOpenCV (const Contour2Df &contour)
{
std::vector<cv::Point2f> output;
for (int i = 0; i < contour.size(); i++)
{
output.push_back(cv::Point2f(contour[i]->getX(), contour[i]->getY()));
}
return output;
}
// Compute the intersection between a edge and a rectangle
bool Liang_Barsky (cv::Point2f& p1, cv::Point2f& p2, Rectanglei& rect, cv::Point2f& p1_out, cv::Point2f& p2_out)
{
int p[4];
int q[4];
int x1 = p1.x;
int y1 = p1.y;
int x2 = p2.x;
int y2 = p2.y;
int xmin = rect.startX;
int xmax = xmin + rect.size.width;
int ymin = rect.startY;
int ymax = ymin + rect.size.height;
int dx = x2 - x1;
int dy = y2 - y1;
p[0] = -dx;
p[1] = dx;
p[2] = -dy;
p[3] = dy;
q[0] = x1 - xmin;
q[1] = xmax - x1;
q[2] = y1 - ymin;
q[3] = ymax - y1;
for (int i = 0 ; i < 4; i++)
{
if (p[i] == 0)
{
// line is parallel to one of the clipping boundary.
if (i < 2)
{
// Line is horizontal
if (y1 < ymin)
{
y1 = ymin;
}
if(y2>ymax)
{
y2=ymax;
}
p1_out.x = x1;
p1_out.y = y1;
p2_out.x = x2;
p2_out.y = y2;
return true;
}
if (i>1)
{
// Line is vertical
if(x1<xmin)
{
x1=xmin;
}
if(x2>xmax)
{
x2=xmax;
}
p1_out.x = x1;
p1_out.y = y1;
p2_out.x = x2;
p2_out.y = y2;
return true;
}
}
}
float t1 = 0.0f;
float t2 = 1.0f;
float temp;
for(int i=0;i<4;i++)
{
temp=(float)q[i]/(float)p[i];
if(p[i]<0)
{
if(t1<=temp)
t1=temp;
}
else
{
if(t2>temp)
t2=temp;
}
}
if (t1 < t2)
{
p1_out.x = x1 + t1 * p[1];
p2_out.x = x1 + t2 * p[1];
p1_out.y = y1 + t1 * p[3];
p2_out.y = y1 + t2 * p[3];
return true;
}
return false;
}
void SolAROpenCVHelper::drawCVLine (cv::Mat& inputImage, cv::Point2f& p1, cv::Point2f& p2, cv::Scalar color, int thickness)
{
Rectanglei rect = {0, 0, Sizei{(uint32_t)inputImage.cols, (uint32_t)inputImage.rows}};
float x1, x2, y1, y2;
x1 = p1.x;
y1 = p1.y;
x2 = p2.x;
y2 = p2.y;
if (x1>=0 && x1 < inputImage.cols && y1>=0 && y1 < inputImage.rows &&
x2>=0 && x2 < inputImage.cols && y2>=0 && y2 < inputImage.rows)
cv::line(inputImage, p1, p2, color, thickness, CV_AA);
else
{
cv::Point2f p1_result;
cv::Point2f p2_result;
if (Liang_Barsky(p1, p2, rect, p1_result, p2_result))
cv::line(inputImage, p1_result, p2_result, color, thickness, CV_AA);
}
}
}
}
}
| 28.184211 | 172 | 0.570495 | [
"vector"
] |
e9739c744c0eabfec08a5ec2d8eb1d386a042614 | 29,897 | tpp | C++ | core/src/spatial_discretization/finite_element_method/01_stiffness_matrix_stencils.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 17 | 2018-11-25T19:29:34.000Z | 2021-09-20T04:46:22.000Z | core/src/spatial_discretization/finite_element_method/01_stiffness_matrix_stencils.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 1 | 2020-11-12T15:15:58.000Z | 2020-12-29T15:29:24.000Z | core/src/spatial_discretization/finite_element_method/01_stiffness_matrix_stencils.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 4 | 2018-10-17T12:18:10.000Z | 2021-05-28T13:24:20.000Z | #include "spatial_discretization/finite_element_method/01_matrix.h"
#include <Python.h>
#include <memory>
#include <petscksp.h>
#include <petscsys.h>
#include "mesh/structured_regular_fixed.h"
#include "basis_function/lagrange.h"
#include <memory>
#include <functional>
#include "spatial_discretization/spatial_discretization.h"
#include "interfaces/runnable.h"
#include "control/dihu_context.h"
#include "utility/petsc_utility.h"
#include "data_management/finite_element_method/finite_elements.h"
#include "equation/laplace.h"
#include "equation/poisson.h"
#include "equation/type_traits.h"
#include "mesh/mesh.h"
#include "control/types.h"
namespace SpatialDiscretization
{
// 1D stiffness matrix
template<typename QuadratureType,typename Term>
void FiniteElementMethodMatrix<FunctionSpace::FunctionSpace<Mesh::StructuredRegularFixedOfDimension<1>,BasisFunction::LagrangeOfOrder<1>>,QuadratureType,1,Term,Mesh::StructuredRegularFixedOfDimension<1>,Equation::hasLaplaceOperator<Term>,BasisFunction::LagrangeOfOrder<1>>::
setStiffnessMatrix()
{
LOG(TRACE) << "setStiffnessMatrix 1D for Mesh::RegularFixed using stencils";
typedef typename FunctionSpace::FunctionSpace<Mesh::StructuredRegularFixedOfDimension<1>, BasisFunction::LagrangeOfOrder<1>> FunctionSpaceType;
// get settings values
std::shared_ptr<FunctionSpaceType> functionSpace = std::static_pointer_cast<FunctionSpaceType>(this->data_.functionSpace());
element_no_t nElements = functionSpace->nElementsLocal();
node_no_t nNodes0 = functionSpace->nNodesLocalWithGhosts(0);
const double elementLength = functionSpace->meshWidth();
double integralFactor = 1./elementLength;
double prefactor;
this->prefactor_.getValue((element_no_t)0, prefactor); // prefactor value is constant over the domain
integralFactor = prefactor*integralFactor;
LOG(DEBUG) << " Use settings nElements=" <<nElements << ", elementLength=" << elementLength;
// fill stiffness matrix
// M_ij = -int[0,1] dphi_i/dxi * dphi_j/dxi * (dxi/ds)^2 ds = l
std::shared_ptr<PartitionedPetscMat<FunctionSpaceType>> stiffnessMatrix = this->data_.stiffnessMatrix();
// stencil values
// stencil for -Δu in 1D: [1 _-2_ 1] (element contribution: [_-1_ 1])
const int center = 1;
const double stencilCenter[3] = {1.0, -2.0, 1.0};
const double stencilSide[2] = {1.0, -1.0}; // left side of stencil
double value;
dof_no_t dofNo;
// loop over all dofs and set values with stencilCenter
// set entries for interior nodes
for (int x=1; x<nNodes0-1; x++)
{
dofNo = x;
for (int i=-1; i<=1; i++) // x
{
value = stencilCenter[center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, x+i, value, INSERT_VALUES);
}
}
// call MatAssemblyBegin, MatAssemblyEnd
stiffnessMatrix->assembly(MAT_FLUSH_ASSEMBLY);
// set entries for boundary nodes on edges
// left boundary (x=0)
int x = 0;
dofNo = x;
for (int i=-1; i<=0; i++) // -x
{
value = stencilSide[center+i]*integralFactor;
stiffnessMatrix->setValue(dofNo, x-i, value, ADD_VALUES);
}
// right boundary (x=nNodes0-1)
x = nNodes0-1;
dofNo = x;
for (int i=-1; i<=0; i++) // x
{
value = stencilSide[center+i]*integralFactor;
stiffnessMatrix->setValue(dofNo, x+i, value, ADD_VALUES);
}
// call MatAssemblyBegin, MatAssemblyEnd
stiffnessMatrix->assembly(MAT_FINAL_ASSEMBLY);
}
// 2D stiffness matrix
template<typename QuadratureType,typename Term>
void FiniteElementMethodMatrix<FunctionSpace::FunctionSpace<Mesh::StructuredRegularFixedOfDimension<2>,BasisFunction::LagrangeOfOrder<1>>,QuadratureType,1,Term,Mesh::StructuredRegularFixedOfDimension<2>,Equation::hasLaplaceOperator<Term>,BasisFunction::LagrangeOfOrder<1>>::
setStiffnessMatrix()
{
LOG(TRACE) << "setStiffnessMatrix 2D for Mesh::RegularFixed using stencils";
typedef FunctionSpace::FunctionSpace<Mesh::StructuredRegularFixedOfDimension<2>, BasisFunction::LagrangeOfOrder<1>> FunctionSpaceType;
// get settings value
std::shared_ptr<FunctionSpaceType> functionSpace = std::static_pointer_cast<FunctionSpaceType>(this->data_.functionSpace());
element_no_t nElements0 = functionSpace->nElementsPerCoordinateDirectionLocal(0);
element_no_t nElements1 = functionSpace->nElementsPerCoordinateDirectionLocal(1);
node_no_t nNodes0 = functionSpace->nNodesLocalWithGhosts(0);
node_no_t nNodes1 = functionSpace->nNodesLocalWithGhosts(1);
double elementLength0 = functionSpace->meshWidth();
double elementLength1 = functionSpace->meshWidth();
if (fabs(elementLength0-elementLength1) > 1e-15)
{
LOG(ERROR) << "Mesh resolution of 2D regular fixed mesh is not uniform! " << std::endl
<< "Mesh widths: x: " << elementLength0 << ", y: " << elementLength1 << std::endl
<< "This means that the stiffness matrix will be wrong. Mesh::RegularFixed meshes use stencil notation "
<< "and can only handle uniform meshes correctly. To use non-uniform meshes, consider using Mesh::Deformable!";
}
double integralFactor = 1.;
double prefactor;
this->prefactor_.getValue(0, prefactor); // prefactor value is constant over the domain
integralFactor = prefactor*integralFactor;
LOG(DEBUG) << "Use settings nElements=" <<nElements0<< "x" <<nElements1<< ", elementLength=" << elementLength0<< "x" << elementLength1;
LOG(DEBUG) << "integralFactor=" <<integralFactor;
// fill stiffness matrix
// M_ij = -int[0,1] dphi_i/dxi * dphi_j/dxi * (dxi/ds)^2 ds = l
// stencil for -Δu in 2D: [1 1 1] (element contribution: [ 1/6 1/3])
// 1/3*[1 _-8_ 1] [_-2/3_ 1/6]
// [1 1 1]
std::shared_ptr<PartitionedPetscMat<FunctionSpaceType>> stiffnessMatrix = this->data_.stiffnessMatrix();
const int center = 1;
const double stencilCenter[3][3] = {
{1./3, 1./3, 1./3},
{1./3, -8./3, 1./3},
{1./3, 1./3, 1./3}};
const double stencilEdge[2][3] = {
{1./3, 1./3, 1./3},
{1./6, -4./3, 1./6}
};
const double stencilCorner[2][2] = {
{1./3, 1./6},
{1./6, -2./3}
};
std::function<node_no_t(int,int)> dofIndex = [&functionSpace](int x, int y) -> node_no_t
{
return functionSpace->meshPartition()->getNodeNoLocal(std::array<int,2>({x,y})); // nDofsPerNode == 1
};
double value;
dof_no_t dofNo;
// loop over all dofs and set values with stencilCenter
// set entries for interior nodes
for (int y=1; y<nNodes1-1; y++)
{
for (int x=1; x<nNodes0-1; x++)
{
dofNo = dofIndex(x, y);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
value = stencilCenter[center+i][center+j]*integralFactor;
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j), value, INSERT_VALUES);
}
}
}
}
// call MatAssemblyBegin, MatAssemblyEnd
stiffnessMatrix->assembly(MAT_FLUSH_ASSEMBLY);
// set entries for boundary nodes on edges
// left boundary (x=0)
for (int y=1; y<nNodes1-1; y++)
{
int x = 0;
dof_no_t dofNo = dofIndex(x,y);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=1; j++) // y
{
value = stencilEdge[center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j), value, ADD_VALUES);
}
}
}
// right boundary (x=nNodes0-1)
for (int y=1; y<nNodes1-1; y++)
{
int x = nNodes0-1;
dof_no_t dofNo = dofIndex(x,y);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
value = stencilEdge[center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j), value, ADD_VALUES);
}
}
}
// bottom boundary (y=0)
for (int x=1; x<nNodes0-1; x++)
{
int y = 0;
dof_no_t dofNo = dofIndex(x,y);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
value = stencilEdge[center+j][center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j), value, ADD_VALUES);
}
}
}
// top boundary (y=nNodes1-1)
for (int x=1; x<nNodes0-1; x++)
{
int y = nNodes1-1;
dof_no_t dofNo = dofIndex(x,y);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
value = stencilEdge[center+j][center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j), value, ADD_VALUES);
}
}
}
// corner nodes
int x,y;
// bottom left (x=0, y=0)
x = 0;
y = 0;
dofNo = dofIndex(x,y);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // -y
{
value = stencilCorner[center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y-j), value, ADD_VALUES);
}
}
// bottom right (x=nNodes0-1, y=0)
x = nNodes0-1;
y = 0;
dofNo = dofIndex(x,y);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
value = stencilCorner[center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j), value, ADD_VALUES);
}
}
// top left (x=0, y=nNodes1-1)
x = 0;
y = nNodes1-1;
dofNo = dofIndex(x,y);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // y
{
value = stencilCorner[center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j), value, ADD_VALUES);
}
}
// top right (x=nNodes0-1, y=nNodes1-1)
x = nNodes0-1;
y = nNodes1-1;
dofNo = dofIndex(x,y);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
value = stencilCorner[center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j), value, ADD_VALUES);
}
}
stiffnessMatrix->assembly(MAT_FINAL_ASSEMBLY);
}
// 3D stiffness matrix
template<typename QuadratureType,typename Term>
void FiniteElementMethodMatrix<FunctionSpace::FunctionSpace<Mesh::StructuredRegularFixedOfDimension<3>,BasisFunction::LagrangeOfOrder<1>>,QuadratureType,1,Term,Mesh::StructuredRegularFixedOfDimension<3>,Equation::hasLaplaceOperator<Term>,BasisFunction::LagrangeOfOrder<1>>::
setStiffnessMatrix()
{
typedef FunctionSpace::FunctionSpace<Mesh::StructuredRegularFixedOfDimension<3>, BasisFunction::LagrangeOfOrder<1>> FunctionSpaceType;
LOG(TRACE) << "setStiffnessMatrix 3D for Mesh::RegularFixed using stencils";
// get settings values
std::shared_ptr<FunctionSpaceType> functionSpace = std::static_pointer_cast<FunctionSpaceType>(this->data_.functionSpace());
element_no_t nElements0 = functionSpace->nElementsPerCoordinateDirectionLocal(0);
element_no_t nElements1 = functionSpace->nElementsPerCoordinateDirectionLocal(1);
element_no_t nElements2 = functionSpace->nElementsPerCoordinateDirectionLocal(2);
node_no_t nNodes0 = functionSpace->nNodesLocalWithGhosts(0);
node_no_t nNodes1 = functionSpace->nNodesLocalWithGhosts(1);
node_no_t nNodes2 = functionSpace->nNodesLocalWithGhosts(2);
double elementLength0 = functionSpace->meshWidth();
double elementLength1 = functionSpace->meshWidth();
double elementLength2 = functionSpace->meshWidth();
if (fabs(elementLength0-elementLength1) > 1e-15 || fabs(elementLength0-elementLength2) > 1e-15)
{
LOG(ERROR) << "Mesh resolution of 3D regular fixed mesh is not uniform! " << std::endl
<< "Mesh widths: x: " << elementLength0 << ", y: " << elementLength1 << ", z: " << elementLength2 << std::endl
<< "This means that the stiffness matrix will be wrong. Mesh::RegularFixed meshes use stencil notation "
<< "and can only handle uniform meshes correctly. To use non-uniform meshes, consider using Mesh::Deformable!";
}
double integralFactor = elementLength0;
double prefactor;
this->prefactor_.getValue(0, prefactor); // prefactor value is constant over the domain
integralFactor = prefactor*integralFactor;
LOG(DEBUG) << "Use settings nElements=" <<nElements0<< "x" <<nElements1<< "x" <<nElements2<<
", elementLength=" << elementLength0<< "x" << elementLength1<< "x" << elementLength2;
LOG(DEBUG) << "integralFactor=" <<integralFactor;
// fill stiffness matrix
// M_ij = -int[0,1] dphi_i/dxi * dphi_j/dxi * (dxi/ds)^2 ds = l
// stencil for -Δu in 3D: bottom: [1 2 1] (element contribution: center: [ 0 1/12]
// 1/12*[2 _0_ 2] [_-4/12_ 0]
// [1 2 1]
// bottom:[ 1/12 1/12]
// center: [ 2 0 2] [ 0 1/12] )
// 1/12*[ 0 _-32_ 0]
// [ 2 0 2]
//
// top: like bottom
// coordinate system
// x axis: left -> right
// y axis: front -> back
// z axis: bottom -> top
const int center = 1;
const double stencilCenter[3][3][3] = {
{{1./12, 2./12, 1./12}, //bottom
{2./12, 0./12, 2./12},
{1./12, 2./12, 1./12}},
{{2./12, 0./12, 2./12}, //center
{0./12, -32./12, 0./12},
{2./12, 0./12, 2./12}},
{{1./12, 2./12, 1./12}, //top
{2./12, 0./12, 2./12},
{1./12, 2./12, 1./12}},
};
const double stencilBoundarySurface[2][3][3] = {
{{1./12, 2./12, 1./12}, //bottom
{2./12, 0./12, 2./12},
{1./12, 2./12, 1./12}},
{{1./12, 0./12, 1./12}, //center
{0./12, -16./12, 0./12},
{1./12, 0./12, 1./12}},
};
const double stencilBoundaryEdge[2][2][3] = {
{{1./12, 2./12, 1./12}, //bottom
{1./12, 0./12, 1./12}},
{{1./12, 0./12, 1./12},
{0./12, -8./12, 0./12}} //center
};
const double stencilCorner[2][2][2] = {
{{1./12, 1./12},
{1./12, 0./12}}, //bottom
{{1./12, 0./12},
{0./12, -4./12}}, //center
};
std::shared_ptr<PartitionedPetscMat<FunctionSpaceType>> stiffnessMatrix = this->data_.stiffnessMatrix();
auto dofIndex = [&functionSpace](int x, int y, int z)
{
return functionSpace->meshPartition()->getNodeNoLocal(std::array<int,3>({x,y,z})); // nDofsPerNode == 1
};
double value;
dof_no_t dofNo;
// loop over all dofs and set values with stencilCenter
// set entries for interior nodes
for (int z=1; z<nNodes2-1; z++)
{
for (int y=1; y<nNodes1-1; y++)
{
for (int x=1; x<nNodes0-1; x++)
{
dofNo = dofIndex(x, y, z);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilCenter[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, INSERT_VALUES);
}
}
}
}
}
}
// call MatAssemblyBegin, MatAssemblyEnd
stiffnessMatrix->assembly(MAT_FLUSH_ASSEMBLY);
// set entries for boundary nodes on surface boundaries
// left boundary (x = 0)
for (int z=1; z<nNodes2-1; z++)
{
for (int y=1; y<nNodes1-1; y++)
{
int x = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundarySurface[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
}
// right boundary (x = nNodes0-1)
for (int z=1; z<nNodes2-1; z++)
{
for (int y=1; y<nNodes1-1; y++)
{
int x = nNodes0-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundarySurface[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
}
// front boundary (y = 0)
for (int z=1; z<nNodes2-1; z++)
{
for (int x=1; x<nNodes0-1; x++)
{
int y = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundarySurface[center+j][center+i][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j, z+k), value, ADD_VALUES);
}
}
}
}
}
// back boundary (y = nNodes1-1)
for (int z=1; z<nNodes2-1; z++)
{
for (int x=1; x<nNodes0-1; x++)
{
int y = nNodes1-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundarySurface[center+j][center+i][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
}
// bottom boundary (z = 0)
for (int y=1; y<nNodes1-1; y++)
{
for (int x=1; x<nNodes0-1; x++)
{
int z = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilBoundarySurface[center+k][center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z-k), value, ADD_VALUES);
}
}
}
}
}
// top boundary (z = nNodes2-1)
for (int y=1; y<nNodes1-1; y++)
{
for (int x=1; x<nNodes0-1; x++)
{
int z = nNodes2-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilBoundarySurface[center+k][center+i][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
}
// set entries for boundary nodes on edge boundaries
// bottom left (x=0,z=0)
for (int y=1; y<nNodes1-1; y++)
{
int x = 0;
int z = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilBoundaryEdge[center+i][center+k][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j, z-k), value, ADD_VALUES);
}
}
}
}
// bottom right (x=nNodes0-1,z=0)
for (int y=1; y<nNodes1-1; y++)
{
int x = nNodes0-1;
int z = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilBoundaryEdge[center+i][center+k][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z-k), value, ADD_VALUES);
}
}
}
}
// top left (x=0,z=nNodes2-1)
for (int y=1; y<nNodes1-1; y++)
{
int x = 0;
int z = nNodes2-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilBoundaryEdge[center+i][center+k][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
// top right (x=nNodes0-1,z=nNodes2-1)
for (int y=1; y<nNodes1-1; y++)
{
int x = nNodes0-1;
int z = nNodes2-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=1; j++) // y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilBoundaryEdge[center+i][center+k][center+j]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
// bottom front (y=0,z=0)
for (int x=1; x<nNodes0-1; x++)
{
int y = 0;
int z = 0;
dof_no_t dofNo = dofIndex(x,y,z);
value = 0;
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilBoundaryEdge[center+j][center+k][center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j, z-k), value, ADD_VALUES);
}
}
}
}
// bottom back (y=nNodes1-1,z=0)
for (int x=1; x<nNodes0-1; x++)
{
int y = nNodes1-1;
int z = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilBoundaryEdge[center+j][center+k][center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z-k), value, ADD_VALUES);
}
}
}
}
// top front (y=0,z=nNodes2-1)
for (int x=1; x<nNodes0-1; x++)
{
int y = 0;
int z = nNodes2-1;
dof_no_t dofNo = dofIndex(x,y,z);
value = 0;
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilBoundaryEdge[center+j][center+k][center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j, z+k), value, ADD_VALUES);
}
}
}
}
// top back (y=nNodes1-1,z=nNodes2-1)
for (int x=1; x<nNodes0-1; x++)
{
int y = nNodes1-1;
int z = nNodes2-1;
dof_no_t dofNo = dofIndex(x,y,z);
value = 0;
for (int i=-1; i<=1; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilBoundaryEdge[center+j][center+k][center+i]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
// left front (x=0,y=0)
for (int z=1; z<nNodes2-1; z++)
{
int x = 0;
int y = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundaryEdge[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y-j, z+k), value, ADD_VALUES);
}
}
}
}
// left back (x=0,y=nNodes1-1)
for (int z=1; z<nNodes2-1; z++)
{
int x = 0;
int y = nNodes1-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundaryEdge[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
// right front (x=nNodes0-1,y=0)
for (int z=1; z<nNodes2-1; z++)
{
int x = nNodes0-1;
int y = 0;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundaryEdge[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j, z+k), value, ADD_VALUES);
}
}
}
}
// right back (x=nNodes0-1,y=nNodes1-1)
for (int z=1; z<nNodes2-1; z++)
{
int x = nNodes0-1;
int y = nNodes1-1;
dof_no_t dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=1; k++) // z
{
value = stencilBoundaryEdge[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
}
// corner nodes
int x,y,z;
// bottom front left (x=0,y=0,z=0)
x = 0;
y = 0;
z = 0;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y-j, z-k), value, ADD_VALUES);
}
}
}
// bottom front right (x=nNodes0-1,y=0,z=0)
x = nNodes0-1;
y = 0;
z = 0;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j, z-k), value, ADD_VALUES);
}
}
}
// bottom back left (x=0,y=nNodes1-1,z=0)
x = 0;
y = nNodes1-1;
z = 0;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j, z-k), value, ADD_VALUES);
}
}
}
// bottom back right (x=nNodes0-1,y=nNodes1-1,z=0)
x = nNodes0-1;
y = nNodes1-1;
z = 0;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=0; k++) // -z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z-k), value, ADD_VALUES);
}
}
}
// top front left (x=0,y=0,z=nNodes2-1)
x = 0;
y = 0;
z = nNodes2-1;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y-j, z+k), value, ADD_VALUES);
}
}
}
// top front right (x=nNodes0-1,y=0,z=nNodes2-1)
x = nNodes0-1;
y = 0;
z = nNodes2-1;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // -y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y-j, z+k), value, ADD_VALUES);
}
}
}
// top back left (x=0,y=nNodes1-1,z=nNodes2-1)
x = 0;
y = nNodes1-1;
z = nNodes2-1;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // -x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x-i, y+j, z+k), value, ADD_VALUES);
}
}
}
// top back right (x=nNodes0-1,y=nNodes1-1,z=nNodes2-1)
x = nNodes0-1;
y = nNodes1-1;
z = nNodes2-1;
dofNo = dofIndex(x,y,z);
for (int i=-1; i<=0; i++) // x
{
for (int j=-1; j<=0; j++) // y
{
for (int k=-1; k<=0; k++) // z
{
value = stencilCorner[center+i][center+j][center+k]*integralFactor;
// matrix row column
stiffnessMatrix->setValue(dofNo, dofIndex(x+i, y+j, z+k), value, ADD_VALUES);
}
}
}
stiffnessMatrix->assembly(MAT_FINAL_ASSEMBLY);
}
} // namespace
| 30.321501 | 274 | 0.533398 | [
"mesh",
"3d"
] |
e97592c888c61110e8e0aac0c1ad6e515eb2c5c3 | 4,212 | cpp | C++ | examples/mnist/dataInput/mnistDataInput.cpp | eidelen/EidNN | 80999b1228eda4cab70b060bdaa6d257f8143bb1 | [
"MIT"
] | 3 | 2021-05-14T15:03:03.000Z | 2021-12-05T08:31:38.000Z | examples/mnist/dataInput/mnistDataInput.cpp | eidelen/EidNN | 80999b1228eda4cab70b060bdaa6d257f8143bb1 | [
"MIT"
] | null | null | null | examples/mnist/dataInput/mnistDataInput.cpp | eidelen/EidNN | 80999b1228eda4cab70b060bdaa6d257f8143bb1 | [
"MIT"
] | 3 | 2020-08-13T15:44:05.000Z | 2021-06-07T16:16:53.000Z | /****************************************************************************
** Copyright (c) 2017 Adrian Schneider
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
**
*****************************************************************************/
#include "mnistDataInput.h"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
MnistDataInput::MnistDataInput()
{
load();
}
MnistDataInput::~MnistDataInput()
{
}
bool MnistDataInput::loadMNISTSample( const std::vector<std::vector<double>>& imgSet, const std::vector<uint8_t>& lableSet,
const size_t& idx, Eigen::MatrixXd& img, uint8_t& lable)
{
if( std::max(imgSet.size(), lableSet.size()) <= idx )
return false;
lable = lableSet.at( idx );
const std::vector<double>& imgV = imgSet.at( idx );
img = Eigen::MatrixXd( imgV.size(), 1 );
for( size_t i = 0; i < imgV.size(); i++ )
img( int(i), 0 ) = imgV.at(i);
return true;
}
void MnistDataInput::load()
{
// MNIST_DATA_LOCATION passed by cmake
auto mnistinputNormalized = mnist::read_dataset<std::vector, std::vector, double, uint8_t>(MNIST_DATA_LOCATION);
mnist::normalize_dataset(mnistinputNormalized);
// Load training data
for( size_t k = 0; k < mnistinputNormalized.training_images.size(); k++ )
{
Eigen::MatrixXd xInNormalized; uint8_t lable;
loadMNISTSample( mnistinputNormalized.training_images, mnistinputNormalized.training_labels, k, xInNormalized, lable );
addTrainingSample(xInNormalized, static_cast<int>(lable));
}
// Load testing data
for( size_t k = 0; k < mnistinputNormalized.test_images.size(); k++ )
{
Eigen::MatrixXd xInNormalized; uint8_t lable;
loadMNISTSample( mnistinputNormalized.test_images, mnistinputNormalized.test_labels, k, xInNormalized, lable );
addTestSample( xInNormalized, static_cast<int>(lable));
}
generateFromLables();
// get the test images as images
auto mnistPixelImages = mnist::read_dataset<std::vector, std::vector, double, uint8_t>(MNIST_DATA_LOCATION);
for( size_t k = 0; k < mnistPixelImages.test_images.size(); k++ )
{
Eigen::MatrixXd xImg; uint8_t lable;
loadMNISTSample( mnistPixelImages.test_images, mnistPixelImages.test_labels, k, xImg, lable );
DataElement de;
de.input = xImg;
de.lable = lable;
m_testImages.push_back(de);
}
}
DataElement MnistDataInput::getTestImageAsPixelValues( size_t idx ) const
{
return m_testImages.at(idx);
}
Eigen::MatrixXd MnistDataInput::representation( const Eigen::MatrixXd& input, bool* representationAvailable ) const
{
size_t imgW = 28;
size_t imgH = 28;
// check that vector length equal to number of required pixels
if( imgH * imgW != input.rows() )
{
*representationAvailable = false;
return input;
}
Eigen::MatrixXd rep = Eigen::MatrixXd(imgH,imgW);
for( size_t h = 0; h < imgH; h++ )
{
for( size_t w = 0; w < imgW; w++ )
{
rep(h,w) = input(imgW*h+w,0);
}
}
*representationAvailable = true;
return rep;
}
| 34.809917 | 127 | 0.65622 | [
"vector"
] |
e975bf7d50b98ebf39656809e220370c93da6e41 | 6,353 | cpp | C++ | testing/parser/css/tokenizer_consumestringtoken.cpp | usadson/WebEngine | 73f436535a70c6c9d7f3a5c565650b6152effd8d | [
"BSD-2-Clause"
] | 3 | 2020-03-28T01:36:44.000Z | 2020-06-19T23:55:08.000Z | testing/parser/css/tokenizer_consumestringtoken.cpp | usadson/WebEngine | 73f436535a70c6c9d7f3a5c565650b6152effd8d | [
"BSD-2-Clause"
] | null | null | null | testing/parser/css/tokenizer_consumestringtoken.cpp | usadson/WebEngine | 73f436535a70c6c9d7f3a5c565650b6152effd8d | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (C) 2020 Tristan. All Rights Reserved.
* This file is licensed under the BSD 2-Clause license.
* See the COPYING file for licensing information.
*/
#include <random>
#include <variant>
#include <vector>
#include <cstring>
#include "data/text/encoding/utf8.hpp"
#include "data/text/ustring.hpp"
namespace CSS {
class TokenizerConsumeStringToken : public ::testing::Test {
public:
Context context {&ParseErrorTester::ReporterEndpoint};
std::random_device randomDevice;
std::mt19937 randomGenerator {randomDevice()};
std::uniform_int_distribution<Unicode::CodePoint> integerDistributor {0, Unicode::LAST_ALLOWED_CODE_POINT};
[[nodiscard]] Unicode::CodePoint
GetRandomCodePoint() noexcept {
return integerDistributor(randomGenerator);
}
void
CompareCodePointVectors(const std::vector<Unicode::CodePoint> &tokenizer,
const std::vector<Unicode::CodePoint> &expected) const noexcept {
ASSERT_EQ(tokenizer, expected) << "Comparison failed: tokenizer=\"" << Unicode::UString(tokenizer)
<< "\" expected=\"" << Unicode::UString(expected) << '"';
}
void
TestLegal(
const Unicode::UString &string, Unicode::CodePoint ending, const std::vector<Unicode::CodePoint> &result) {
Tokenizer tokenizer(context, string);
ASSERT_TRUE(tokenizer.ConsumeStringToken(ending));
ASSERT_FALSE(ParseErrorTester::WasParseErrorFired());
ASSERT_EQ(tokenizer.tokens.size(), 1);
ASSERT_EQ(tokenizer.tokens[0].type, Token::Type::STRING);
const auto *data = std::get_if<TokenCodePointsData>(&tokenizer.tokens[0].data);
ASSERT_NE(data, nullptr);
CompareCodePointVectors(data->codePoints, result);
}
// An parse error will be fired and no token will be emitted.
void
TestIllegalFatal(const Unicode::UString &string, Unicode::CodePoint ending, ParseError expectedError) {
Tokenizer tokenizer(context, string);
ASSERT_TRUE(tokenizer.ConsumeStringToken(ending));
ASSERT_TRUE(ParseErrorTester::WasParseErrorFired(expectedError));
ASSERT_TRUE(tokenizer.tokens.empty());
}
// An parse error will be fired and no token will be emitted.
void
TestIllegalBadString(const Unicode::UString &string, Unicode::CodePoint ending, ParseError expectedError) {
Tokenizer tokenizer(context, string);
ASSERT_TRUE(tokenizer.ConsumeStringToken(ending));
ASSERT_TRUE(ParseErrorTester::WasParseErrorFired(expectedError));
ASSERT_EQ(tokenizer.tokens.size(), 1);
ASSERT_EQ(tokenizer.tokens[0].type, Token::Type::BAD_STRING);
ASSERT_TRUE(std::holds_alternative<std::nullptr_t>(tokenizer.tokens[0].data));
ASSERT_EQ(std::get<std::nullptr_t>(tokenizer.tokens[0].data), nullptr);
}
};
TEST_F(TokenizerConsumeStringToken, TestEmptyQuotationMarkEnding) {
const Unicode::UString string("\"");
const Unicode::CodePoint ending = Unicode::QUOTATION_MARK;
const std::vector<Unicode::CodePoint> result = {};
TestLegal(string, ending, result);
}
TEST_F(TokenizerConsumeStringToken, TestEmptyApostropheEnding) {
const Unicode::UString string("'");
const Unicode::CodePoint ending = Unicode::APOSTROPHE;
const std::vector<Unicode::CodePoint> result = {};
TestLegal(string, ending, result);
}
TEST_F(TokenizerConsumeStringToken, TestEmptyRandomEnding) {
Unicode::CodePoint ending;
while ((ending = GetRandomCodePoint()) == Unicode::LINE_FEED) {
}
Unicode::UString string(ending);
const std::vector<Unicode::CodePoint> result = {};
TestLegal(string, ending, result);
}
TEST_F(TokenizerConsumeStringToken, TestEOF) {
const Unicode::CodePoint ending = Unicode::APOSTROPHE;
const Unicode::UString string;
TestIllegalFatal(string, ending, ParseError::EOF_IN_CONSUMING_STRING);
}
TEST_F(TokenizerConsumeStringToken, TestNewLine) {
const Unicode::CodePoint ending = Unicode::APOSTROPHE;
const Unicode::UString string(Unicode::LINE_FEED);
TestIllegalBadString(string, ending, ParseError::NEWLINE_IN_CONSUMING_STRING);
}
TEST_F(TokenizerConsumeStringToken, TestEscapedNewLine) {
Unicode::UString string {'\\', '\n', '"'};
const Unicode::CodePoint ending = Unicode::QUOTATION_MARK;
const std::vector<Unicode::CodePoint> result;
TestLegal(string, ending, result);
}
TEST_F(TokenizerConsumeStringToken, TestEscapedNewLineInText) {
Unicode::UString string("Hello this is long thus \\\nwe begin on a new line.'");
const Unicode::CodePoint ending = Unicode::APOSTROPHE;
const char *text = "Hello this is long thus we begin on a new line.";
const auto result = TextEncoding::UTF8::ASCIIDecode(text, strlen(text));
TestLegal(string, ending, result);
}
TEST_F(TokenizerConsumeStringToken, TestEscapedCodePoint) {
Unicode::UString string {'H', 'e', '\\', '0', '0', '0', '0', '6', 'C', 'l', 'o', '"'};
const Unicode::CodePoint ending = Unicode::QUOTATION_MARK;
const std::vector<Unicode::CodePoint> result {'H', 'e', 'l', 'l', 'o'};
TestLegal(string, ending, result);
}
TEST_F(TokenizerConsumeStringToken, TestCalledByConsumeTokenQuotationMark) {
const Unicode::UString input {'"', 'T', 'h', 'i', 's', '"'};
const std::vector<Unicode::CodePoint> expected {'T', 'h', 'i', 's'};
Unicode::CodePoint character;
Tokenizer tokenizer(context, input);
ASSERT_TRUE(tokenizer.stream.Next(&character));
ASSERT_TRUE(tokenizer.ConsumeToken(character));
ASSERT_FALSE(ParseErrorTester::WasParseErrorFired());
ASSERT_EQ(tokenizer.tokens.size(), 1);
ASSERT_EQ(tokenizer.tokens[0].type, Token::Type::STRING);
const auto *data = std::get_if<TokenCodePointsData>(&tokenizer.tokens[0].data);
ASSERT_NE(data, nullptr);
CompareCodePointVectors(data->codePoints, expected);
}
TEST_F(TokenizerConsumeStringToken, TestCalledByConsumeTokenApostrophe) {
const Unicode::UString input {'\'', 'T', 'h', 'i', 's', '\''};
const std::vector<Unicode::CodePoint> expected {'T', 'h', 'i', 's'};
Unicode::CodePoint character;
Tokenizer tokenizer(context, input);
ASSERT_TRUE(tokenizer.stream.Next(&character));
ASSERT_TRUE(tokenizer.ConsumeToken(character));
ASSERT_FALSE(ParseErrorTester::WasParseErrorFired());
ASSERT_EQ(tokenizer.tokens.size(), 1);
ASSERT_EQ(tokenizer.tokens[0].type, Token::Type::STRING);
const auto *data = std::get_if<TokenCodePointsData>(&tokenizer.tokens[0].data);
ASSERT_NE(data, nullptr);
CompareCodePointVectors(data->codePoints, expected);
}
} // namespace CSS
| 39.216049 | 110 | 0.736345 | [
"vector"
] |
e977f3b39111ef9639ae8f6fa88dc0fa4f10d3fe | 1,355 | cpp | C++ | src/sensors/analog_input.cpp | JCHPAUL/SensESP | 4209c70d466230f3308002c435c0b5eafec2fef8 | [
"Apache-2.0"
] | null | null | null | src/sensors/analog_input.cpp | JCHPAUL/SensESP | 4209c70d466230f3308002c435c0b5eafec2fef8 | [
"Apache-2.0"
] | null | null | null | src/sensors/analog_input.cpp | JCHPAUL/SensESP | 4209c70d466230f3308002c435c0b5eafec2fef8 | [
"Apache-2.0"
] | 1 | 2020-07-10T22:35:05.000Z | 2020-07-10T22:35:05.000Z | #include "analog_input.h"
#include "Arduino.h"
#include "sensesp.h"
AnalogInput::AnalogInput(uint8_t pin, uint read_delay, String config_path,
float output_scale)
: NumericSensor(config_path),
pin{pin},
read_delay{read_delay},
output_scale{output_scale} {
analog_reader = new AnalogReader(pin);
load_configuration();
}
void AnalogInput::update() {
this->emit(output_scale * analog_reader->read());
}
void AnalogInput::enable() {
if (this->analog_reader->configure()) {
app.onRepeat(read_delay, [this]() { this->update(); });
}
}
void AnalogInput::get_configuration(JsonObject& root) {
root["read_delay"] = read_delay;
root["value"] = output;
};
static const char SCHEMA[] PROGMEM = R"###({
"type": "object",
"properties": {
"read_delay": { "title": "Read delay", "type": "number", "description": "Number of milliseconds between each analogRead(A0)" },
"value": { "title": "Last value", "type" : "number", "readOnly": true }
}
})###";
String AnalogInput::get_config_schema() { return FPSTR(SCHEMA); }
bool AnalogInput::set_configuration(const JsonObject& config) {
String expected[] = {"read_delay"};
for (auto str : expected) {
if (!config.containsKey(str)) {
return false;
}
}
read_delay = config["read_delay"];
return true;
}
| 26.568627 | 135 | 0.64428 | [
"object"
] |
e97d38dee31770ac78de649066c0620cfef8ad74 | 699 | cc | C++ | file/hash.cc | algorithm-ninja/ghost | a86ca99c6f295f31b5333acf57c1efff722acc04 | [
"MIT"
] | null | null | null | file/hash.cc | algorithm-ninja/ghost | a86ca99c6f295f31b5333acf57c1efff722acc04 | [
"MIT"
] | null | null | null | file/hash.cc | algorithm-ninja/ghost | a86ca99c6f295f31b5333acf57c1efff722acc04 | [
"MIT"
] | null | null | null | #include "file/hash.h"
#include "config.h"
#include "file/file.h"
#include "highwayhash/highwayhash.h"
using namespace highwayhash;
std::vector<uint64_t> HashFile(const std::string &path) {
File f(path);
size_t num_chunk = (f.size() + kChunkSize - 1) / kChunkSize;
std::vector<uint64_t> ret(num_chunk);
static const HHKey key HH_ALIGNAS(32) = {1, 2, 3, 4};
#pragma omp parallel for
for (size_t i = 0; i < num_chunk; i++) {
size_t off = i * kChunkSize;
size_t sz = std::max<size_t>(f.size(), (i + 1) * kChunkSize) - off;
HHResult64 result;
HHStateT<HH_TARGET> state(key);
HighwayHashT(&state, f.data() + off, sz, &result);
ret[i] = result;
}
return ret;
}
| 24.964286 | 71 | 0.648069 | [
"vector"
] |
e97f64d937f12d6a00290484bcff48d1af78fb04 | 5,112 | hpp | C++ | include/eve/detail/function/simd/x86/load.hpp | leha-bot/eve | 30e7a7f6bcc5cf524a6c2cc624234148eee847be | [
"MIT"
] | null | null | null | include/eve/detail/function/simd/x86/load.hpp | leha-bot/eve | 30e7a7f6bcc5cf524a6c2cc624234148eee847be | [
"MIT"
] | null | null | null | include/eve/detail/function/simd/x86/load.hpp | leha-bot/eve | 30e7a7f6bcc5cf524a6c2cc624234148eee847be | [
"MIT"
] | null | null | null | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/as.hpp>
#include <eve/concept/memory.hpp>
#include <eve/concept/vectorizable.hpp>
#include <eve/detail/abi.hpp>
#include <eve/detail/category.hpp>
#include <eve/detail/function/to_logical.hpp>
namespace eve::detail
{
//================================================================================================
// Regular loads
//================================================================================================
template<typename T, typename N, simd_compatible_ptr<wide<T,N>> Ptr >
EVE_FORCEINLINE auto load_( EVE_SUPPORTS(cpu_)
, ignore_none_ const&, safe_type const&
, eve::as<wide<T, N>> const &, Ptr p
)
requires dereference_as<T, Ptr>::value && x86_abi<abi_t<T, N>>
{
constexpr auto cat = categorize<wide<T, N>>();
constexpr bool isfull512 = N::value*sizeof(T) == x86_512_::bytes;
constexpr bool isfull256 = N::value*sizeof(T) == x86_256_::bytes;
constexpr bool isfull128 = N::value*sizeof(T) == x86_128_::bytes;
if constexpr( !std::is_pointer_v<Ptr> )
{
if constexpr( isfull512 )
{
if constexpr( cat == category::float64x8 ) return _mm512_load_pd(p.get());
else if constexpr( cat == category::float32x16 ) return _mm512_load_ps(p.get());
else return _mm512_load_si512((__m512i *)p.get());
}
else if constexpr( isfull256 )
{
if constexpr( cat == category::float64x4 ) return _mm256_load_pd(p.get());
else if constexpr( cat == category::float32x8 ) return _mm256_load_ps(p.get());
else return _mm256_load_si256((__m256i *)p.get());
}
else if constexpr( isfull128 )
{
if constexpr( cat == category::float64x2 ) return _mm_load_pd(p.get());
else if constexpr( cat == category::float32x4 ) return _mm_load_ps(p.get());
else return _mm_load_si128((__m128i *)p.get());
}
else
{
typename wide<T, N>::storage_type that{};
std::memcpy(&that, p.get(), N::value * sizeof(T));
return that;
}
}
else
{
if constexpr( isfull512 )
{
if constexpr( cat == category::float64x8 ) return _mm512_loadu_pd(p);
else if constexpr( cat == category::float32x16 ) return _mm512_loadu_ps(p);
else return _mm512_loadu_si512((__m512i *)p);
}
else if constexpr( isfull256 )
{
if constexpr( cat == category::float64x4 ) return _mm256_loadu_pd(p);
else if constexpr( cat == category::float32x8 ) return _mm256_loadu_ps(p);
else return _mm256_loadu_si256((__m256i *)p);
}
else if constexpr( isfull128 )
{
if constexpr( cat == category::float64x2 ) return _mm_loadu_pd(p);
else if constexpr( cat == category::float32x4 ) return _mm_loadu_ps(p);
else return _mm_loadu_si128((__m128i *)p);
}
else
{
typename wide<T, N>::storage_type that{};
std::memcpy(&that, p, N::value * sizeof(T));
return that;
}
}
}
//================================================================================================
// logical loads require some specific setup
//================================================================================================
template<typename T, typename N, typename Ptr>
EVE_FORCEINLINE logical<wide<T, N>> load_ ( EVE_SUPPORTS(cpu_)
, ignore_none_ const&, safe_type const&
, eve::as<logical<wide<T, N>>> const& tgt
, Ptr p
)
requires dereference_as<logical<T>, Ptr>::value && x86_abi<abi_t<T, N>>
{
auto block = [&]() -> wide<T, N>
{
using wtg = eve::as<wide<T, N>>;
return load(ignore_none, safe, wtg{}, ptr_cast<T const>(p));
}();
if constexpr( current_api >= avx512 ) return to_logical(block);
else return bit_cast(block, tgt);
}
template<typename Iterator, typename T, typename N>
EVE_FORCEINLINE logical<wide<T, N>> load_ ( EVE_SUPPORTS(cpu_)
, ignore_none_ const&, safe_type const&
, eve::as<logical<wide<T, N>>> const &
, Iterator b, Iterator e
) noexcept
requires x86_abi<abi_t<T, N>>
{
auto block = [&]() -> wide<T, N>
{
using tgt = eve::as<wide<T, N>>;
return load(ignore_none, safe, tgt(), b, e);
}();
return to_logical(block);
}
}
| 39.627907 | 100 | 0.490219 | [
"vector"
] |
e981e2f2e956822ec63584cd3984ae7ffeebfae0 | 2,576 | cpp | C++ | SpotiHook/dllmain.cpp | kernel1337/SpotiHook | 9b51003a42fe7c2505755a96e07bc673054c77fc | [
"MIT"
] | 1 | 2020-11-10T16:57:21.000Z | 2020-11-10T16:57:21.000Z | SpotiHook/dllmain.cpp | maxarmin/SpotiHook | 9b51003a42fe7c2505755a96e07bc673054c77fc | [
"MIT"
] | null | null | null | SpotiHook/dllmain.cpp | maxarmin/SpotiHook | 9b51003a42fe7c2505755a96e07bc673054c77fc | [
"MIT"
] | null | null | null | // dllmain.cpp : Definisce il punto di ingresso per l'applicazione DLL.
#pragma once
#include "imports.h"
#include "window_hook.h"
#include "render_proxy.h"
#include "overlay.h"
#include "menu.h"
#include "patchAds.h"
#include "patchAutoUpdates.h"
#include "patchDownloads.h"
void Init() {
HWND hWnd = NULL;
AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
printf("[<] Initializing...");
while (!hWnd)
{
printf(".");
hWnd = WindowHook();
Sleep(5);
}
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_SHOWWINDOW);
printf("\n[+] Found nVidia hWnd!\n");
initD3D(hWnd);
printf("[+] DirectX initialized!\n");
zgui::functions.draw_line = line;
zgui::functions.draw_rect = rect;
zgui::functions.draw_filled_rect = filled_rect;
zgui::functions.draw_text = text;
zgui::functions.get_text_size = get_text_size;
zgui::functions.get_frametime = get_frametime;
printf("[+] GUI render proxy initialized!\n");
//CreateThread(0, 0, (LPTHREAD_START_ROUTINE)MsgLoop, 0, 0, 0);
/*MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(code_base_here, &mbi, sizeof(mbi));
for (ULONG baseOfCode = code_base_here; baseOfCode < end_of_code_here; baseOfCode += mbi.RegionSize) {
VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READWRITE, &mbi.Protect);
// Do stuff
VirtualProtect(mbi.BaseAddress, mbi.RegionSize, mbi.Protect, &mbi.Protect); // Set it back to normal
VirtualQuery(baseOfCode, &mbi, sizeof(mbi));
} */
XPatchDownloads();
//XPatchAutoUpdates();
XPatchAds();
while (true)
render_scene();
}
void render_scene()
{
// clear the window alpha
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0f, 0);
d3ddev->BeginScene(); // begins the 3D scene
GUI::renderMenu();
d3ddev->EndScene(); // ends the 3D scene
d3ddev->Present(NULL, NULL, NULL, NULL); // displays the created frame on the screen
//Sleep(16);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hModule);
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Init, 0, 0, 0);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| 29.953488 | 121 | 0.645963 | [
"render",
"3d"
] |
e995dff41264e1d38fc70e4557958f51ac6851e6 | 7,145 | cpp | C++ | main.cpp | braiden-vasco/vismeit | 94da82cd207432380c983b949b09f3dc9af83bc6 | [
"MIT"
] | null | null | null | main.cpp | braiden-vasco/vismeit | 94da82cd207432380c983b949b09f3dc9af83bc6 | [
"MIT"
] | null | null | null | main.cpp | braiden-vasco/vismeit | 94da82cd207432380c983b949b09f3dc9af83bc6 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "ext.h"
static const char *const window_title = "Vismeit";
static const int initial_window_width = 640;
static const int initial_window_height = 480;
static int screen_width = initial_window_width;
static int screen_height = initial_window_height;
struct Vertex3fAttribute
{
GLfloat x, y, z;
};
struct Color3fAttribute
{
GLfloat r, g, b;
};
static GLuint a_program;
static GLint a_coord3d_attribute, a_v_color_attribute;
static GLint a_mvp_uniform;
static GLuint vbo_cube_vertices, vbo_cube_colors;
static GLuint ibo_cube_elements;
static int init_resources();
static void on_reshape(int width, int height);
static void on_idle();
static void on_display();
int main(int argc, char* argv[]) {
ruby_init();
Init_vismeit();
glutInit(&argc, argv);
glutInitContextVersion(2, 0);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA | GLUT_DEPTH);
glutInitWindowSize(initial_window_width, initial_window_height);
glutCreateWindow(window_title);
const GLenum glew_status = glewInit();
if (glew_status != GLEW_OK) {
fprintf(stderr, "Error: %s\n", glewGetErrorString(glew_status));
return 1;
}
if (init_resources()) {
glutReshapeFunc(on_reshape);
glutIdleFunc(on_idle);
glutDisplayFunc(on_display);
glutMainLoop();
}
ruby_cleanup(0);
return 0;
}
int init_resources()
{
const VALUE rb_cube_vertex_attributes = rb_eval_string(
"["
" -1.0, -1.0, 1.0,"
" 1.0, -1.0, 1.0,"
" 1.0, 1.0, 1.0,"
" -1.0, 1.0, 1.0,"
" -1.0, -1.0, -1.0,"
" 1.0, -1.0, -1.0,"
" 1.0, 1.0, -1.0,"
" -1.0, 1.0, -1.0,"
"].pack('f*').freeze" // float
);
const VALUE rb_cube_color_attributes = rb_eval_string(
"["
" 1.0, 0.0, 0.0,"
" 0.0, 1.0, 0.0,"
" 0.0, 0.0, 1.0,"
" 1.0, 1.0, 1.0,"
" 1.0, 0.0, 0.0,"
" 0.0, 1.0, 0.0,"
" 0.0, 0.0, 1.0,"
" 1.0, 1.0, 1.0,"
"].pack('f*').freeze" // float
);
const VALUE rb_cube_elements = rb_eval_string(
"["
" 0, 1, 2,"
" 2, 3, 0,"
" 1, 5, 6,"
" 6, 2, 1,"
" 7, 6, 5,"
" 5, 4, 7,"
" 4, 0, 3,"
" 3, 7, 4,"
" 4, 5, 1,"
" 1, 0, 4,"
" 3, 2, 6,"
" 6, 7, 3,"
"].pack('S*').freeze" // unsigned short
);
const VALUE rb_a_program = rb_eval_string(
"Vismeit::Program.new([ \n"
" Vismeit::Shader.new(:vertex_shader, File.read('sh/a.vert')), \n"
" Vismeit::Shader.new(:fragment_shader, File.read('sh/a.frag')), \n"
"]) \n"
);
const VALUE rb_a_coord3d_attrib = rb_funcall(
rb_eval_string("Vismeit::Attrib"),
rb_intern("new"),
2,
rb_a_program,
rb_str_new_cstr("coord3d")
);
const VALUE rb_a_v_color_attrib = rb_funcall(
rb_eval_string("Vismeit::Attrib"),
rb_intern("new"),
2,
rb_a_program,
rb_str_new_cstr("v_color")
);
const VALUE rb_a_mvp_uniform = rb_funcall(
rb_eval_string("Vismeit::Uniform"),
rb_intern("new"),
2,
rb_a_program,
rb_str_new_cstr("mvp")
);
const VALUE rb_cube_vertex_vbo = rb_funcall(
rb_eval_string("Vismeit::ArrayBuffer"),
rb_intern("new"),
1,
rb_cube_vertex_attributes
);
const VALUE rb_cube_color_vbo = rb_funcall(
rb_eval_string("Vismeit::ArrayBuffer"),
rb_intern("new"),
1,
rb_cube_color_attributes
);
const VALUE rb_cube_element_ibo = rb_funcall(
rb_eval_string("Vismeit::ElementArrayBuffer"),
rb_intern("new"),
1,
rb_cube_elements
);
CDATA_mVismeit_cProgram *cdata_a_program;
CDATA_mVismeit_cAttrib *cdata_a_coord3d_attrib;
CDATA_mVismeit_cAttrib *cdata_a_v_color_attrib;
CDATA_mVismeit_cUniform *cdata_a_mvp_uniform;
CDATA_mVismeit_cArrayBuffer *cdata_cube_vertex_vbo;
CDATA_mVismeit_cArrayBuffer *cdata_cube_color_vbo;
CDATA_mVismeit_cElementArrayBuffer *cdata_cube_element_ibo;
Data_Get_Struct(rb_a_program,
CDATA_mVismeit_cProgram, cdata_a_program);
Data_Get_Struct(rb_a_coord3d_attrib,
CDATA_mVismeit_cAttrib, cdata_a_coord3d_attrib);
Data_Get_Struct(rb_a_v_color_attrib,
CDATA_mVismeit_cAttrib, cdata_a_v_color_attrib);
Data_Get_Struct(rb_a_mvp_uniform,
CDATA_mVismeit_cUniform, cdata_a_mvp_uniform);
Data_Get_Struct(rb_cube_vertex_vbo,
CDATA_mVismeit_cArrayBuffer, cdata_cube_vertex_vbo);
Data_Get_Struct(rb_cube_color_vbo,
CDATA_mVismeit_cArrayBuffer, cdata_cube_color_vbo);
Data_Get_Struct(rb_cube_element_ibo,
CDATA_mVismeit_cElementArrayBuffer, cdata_cube_element_ibo);
a_program = cdata_a_program->gl_id;
a_coord3d_attribute = cdata_a_coord3d_attrib->gl_id;
a_v_color_attribute = cdata_a_v_color_attrib->gl_id;
a_mvp_uniform = cdata_a_mvp_uniform->gl_id;
vbo_cube_vertices = cdata_cube_vertex_vbo->gl_id;
vbo_cube_colors = cdata_cube_color_vbo->gl_id;
ibo_cube_elements = cdata_cube_element_ibo->gl_id;
return 1;
}
void on_reshape(const int width, const int height)
{
screen_width = width;
screen_height = height;
}
void on_idle()
{
const float angle = glutGet(GLUT_ELAPSED_TIME) / 1000.0 * 45;
glm::vec3 axis_y(0, 1, 0);
glm::mat4 anim = glm::rotate(glm::mat4(1.0f), glm::radians(angle), axis_y);
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0, 0.0, -4.0));
glm::mat4 view = glm::lookAt(glm::vec3(0.0, 2.0, 0.0), glm::vec3(0.0, 0.0, -4.0), glm::vec3(0.0, 1.0, 0.0));
glm::mat4 projection = glm::perspective(45.0f, 1.0f*screen_width/screen_height, 0.1f, 10.0f);
glm::mat4 mvp = projection * view * model * anim;
glUseProgram(a_program);
glUniformMatrix4fv(a_mvp_uniform, 1, GL_FALSE, glm::value_ptr(mvp));
glutPostRedisplay();
}
void on_display()
{
glViewport(0, 0, screen_width, screen_height);
glClearColor(1.0, 1.0, 1.0, 1.0);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glUseProgram(a_program);
glEnableVertexAttribArray(a_coord3d_attribute);
glEnableVertexAttribArray(a_v_color_attribute);
glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_vertices);
glVertexAttribPointer(
a_coord3d_attribute,
3,
GL_FLOAT,
GL_FALSE,
0,
0
);
glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_colors);
glVertexAttribPointer(
a_v_color_attribute,
3,
GL_FLOAT,
GL_FALSE,
0,
0
);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_cube_elements);
int size;
glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
glutSwapBuffers();
}
| 25.158451 | 110 | 0.652764 | [
"model"
] |
e9a9e2b4d8e0f19967fae3f5c76e6949429423e8 | 120,803 | cpp | C++ | src/net_processing.cpp | gandrewstone/bitcoin | 05de381c02eb4bfca94957733acadfa217527f25 | [
"MIT"
] | 535 | 2015-09-04T15:10:08.000Z | 2022-03-17T20:51:05.000Z | src/net_processing.cpp | gandrewstone/bitcoin | 05de381c02eb4bfca94957733acadfa217527f25 | [
"MIT"
] | 1,269 | 2016-01-31T20:21:24.000Z | 2022-03-16T01:20:08.000Z | src/net_processing.cpp | gandrewstone/bitcoin | 05de381c02eb4bfca94957733acadfa217527f25 | [
"MIT"
] | 295 | 2015-10-19T16:12:29.000Z | 2021-08-02T20:05:17.000Z | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2018-2020 The Bitcoin Unlimited developers
// Copyright (C) 2019-2020 Tom Zander <tomz@freedommail.ch>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "net_processing.h"
#include "DoubleSpendProof.h"
#include "DoubleSpendProofStorage.h"
#include "addrman.h"
#include "blockrelay/blockrelay_common.h"
#include "blockrelay/compactblock.h"
#include "blockrelay/graphene.h"
#include "blockrelay/mempool_sync.h"
#include "blockrelay/thinblock.h"
#include "blockstorage/blockstorage.h"
#include "chain.h"
#include "dosman.h"
#include "electrum/electrs.h"
#include "expedited.h"
#include "extversionkeys.h"
#include "main.h"
#include "merkleblock.h"
#include "nodestate.h"
#include "requestManager.h"
#include "timedata.h"
#include "txadmission.h"
#include "validation/validation.h"
#include "validationinterface.h"
#include "version.h"
extern std::atomic<int64_t> nTimeBestReceived;
extern std::atomic<int> nPreferredDownload;
extern int nSyncStarted;
extern CTweak<unsigned int> maxBlocksInTransitPerPeer;
extern CTweak<uint64_t> grapheneMinVersionSupported;
extern CTweak<uint64_t> grapheneMaxVersionSupported;
extern CTweak<uint64_t> grapheneFastFilterCompatibility;
extern CTweak<uint64_t> mempoolSyncMinVersionSupported;
extern CTweak<uint64_t> mempoolSyncMaxVersionSupported;
extern CTweak<uint64_t> syncMempoolWithPeers;
extern CTweak<uint32_t> randomlyDontInv;
extern CTweak<uint32_t> doubleSpendProofs;
extern CTweak<bool> extVersionEnabled;
/** How many inbound connections will we track before pruning entries */
const uint32_t MAX_INBOUND_CONNECTIONS_TRACKED = 10000;
/** maximum size (in bytes) of a batched set of transactions */
static const uint32_t MAX_TXN_BATCH_SIZE = 10000;
// Requires cs_main
bool CanDirectFetch(const Consensus::Params &consensusParams)
{
return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
}
void UpdatePreferredDownload(CNode *node)
{
CNodeStateAccessor state(nodestate, node->GetId());
DbgAssert(state != nullptr, return );
nPreferredDownload.fetch_sub(state->fPreferredDownload);
// Whether this node should be marked as a preferred download node.
state->fPreferredDownload = !node->fOneShot && !node->fClient;
// BU allow downloads from inbound nodes; this may have been limited to stop attackers from connecting
// and offering a bad chain. However, we are connecting to multiple nodes and so can choose the most work
// chain on that basis.
// state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
// LOG(NET, "node %s preferred DL: %d because (%d || %d) && %d && %d\n", node->GetLogName(),
// state->fPreferredDownload, !node->fInbound, node->fWhitelisted, !node->fOneShot, !node->fClient);
nPreferredDownload.fetch_add(state->fPreferredDownload);
}
// Requires cs_main
bool PeerHasHeader(const CNodeState *state, CBlockIndex *pindex)
{
if (pindex == nullptr)
return false;
if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
return true;
if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
return true;
return false;
}
void static ProcessGetData(CNode *pfrom, const Consensus::Params &consensusParams, std::deque<CInv> &vInv)
{
std::vector<CInv> vNotFound;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
std::deque<CInv>::iterator it = vInv.begin();
while (it != vInv.end())
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize() + ss.size())
{
LOG(REQ, "Postponing %d getdata requests. Send buffer is too large: %d\n", vInv.size(), pfrom->nSendSize);
break;
}
if (shutdown_threads.load() == true)
{
return;
}
// start processing inventory here
const CInv &inv = *it;
it++;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK)
{
auto *mi = LookupBlockIndex(inv.hash);
if (mi)
{
bool fSend = false;
{
LOCK(cs_main);
if (chainActive.Contains(mi))
{
fSend = true;
}
else
{
static const int nOneMonth = 30 * 24 * 60 * 60;
// To prevent fingerprinting attacks, only send blocks outside of the active
// chain if they are valid, and no more than a month older (both in time, and in
// best equivalent proof of work) than the best header chain we know about.
{
READLOCK(cs_mapBlockIndex);
fSend = mi->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
(pindexBestHeader.load()->GetBlockTime() - mi->GetBlockTime() < nOneMonth) &&
(GetBlockProofEquivalentTime(
*pindexBestHeader, *mi, *pindexBestHeader, consensusParams) < nOneMonth);
}
if (!fSend)
{
LOG(NET, "%s: ignoring request from peer=%s for old block that isn't in the main chain\n",
__func__, pfrom->GetLogName());
}
else
{
// Don't relay excessive blocks that are not on the active chain
if (mi->nStatus & BLOCK_EXCESSIVE)
fSend = false;
if (!fSend)
LOG(NET, "%s: ignoring request from peer=%s for excessive block of height %d not on "
"the main chain\n",
__func__, pfrom->GetLogName(), mi->nHeight);
}
// TODO: in the future we can throttle old block requests by setting send=false if we are out
// of bandwidth
}
}
// disconnect node in case we have reached the outbound limit for serving historical blocks
// never disconnect whitelisted nodes
static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
if (fSend && CNode::OutboundTargetReached(true) &&
(((pindexBestHeader != nullptr) &&
(pindexBestHeader.load()->GetBlockTime() - mi->GetBlockTime() > nOneWeek)) ||
inv.type == MSG_FILTERED_BLOCK) &&
!pfrom->fWhitelisted)
{
LOG(NET, "historical block serving limit reached, disconnect peer %s\n", pfrom->GetLogName());
// disconnect node
pfrom->fDisconnect = true;
fSend = false;
}
// Avoid leaking prune-height by never sending blocks below the
// NODE_NETWORK_LIMITED threshold.
// Add two blocks buffer extension for possible races
if (fSend && !pfrom->fWhitelisted &&
((((nLocalServices & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) &&
((nLocalServices & NODE_NETWORK) != NODE_NETWORK) &&
(chainActive.Tip()->nHeight - mi->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2))))
{
LOG(NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n",
pfrom->GetId());
// disconnect node and prevent it from stalling (would
// otherwise wait for the missing block)
pfrom->fDisconnect = true;
fSend = false;
}
// Pruned nodes may have deleted the block, so check whether
// it's available before trying to send.
if (fSend && mi->nStatus & BLOCK_HAVE_DATA)
{
// Send block from disk
CBlock block;
if (!ReadBlockFromDisk(block, mi, consensusParams))
{
// its possible that I know about it but haven't stored it yet
LOG(THIN, "unable to load block %s from disk\n",
mi->phashBlock ? mi->phashBlock->ToString() : "");
// no response
}
else
{
if (inv.type == MSG_BLOCK)
{
pfrom->blocksSent += 1;
pfrom->PushMessage(NetMsgType::BLOCK, block);
}
else if (inv.type == MSG_CMPCT_BLOCK)
{
LOG(CMPCT, "Sending compactblock via getdata message\n");
SendCompactBlock(MakeBlockRef(block), pfrom, inv);
}
else // MSG_FILTERED_BLOCK)
{
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
{
CMerkleBlock merkleBlock(block, *pfrom->pfilter);
pfrom->PushMessage(NetMsgType::MERKLEBLOCK, merkleBlock);
pfrom->blocksSent += 1;
// CMerkleBlock just contains hashes, so also push any transactions in the block the
// client did not see. This avoids hurting performance by pointlessly requiring a
// round-trip.
//
// Note that there is currently no way for a node to request any single transactions
// we didn't send here - they must either disconnect and retry or request the full
// block. Thus, the protocol spec specified allows for us to provide duplicate txn
// here, however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
for (PairType &pair : merkleBlock.vMatchedTxn)
{
pfrom->txsSent += 1;
pfrom->PushMessage(NetMsgType::TX, block.vtx[pair.first]);
}
}
// else
// no response
}
// Trigger the peer node to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
std::vector<CInv> oneInv;
oneInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
pfrom->PushMessage(NetMsgType::INV, oneInv);
pfrom->hashContinue.SetNull();
}
}
}
}
}
else if (inv.type == MSG_DOUBLESPENDPROOF && doubleSpendProofs.Value() == true)
{
DoubleSpendProof dsp = mempool.doubleSpendProofStorage()->lookup(inv.hash);
if (!dsp.isEmpty())
{
CDataStream ssDSP(SER_NETWORK, PROTOCOL_VERSION);
ssDSP.reserve(600);
ssDSP << dsp;
pfrom->PushMessage(NetMsgType::DSPROOF, ssDSP);
}
else
{
pfrom->PushMessage(NetMsgType::REJECT, std::string(NetMsgType::DSPROOF), REJECT_INVALID,
std::string("dsproof requested was not found"));
}
}
else if (inv.IsKnownType())
{
CTransactionRef ptx = nullptr;
// Send stream from relay memory
{
// We need to release this lock before push message. There is a potential deadlock because
// cs_vSend is often taken before cs_mapRelay
LOCK(cs_mapRelay);
std::map<CInv, CTransactionRef>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end())
{
ptx = (*mi).second;
}
}
if (!ptx)
{
ptx = CommitQGet(inv.hash);
if (!ptx)
{
ptx = mempool.get(inv.hash);
}
}
// If we found a txn then push it
if (ptx)
{
if (pfrom->txConcat)
{
ss << *ptx;
// Send the concatenated txns if we're over the limit. We don't want to batch
// too many and end up delaying the send.
if (ss.size() > MAX_TXN_BATCH_SIZE)
{
pfrom->PushMessage(NetMsgType::TX, ss);
ss.clear();
}
}
else
{
// Or if this is not a peer that supports
// concatenation then send the transaction right away.
pfrom->PushMessage(NetMsgType::TX, ptx);
}
pfrom->txsSent += 1;
}
else
{
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
GetMainSignals().Inventory(inv.hash);
// Send only one of these message type before breaking. These type of requests use more
// resources to process and send, therefore we don't want some a peer to, intentionlally or
// unintentionally, dominate our network layer.
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK)
break;
}
// Send the batched transactions if any to send.
if (!ss.empty())
{
pfrom->PushMessage(NetMsgType::TX, ss);
}
// Erase all messages inv's we processed
vInv.erase(vInv.begin(), it);
if (!vNotFound.empty())
{
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage(NetMsgType::NOTFOUND, vNotFound);
}
}
static void handleAddressAfterInit(CNode *pfrom)
{
if (!pfrom->fInbound)
{
// Advertise our address
if (fListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
FastRandomContext insecure_rand;
if (addr.IsRoutable())
{
LOG(NET, "ProcessMessages: advertising address %s\n", addr.ToString());
pfrom->PushAddress(addr, insecure_rand);
}
else if (IsPeerAddrLocalGood(pfrom))
{
addr.SetIP(pfrom->addrLocal);
LOG(NET, "ProcessMessages: advertising address %s\n", addr.ToString());
pfrom->PushAddress(addr, insecure_rand);
}
}
// Get recent addresses
pfrom->fGetAddr = true;
pfrom->PushMessage(NetMsgType::GETADDR);
addrman.Good(pfrom->addr);
}
else
{
if (((CNetAddr)pfrom->addr) == (CNetAddr)pfrom->addrFrom_advertised)
{
addrman.Add(pfrom->addrFrom_advertised, pfrom->addrFrom_advertised);
addrman.Good(pfrom->addrFrom_advertised);
}
}
}
static void enableSendHeaders(CNode *pfrom)
{
// Tell our peer we prefer to receive headers rather than inv's
// We send this to non-NODE NETWORK peers as well, because even
// non-NODE NETWORK peers can announce blocks (such as pruning
// nodes)
if (pfrom->nVersion >= SENDHEADERS_VERSION)
pfrom->PushMessage(NetMsgType::SENDHEADERS);
}
static void enableCompactBlocks(CNode *pfrom)
{
// Tell our peer that we support compact blocks
if (IsCompactBlocksEnabled() && (pfrom->nVersion >= COMPACTBLOCKS_VERSION))
{
bool fHighBandwidth = false;
uint64_t nVersion = 1;
pfrom->PushMessage(NetMsgType::SENDCMPCT, fHighBandwidth, nVersion);
}
}
bool ProcessMessage(CNode *pfrom, std::string strCommand, CDataStream &vRecv, int64_t nStopwatchTimeReceived)
{
int64_t receiptTime = GetTime();
const CChainParams &chainparams = Params();
unsigned int msgSize = vRecv.size(); // BU for statistics
UpdateRecvStats(pfrom, strCommand, msgSize, nStopwatchTimeReceived);
LOG(NET, "received: %s (%u bytes) peer=%s\n", SanitizeString(strCommand), msgSize, pfrom->GetLogName());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
LOGA("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (!(nLocalServices & NODE_BLOOM) &&
(strCommand == NetMsgType::FILTERLOAD || strCommand == NetMsgType::FILTERADD ||
strCommand == NetMsgType::FILTERCLEAR))
{
if (pfrom->nVersion >= NO_BLOOM_VERSION)
{
dosMan.Misbehaving(pfrom, 100);
return false;
}
else
{
LOG(NET, "Inconsistent bloom filter settings peer %s\n", pfrom->GetLogName());
pfrom->fDisconnect = true;
return false;
}
}
bool grapheneVersionCompatible = true;
try
{
NegotiateGrapheneVersion(pfrom);
NegotiateFastFilterSupport(pfrom);
}
catch (const std::runtime_error &e)
{
grapheneVersionCompatible = false;
}
// ------------------------- BEGIN INITIAL COMMAND SET PROCESSING
if (strCommand == NetMsgType::VERSION)
{
int64_t nTime;
CAddress addrMe;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
// Update thin type peer counters. This should be at the top here before we have any
// potential disconnects, because on disconnect the counters will then get decremented.
thinrelay.AddPeers(pfrom);
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// ban peers older than this proto version
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
strprintf("Protocol Version must be %d or greater", MIN_PEER_PROTO_VERSION));
dosMan.Misbehaving(pfrom, 100);
return error("Using obsolete protocol version %i - banning peer=%s version=%s", pfrom->nVersion,
pfrom->GetLogName(), pfrom->cleanSubVer);
}
if (!vRecv.empty())
vRecv >> pfrom->addrFrom_advertised >> nNonce;
if (!vRecv.empty())
{
vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
// Track the user agent string
{
LOCK(cs_mapInboundConnectionTracker);
// Remove a random entry if we've gotten too big.
if (mapInboundConnectionTracker.size() >= MAX_INBOUND_CONNECTIONS_TRACKED)
{
size_t nIndex = GetRandInt(mapInboundConnectionTracker.size() - 1);
auto rand_iter = std::next(mapInboundConnectionTracker.begin(), nIndex);
mapInboundConnectionTracker.erase(rand_iter);
}
// Add the subver string.
mapInboundConnectionTracker[(CNetAddr)pfrom->addr].userAgent = pfrom->cleanSubVer;
}
// ban SV peers
if (pfrom->strSubVer.find("Bitcoin SV") != std::string::npos ||
pfrom->strSubVer.find("(SV;") != std::string::npos)
{
dosMan.Misbehaving(pfrom, 100, BanReasonInvalidPeer);
}
}
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (!vRecv.empty())
vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
else
pfrom->fRelayTxes = true;
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
LOGA("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
pfrom->addrLocal = addrMe;
if (pfrom->fInbound && addrMe.IsRoutable())
{
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
// set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients"
pfrom->fClient = (!(pfrom->nServices & NODE_NETWORK) && !(pfrom->nServices & NODE_NETWORK_LIMITED));
// set nodes not capable of serving the complete blockchain history as "limited nodes"
pfrom->m_limited_node = (!(pfrom->nServices & NODE_NETWORK) && (pfrom->nServices & NODE_NETWORK_LIMITED));
// Potentially mark this peer as a preferred download peer.
UpdatePreferredDownload(pfrom);
// only send extversion message if both peers are using the protocol
if ((nLocalServices & NODE_EXTVERSION) && (pfrom->nServices & NODE_EXTVERSION) &&
extVersionEnabled.Value() == true)
{
// BU expedited procecessing requires the exchange of the listening port id
// The former BUVERSION message has now been integrated into the xmap field in CExtversionMessage.
// prepare extversion message. This must be sent before we send a verack message in the new spec
CExtversionMessage xver;
xver.set_u64c(XVer::EXTVERSION_VERSION_KEY, EXTVERSION_VERSION_VALUE);
xver.set_u64c(XVer::BU_LISTEN_PORT, GetListenPort());
xver.set_u64c(XVer::BU_MSG_IGNORE_CHECKSUM, 1); // we will ignore 0 value msg checksums
xver.set_u64c(XVer::BU_GRAPHENE_MAX_VERSION_SUPPORTED, grapheneMaxVersionSupported.Value());
xver.set_u64c(XVer::BU_GRAPHENE_MIN_VERSION_SUPPORTED, grapheneMinVersionSupported.Value());
xver.set_u64c(XVer::BU_GRAPHENE_FAST_FILTER_PREF, grapheneFastFilterCompatibility.Value());
xver.set_u64c(XVer::BU_MEMPOOL_SYNC, syncMempoolWithPeers.Value());
xver.set_u64c(XVer::BU_MEMPOOL_SYNC_MAX_VERSION_SUPPORTED, mempoolSyncMaxVersionSupported.Value());
xver.set_u64c(XVer::BU_MEMPOOL_SYNC_MIN_VERSION_SUPPORTED, mempoolSyncMinVersionSupported.Value());
xver.set_u64c(XVer::BU_XTHIN_VERSION, 2); // xthin version
size_t nLimitAncestors = GetArg("-limitancestorcount", BU_DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = GetArg("-limitancestorsize", BU_DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
size_t nLimitDescendants = GetArg("-limitdescendantcount", BU_DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = GetArg("-limitdescendantsize", BU_DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000;
xver.set_u64c(XVer::BU_MEMPOOL_ANCESTOR_COUNT_LIMIT, nLimitAncestors);
xver.set_u64c(XVer::BU_MEMPOOL_ANCESTOR_SIZE_LIMIT, nLimitAncestorSize);
xver.set_u64c(XVer::BU_MEMPOOL_DESCENDANT_COUNT_LIMIT, nLimitDescendants);
xver.set_u64c(XVer::BU_MEMPOOL_DESCENDANT_SIZE_LIMIT, nLimitDescendantSize);
xver.set_u64c(XVer::BU_TXN_CONCATENATION, 1);
electrum::set_extversion_flags(xver, chainparams.NetworkIDString());
pfrom->extversionExpected = true;
pfrom->PushMessage(NetMsgType::EXTVERSION, xver);
}
else
{
// Send VERACK handshake message
pfrom->PushMessage(NetMsgType::VERACK);
}
// Change version
{
LOCK(pfrom->cs_vSend);
pfrom->ssSend.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
}
LOG(NET, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%s\n", pfrom->cleanSubVer,
pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetLogName());
int64_t nTimeOffset = nTime - GetTime();
pfrom->nTimeOffset = nTimeOffset;
AddTimeData(pfrom->addr, nTimeOffset);
// Feeler connections exist only to verify if address is online.
if (pfrom->fFeeler)
{
// Should never occur but if it does correct the value.
// We can't have an inbound "feeler" connection, so the value must be improperly set.
DbgAssert(pfrom->fInbound == false, pfrom->fFeeler = false);
if (pfrom->fInbound == false)
{
LOG(NET, "Disconnecting feeler to peer %s\n", pfrom->GetLogName());
pfrom->fDisconnect = true;
}
}
}
else if ((pfrom->nVersion == 0 || pfrom->tVersionSent < 0) && !pfrom->fWhitelisted)
{
// Must have a version message before anything else
dosMan.Misbehaving(pfrom, 1);
pfrom->fDisconnect = true;
return error("%s receieved before VERSION message - disconnecting peer=%s", strCommand, pfrom->GetLogName());
}
else if (strCommand == NetMsgType::EXTVERSION && extVersionEnabled.Value() == true)
{
// set expected to false, we got the message
pfrom->extversionExpected = false;
if (pfrom->fSuccessfullyConnected == true)
{
dosMan.Misbehaving(pfrom, 1);
pfrom->fDisconnect = true;
return error("odd peer behavior: received verack message before extversion, disconnecting \n");
}
LOCK(pfrom->cs_extversion);
vRecv >> pfrom->extversion;
if (pfrom->addrFromPort != 0)
{
LOG(NET, "Encountered odd node that sent BUVERSION before XVERSION. Ignoring duplicate addrFromPort "
"setting. peer=%s version=%s\n",
pfrom->GetLogName(), pfrom->cleanSubVer);
}
pfrom->ReadConfigFromExtversion();
pfrom->PushMessage(NetMsgType::VERACK);
}
else if (!pfrom->fSuccessfullyConnected && GetTime() - pfrom->tVersionSent > VERACK_TIMEOUT &&
pfrom->tVersionSent >= 0)
{
// If verack is not received within timeout then disconnect.
// The peer may be slow so disconnect them only, to give them another chance if they try to re-connect.
// If they are a bad peer and keep trying to reconnect and still do not VERACK, they will eventually
// get banned by the connection slot algorithm which tracks disconnects and reconnects.
pfrom->fDisconnect = true;
LOG(NET, "ERROR: disconnecting - VERACK not received within %d seconds for peer=%s version=%s\n",
VERACK_TIMEOUT, pfrom->GetLogName(), pfrom->cleanSubVer);
// update connection tracker which is used by the connection slot algorithm.
LOCK(cs_mapInboundConnectionTracker);
CNetAddr ipAddress = (CNetAddr)pfrom->addr;
mapInboundConnectionTracker[ipAddress].nEvictions += 1;
mapInboundConnectionTracker[ipAddress].nLastEvictionTime = GetTime();
mapInboundConnectionTracker[ipAddress].userAgent = pfrom->cleanSubVer;
return true; // return true so we don't get any process message failures in the log.
}
else if (strCommand == NetMsgType::VERACK)
{
if (pfrom->fSuccessfullyConnected == true)
{
dosMan.Misbehaving(pfrom, 1);
pfrom->fDisconnect = true;
return error("duplicate verack messages");
}
pfrom->SetRecvVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
if (pfrom->extversionExpected.load() == true)
{
// if we expected extversion but got a verack it is possible there is a service bit
// mismatch so we should send a verack response because the peer might not
// support extversion
pfrom->PushMessage(NetMsgType::VERACK);
}
handleAddressAfterInit(pfrom);
enableSendHeaders(pfrom);
enableCompactBlocks(pfrom);
// Tell the peer what maximum xthin bloom filter size we will consider acceptable.
// FIXME: integrate into extversion as well
if (pfrom->ThinBlockCapable() && IsThinBlocksEnabled())
{
pfrom->PushMessage(NetMsgType::FILTERSIZEXTHIN, nXthinBloomFilterSize);
}
// This step done after final handshake
CheckAndRequestExpeditedBlocks(pfrom);
pfrom->fSuccessfullyConnected = true;
}
else if (strCommand == NetMsgType::XUPDATE)
{
CExtversionMessage xUpdate;
vRecv >> xUpdate;
// check for peer trying to change non-changeable key
for (auto entry : xUpdate.xmap)
{
if (XVer::IsChangableKey(entry.first))
{
LOCK(pfrom->cs_extversion);
pfrom->extversion.xmap[entry.first] = xUpdate.xmap[entry.first];
}
}
}
else if (strCommand == NetMsgType::SENDHEADERS)
{
CNodeStateAccessor(nodestate, pfrom->GetId())->fPreferHeaders = true;
}
else if (strCommand == NetMsgType::FILTERSIZEXTHIN)
{
if (pfrom->ThinBlockCapable())
{
uint32_t nSize = 0;
vRecv >> nSize;
pfrom->nXthinBloomfilterSize.store(nSize);
// As a safeguard don't allow a smaller max bloom filter size than the default max size.
if (!pfrom->nXthinBloomfilterSize || (pfrom->nXthinBloomfilterSize < SMALLEST_MAX_BLOOM_FILTER_SIZE))
{
pfrom->PushMessage(
NetMsgType::REJECT, strCommand, REJECT_INVALID, std::string("filter size was too small"));
LOG(NET, "Disconnecting %s: bloom filter size too small\n", pfrom->GetLogName());
pfrom->fDisconnect = true;
return false;
}
}
else
{
pfrom->fDisconnect = true;
return false;
}
}
else if (strCommand == NetMsgType::PING)
{
LeaveCritical(&pfrom->csMsgSerializer);
EnterCritical("pfrom.csMsgSerializer", __FILE__, __LINE__, (void *)(&pfrom->csMsgSerializer),
LockType::SHARED_MUTEX, OwnershipType::EXCLUSIVE);
uint64_t nonce = 0;
vRecv >> nonce;
// although PONG was enabled in BIP31, all clients should handle it at this point
// and unknown messages are silently dropped. So for simplicity, always respond with PONG
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage(NetMsgType::PONG, nonce);
LeaveCritical(&pfrom->csMsgSerializer);
EnterCritical("pfrom.csMsgSerializer", __FILE__, __LINE__, (void *)(&pfrom->csMsgSerializer),
LockType::SHARED_MUTEX, OwnershipType::SHARED);
}
// ------------------------- END INITIAL COMMAND SET PROCESSING
else if (!pfrom->fSuccessfullyConnected)
{
LOG(NET, "Ignoring command %s that comes in before initial handshake is finished. peer=%s version=%s\n",
strCommand, pfrom->GetLogName(), pfrom->cleanSubVer);
// Ignore any other commands early in the handshake
return false;
}
else if (strCommand == NetMsgType::ADDR)
{
std::vector<CAddress> vAddr;
vRecv >> vAddr;
if (vAddr.size() > 1000)
{
dosMan.Misbehaving(pfrom, 20);
return error("message addr size() = %u", vAddr.size());
}
// To avoid malicious flooding of our address table, only allow unsolicited ADDR messages to
// insert the connecting IP. We need to allow this IP to be inserted, or there is no way for that node
// to tell the network about itself if its behind a NAT.
// Digression about how things work behind a NAT:
// Node A periodically ADDRs node B with the address that B reported to A as A's own
// address (in the VERSION message).
//
// The purpose of using exchange here is to atomically set to false and also get whether I asked for an addr
if (!pfrom->fGetAddr.exchange(0) && pfrom->fInbound)
{
bool reportedOwnAddr = false;
CAddress ownAddr;
for (CAddress &addr : vAddr)
{
// server listen port will be different. We want to compare IPs and then use provided port
if ((CNetAddr)addr == (CNetAddr)pfrom->addr)
{
ownAddr = addr;
reportedOwnAddr = true;
break;
}
}
if (reportedOwnAddr)
{
vAddr.resize(1); // Get rid of every address the remote node tried to inject except itself.
vAddr[0] = ownAddr;
}
else
{
// Today unsolicited ADDRs are not illegal, but we should consider misbehaving on this (if we add logic
// to unmisbehaving over time), because a few unsolicited ADDRs are ok from a DOS perspective but lots
// are not.
// dosMan.Misbehaving(pfrom, 1);
return true; // We don't want to process any other addresses, but giving them is not an error
}
}
// Store the new addresses
std::vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
FastRandomContext insecure_rand;
for (CAddress &addr : vAddr)
{
if (shutdown_threads.load() == true)
{
return false;
}
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the addrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt.IsNull())
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = ArithToUint256(
UintToArith256(hashSalt) ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60)));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
std::multimap<uint256, CNode *> mapMix;
for (CNode *pnode : vNodes)
{
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(std::make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (std::multimap<uint256, CNode *>::iterator mi = mapMix.begin();
mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr, insecure_rand);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (pfrom->fOneShot)
{
LOG(NET, "Disconnecting %s: one shot\n", pfrom->GetLogName());
pfrom->fDisconnect = true;
}
}
// Ignore this message if sent from a node advertising a version earlier than the first CB release (70014)
else if (strCommand == NetMsgType::SENDCMPCT && pfrom->nVersion >= COMPACTBLOCKS_VERSION)
{
bool fHighBandwidth = false;
uint64_t nVersion = 0;
vRecv >> fHighBandwidth >> nVersion;
// BCH network currently only supports version 1 (v2 is segwit support on BTC)
// May need to be updated in the future if other clients deploy a new version
pfrom->fSupportsCompactBlocks = nVersion == 1;
// Increment compact block peer counter.
thinrelay.AddCompactBlockPeer(pfrom);
}
else if (strCommand == NetMsgType::INV)
{
if (fImporting || fReindex)
return true;
std::vector<CInv> vInv;
vRecv >> vInv;
LOG(NET, "Received INV list of size %d\n", vInv.size());
// Message Consistency Checking
// Check size == 0 to be intolerant of an empty and useless request.
// Validate that INVs are a valid type and not null.
if (vInv.size() > MAX_INV_SZ || vInv.empty())
{
dosMan.Misbehaving(pfrom, 20);
return error("message inv size() = %u", vInv.size());
}
// Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
fBlocksOnly = false;
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
if (shutdown_threads.load() == true)
return false;
const CInv &inv = vInv[nInv];
if (!((inv.type == MSG_TX) || (inv.type == MSG_BLOCK) || inv.type == MSG_DOUBLESPENDPROOF))
{
LOG(NET, "message inv invalid type = %u hash %s", inv.type, inv.hash.ToString());
return false;
}
else if (inv.hash.IsNull())
{
LOG(NET, "message inv has null hash %s", inv.type, inv.hash.ToString());
return false;
}
if (inv.type == MSG_BLOCK)
{
LOCK(cs_main);
bool fAlreadyHaveBlock = AlreadyHaveBlock(inv);
LOG(NET, "got BLOCK inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHaveBlock ? "have" : "new",
pfrom->id);
requester.UpdateBlockAvailability(pfrom->GetId(), inv.hash);
// RE !IsInitialBlockDownload(): We do not want to get the block if the system is executing the initial
// block download because
// blocks are stored in block files in the order of arrival. So grabbing blocks "early" will cause new
// blocks to be sprinkled
// throughout older block files. This will stop those files from being pruned.
// !IsInitialBlockDownload() can be removed if
// a better block storage system is devised.
if ((!fAlreadyHaveBlock && !IsInitialBlockDownload()) ||
(!fAlreadyHaveBlock && Params().NetworkIDString() == "regtest"))
{
// Since we now only rely on headers for block requests, if we get an INV from an older node or
// if there was a very large re-org which resulted in a revert to block announcements via INV,
// we will instead request the header rather than the block. This is safer and prevents an
// attacker from sending us fake INV's for blocks that do not exist or try to get us to request
// and download fake blocks.
pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash);
}
else
{
LOG(NET, "skipping request of block %s. already have: %d importing: %d reindex: %d "
"isChainNearlySyncd: %d\n",
inv.hash.ToString(), fAlreadyHaveBlock, fImporting, fReindex, IsChainNearlySyncd());
}
}
else if (inv.type == MSG_TX)
{
bool fAlreadyHaveTx = TxAlreadyHave(inv);
// LOG(NET, "got inv: %s %d peer=%s\n", inv.ToString(), fAlreadyHaveTx ? "have" : "new",
// pfrom->GetLogName());
LOG(NET, "got inv: %s have: %d peer=%s\n", inv.ToString(), fAlreadyHaveTx, pfrom->GetLogName());
pfrom->AddInventoryKnown(inv);
if (fBlocksOnly)
{
LOG(NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(),
pfrom->id);
}
// RE !IsInitialBlockDownload(): during IBD, its a waste of bandwidth to grab transactions, they will
// likely be included in blocks that we IBD download anyway. This is especially important as
// transaction volumes increase.
else if (!fAlreadyHaveTx && !IsInitialBlockDownload())
{
requester.AskFor(inv, pfrom);
}
}
else if (inv.type == MSG_DOUBLESPENDPROOF && doubleSpendProofs.Value() == true)
{
std::vector<CInv> vGetData;
vGetData.push_back(inv);
pfrom->PushMessage(NetMsgType::GETDATA, vGetData);
}
// Track requests for our stuff.
GetMainSignals().Inventory(inv.hash);
if (pfrom->nSendSize > (SendBufferSize() * 2))
{
dosMan.Misbehaving(pfrom, 50);
return error("send buffer size() = %u", pfrom->nSendSize);
}
}
}
else if (strCommand == NetMsgType::GETDATA)
{
if (fImporting || fReindex)
{
LOG(NET, "received getdata from %s but importing\n", pfrom->GetLogName());
return true;
}
std::vector<CInv> vInv;
vRecv >> vInv;
// BU check size == 0 to be intolerant of an empty and useless request
if ((vInv.size() > MAX_INV_SZ) || (vInv.size() == 0))
{
dosMan.Misbehaving(pfrom, 20);
return error("message getdata size() = %u", vInv.size());
}
// Validate that INVs are a valid type
std::deque<CInv> invDeque;
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (!((inv.type == MSG_TX) || (inv.type == MSG_BLOCK) || (inv.type == MSG_FILTERED_BLOCK) ||
(inv.type == MSG_CMPCT_BLOCK) || inv.type == MSG_DOUBLESPENDPROOF))
{
dosMan.Misbehaving(pfrom, 20, BanReasonInvalidInventory);
return error("message inv invalid type = %u", inv.type);
}
// Make basic checks
if (inv.type == MSG_CMPCT_BLOCK)
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
}
invDeque.push_back(inv);
}
if (fDebug || (invDeque.size() != 1))
LOG(NET, "received getdata (%u invsz) peer=%s\n", invDeque.size(), pfrom->GetLogName());
if ((fDebug && invDeque.size() > 0) || (invDeque.size() == 1))
LOG(NET, "received getdata for: %s peer=%s\n", invDeque[0].ToString(), pfrom->GetLogName());
// Run process getdata and process as much of the getdata's as we can before taking the lock
// and appending the remainder to the vRecvGetData queue.
ProcessGetData(pfrom, chainparams.GetConsensus(), invDeque);
if (!invDeque.empty())
{
LOCK(pfrom->csRecvGetData);
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), invDeque.begin(), invDeque.end());
}
}
else if (strCommand == NetMsgType::GETBLOCKS)
{
if (fImporting || fReindex)
return true;
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex *pindex = FindForkInGlobalIndex(chainActive, locator);
// Send the rest of the chain
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
LOG(NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1),
hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex))
{
if (pindex->GetBlockHash() == hashStop)
{
LOG(NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
// If pruning, don't inv blocks unless we have on disk and are likely to still have
// for some reasonable time window (1 hour) that block relay might require.
const int nPrunedBlocksLikelyToHave =
MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
{
READLOCK(cs_mapBlockIndex); // for nStatus
if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) ||
pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
{
LOG(NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight,
pindex->GetBlockHash().ToString());
break;
}
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll
// trigger the peer to getblocks the next batch of inventory.
LOG(NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == NetMsgType::GETHEADERS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex *pindex = nullptr;
if (locator.IsNull())
{
pindex = LookupBlockIndex(hashStop);
if (!pindex)
return true;
}
std::vector<CBlock> vHeaders;
{
LOCK(cs_main); // for chainActive
if (!locator.IsNull())
{
// Find the last block the caller has in the main chain
pindex = FindForkInGlobalIndex(chainActive, locator);
if (pindex)
pindex = chainActive.Next(pindex);
}
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
int nLimit = MAX_HEADERS_RESULTS;
LOG(NET, "getheaders height %d for block %s from peer %s\n", (pindex ? pindex->nHeight : -1),
hashStop.ToString(), pfrom->GetLogName());
for (; pindex; pindex = chainActive.Next(pindex))
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
}
// pindex can be nullptr either if we sent chainActive.Tip() OR
// if our peer has chainActive.Tip() (and thus we are sending an empty
// headers message). In both cases it's safe to update
// pindexBestHeaderSent to be our tip.
{
CNodeStateAccessor state(nodestate, pfrom->GetId());
state->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
}
pfrom->PushMessage(NetMsgType::HEADERS, vHeaders);
}
else if (strCommand == NetMsgType::TX)
{
// Stop processing the transaction early if
// We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) &&
(!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
{
LOG(NET, "transaction sent in violation of protocol peer=%d\n", pfrom->id);
return true;
}
// Process as many concatenated txns as there may be in this message
while (!vRecv.empty())
{
// Put the tx on the tx admission queue for processing
CTxInputData txd;
vRecv >> txd.tx;
// Indicate that the tx was received and is about to be processed. Setting the processing flag
// prevents us from re-requesting the txn during the time of processing and before mempool acceptance.
requester.ProcessingTxn(txd.tx->GetHash(), pfrom);
// Processing begins here where we enqueue the transaction.
txd.nodeId = pfrom->id;
txd.nodeName = pfrom->GetLogName();
txd.whitelisted = pfrom->fWhitelisted;
EnqueueTxForAdmission(txd);
CInv inv(MSG_TX, txd.tx->GetHash());
pfrom->AddInventoryKnown(inv);
requester.UpdateTxnResponseTime(inv, pfrom);
}
}
else if (strCommand == NetMsgType::HEADERS) // Ignore headers received while importing
{
if (fImporting)
{
LOG(NET, "skipping processing of HEADERS because importing\n");
return true;
}
if (fReindex)
{
LOG(NET, "skipping processing of HEADERS because reindexing\n");
return true;
}
std::vector<CBlockHeader> headers;
// Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
unsigned int nCount = ReadCompactSize(vRecv);
if (nCount > MAX_HEADERS_RESULTS)
{
dosMan.Misbehaving(pfrom, 20);
return error("headers message size = %u", nCount);
}
headers.resize(nCount);
for (unsigned int n = 0; n < nCount; n++)
{
vRecv >> headers[n];
ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
}
// Nothing interesting. Stop asking this peers for more headers.
if (nCount == 0)
{
LOG(NET, "No more headers from peer %s\n", pfrom->GetLogName());
return true;
}
CBlockIndex *pindexLast = nullptr;
{
// We need to handle appending the header and analyzing the unconnected ones sequentially, or
// 2 simultaneously processed header messages may cause an out of order header to not be reconnected
// when its parent arrives.
// We are reusing csUnConnected headers to both force this code to be sequential and to protect
// the unconnected headers data structure.
LOCK(csUnconnectedHeaders);
// Check all headers to make sure they are continuous before attempting to accept them.
// This prevents and attacker from keeping us from doing direct fetch by giving us out
// of order headers.
bool fNewUnconnectedHeaders = false;
uint256 hashLastBlock;
hashLastBlock.SetNull();
for (const CBlockHeader &header : headers)
{
// LOG(NET, "Received header %s from %s\n", header.GetHash().ToString(), pfrom->GetLogName());
// check that the first header has a previous block in the blockindex.
if (hashLastBlock.IsNull())
{
if (LookupBlockIndex(header.hashPrevBlock))
hashLastBlock = header.hashPrevBlock;
}
// Add this header to the map if it doesn't connect to a previous header
if (header.hashPrevBlock != hashLastBlock)
{
// If we still haven't finished downloading the initial headers during node sync and we get
// an out of order header then we must disconnect the node so that we can finish downloading
// initial headers from a diffeent peer. An out of order header at this point is likely an attack
// to prevent the node from syncing.
if (header.GetBlockTime() < GetAdjustedTime() - 24 * 60 * 60)
{
pfrom->fDisconnect = true;
return error("non-continuous-headers sequence during node sync - disconnecting peer=%s",
pfrom->GetLogName());
}
fNewUnconnectedHeaders = true;
}
// if we have an unconnected header then add every following header to the unconnected headers cache.
if (fNewUnconnectedHeaders)
{
uint256 hash = header.GetHash();
// LOG(NET, "Header %s from %s is unconnected\n", hash.ToString(), pfrom->GetLogName());
if (mapUnConnectedHeaders.size() < MAX_UNCONNECTED_HEADERS)
mapUnConnectedHeaders[hash] = std::make_pair(header, GetTime());
else
LOG(NET, "Ignoring header %s -- too many unconnected headers.\n", hash.ToString());
// update hashLastUnknownBlock so that we'll be able to download the block from this peer even
// if we receive the headers, which will connect this one, from a different peer.
requester.UpdateBlockAvailability(pfrom->GetId(), hash);
}
hashLastBlock = header.GetHash();
}
// return without error if we have an unconnected header. This way we can try to connect it when the next
// header arrives.
if (fNewUnconnectedHeaders)
return true;
{
// If possible add any previously unconnected headers to the headers vector and remove any expired
// entries.
std::map<uint256, std::pair<CBlockHeader, int64_t> >::iterator mi = mapUnConnectedHeaders.begin();
while (mi != mapUnConnectedHeaders.end())
{
std::map<uint256, std::pair<CBlockHeader, int64_t> >::iterator toErase = mi;
// Add the header if it connects to the previous header
if (headers.back().GetHash() == (*mi).second.first.hashPrevBlock)
{
headers.push_back((*mi).second.first);
mapUnConnectedHeaders.erase(toErase);
// if you found one to connect then search from the beginning again in case there is another
// that will connect to this new header that was added.
mi = mapUnConnectedHeaders.begin();
continue;
}
// Remove any entries that have been in the cache too long. Unconnected headers should only exist
// for a very short while, typically just a second or two.
int64_t nTimeHeaderArrived = (*mi).second.second;
uint256 headerHash = (*mi).first;
mi++;
if (GetTime() - nTimeHeaderArrived >= UNCONNECTED_HEADERS_TIMEOUT)
{
mapUnConnectedHeaders.erase(toErase);
}
// At this point we know the headers in the list received are known to be in order, therefore,
// check if the header is equal to some other header in the list. If so then remove it from the
// cache.
else
{
for (const CBlockHeader &header : headers)
{
if (header.GetHash() == headerHash)
{
mapUnConnectedHeaders.erase(toErase);
break;
}
}
}
}
}
// Check and accept each header in dependency order (oldest block to most recent)
int i = 0;
for (const CBlockHeader &header : headers)
{
CValidationState state;
if (!AcceptBlockHeader(header, state, chainparams, &pindexLast))
{
// Disconnect any peers that give us a bad checkpointed header.
// This prevents us from getting stuck in IBD where we download the intial headers.
// If we don't disconnect then we could end up attempting to download headers
// only from peers that are not on our own fork.
if (state.GetRejectCode() == REJECT_CHECKPOINT)
{
pfrom->fDisconnect = true;
}
int nDos;
if (state.IsInvalid(nDos))
{
if (nDos > 0)
{
dosMan.Misbehaving(pfrom, nDos);
}
}
// all headers from this one forward reference a fork that we don't follow, so erase them
headers.erase(headers.begin() + i, headers.end());
nCount = headers.size();
break;
}
else
PV->UpdateMostWorkOurFork(header);
i++;
}
}
if (pindexLast)
requester.UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
if (nCount == MAX_HEADERS_RESULTS && pindexLast)
{
// Headers message had its maximum size; the peer may have more headers.
// TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
// from there instead.
LOG(NET, "more getheaders (%d) to end to peer=%s (startheight:%d)\n", pindexLast->nHeight,
pfrom->GetLogName(), pfrom->nStartingHeight);
pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256());
{
int64_t now = GetTime();
CNodeStateAccessor state(nodestate, pfrom->GetId());
DbgAssert(state != nullptr, );
if (state != nullptr)
state->nSyncStartTime = now; // reset the time because more headers needed
}
// During the process of IBD we need to update block availability for every connected peer. To do that we
// request, from each NODE_NETWORK peer, a header that matches the last blockhash found in this recent set
// of headers. Once the requested header is received then the block availability for this peer will get
// updated.
if (IsInitialBlockDownload())
{
// To maintain locking order with cs_main we have to addrefs for each node and then release
// the lock on cs_vNodes before aquiring cs_main further down.
std::vector<CNode *> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
for (CNode *pnode : vNodes)
{
pnode->AddRef();
}
}
for (CNode *pnode : vNodesCopy)
{
if (!pnode->fClient && pnode != pfrom)
{
bool ask = false;
{
CNodeStateAccessor state(nodestate, pfrom->GetId());
DbgAssert(state != nullptr, ); // do not return, we need to release refs later.
if (state == nullptr)
continue;
ask = (state->pindexBestKnownBlock == nullptr ||
pindexLast->nChainWork > state->pindexBestKnownBlock->nChainWork);
} // let go of the CNodeState lock before we PushMessage since that is trapping op.
if (ask)
{
// We only want one single header so we pass a null for CBlockLocator.
pnode->PushMessage(NetMsgType::GETHEADERS, CBlockLocator(), pindexLast->GetBlockHash());
LOG(NET | BLK, "Requesting header for blockavailability, peer=%s block=%s height=%d\n",
pnode->GetLogName(), pindexLast->GetBlockHash().ToString().c_str(),
pindexBestHeader.load()->nHeight);
}
}
}
// release refs
for (CNode *pnode : vNodesCopy)
pnode->Release();
}
}
bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
{
CNodeStateAccessor state(nodestate, pfrom->GetId());
DbgAssert(state != nullptr, return false);
// During the initial peer handshake we must receive the initial headers which should be greater
// than or equal to our block height at the time of requesting GETHEADERS. This is because the peer has
// advertised a height >= to our own. Furthermore, because the headers max returned is as much as 2000 this
// could not be a mainnet re-org.
if (!state->fFirstHeadersReceived)
{
// We want to make sure that the peer doesn't just send us any old valid header. The block height of the
// last header they send us should be equal to our block height at the time we made the GETHEADERS
// request.
if (pindexLast && state->nFirstHeadersExpectedHeight <= pindexLast->nHeight)
{
state->fFirstHeadersReceived = true;
LOG(NET, "Initial headers received for peer=%s\n", pfrom->GetLogName());
}
// Allow for very large reorgs (> 2000 blocks) on the nol test chain or other test net.
if (Params().NetworkIDString() != "main" && Params().NetworkIDString() != "regtest")
state->fFirstHeadersReceived = true;
}
}
// update the syncd status. This should come before we make calls to requester.AskFor().
IsChainNearlySyncdInit();
IsInitialBlockDownloadInit();
// If this set of headers is valid and ends in a block with at least as
// much work as our tip, download as much as possible.
if (fCanDirectFetch && pindexLast && pindexLast->IsValid(BLOCK_VALID_TREE) &&
chainActive.Tip()->nChainWork <= pindexLast->nChainWork)
{
// Set tweak value. Mostly used in testing direct fetch.
if (maxBlocksInTransitPerPeer.Value() != 0)
pfrom->nMaxBlocksInTransit.store(maxBlocksInTransitPerPeer.Value());
std::vector<CBlockIndex *> vToFetch;
CBlockIndex *pindexWalk = pindexLast;
// Calculate all the blocks we'd need to switch to pindexLast.
while (pindexWalk && !chainActive.Contains(pindexWalk))
{
vToFetch.push_back(pindexWalk);
pindexWalk = pindexWalk->pprev;
}
// Download as much as possible, from earliest to latest.
unsigned int nAskFor = 0;
for (auto pindex_iter = vToFetch.rbegin(); pindex_iter != vToFetch.rend(); pindex_iter++)
{
CBlockIndex *pindex = *pindex_iter;
// pindex must be nonnull because we populated vToFetch a few lines above
CInv inv(MSG_BLOCK, pindex->GetBlockHash());
if (!AlreadyHaveBlock(inv))
{
requester.AskFor(inv, pfrom);
LOG(REQ, "AskFor block via headers direct fetch %s (%d) peer=%d\n",
pindex->GetBlockHash().ToString(), pindex->nHeight, pfrom->id);
nAskFor++;
}
// We don't care about how many blocks are in flight. We just need to make sure we don't
// ask for more than the maximum allowed per peer because the request manager will take care
// of any duplicate requests.
if (nAskFor >= pfrom->nMaxBlocksInTransit.load())
{
LOG(NET, "Large reorg, could only direct fetch %d blocks\n", nAskFor);
break;
}
}
if (nAskFor > 1)
{
LOG(NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
}
}
CheckBlockIndex(chainparams.GetConsensus());
}
// Handle Xthinblocks and Thinblocks
else if (strCommand == NetMsgType::GET_XTHIN && !fImporting && !fReindex && IsThinBlocksEnabled())
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
CBloomFilter filterMemPool;
CInv inv;
vRecv >> inv >> filterMemPool;
// Message consistency checking
if (inv.hash.IsNull())
{
dosMan.Misbehaving(pfrom, 100);
return error("invalid get_xthin type=%u hash=%s", inv.type, inv.hash.ToString());
}
// Validates that the filter is reasonably sized.
LoadFilter(pfrom, &filterMemPool);
{
auto *invIndex = LookupBlockIndex(inv.hash);
if (!invIndex)
{
dosMan.Misbehaving(pfrom, 100);
return error("Peer %srequested nonexistent block %s", pfrom->GetLogName(), inv.hash.ToString());
}
CBlock block;
const Consensus::Params &consensusParams = Params().GetConsensus();
if (!ReadBlockFromDisk(block, invIndex, consensusParams))
{
// We don't have the block yet, although we know about it.
return error(
"Peer %s requested block %s that cannot be read", pfrom->GetLogName(), inv.hash.ToString());
}
else
{
SendXThinBlock(MakeBlockRef(block), pfrom, inv);
}
}
}
else if (strCommand == NetMsgType::GET_THIN && !fImporting && !fReindex && IsThinBlocksEnabled())
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
CInv inv;
vRecv >> inv;
// Message consistency checking
if (inv.hash.IsNull())
{
dosMan.Misbehaving(pfrom, 100);
return error("invalid get_thin type=%u hash=%s", inv.type, inv.hash.ToString());
}
auto *invIndex = LookupBlockIndex(inv.hash);
if (!invIndex)
{
dosMan.Misbehaving(pfrom, 100);
return error("Peer %srequested nonexistent block %s", pfrom->GetLogName(), inv.hash.ToString());
}
CBlock block;
const Consensus::Params &consensusParams = Params().GetConsensus();
if (!ReadBlockFromDisk(block, invIndex, consensusParams))
{
// We don't have the block yet, although we know about it.
return error("Peer %s requested block %s that cannot be read", pfrom->GetLogName(), inv.hash.ToString());
}
else
{
SendXThinBlock(MakeBlockRef(block), pfrom, inv);
}
}
else if (strCommand == NetMsgType::XPEDITEDREQUEST)
{
return HandleExpeditedRequest(vRecv, pfrom);
}
else if (strCommand == NetMsgType::XPEDITEDBLK)
{
// ignore the expedited message unless we are at the chain tip...
if (!fImporting && !fReindex && !IsInitialBlockDownload())
{
LOCK(pfrom->cs_thintype);
if (!HandleExpeditedBlock(vRecv, pfrom))
return false;
}
}
else if (strCommand == NetMsgType::XTHINBLOCK && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsThinBlocksEnabled())
{
LOCK(pfrom->cs_thintype);
return CXThinBlock::HandleMessage(vRecv, pfrom, strCommand, 0);
}
else if (strCommand == NetMsgType::THINBLOCK && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsThinBlocksEnabled())
{
LOCK(pfrom->cs_thintype);
return CThinBlock::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::GET_XBLOCKTX && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsThinBlocksEnabled())
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
LOCK(pfrom->cs_thintype);
return CXRequestThinBlockTx::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::XBLOCKTX && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsThinBlocksEnabled())
{
LOCK(pfrom->cs_thintype);
return CXThinBlockTx::HandleMessage(vRecv, pfrom);
}
// Handle Graphene blocks
else if (strCommand == NetMsgType::GET_GRAPHENE && !fImporting && !fReindex && IsGrapheneBlockEnabled() &&
grapheneVersionCompatible)
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
LOCK(pfrom->cs_thintype);
return HandleGrapheneBlockRequest(vRecv, pfrom, chainparams);
}
else if (strCommand == NetMsgType::GRAPHENEBLOCK && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsGrapheneBlockEnabled() && grapheneVersionCompatible)
{
LOCK(pfrom->cs_thintype);
return CGrapheneBlock::HandleMessage(vRecv, pfrom, strCommand, 0);
}
else if (strCommand == NetMsgType::GET_GRAPHENETX && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsGrapheneBlockEnabled() && grapheneVersionCompatible)
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
LOCK(pfrom->cs_thintype);
return CRequestGrapheneBlockTx::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::GRAPHENETX && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsGrapheneBlockEnabled() && grapheneVersionCompatible)
{
LOCK(pfrom->cs_thintype);
return CGrapheneBlockTx::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::GET_GRAPHENE_RECOVERY && IsGrapheneBlockEnabled() && grapheneVersionCompatible)
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
LOCK(pfrom->cs_thintype);
return HandleGrapheneBlockRecoveryRequest(vRecv, pfrom, chainparams);
}
else if (strCommand == NetMsgType::GRAPHENE_RECOVERY && IsGrapheneBlockEnabled() && grapheneVersionCompatible)
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
LOCK(pfrom->cs_thintype);
return HandleGrapheneBlockRecoveryResponse(vRecv, pfrom, chainparams);
}
// Handle Compact Blocks
else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsCompactBlocksEnabled())
{
LOCK(pfrom->cs_thintype);
return CompactBlock::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::GETBLOCKTXN && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsCompactBlocksEnabled())
{
if (!requester.CheckForRequestDOS(pfrom, chainparams))
return false;
LOCK(pfrom->cs_thintype);
return CompactReRequest::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex && !IsInitialBlockDownload() &&
IsCompactBlocksEnabled())
{
LOCK(pfrom->cs_thintype);
return CompactReReqResponse::HandleMessage(vRecv, pfrom);
}
// Mempool synchronization request
else if (strCommand == NetMsgType::GET_MEMPOOLSYNC)
{
return HandleMempoolSyncRequest(vRecv, pfrom);
}
else if (strCommand == NetMsgType::MEMPOOLSYNC)
{
return CMempoolSync::ReceiveMempoolSync(vRecv, pfrom, strCommand);
}
// Mempool synchronization transaction request
else if (strCommand == NetMsgType::GET_MEMPOOLSYNCTX)
{
return CRequestMempoolSyncTx::HandleMessage(vRecv, pfrom);
}
else if (strCommand == NetMsgType::MEMPOOLSYNCTX)
{
return CMempoolSyncTx::HandleMessage(vRecv, pfrom);
}
// Handle full blocks
else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlockRef pblock(new CBlock());
{
uint64_t nCheckBlockSize = vRecv.size();
vRecv >> *pblock;
// Sanity check. The serialized block size should match the size that is in our receive queue. If not
// this could be an attack block of some kind.
DbgAssert(nCheckBlockSize == pblock->GetBlockSize(), return true);
}
CInv inv(MSG_BLOCK, pblock->GetHash());
LOG(BLK, "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
UnlimitedLogBlock(*pblock, inv.hash.ToString(), receiptTime);
if (IsChainNearlySyncd()) // BU send the received block out expedited channels quickly
{
CValidationState state;
if (CheckBlockHeader(*pblock, state, true)) // block header is fine
SendExpeditedBlock(*pblock, pfrom);
}
{ // reset the getheaders time because block can consume all bandwidth
int64_t now = GetTime();
CNodeStateAccessor state(nodestate, pfrom->GetId());
DbgAssert(state != nullptr, );
if (state != nullptr)
state->nSyncStartTime = now; // reset the time because more headers needed
}
pfrom->nPingUsecStart = GetStopwatchMicros(); // Reset ping time because block can consume all bandwidth
// Message consistency checking
// NOTE: consistency checking is handled by checkblock() which is called during
// ProcessNewBlock() during HandleBlockMessage.
PV->HandleBlockMessage(pfrom, strCommand, pblock, inv);
}
else if (strCommand == NetMsgType::GETADDR)
{
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making nodes which are behind NAT and can only make outgoing connections ignore
// the getaddr message mitigates the attack.
if (!pfrom->fInbound)
{
LOG(NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->id);
return true;
}
// Only send one GetAddr response per connection to reduce resource waste
// and discourage addr stamping of INV announcements.
if (pfrom->fSentAddr)
{
LOG(NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
return true;
}
pfrom->fSentAddr = true;
LOCK(pfrom->cs_vSend);
pfrom->vAddrToSend.clear();
std::vector<CAddress> vAddr = addrman.GetAddr();
FastRandomContext insecure_rand;
for (const CAddress &addr : vAddr)
pfrom->PushAddress(addr, insecure_rand);
}
else if (strCommand == NetMsgType::MEMPOOL)
{
if (CNode::OutboundTargetReached(false) && !pfrom->fWhitelisted)
{
LOG(NET, "mempool request with bandwidth limit reached, disconnect peer %s\n", pfrom->GetLogName());
pfrom->fDisconnect = true;
return true;
}
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
std::vector<CInv> vInv;
// Because we have to take cs_filter after mempool.cs, in order to maintain locking order, we
// need find out if a filter is present first before later doing the mempool.get().
bool fHaveFilter = false;
{
LOCK(pfrom->cs_filter);
fHaveFilter = pfrom->pfilter ? true : false;
}
for (uint256 &hash : vtxid)
{
CInv inv(MSG_TX, hash);
if (fHaveFilter)
{
CTransactionRef ptx = nullptr;
ptx = mempool.get(inv.hash);
if (ptx == nullptr)
continue; // another thread removed since queryHashes, maybe...
LOCK(pfrom->cs_filter);
if (!pfrom->pfilter->IsRelevantAndUpdate(ptx))
continue;
}
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ)
{
pfrom->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
if (vInv.size() > 0)
pfrom->PushMessage(NetMsgType::INV, vInv);
}
else if (strCommand == NetMsgType::PONG)
{
int64_t pingUsecEnd = nStopwatchTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce))
{
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0)
{
if (nonce == pfrom->nPingNonceSent)
{
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0)
{
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
}
else
{
// This should never happen
sProblem = "Timing mishap";
}
}
else
{
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0)
{
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
}
else
{
sProblem = "Unsolicited pong without ping";
}
}
else
{
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty()))
{
LOG(NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n", pfrom->id, sProblem,
pfrom->nPingNonceSent, nonce, nAvail);
}
if (bPingFinished)
{
pfrom->nPingNonceSent = 0;
}
}
else if (strCommand == NetMsgType::FILTERLOAD)
{
CBloomFilter filter;
vRecv >> filter;
if (!filter.IsWithinSizeConstraints())
{
// There is no excuse for sending a too-large filter
dosMan.Misbehaving(pfrom, 100);
return false;
}
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
if (!pfrom->pfilter->IsEmpty())
pfrom->fRelayTxes = true;
else
pfrom->fRelayTxes = false;
}
else if (strCommand == NetMsgType::FILTERADD)
{
std::vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
dosMan.Misbehaving(pfrom, 100);
}
else
{
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
pfrom->pfilter->insert(vData);
else
dosMan.Misbehaving(pfrom, 100);
}
}
else if (strCommand == NetMsgType::FILTERCLEAR)
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter();
pfrom->fRelayTxes = true;
}
else if (strCommand == NetMsgType::DSPROOF)
{
if (doubleSpendProofs.Value() == true)
{
LOG(DSPROOF, "Received a double spend proof from peer:%d\n", pfrom->GetId());
uint256 dspHash;
try
{
DoubleSpendProof dsp;
vRecv >> dsp;
if (dsp.isEmpty())
throw std::runtime_error("Double spend proof is empty");
dspHash = dsp.GetHash();
DoubleSpendProof::Validity validity;
{
READLOCK(mempool.cs_txmempool);
validity = dsp.validate(mempool);
}
switch (validity)
{
case DoubleSpendProof::Valid:
{
LOG(DSPROOF, "Double spend proof is valid from peer:%d\n", pfrom->GetId());
const auto ptx = mempool.addDoubleSpendProof(dsp);
if (ptx.get())
{
// find any descendants of this double spent transaction. If there are any
// then we must also forward this double spend proof to any SPV peers that
// want to know about this tx or its descendants.
CTxMemPool::setEntries setDescendants;
{
READLOCK(mempool.cs_txmempool);
CTxMemPool::indexed_transaction_set::const_iterator iter =
mempool.mapTx.find(ptx->GetHash());
if (iter == mempool.mapTx.end())
{
break;
}
else
{
mempool._CalculateDescendants(iter, setDescendants);
}
}
// added to mempool correctly, then forward to nodes.
broadcastDspInv(ptx, dspHash, &setDescendants);
}
break;
}
case DoubleSpendProof::MissingUTXO:
case DoubleSpendProof::MissingTransaction:
LOG(DSPROOF, "Double spend proof is orphan: postponed\n");
mempool.doubleSpendProofStorage()->addOrphan(dsp, pfrom->GetId());
break;
case DoubleSpendProof::Invalid:
throw std::runtime_error(strprintf("Double spend proof didn't validate (%s)", dspHash.ToString()));
default:
return false;
}
}
catch (const std::exception &e)
{
LOG(DSPROOF, "Failure handling double spend proof. Peer: %d Reason: %s\n", pfrom->GetId(), e.what());
if (!dspHash.IsNull())
mempool.doubleSpendProofStorage()->markProofRejected(dspHash);
dosMan.Misbehaving(pfrom->GetId(), 10);
return false;
}
}
}
else if (strCommand == NetMsgType::REJECT)
{
// BU: Request manager: this was restructured to not just be active in fDebug mode so that the request manager
// can be notified of request rejections.
try
{
std::string strMsg;
unsigned char ccode;
std::string strReason;
uint256 hash;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >>
LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
std::ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
// BU: Check request manager reject codes
if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
{
vRecv >> hash;
ss << ": hash " << hash.ToString();
// We need to see this reject message in either "req" or "net" debug mode
LOG(REQ | NET, "Reject %s\n", SanitizeString(ss.str()));
if (strMsg == NetMsgType::BLOCK)
{
requester.Rejected(CInv(MSG_BLOCK, hash), pfrom, ccode);
}
else if (strMsg == NetMsgType::TX)
{
requester.Rejected(CInv(MSG_TX, hash), pfrom, ccode);
}
}
// if (fDebug) {
// ostringstream ss;
// ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
// if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
// {
// ss << ": hash " << hash.ToString();
// }
// LOG(NET, "Reject %s\n", SanitizeString(ss.str()));
// }
}
catch (const std::ios_base::failure &)
{
// Avoid feedback loops by preventing reject messages from triggering a new reject message.
LOG(NET, "Unparseable reject message received\n");
LOG(REQ, "Unparseable reject message received\n");
}
}
else
{
// Ignore unknown commands for extensibility
LOG(NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
}
return true;
}
bool ProcessMessages(CNode *pfrom)
{
const CChainParams &chainparams = Params();
// if (fDebug)
// LOGA("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
// Check getdata requests first if there are no priority messages waiting.
if (!fPriorityRecvMsg.load())
{
TRY_LOCK(pfrom->csRecvGetData, locked);
if (locked && !pfrom->vRecvGetData.empty())
{
ProcessGetData(pfrom, chainparams.GetConsensus(), pfrom->vRecvGetData);
}
}
int msgsProcessed = 0;
// Don't bother if send buffer is too full to respond anyway
CNode *pfrom_original = pfrom;
std::deque<std::pair<CNodeRef, CNetMessage> > vPriorityRecvQ_delay;
while ((!pfrom->fDisconnect) && (pfrom->nSendSize < SendBufferSize()) && (shutdown_threads.load() == false))
{
CNodeRef noderef;
bool fIsPriority = false;
READLOCK(pfrom->csMsgSerializer);
CNetMessage msg;
bool fUseLowPriorityMsg = true;
bool fUsePriorityMsg = true;
// try to complete the handshake before handling messages that require us to be fSuccessfullyConnected
if (pfrom->fSuccessfullyConnected == false)
{
TRY_LOCK(pfrom->cs_vRecvMsg, lockRecv);
if (!lockRecv)
break;
if (pfrom->vRecvMsg_handshake.empty())
break;
// get the message from the queue
// simply getting the front message should be sufficient, the only time a extversion or verack is sent is
// once the previous has been processed so tracking which stage of the handshake we are on is overkill
std::swap(msg, pfrom->vRecvMsg_handshake.front());
pfrom->vRecvMsg_handshake.pop_front();
pfrom->currentRecvMsgSize -= msg.size();
msgsProcessed++;
}
else
{
{
TRY_LOCK(pfrom->cs_vRecvMsg, lockRecv);
if (!lockRecv)
break;
if (pfrom->vRecvMsg_handshake.empty() == false)
{
std::string frontCommand = pfrom->vRecvMsg_handshake.front().hdr.GetCommand();
if (frontCommand == NetMsgType::VERSION || frontCommand == NetMsgType::VERACK ||
frontCommand == NetMsgType::EXTVERSION)
{
pfrom->vRecvMsg_handshake.clear();
pfrom->fDisconnect = true;
dosMan.Misbehaving(pfrom, 1);
return error(
"recieved early handshake message after successfully connected, disconnecting peer=%s",
pfrom->GetLogName());
}
}
}
// Get next message to process checking whether it is a priority messasge and if so then
// process it right away. It doesn't matter that the peer where the message came from is
// different than the one we are currently procesing as we will switch to the correct peer
// automatically. Furthermore by using and holding the CNodeRef we automatically maintain
// a node reference to the priority peer.
if (fUsePriorityMsg && fPriorityRecvMsg.load())
{
TRY_LOCK(cs_priorityRecvQ, locked);
if (locked && !vPriorityRecvQ.empty())
{
// Get the message out of queue.
std::swap(noderef, vPriorityRecvQ.front().first);
std::swap(msg, vPriorityRecvQ.front().second);
vPriorityRecvQ.pop_front();
if (vPriorityRecvQ.empty())
fPriorityRecvMsg.store(false);
// check if we should process the message.
CNode *pnode = noderef.get();
if (pnode->fDisconnect)
{
// if the node is to be disconnected dont bother responding
continue;
}
if (pnode->nSendSize > SendBufferSize())
{
// if the nodes send is full, delay the processing of this message until a time when
// send is not full
vPriorityRecvQ_delay.emplace_back(std::move(noderef), std::move(msg));
continue;
}
fIsPriority = true;
fUseLowPriorityMsg = false;
}
else if (locked && vPriorityRecvQ.empty())
{
fPriorityRecvMsg.store(false);
fUseLowPriorityMsg = true;
}
}
if (fUseLowPriorityMsg)
{
TRY_LOCK(pfrom->cs_vRecvMsg, lockRecv);
if (!lockRecv)
break;
if (pfrom->vRecvMsg.empty())
break;
// get the message from the queue
std::swap(msg, pfrom->vRecvMsg.front());
pfrom->vRecvMsg.pop_front();
}
// Check if this is a priority message and if so then modify pfrom to be the peer which
// this priority message came from.
if (fIsPriority)
pfrom = noderef.get();
else
pfrom->currentRecvMsgSize -= msg.size();
msgsProcessed++;
}
// if (fDebug)
// LOGA("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, pfrom->GetMagic(chainparams), MESSAGE_START_SIZE) != 0)
{
// Setting the cleanSubVer string allows us to present this peer in the bantable
// with a likely peer type if it uses the BitcoinCore network magic.
if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), MESSAGE_START_SIZE) == 0)
{
pfrom->cleanSubVer = "BitcoinCore Network application";
}
LOG(NET, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%s\n", SanitizeString(msg.hdr.GetCommand()),
pfrom->GetLogName());
if (!pfrom->fWhitelisted)
{
// ban for 4 hours
dosMan.Ban(pfrom->addr, pfrom->cleanSubVer, BanReasonInvalidMessageStart, 4 * 60 * 60);
}
fOk = false;
break;
}
// Read header
CMessageHeader &hdr = msg.hdr;
if (!hdr.IsValid(pfrom->GetMagic(chainparams)))
{
LOG(NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%s\n", SanitizeString(hdr.GetCommand()),
pfrom->GetLogName());
continue;
}
std::string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
CDataStream &vRecv = msg.vRecv;
#if 0 // Do not waste my CPU calculating a checksum provided by an untrusted node
// TCP already has one that is sufficient for network errors. The checksum does not increase security since
// an attacker can always provide a bad message with a good checksum.
// This code is removed by comment so it is clear that it is a deliberate omission.
if (hdr.nChecksum != 0)
{
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = ReadLE32((unsigned char *)&hash);
if (nChecksum != hdr.nChecksum)
{
LOG(NET, "%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
}
#endif
// Process message
bool fRet = false;
try
{
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nStopwatch);
if (shutdown_threads.load() == true)
{
return false;
}
}
catch (const std::ios_base::failure &e)
{
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message"));
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
LOG(NET, "%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than "
"its stated length\n",
__func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
LOG(NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand),
nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (const boost::thread_interrupted &)
{
throw;
}
catch (const std::exception &e)
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
catch (...)
{
PrintExceptionContinue(nullptr, "ProcessMessages()");
}
if (!fRet)
LOG(NET, "%s(%s, %u bytes) FAILED peer %s\n", __func__, SanitizeString(strCommand), nMessageSize,
pfrom->GetLogName());
if (msgsProcessed > 2000)
break; // let someone else do something periodically
// Swap back to the original peer if we just processed a priority message
if (fIsPriority)
pfrom = pfrom_original;
}
{
LOCK(cs_priorityRecvQ);
// re-add the priority messages we delayed back to the queue so that we can try them again later
vPriorityRecvQ.insert(vPriorityRecvQ.end(), vPriorityRecvQ_delay.begin(), vPriorityRecvQ_delay.end());
if (!vPriorityRecvQ.empty())
fPriorityRecvMsg.store(true);
}
return fOk;
}
bool SendMessages(CNode *pto)
{
const Consensus::Params &consensusParams = Params().GetConsensus();
{
// First set fDisconnect if appropriate.
pto->DisconnectIfBanned();
// Check for an internal disconnect request and if true then set fDisconnect. This would typically happen
// during initial sync when a peer has a slow connection and we want to disconnect them. We want to then
// wait for any blocks that are still in flight before disconnecting, rather than re-requesting them again.
if (pto->fDisconnectRequest)
{
NodeId nodeid = pto->GetId();
int nInFlight = requester.GetNumBlocksInFlight(nodeid);
LOG(IBD, "peer %s, checking disconnect request with %d in flight blocks\n", pto->GetLogName(), nInFlight);
if (nInFlight == 0)
{
pto->fDisconnect = true;
LOG(IBD, "peer %s, disconnect request was set, so disconnected\n", pto->GetLogName());
}
}
// Now exit early if disconnecting or the version handshake is not complete. We must not send PING or other
// connection maintenance messages before the handshake is done.
if (pto->fDisconnect || !pto->fSuccessfullyConnected)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued)
{
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < (int64_t)GetStopwatchMicros())
{
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend)
{
uint64_t nonce = 0;
while (nonce == 0)
{
GetRandBytes((unsigned char *)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetStopwatchMicros();
pto->nPingNonceSent = nonce;
pto->PushMessage(NetMsgType::PING, nonce);
}
// Check to see if there are any thin type blocks in flight that have gone beyond the
// timeout interval. If so then we need to disconnect them so that the thintype data is nullified.
// We could null the associated data here but that would possibly cause a node to be banned later if
// the thin type block finally did show up, so instead we just disconnect this slow node.
thinrelay.CheckForDownloadTimeout(pto);
// Check for block download timeout and disconnect node if necessary. Does not require cs_main.
int64_t nNow = GetStopwatchMicros();
requester.DisconnectOnDownloadTimeout(pto, consensusParams, nNow);
// Address refresh broadcast
if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow)
{
AdvertiseLocal(pto);
pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
}
//
// Message: addr
//
if (pto->nNextAddrSend < nNow)
{
LOCK(pto->cs_vSend);
pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
std::vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
for (const CAddress &addr : pto->vAddrToSend)
{
if (!pto->addrKnown.contains(addr.GetKey()))
{
pto->addrKnown.insert(addr.GetKey());
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage(NetMsgType::ADDR, vAddr);
vAddr.clear();
}
}
}
if (!vAddr.empty())
pto->PushMessage(NetMsgType::ADDR, vAddr);
pto->vAddrToSend.clear();
}
CNodeState statem(CAddress(), "");
const CNodeState *state = &statem;
{
CNodeStateAccessor stateAccess(nodestate, pto->GetId());
if (state == nullptr)
{
return true;
}
statem = *stateAccess;
}
// If a sync has been started check whether we received the first batch of headers requested within the timeout
// period. If not then disconnect and ban the node and a new node will automatically be selected to start the
// headers download.
if ((state->fSyncStarted) && (state->nSyncStartTime < GetTime() - INITIAL_HEADERS_TIMEOUT) &&
(!state->fFirstHeadersReceived) && !pto->fWhitelisted)
{
// pto->fDisconnect = true;
LOGA("Initial headers were either not received or not received before the timeout\n", pto->GetLogName());
}
// Start block sync
if (pindexBestHeader == nullptr)
pindexBestHeader = chainActive.Tip();
// Download if this is a nice peer, or we have no nice peers and this one might do.
bool fFetch = state->fPreferredDownload || (nPreferredDownload.load() == 0 && !pto->fOneShot);
if (!state->fSyncStarted && !fImporting && !fReindex)
{
// Only allow the downloading of headers from a single pruned peer.
static int nSyncStartedPruned = 0;
if (pto->fClient && nSyncStartedPruned >= 1)
fFetch = false;
// Only actively request headers from a single peer, unless we're close to today.
if ((nSyncStarted < MAX_HEADER_REQS_DURING_IBD && fFetch) ||
chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - SINGLE_PEER_REQUEST_MODE_AGE)
{
const CBlockIndex *pindexStart = chainActive.Tip();
/* If possible, start at the block preceding the currently
best known header. This ensures that we always get a
non-empty list of headers back as long as the peer
is up-to-date. With a non-empty response, we can initialise
the peer's known best block. This wouldn't be possible
if we requested starting at pindexBestHeader and
got back an empty response. */
if (pindexStart->pprev)
pindexStart = pindexStart->pprev;
// BU Bug fix for Core: Don't start downloading headers unless our chain is shorter
if (pindexStart->nHeight < pto->nStartingHeight)
{
CNodeStateAccessor modableState(nodestate, pto->GetId());
modableState->fSyncStarted = true;
modableState->nSyncStartTime = GetTime();
modableState->fRequestedInitialBlockAvailability = true;
modableState->nFirstHeadersExpectedHeight = pindexStart->nHeight;
nSyncStarted++;
if (pto->fClient)
nSyncStartedPruned++;
LOG(NET, "initial getheaders (%d) to peer=%s (startheight:%d)\n", pindexStart->nHeight,
pto->GetLogName(), pto->nStartingHeight);
pto->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256());
}
}
}
// During IBD and when a new NODE_NETWORK peer connects we have to ask for if it has our best header in order
// to update our block availability. We only want/need to do this only once per peer (if the initial batch of
// headers has still not been etirely donwnloaded yet then the block availability will be updated during that
// process rather than here).
if (IsInitialBlockDownload() && !state->fRequestedInitialBlockAvailability &&
state->pindexBestKnownBlock == nullptr && !fReindex && !fImporting)
{
if (!pto->fClient)
{
CNodeStateAccessor(nodestate, pto->GetId())->fRequestedInitialBlockAvailability = true;
// We only want one single header so we pass a null CBlockLocator.
pto->PushMessage(NetMsgType::GETHEADERS, CBlockLocator(), pindexBestHeader.load()->GetBlockHash());
LOG(NET | BLK, "Requesting header for initial blockavailability, peer=%s block=%s height=%d\n",
pto->GetLogName(), pindexBestHeader.load()->GetBlockHash().ToString(),
pindexBestHeader.load()->nHeight);
}
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex && !fImporting && !IsInitialBlockDownload())
{
GetMainSignals().Broadcast(nTimeBestReceived.load());
}
//
// Try sending block announcements via headers
//
{
// If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
// list of block hashes we're relaying, and our peer wants
// headers announcements, then find the first header
// not yet known to our peer but would connect, and send.
// If no header would connect, or if we have too many
// blocks, or if the peer doesn't want headers, just
// add all to the inv queue.
std::vector<uint256> vBlocksToAnnounce;
{
// Make a copy so that we do not need to keep
// cs_inventory which cannot be taken before cs_main.
LOCK(pto->cs_inventory);
vBlocksToAnnounce.swap(pto->vBlockHashesToAnnounce);
}
std::vector<CBlock> vHeaders;
bool fRevertToInv = (!state->fPreferHeaders || vBlocksToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
// Ensure pindexBestKnownBlock is up-to-date
requester.ProcessBlockAvailability(pto->id);
if (!fRevertToInv)
{
bool fFoundStartingHeader = false;
// Try to find first header that our peer doesn't have, and
// then send all headers past that one. If we come across any
// headers that aren't on chainActive, give up.
for (const uint256 &hash : vBlocksToAnnounce)
{
CBlockIndex *pindex = nullptr;
pindex = LookupBlockIndex(hash);
// Skip blocks that we don't know about.
if (!pindex)
continue;
if (pBestIndex != nullptr && pindex->pprev != pBestIndex)
{
// This means that the list of blocks to announce don't
// connect to each other.
// This shouldn't really be possible to hit during
// regular operation (because reorgs should take us to
// a chain that has some block not on the prior chain,
// which should be caught by the prior check), but one
// way this could happen is by using invalidateblock /
// reconsiderblock repeatedly on the tip, causing it to
// be added multiple times to vBlocksToAnnounce.
// Robustly deal with this rare situation by reverting
// to an inv.
fRevertToInv = true;
break;
}
pBestIndex = pindex;
if (fFoundStartingHeader)
{
// add this to the headers message
vHeaders.push_back(pindex->GetBlockHeader());
}
else if (PeerHasHeader(state, pindex))
{
continue; // keep looking for the first new block
}
else if (pindex->pprev == nullptr || PeerHasHeader(state, pindex->pprev))
{
// Peer doesn't have this header but they do have the prior one.
// Start sending headers.
fFoundStartingHeader = true;
vHeaders.push_back(pindex->GetBlockHeader());
}
else
{
// Peer doesn't have this header or the prior one -- nothing will
// connect, so bail out.
fRevertToInv = true;
break;
}
}
}
if (fRevertToInv)
{
// If falling back to using an inv, just try to inv the tip.
// The last entry in vBlocksToAnnounce was our tip at some point
// in the past.
if (!vBlocksToAnnounce.empty())
{
for (const uint256 &hashToAnnounce : vBlocksToAnnounce)
{
CBlockIndex *pindex = nullptr;
pindex = LookupBlockIndex(hashToAnnounce);
// Skip blocks that we don't know about.
if (!pindex)
continue;
// If the peer announced this block to us, don't inv it back.
// (Since block announcements may not be via inv's, we can't solely rely on
// setInventoryKnown to track this.)
if (!PeerHasHeader(state, pindex))
{
pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
LOG(NET, "%s: sending inv peer=%d hash=%s\n", __func__, pto->id, hashToAnnounce.ToString());
}
}
}
}
else if (!vHeaders.empty())
{
if (vHeaders.size() > 1)
{
LOG(NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__, vHeaders.size(),
vHeaders.front().GetHash().ToString(), vHeaders.back().GetHash().ToString(), pto->id);
}
else
{
LOG(NET, "%s: sending header %s to peer=%d\n", __func__, vHeaders.front().GetHash().ToString(),
pto->id);
}
{
LOCK(pto->cs_vSend);
pto->PushMessage(NetMsgType::HEADERS, vHeaders);
}
CNodeStateAccessor(nodestate, pto->GetId())->pindexBestHeaderSent = pBestIndex;
}
}
//
// Message: inventory
//
// We must send all INV's before returning otherwise, under very heavy transaction rates, we could end up
// falling behind in sending INV's and vInventoryToSend could possibly get quite large.
bool haveInv2Send = false;
{
LOCK(pto->cs_inventory);
haveInv2Send = !pto->vInventoryToSend.empty();
}
if (haveInv2Send)
{
std::vector<CInv> vInvSend;
FastRandomContext rnd;
while (1)
{
// Send message INV up to the MAX_INV_TO_SEND. Once we reach the max then send the INV message
// and if there is any remaining it will be sent on the next iteration until vInventoryToSend is empty.
int nToErase = 0;
{
// BU - here we only want to forward message inventory if our peer has actually been requesting
// useful data or giving us useful data. We give them 2 minutes to be useful but then choke off
// their inventory. This prevents fake peers from connecting and listening to our inventory
// while providing no value to the network.
// However we will still send them block inventory in the case they are a pruned node or wallet
// waiting for block announcements, therefore we have to check each inv in pto->vInventoryToSend.
bool fChokeTxInv =
(pto->nActivityBytes == 0 && (GetStopwatchMicros() - pto->nStopwatchConnected) > 120 * 1000000);
// Find INV's which should be sent, save them to vInvSend, and then erase from vInventoryToSend.
LOCK(pto->cs_inventory);
int invsz = std::min((int)pto->vInventoryToSend.size(), MAX_INV_TO_SEND);
vInvSend.reserve(invsz);
for (const CInv &inv : pto->vInventoryToSend)
{
nToErase++;
if (inv.type == MSG_TX)
{
if (fChokeTxInv)
continue;
// randomly don't inv but always send inventory to spv clients
if (((rnd.rand32() % 100) < randomlyDontInv.Value()) && !pto->fClient)
continue;
// skip if we already know about this one
if (pto->filterInventoryKnown.contains(inv.hash))
continue;
}
vInvSend.push_back(inv);
pto->filterInventoryKnown.insert(inv.hash);
if (vInvSend.size() >= MAX_INV_TO_SEND)
break;
}
if (nToErase > 0)
{
pto->vInventoryToSend.erase(
pto->vInventoryToSend.begin(), pto->vInventoryToSend.begin() + nToErase);
}
else // exit out of the while loop if nothing was done
{
break;
}
}
// To maintain proper locking order we have to push the message when we do not hold cs_inventory which
// was held in the section above.
if (nToErase > 0)
{
LOCK(pto->cs_vSend);
if (!vInvSend.empty())
{
pto->PushMessage(NetMsgType::INV, vInvSend);
vInvSend.clear();
}
}
}
}
// If the chain is not entirely sync'd then look for new blocks to download.
//
// Also check an edge condition, where we've invalidated a chain and set the pindexBestHeader to the
// new most work chain, as a result we may end up just connecting whatever blocks are in setblockindexcandidates
// resulting in pindexBestHeader equalling the chainActive.Tip() causing us to stop checking for more blocks to
// download (our chain will now not sync until the next block announcement is received). Therefore, if the
// best invalid chain work is still greater than our chaintip then we have to keep looking for more blocks
// to download.
//
// Use temporaries for the chain tip and best invalid because they are both atomics and either could
// be nullified between the two calls.
CBlockIndex *pTip = chainActive.Tip();
CBlockIndex *pBestInvalid = pindexBestInvalid.load();
if (!IsChainSyncd() || (pBestInvalid && pTip && pBestInvalid->nChainWork > pTip->nChainWork))
{
TRY_LOCK(cs_main, locked);
if (locked)
{ // I don't need to deal w/ blocks as often as tx and this is time consuming
// Request the next blocks. Mostly this will get executed during IBD but sometimes even
// when the chain is syncd a block will get request via this method.
requester.RequestNextBlocksToDownload(pto);
}
}
}
return true;
}
| 42.746992 | 120 | 0.546526 | [
"object",
"vector"
] |
e9b70731b2ea0f873d88b357f173ea48f1fea3c3 | 2,004 | cpp | C++ | DemoProject/FarmGame/Chicken.cpp | spywhere/Legacy-ParticlePlay | 0c1ec6e4706f72b64e0408cc79cdeffce535b484 | [
"BSD-3-Clause"
] | null | null | null | DemoProject/FarmGame/Chicken.cpp | spywhere/Legacy-ParticlePlay | 0c1ec6e4706f72b64e0408cc79cdeffce535b484 | [
"BSD-3-Clause"
] | null | null | null | DemoProject/FarmGame/Chicken.cpp | spywhere/Legacy-ParticlePlay | 0c1ec6e4706f72b64e0408cc79cdeffce535b484 | [
"BSD-3-Clause"
] | null | null | null | #include "Chicken.hpp"
#include <iostream>
#include <cmath>
const double PI = std::acos(-1);
Chicken::Chicken(Spritesheet* spritesheet, int startX, int startY) : Entity(spritesheet, startX, startY){
this->spritesheet = new Spritesheet(spritesheet->GetSheet(), 16, 16, 3.5f);
this->angle = 180;
}
void Chicken::Render(ppGraphics* graphics){
int xTile = 0;
SDL_RendererFlip flip = ppImage::NO_FLIP;
int offsetY = 0;
if(this->GetDirection() > 0){
if(this->GetDirection() == 2){
flip = (SDL_RendererFlip)(flip | ppImage::FLIP_HORIZONTAL);
}
if((this->GetPositionX()+this->GetPositionY())%25 > 12){
xTile += 1;
offsetY += 3;
}
}else{
xTile = 2;
if((this->GetPositionX()+this->GetPositionY())%25 > 12){
xTile += 1;
}
}
Tile *entityTile = this->spritesheet->GetTile(xTile, 14);
if(this->inWater){
entityTile->SetClip(1.0f, 0.5f);
offsetY += 20;
}
entityTile->Render(graphics, this->GetPositionX()-entityTile->GetWidth()/2, offsetY+this->GetPositionY()-entityTile->GetHeight()/2, flip);
}
void Chicken::Update(ppInput* input, int delta){
Entity::Update(input, delta);
ppRandomizer* randomizer = input->GetGame()->GetRandomizer();
if(randomizer->NextInt(1000) < 1){
ppGenericSound* sound = input->GetGame()->GetInteractiveMusicSystem()->GetSound(this->soundName);
if(sound && sound->IsStop()){
sound->Play();
}
}
this->angle += randomizer->NextInt(-5, 5);
this->angle %= 360;
if(this->GetPositionY() < 20 && std::cos(this->angle/180.0f*PI) < 0){
this->angle += 180;
}else if(this->GetPositionY() >= input->GetGame()->GetHeight()-20 && std::cos(this->angle/180.0f*PI) > 0){
this->angle += 180;
}else if(this->GetPositionX() < 20 && std::sin(this->angle/180.0f*PI) < 0){
this->angle += 180;
}else if(this->GetPositionX() >= input->GetGame()->GetWidth()-20 && std::sin(this->angle/180.0f*PI) > 0){
this->angle += 180;
}
this->MoveY((int)(std::cos(this->angle/180.0f*PI)*2.0f));
this->MoveX((int)(std::sin(this->angle/180.0f*PI)*2.0f));
}
| 31.809524 | 139 | 0.653194 | [
"render"
] |
e9c52f92560cb69571ac9c513882815699fdd83e | 30,138 | cpp | C++ | micromouse2014/micromouse2014/Maze.cpp | CarltonSemple/MicroMouse | 3b28f90ff277395a67f20dc7a6ff6dccadaed9e4 | [
"MIT"
] | null | null | null | micromouse2014/micromouse2014/Maze.cpp | CarltonSemple/MicroMouse | 3b28f90ff277395a67f20dc7a6ff6dccadaed9e4 | [
"MIT"
] | null | null | null | micromouse2014/micromouse2014/Maze.cpp | CarltonSemple/MicroMouse | 3b28f90ff277395a67f20dc7a6ff6dccadaed9e4 | [
"MIT"
] | null | null | null | #include "Maze.h"
namespace Data
{
static int openings = 0;
/// <summary>
/// Method find
/// This method checks to see if Location loc
/// exists in the current vector of Locations
/// that contains the candidates for a new
/// Room object.
/// </summary>
int Maze::find(Location * loc)
{
for (unsigned int i = 0; i < opening_locations.size(); i++)
if (opening_locations[i]->x == loc->x && opening_locations[i]->y == loc->y)
return i;
return -1;
}
/// <summary>
/// Method clearMaze
/// This method clears the maze and initializes
/// the grid.
/// </summary>
void Maze::clearMaze()
{
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
maze[i][j] = new Room(-1, i, j);
}
/*
Clear the boolean checked values for all of the rooms. reset to an empty map
*/
void Maze::clearChecked()
{
for (int o = 0; o < 16; o++)
for (int i = 0; i < 16; i++)
maze[o][i]->checked.clear();
}
void Maze::resetBreadthHeuristics()
{
for (int o = 0; o < 16; o++)
for (int i = 0; i < 16; i++)
maze[o][i]->set_breadth_heuristic(std::numeric_limits<int>::max());
}
/// <summary>
/// Method cleanMaze
/// This method is called after makeMaze() and will
/// clean up the maze by removing all closed off rooms
/// as well as all open 2x2 instances that occur that
/// are not in the center of the maze.
/// </summary>
void Maze::cleanMaze()
{
// This will remove all chunks of empty rooms
clearEmptyRooms();
// This will remove all 2x2 instances
clearPillars();
}
void Maze::clearPillars()
{
Room *topLeft, *topRight, *bottomLeft, *bottomRight;
for (int i = 0; i < dimensions - 1; i++) // rows
{
for (int j = 0; j < dimensions - 1; j++) // columns
{
if (i == 7 && j == 7)
continue;
topLeft = maze[i][j];
topRight = maze[i][j + 1];
bottomLeft = maze[i + 1][j];
bottomRight = maze[i + 1][j + 1];
if (!topLeft->getOpenings()[2] && !topRight->getOpenings()[0] && !bottomLeft->getOpenings()[2] && !bottomRight->getOpenings()[0] &&
!topLeft->getOpenings()[1] && !topRight->getOpenings()[1] && !bottomLeft->getOpenings()[3] && !bottomRight->getOpenings()[3])
{
int random = rand() % 4;
if (random == 0) // generate wall on left
{
maze[i][j]->setWall(1, true);
maze[i + 1][j]->setWall(3, true);
}
else if (random == 1) // generate wall on bottom
{
maze[i + 1][j]->setWall(2, true);
maze[i + 1][j + 1]->setWall(0, true);
}
else if (random == 2) // generate wall on right side
{
maze[i + 1][j + 1]->setWall(3, true);
maze[i][j + 1]->setWall(1, true);
}
else if (random == 3) // generate wall on top side
{
maze[i][j]->setWall(2, true);
maze[i][j + 1]->setWall(0, true);
}
}
}
}
}
void Maze::clearEmptyRooms()
{
std::vector<Room*> rooms;
Room* room;
for (int i = 0; i < dimensions; i++)
{
for (int j = 0; j < dimensions; j++)
{
room = maze[i][j];
if (room->getPassages() == 0)
{
rooms = getAdjacentRooms(i, j);
int random = rand() % 4;
int x = 0, y = 0;
while (true)
{
while (rooms[random]->getPassages() == 0)
random = rand() % 4;
x = rooms[random]->Location().x;
y = rooms[random]->Location().y;
if ((x != 7 && x != 8) || (y != 7 && y != 8))
break;
else
random = rand() % 4;
}
maze[x][y]->setWall((random > 1) ? random - 2 : random + 2, false);
maze[i][j]->setWall(random, false);
rooms.clear();
}
}
}
}
/// <summary>
/// Method setWallParents
/// This method is called after cleanMaze(). This
/// method will go through the generated rooms and
/// assign the second parent of each wall. I do this
/// after the creation of the maze because if you
/// try to implement it during the creation, some
/// parents may be lost, and/or it would require
/// much complexity to add the parents dynamically.
/// </summary>
void Maze::setWallParents()
{
Room *Current, *Left, *Right, *Top, *Bottom;
for (int i = 0; i < dimensions; i++) // rows
{
for (int j = 0; j < dimensions; j++) // columns
{
Current = maze[i][j];
Left = Right = Top = Bottom = nullptr;
if (j == 0) // left side
{
if (i != 0) // not top left corner
Top = maze[i - 1][j];
Right = maze[i][j + 1];
if (i != dimensions - 1) // not top right corner
Bottom = maze[i + 1][j];
}
else if (j == dimensions - 1) // right side
{
if (i != 0) // not top left corner
Top = maze[i - 1][j];
Left = maze[i][j - 1];
if (i != dimensions - 1) // not top right corner
Bottom = maze[i + 1][j];
}
else // top,bottom,middle
{
Left = maze[i][j - 1];
Right = maze[i][j + 1];
if (i == 0) // top, but not corners
Bottom = maze[i + 1][j];
else if (i == dimensions - 1) // bottom, but not corners
Top = maze[i - 1][j];
else // middle of maze
{
Top = maze[i - 1][j];
Bottom = maze[i + 1][j];
}
}
if (Left != nullptr) // Room to the left
Left->getWalls()[2]->setParent(1, Current);
if (Right != nullptr) // Room to the right
Right->getWalls()[0]->setParent(1, Current);
if (Top != nullptr)
Top->getWalls()[1]->setParent(1, Current);
if (Bottom != nullptr)
Bottom->getWalls()[3]->setParent(1, Current);
}
}
// clean up..
for (int i = 0; i < dimensions; i++) // rows
{
for (int j = 0; j < dimensions; j++) // columns
{
Current = maze[i][j];
Right = (j != dimensions - 1) ? maze[i][j + 1] : nullptr;
Bottom = (i != dimensions - 1) ? maze[i + 1][j] : nullptr;
if (Right != nullptr) // Room to the right
Right->getWalls()[0] = Current->getWalls()[2];
if (Bottom != nullptr)
Bottom->getWalls()[3] = Current->getWalls()[1];
}
}
}
/// <summary>
/// Method makeMaze
/// This method is called after initMaze() and will
/// generate the remainder of the grid based on the
/// rooms that were initialized in initMaze().
/// </summary>
void Maze::makeMaze()
{
Location* loc; // a Location (X,Y) object, used for locating open rooms
Room* r; // a Room object, used for generating rooms to put in grid
int choice = -1; // decides which room to make
// Diregard lastX and lastY; they're here to determine which room
// was generated last. Variables X and Y refer to the current location
// being looked at as a candidate for a new room. Variable currentLocSize
// is a dummy variable to hold the size of the vector containing all of
// the valid locations to put a room. This changes within the loop and
// therefore needs to be stored in a temporary variable.
int X = 0, Y = 0, currentLocSize = 0;
// Variable iterations is a safety; if anything goes wrong, iterations
// will tell the program to retry.
int iterations = 0;
// while the maze isn't full..
while (rooms < dimensions*dimensions && openings > 0)
{
iterations++;
if (iterations > dimensions*dimensions)
{
// realistically, this number should never be
// reached if there are no errors because multiple
// rooms are being created in each iteration.
rooms = 0;
initMaze();
makeMaze();
return;
}
// set the temporary variable
currentLocSize = opening_locations.size();
for (int j = 0; j < currentLocSize; j++) // how many spots have openings
{
// get the current candidate for a new room
X = opening_locations[j]->x;
Y = opening_locations[j]->y;
choice = getChoice(X, Y); // decide which room to make
r = new Room(choice, X, Y); // make the room
rooms++; // increment number of rooms
openings += r->getPassages() - getNumberOfAdjacentRooms(X, Y) * 2; // update the amounts of pathways remaining in grid
maze[X][Y] = r; // add the room to the grid
// Check all four sides of new rooms and find the
// existing rooms around it as well as the spots
// that would be candidates for a new room. I
// have the initial if statement to avoid IndexOutOfBounds
// errors.
if (X - 1 >= 0) // check above
if (maze[X - 1][Y]->getPassages() == 0)
if (maze[X][Y]->getOpenings()[3] == 0)
{
loc = new Location(X - 1, Y);
if (find(loc) == -1)
opening_locations.push_back(loc);
}
if (X + 1 < dimensions) // check below
if (maze[X + 1][Y]->getPassages() == 0)
if (maze[X][Y]->getOpenings()[1] == 0)
{
loc = new Location(X + 1, Y);
if (find(loc) == -1)
opening_locations.push_back(loc);
}
if (Y - 1 >= 0) // check left
if (maze[X][Y - 1]->getPassages() == 0)
if (maze[X][Y]->getOpenings()[0] == 0)
{
loc = new Location(X, Y - 1);
if (find(loc) == -1)
opening_locations.push_back(loc);
}
if (Y + 1 < dimensions) // check right
if (maze[X][Y + 1]->getPassages() == 0)
if (maze[X][Y]->getOpenings()[2] == 0)
{
loc = new Location(X, Y + 1);
if (find(loc) == -1)
opening_locations.push_back(loc);
}
}
for (int j = 0; j < currentLocSize; j++)
opening_locations.pop_front();
}
cleanMaze();
setWallParents();
}
/// <summary>
/// Method initMaze
/// This method will initialze a new maze, clearing
/// any old information and resetting the random seed
/// to ensure each maze is (most likely) different
/// from the last. It also creates the four corners
/// and four middle rooms.
/// </summary>
void Maze::initMaze()
{
srand(time(NULL));
current = new Location(-1, -1);
// clears/initializes maze
clearMaze();
if (dimensions != 16)
return;
Room* r;
/******CENTER ROOMS******/
// use choice to randomly choose which center 4 rooms to make
// There are 8 possible combinations..
// *NOTE: options go 0-7, although below they are labeled 1-8
int random = rand() % 8;
/******OPTIONS******/
// OPTION 1:
// opening on left-bottom
//
// OPTION 2:
// opening left-top
//
// OPTION 3:
// opening top-left
//
// OPTION 4:
// opening top-right
//
// OPTION 5:
// opening on right-top
//
// OPTION 6:
// opening right-bottom
//
// OPTION 7:
// opening bottom-right
//
// OPTION 8:
// opening bottom-left
/*******************/
// using random, make each room individually as opposed to 4 separate set ups..
// top left room
if (random != 1 && random != 2) // all choices besides 1 and 2 are the same for top left..
r = new Room(9, 7, 7); // left and top are walls
else if (random == 1)
{
r = new Room(5, 7, 7); // top is a wall
opening_locations.push_back(new Location(7, 6));
}
else // random = 2
{
r = new Room(2, 7, 7); // left is a wall
opening_locations.push_back(new Location(6, 7));
}
rooms++;
maze[7][7] = r;
goal[0] = r;
// top right room
if (random != 3 && random != 4) // all choices besides 3 and 4 are the same for top right..
r = new Room(11, 7, 8); // right and top are walls
else if (random == 3)
{
r = new Room(4, 7, 8); // right is a wall
opening_locations.push_back(new Location(6, 8));
}
else // random = 4
{
r = new Room(5, 7, 8); // top is a wall
opening_locations.push_back(new Location(7, 9));
}
rooms++;
maze[7][8] = r;
goal[1] = r;
// bottom right room
if (random != 5 && random != 6) // all choices besides 5 and 6 are the same for bottom right..
r = new Room(7, 8, 8); // right and bottom are walls
else if (random == 5)
{
r = new Room(3, 8, 8); // bottom is a wall
opening_locations.push_back(new Location(8, 9));
}
else // random = 6
{
r = new Room(4, 8, 8); // right is a wall
opening_locations.push_back(new Location(9, 8));
}
rooms++;
maze[8][8] = r;
goal[2] = r;
// bottom left room
if (random != 7 && random != 0) // all choices besides 7 and 0 are the same for bottom left..
r = new Room(6, 8, 7); // left and bottom are walls
else if (random == 7)
{
r = new Room(2, 8, 7); // left is a wall
opening_locations.push_back(new Location(9, 7));
}
else // random = 0
{
r = new Room(3, 8, 7); // bottom is a wall
opening_locations.push_back(new Location(8, 6));
}
rooms++;
maze[8][7] = r;
goal[3] = r;
/******CORNER ROOMS******/
// top left
r = new Room(getChoice(0, 0), 0, 0);
rooms++;
maze[0][0] = r;
if (!maze[0][0]->getOpenings()[1])
opening_locations.push_back(new Location(1, 0));
if (!maze[0][0]->getOpenings()[2])
opening_locations.push_back(new Location(0, 1));
// top right
r = new Room(getChoice(0, dimensions - 1), 0, dimensions - 1);
rooms++;
maze[0][dimensions - 1] = r;
if (!maze[0][dimensions - 1]->getOpenings()[0])
opening_locations.push_back(new Location(1, dimensions - 1));
if (!maze[0][dimensions - 1]->getOpenings()[1])
opening_locations.push_back(new Location(0, dimensions - 2));
// bottom right
r = new Room(getChoice(dimensions - 1, dimensions - 1), dimensions - 1, dimensions - 1);
rooms++;
maze[dimensions - 1][dimensions - 1] = r;
if (!maze[dimensions - 1][dimensions - 1]->getOpenings()[0])
opening_locations.push_back(new Location(dimensions - 1, dimensions - 2));
if (!maze[dimensions - 1][dimensions - 1]->getOpenings()[3])
opening_locations.push_back(new Location(dimensions - 2, dimensions - 1));
// bottom left
r = new Room(getChoice(dimensions - 1, 0), dimensions - 1, 0);
rooms++;
maze[dimensions - 1][0] = r;
if (!maze[dimensions - 1][0]->getOpenings()[2])
opening_locations.push_back(new Location(dimensions - 1, 1));
if (!maze[dimensions - 1][0]->getOpenings()[3])
opening_locations.push_back(new Location(dimensions - 2, 0));
openings = opening_locations.size();
random = rand() % 4;
if (random == 0) // start in top left corner
{
start = new Location(0, 0); direction = Direction::Right;
}
else if (random == 1) // start in top right corner
{
start = new Location(0, dimensions - 1); direction = Direction::Left;
}
else if (random == 2) // start in bottom right corner
{
start = new Location(dimensions - 1, dimensions - 1); direction = Direction::Left;
}
else // start in bottom left corner
{
start = new Location(dimensions - 1, 0); direction = Direction::Right;
}
current = new Location(start->x, start->y);
}
/// <summary>
/// Method getAdjacentRooms
/// This method is returns the number of rooms directly
/// connected to the given location. This can be modified
/// to return the actual Room objects if needed..
/// </summary>
int Maze::getNumberOfAdjacentRooms(int x, int y)
{
int total = 0;
if (x - 1 >= 0) // check above
if (maze[x - 1][y]->getPassages() != 0 && maze[x - 1][y]->getOpenings()[1] == 0)
total++;
if (x + 1 < dimensions) // check below
if (maze[x + 1][y]->getPassages() != 0 && maze[x + 1][y]->getOpenings()[3] == 0)
total++;
if (y - 1 >= 0) // check left
if (maze[x][y - 1]->getPassages() != 0 && maze[x][y - 1]->getOpenings()[2] == 0)
total++;
if (y + 1 < dimensions) // check right
if (maze[x][y + 1]->getPassages() != 0 && maze[x][y + 1]->getOpenings()[0] == 0)
total++;
return total;
}
std::vector<Room*> Maze::getAdjacentRooms(int x, int y)
{
std::vector<Room*> rooms;
int total = 0;
if (y - 1 >= 0) // check left
rooms.push_back(maze[x][y - 1]);
else
rooms.push_back(new Room());
if (x + 1 < dimensions) // check below
rooms.push_back(maze[x + 1][y]);
else
rooms.push_back(new Room());
if (y + 1 < dimensions) // check right
rooms.push_back(maze[x][y + 1]);
else
rooms.push_back(new Room());
if (x - 1 >= 0) // check above
rooms.push_back(maze[x - 1][y]);
else
rooms.push_back(new Room());
return rooms;
}
void clearTerminal()
{
// I suppose this works for now..
for (int i = 0; i < 10; i++)
std::cout << "\n\n\n\n\n";
}
/// <summary>
/// Method printMaze
/// This method prints out the maze in a nice fashion.
/// If the parameter is true, only known walls will be
/// printed, otherwise all walls will be printed.
/// </summary>
void Maze::printMaze(bool walls_hidden)
{
bool show = true;
Room* currentRoom;
char room[9];
std::vector<Wall*> walls(4);
// 3 "rows" = row; 3 "columns" = column
for (int i = 0; i < dimensions; i++) // rows
{
for (int k = 0; k < 3; k++) // "rows"
{
for (int j = 0; j < dimensions; j++) // columns
{
currentRoom = maze[i][j];
walls = currentRoom->getWalls();
memcpy(room, currentRoom->getRoom(), 9);
for (int m = 0; m < 3; m++) // "columns"
{
if (m == 1 && k == 1) // center square
{
//if (start->x == i && start->y == j) // start
// std::cout << "*";
if (current->x == i && current->y == j) // current location
{
// Print the direction. Will not appear humanly natural due to the nature of x=row y=column
switch (direction)
{
case Data::Left: std::cout << "^"; break;
case Data::Up: std::cout << ">"; break;
case Data::Right: std::cout << "V"; break;
case Data::Down: std::cout << "<"; break;
}
}
else if (currentRoom->getPassages() != 0)
std::cout << " ";
else
std::cout << room[m + (k * 3)];
}
else // walls
{
if (walls_hidden)
{
show = false;
if (k == 0) // left walls
{
if (walls[0]->known >= 0)
show = true;
}
else if (k == 2) // right walls
{
if (walls[2]->known >= 0)
show = true;
}
else if (m == 0) // top walls
{
if (walls[3]->known >= 0)
show = true;
}
else if (m == 2) // bottom walls
{
if (walls[1]->known >= 0)
show = true;
}
}
if (show)
std::cout << room[m + (k * 3)];
else
std::cout << " ";
}
}
}
if (k % 3 == 1)
std::cout << " " << i;
std::cout << std::endl;
}
}
// last row
for (int i = 0; i < dimensions; i++)
if (i < 10)
std::cout << " " << i << " ";
else
std::cout << " " << i;
std::cout << std::endl;
}
/// <summary>
/// Method printClean
/// Print a new empty line for the number of rows in the maze
/// </summary>
void Maze::printClean()
{
for (int i = 0; i < dimensions; i++)
std::cout << std::endl;
}
/// <summary>
/// Method getChoice
/// This method is where the algorithm decides which
/// room to generate based on the current location
/// and the rooms around the given location. The
/// number it returns is passed to a Room object
/// and in the Room constructor is where the initialization
/// of the actual Room object occurs. This can be modified
/// to simply return the Room object...
/// </summary>
int Maze::getChoice(int x, int y) // current X(row) value, current Y(column) value
{
std::vector<int> choices; // contains a list of possible rooms for each location (x,y)
int choice = -1; // the chosen room, to be returned
// Variables up, down, left, right determine whether or not
// the generated room MUST have an opening on a specific side.
// Variables roomUp, roomDown, roomLeft, roomRight state
// whether or not there is a room adjacent to the given location (x,y).
bool up = false, down = false, left = false, right = false; // true if there's an exit
bool roomUp = false, roomDown = false, roomLeft = false, roomRight = false; // true if room exists
// first if statements are to avoid IndexOutOfBounds errors
if (x - 1 >= 0) // check above
{
if (maze[x - 1][y]->getPassages() != 0) // room exists
{
roomUp = true;
if (!maze[x - 1][y]->getOpenings()[1])
up = true;
}
}
else
roomUp = true;
if (x + 1 < dimensions) // check below
{
if (maze[x + 1][y]->getPassages() != 0)
{
roomDown = true;
if (!maze[x + 1][y]->getOpenings()[3])
down = true;
}
}
else
roomDown = true;
if (y - 1 >= 0) // check left
{
if (maze[x][y - 1]->getPassages() != 0)
{
roomLeft = true;
if (!maze[x][y - 1]->getOpenings()[2])
left = true;
}
}
else
roomLeft = true;
if (y + 1 < dimensions) // check right
{
if (maze[x][y + 1]->getPassages() != 0)
{
roomRight = true;
if (!maze[x][y + 1]->getOpenings()[0])
right = true;
}
}
else
roomRight = true;
// *****************************************************************************
// which rooms can go where?
// This portion of code may seem long; however,
// it's broken down so that any case will only
// hit a maximum of 8 if statements before deciding
// on which rooms to add. The last case technically
// can allow for more if statements to occur, but
// that case is only accessed if you arbitrarily
// add a room, like in the initMaze method.
if (up) // up
{
if (down) // up,down
{
if (left) // up,down,left
{
if (right) // up,down,left,right
choices.push_back(1);
else // up,down,left,!right
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(4);
else
choices.push_back(1);
}
}
else // up,down,!left
{
if (right) // up,down,!left,right
{
if (roomLeft || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(2);
else
choices.push_back(1);
}
else // up,down,!left,!right
{
if (roomLeft)
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(8);
else
choices.push_back(2);
}
else
{
choices.push_back(4);
if (!roomRight)
{
choices.push_back(1);
choices.push_back(2);
}
}
}
}
}
else // up,!down
{
if (left) // up,!down,left
{
if (right) // up,!down,left,right
{
if (roomDown || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(3);
else
choices.push_back(1);
}
else // up,!down,left,!right
{
if (roomDown)
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(7);
else
choices.push_back(3);
}
else
{
choices.push_back(4);
if (!roomRight)
{
choices.push_back(1);
choices.push_back(3);
}
}
}
}
else // up,!down,!left
{
if (right) // up,!down,!left,right
{
if (roomDown)
{
if (roomLeft || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(6);
else
choices.push_back(3);
}
else
{
choices.push_back(2);
if (!roomLeft)
{
choices.push_back(1);
choices.push_back(3);
}
}
}
else // up,!down,!left,!right
{
if (roomDown)
{
if (roomLeft)
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(12);
else
choices.push_back(6);
}
else
{
choices.push_back(7);
if (!roomRight)
{
choices.push_back(3);
choices.push_back(6);
}
}
}
else
{
if (roomLeft)
{
choices.push_back(8);
if (!roomRight)
{
choices.push_back(2);
choices.push_back(6);
}
}
else
{
choices.push_back(4);
choices.push_back(7);
choices.push_back(8);
if (!roomRight)
{
choices.push_back(1);
choices.push_back(2);
choices.push_back(3);
choices.push_back(6);
}
}
}
}
}
}
}
else // !up
{
if (down) // !up,down
{
if (left) // !up,down,left
{
if (right) // !up,down,left,right
{
if (roomUp || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(5);
else
choices.push_back(1);
}
else // !up,down,left,!right
{
if (roomUp)
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(11);
else
choices.push_back(5);
}
else
{
choices.push_back(4);
if (!roomRight)
{
choices.push_back(1);
choices.push_back(5);
}
}
}
}
else // !up,down,!left
{
if (right) // !up,down,!left,right
{
if (roomUp)
{
if (roomLeft || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(9);
else
choices.push_back(5);
}
else
{
choices.push_back(2);
if (!roomLeft)
{
choices.push_back(1);
choices.push_back(5);
}
}
}
else // !up,down,!left,!right
{
if (roomUp)
{
if (roomLeft)
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(14);
else
choices.push_back(9);
}
else
{
choices.push_back(11);
if (!roomRight)
{
choices.push_back(5);
choices.push_back(9);
}
}
}
else
{
if (roomLeft)
{
choices.push_back(8);
if (!roomRight)
{
choices.push_back(2);
choices.push_back(9);
}
}
else
{
choices.push_back(4);
choices.push_back(8);
choices.push_back(11);
if (!roomRight)
{
choices.push_back(1);
choices.push_back(2);
choices.push_back(5);
choices.push_back(9);
}
}
}
}
}
}
else // !up,!down
{
if (left) // !up,!down,left
{
if (right) // !up,!down,left,right
{
if (roomUp)
{
if (roomDown || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(10);
else
choices.push_back(5);
}
else
{
choices.push_back(3);
if (!roomDown)
{
choices.push_back(1);
choices.push_back(5);
}
}
}
else // !up,!down,left,!right
{
if (roomUp)
{
if (roomDown)
{
if (roomRight || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(15);
else
choices.push_back(10);
}
else
{
choices.push_back(11);
if (!roomRight)
{
choices.push_back(5);
choices.push_back(10);
}
}
}
else
{
if (roomDown)
{
choices.push_back(7);
if (!roomRight)
{
choices.push_back(3);
choices.push_back(10);
}
}
else
{
choices.push_back(4);
choices.push_back(7);
choices.push_back(11);
if (!roomRight)
{
choices.push_back(1);
choices.push_back(3);
choices.push_back(5);
choices.push_back(10);
}
}
}
}
}
else // !up,!down,!left
{
if (right) // !up,!down,!left,right
{
if (roomUp)
{
if (roomDown)
{
if (roomLeft || (openings > 3 && rooms > dimensions*dimensions*(3.0 / 4.0)) || (rooms == dimensions*dimensions - 1))
choices.push_back(13);
else
choices.push_back(10);
}
else
{
choices.push_back(9);
if (!roomLeft)
{
choices.push_back(5);
choices.push_back(10);
}
}
}
else
{
if (roomDown)
{
choices.push_back(6);
if (!roomLeft)
{
choices.push_back(3);
choices.push_back(10);
}
}
else
{
choices.push_back(2);
choices.push_back(6);
choices.push_back(9);
if (!roomLeft)
{
choices.push_back(1);
choices.push_back(3);
choices.push_back(5);
choices.push_back(10);
}
}
}
}
else // !up,!down,!left,!right
{
if (x == 0 && y == 0) // top left
{
choices.push_back(9);
choices.push_back(13);
choices.push_back(14);
}
else if (x == 0 && y == dimensions - 1) // top right
{
choices.push_back(11);
choices.push_back(14);
choices.push_back(15);
}
else if (x == dimensions - 1 && y == 0) // bottom left
{
choices.push_back(6);
choices.push_back(12);
choices.push_back(13);
}
else if (x == dimensions - 1 && y == dimensions - 1) // bottom right
{
choices.push_back(7);
choices.push_back(12);
choices.push_back(15);
}
else // not a corner
{
for (int i = 1; i < 16; i++)
choices.push_back(i);
}
}
}
}
}
// As a safety; this statement should always
// be satisfied.
if (choices.size() > 0)
{
int rando = rand() % choices.size();
choice = choices[rando];
choices.clear();
}
return choice;
}
} | 25.758974 | 135 | 0.535238 | [
"object",
"vector"
] |
e9ca4865dbbc8eece8010210f1831352c6d5848f | 1,335 | hpp | C++ | src/Modules/ModuleManager.hpp | Hary309/hry-core | c6547983115d7a34711ce20607c359f4047ec61e | [
"MIT"
] | 8 | 2020-11-13T23:50:16.000Z | 2022-01-03T16:54:00.000Z | src/Modules/ModuleManager.hpp | Hary309/hry-core | c6547983115d7a34711ce20607c359f4047ec61e | [
"MIT"
] | 1 | 2021-01-28T01:56:30.000Z | 2021-04-07T21:45:52.000Z | src/Modules/ModuleManager.hpp | Hary309/hry-core | c6547983115d7a34711ce20607c359f4047ec61e | [
"MIT"
] | 2 | 2021-05-30T18:42:20.000Z | 2021-07-04T09:04:34.000Z | /**
* This file is part of the hry-core project
* @ Author: Piotr Krupa <piotrkrupa06@gmail.com>
* @ License: MIT License
*/
#pragma once
#include <filesystem>
#include <memory>
#include <string>
#include <vector>
#include "Hry/Namespace.hpp"
#include "Hry/SCSSDK/Telemetry.hpp"
#include "Config/ConfigManager.hpp"
#include "Events/EventManager.hpp"
#include "KeyBinding/KeyBindsManager.hpp"
#include "Module.hpp"
HRY_NS_BEGIN
class ModuleManager
{
private:
inline static constexpr auto PluginListFileName = "/plugins.json";
private:
bool _firstInit = true;
std::vector<std::unique_ptr<Module>> _modules;
EventManager& _eventMgr;
ConfigManager& _configMgr;
KeyBindsManager& _keyBindsMgr;
const Telemetry& _telemetry;
std::string _pluginListFilePath;
public:
ModuleManager(
EventManager& eventMgr,
ConfigManager& configMgr,
KeyBindsManager& keyBindsMgr,
const Telemetry& telemetry);
~ModuleManager();
void init();
void scan();
void loadAll();
void unloadAll();
bool load(Module* mod);
void unload(Module* mod);
[[nodiscard]] const auto& getModules() const { return _modules; }
private:
void saveListToFile();
void loadListFromFile();
Module* tryAdd(const std::filesystem::path& path);
};
HRY_NS_END
| 18.802817 | 70 | 0.692135 | [
"vector"
] |
e9cfbb2de074d8e057a62ff732bc92f9fd721a87 | 2,927 | cpp | C++ | Client/CSQImages.cpp | Sladernimo/lhmp-old | 92944fc812c27449cacbb8822d34597f9da07ca4 | [
"Apache-2.0"
] | 8 | 2017-02-13T13:29:39.000Z | 2022-01-12T17:12:04.000Z | Client/CSQImages.cpp | Sladernimo/lhmp-old | 92944fc812c27449cacbb8822d34597f9da07ca4 | [
"Apache-2.0"
] | null | null | null | Client/CSQImages.cpp | Sladernimo/lhmp-old | 92944fc812c27449cacbb8822d34597f9da07ca4 | [
"Apache-2.0"
] | 10 | 2017-01-14T09:41:06.000Z | 2021-10-10T00:02:32.000Z | // (C) LHMP Team 2013-2016; Licensed under Apache 2; See LICENSE;;
#include "CCore.h"
#include "CSQImages.h"
extern CCore* g_CCore;
CSQImage::CSQImage(char* _in_textureName)
{
strcpy(this->textureName, _in_textureName);
this->LoadTexture();
this->referenceCount = 1;
}
CSQImage::~CSQImage()
{
// TODO delete texture
}
LPDIRECT3DTEXTURE8 CSQImage::GetTexture()
{
return this->texture;
}
char* CSQImage::GetImageName()
{
return this->textureName;
}
// intern things
void CSQImage::OnLostDevice()
{
// if exists, release it
if(this->texture)
this->texture->Release();
}
void CSQImage::OnResetDevice()
{
// reload it
this->LoadTexture();
}
void CSQImage::SetRefCount(unsigned short newCount)
{
this->referenceCount = newCount;
}
unsigned short CSQImage::GetRefCount()
{
return this->referenceCount;
}
void CSQImage::LoadTexture()
{
if (D3DXCreateTextureFromFileExA(g_CCore->GetGraphics()->GetDevice(), this->textureName, D3DX_DEFAULT, D3DX_DEFAULT,
1, 0, D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT, D3DX_FILTER_LINEAR,
D3DX_FILTER_LINEAR, 0x10000000,
NULL, NULL, &this->texture) != D3D_OK)
{
this->texture = NULL;
}
}
//-------------------------------------------------------------------------
CSQImages::CSQImages()
{
// clear all slots
for (int i = 0; i < MAX_TEXTURES; i++)
{
this->pool[i] = NULL;
}
}
CSQImage* CSQImages::createTexture(char* textureName)
{
int firstOne = -1;
// check whether texture exists or find a fist free texture
for (int i = 0; i < MAX_TEXTURES; i++)
{
if (pool[i] != NULL)
{
if (strcmp(textureName, pool[i]->GetImageName()) == 0)
{
// if object already exists, increase ref count
pool[i]->SetRefCount(pool[i]->GetRefCount() + 1);
// and return the same handle
return pool[i];
}
}
else {
if (firstOne == -1)
{
firstOne = i;
}
}
}
// if there is an empty slot
if (firstOne != -1)
{
pool[firstOne] = new CSQImage(textureName);
// if texture loading has failed (bad image)
if (pool[firstOne]->GetTexture() == NULL)
{
// delete and return NULL
delete pool[firstOne];
return NULL;
}
return pool[firstOne];
}
// in the end, if we haven't been successful, return NULL
return NULL;
}
void CSQImages::deleteTexture(CSQImage* deletedImage)
{
for (int i = 0; i < MAX_TEXTURES; i++)
{
if (pool[i] == deletedImage)
{
if (pool[i]->GetRefCount() > 1)
{
// if it has multiple references, decrease the references count
pool[i]->SetRefCount(pool[i]->GetRefCount() -1);
}
else {
delete pool[i];
pool[i] = NULL;
}
return;
}
}
}
// Called by game on device lost
void CSQImages::OnLostDevice()
{
for (int i = 0; i < MAX_TEXTURES; i++)
{
if (pool[i] != NULL)
{
pool[i]->OnLostDevice();
}
}
}
// Called by game
void CSQImages::OnResetDevice()
{
for (int i = 0; i < MAX_TEXTURES; i++)
{
if (pool[i] != NULL)
{
pool[i]->OnResetDevice();
}
}
}
| 19.130719 | 117 | 0.629997 | [
"object"
] |
839643a0a27afa732a435e34d500527ac0399a51 | 2,319 | cpp | C++ | tcm/src/v20210413/model/IstiodConfig.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcm/src/v20210413/model/IstiodConfig.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcm/src/v20210413/model/IstiodConfig.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tcm/v20210413/model/IstiodConfig.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcm::V20210413::Model;
using namespace std;
IstiodConfig::IstiodConfig() :
m_workloadHasBeenSet(false)
{
}
CoreInternalOutcome IstiodConfig::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Workload") && !value["Workload"].IsNull())
{
if (!value["Workload"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `IstiodConfig.Workload` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_workload.Deserialize(value["Workload"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_workloadHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void IstiodConfig::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_workloadHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Workload";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_workload.ToJsonObject(value[key.c_str()], allocator);
}
}
WorkloadConfig IstiodConfig::GetWorkload() const
{
return m_workload;
}
void IstiodConfig::SetWorkload(const WorkloadConfig& _workload)
{
m_workload = _workload;
m_workloadHasBeenSet = true;
}
bool IstiodConfig::WorkloadHasBeenSet() const
{
return m_workloadHasBeenSet;
}
| 27.282353 | 131 | 0.701164 | [
"object",
"model"
] |
83a3327de750036a7525ea68a8a549ce27c2a8c6 | 6,914 | cpp | C++ | lib/scipoptsuite-5.0.1/scip/src/objscip/objvardata.cpp | npwebste/UPS_Controller | a90ce2229108197fd48f956310ae2929e0fa5d9a | [
"AFL-1.1"
] | null | null | null | lib/scipoptsuite-5.0.1/scip/src/objscip/objvardata.cpp | npwebste/UPS_Controller | a90ce2229108197fd48f956310ae2929e0fa5d9a | [
"AFL-1.1"
] | null | null | null | lib/scipoptsuite-5.0.1/scip/src/objscip/objvardata.cpp | npwebste/UPS_Controller | a90ce2229108197fd48f956310ae2929e0fa5d9a | [
"AFL-1.1"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program and library */
/* SCIP --- Solving Constraint Integer Programs */
/* */
/* Copyright (C) 2002-2018 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* SCIP is distributed under the terms of the ZIB Academic License. */
/* */
/* You should have received a copy of the ZIB Academic License. */
/* along with SCIP; see the file COPYING. If not email to scip@zib.de. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file objvardata.cpp
* @brief C++ wrapper for user variable data
* @author Tobias Achterberg
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
#include <cassert>
#include "objvardata.h"
/*
* Data structures
*/
/** user variable data */
struct SCIP_VarData
{
scip::ObjVardata* objvardata; /**< user variable data object */
SCIP_Bool deleteobject; /**< should the user variable data object be deleted when variable is freed? */
};
/*
* Callback methods of user variable data
*/
extern "C"
{
/** frees user data of original variable (called when the original variable is freed) */
static
SCIP_DECL_VARDELORIG(varDelorigObj)
{ /*lint --e{715}*/
assert(vardata != NULL);
assert(*vardata != NULL);
assert((*vardata)->objvardata != NULL);
/* call virtual method of vardata object */
SCIP_CALL( (*vardata)->objvardata->scip_delorig(scip, var) );
/* free vardata object */
if( (*vardata)->deleteobject )
delete (*vardata)->objvardata;
/* free vardata data */
delete *vardata;
*vardata = 0; /*lint !e64*/
return SCIP_OKAY;
}
/** creates user data of transformed variable by transforming the original user variable data
* (called after variable was transformed)
*/
static
SCIP_DECL_VARTRANS(varTransObj)
{ /*lint --e{715}*/
scip::ObjVardata* objvardata; /*lint !e78 !e40 !e55 !e530 !e522*/
SCIP_Bool deleteobject;
assert(sourcedata != NULL);
assert(sourcedata->objvardata != NULL);
assert(targetdata != NULL);
assert(*targetdata == NULL);
/* call virtual method of vardata object */
SCIP_CALL( sourcedata->objvardata->scip_trans(scip, targetvar, &objvardata, &deleteobject) ); /*lint !e40*/
/* create transformed user variable data */
*targetdata = new SCIP_VARDATA;
(*targetdata)->objvardata = objvardata; /*lint !e40*/
(*targetdata)->deleteobject = deleteobject;
return SCIP_OKAY;
}
/** frees user data of transformed variable (called when the transformed variable is freed) */
static
SCIP_DECL_VARDELTRANS(varDeltransObj)
{ /*lint --e{715}*/
assert(vardata != NULL);
assert(*vardata != NULL);
assert((*vardata)->objvardata != NULL);
/* call virtual method of vardata object */
SCIP_CALL( (*vardata)->objvardata->scip_deltrans(scip, var) );
/* free vardata object */
if( (*vardata)->deleteobject )
delete (*vardata)->objvardata;
/* free vardata data */
delete *vardata;
*vardata = 0; /*lint !e64*/
return SCIP_OKAY;
}
/** copies user data if you want to copy it to a subscip */
static
SCIP_DECL_VARCOPY(varCopyObj)
{ /*lint --e{715}*/
scip::ObjVardata* objvardata; /*lint !e78 !e40 !e55 !e530 !e522*/
assert(sourcedata != NULL);
assert(sourcedata->objvardata != NULL);
assert(targetdata != NULL);
assert(*targetdata == NULL);
/* call virtual method of probdata object */
SCIP_CALL( sourcedata->objvardata->scip_copy(scip, sourcescip, sourcevar, varmap, consmap, targetvar, &objvardata, result) ); /*lint !e40*/
if( objvardata != 0 )
{
assert(*result == SCIP_SUCCESS);
/* create traget user problem data */
*targetdata = new SCIP_VARDATA;
(*targetdata)->objvardata = objvardata; /*lint !e40*/
(*targetdata)->deleteobject = TRUE; /* always delete object, because we created it */
}
else
{
assert(*result == SCIP_DIDNOTRUN);
*targetdata = 0;
}
return SCIP_OKAY;
}
}
/*
* user variable data specific interface methods
*/
/** create and capture problem variable and associates the given variable data with the variable;
* if variable is of integral type, fractional bounds are automatically rounded
*/
SCIP_RETCODE SCIPcreateObjVar(
SCIP* scip, /**< SCIP data structure */
SCIP_VAR** var, /**< pointer to variable object */
const char* name, /**< name of variable, or NULL for automatic name creation */
SCIP_Real lb, /**< lower bound of variable */
SCIP_Real ub, /**< upper bound of variable */
SCIP_Real obj, /**< objective function value */
SCIP_VARTYPE vartype, /**< type of variable */
SCIP_Bool initial, /**< should var's column be present in the initial root LP? */
SCIP_Bool removable, /**< is var's column removable from the LP (due to aging or cleanup)? */
scip::ObjVardata* objvardata, /**< user variable data object */
SCIP_Bool deleteobject /**< should the user variable data object be deleted when variable is freed? */
)
{
SCIP_VARDATA* vardata;
/* create user variable data */
vardata = new SCIP_VARDATA;
vardata->objvardata = objvardata;
vardata->deleteobject = deleteobject;
/* create variable */
SCIP_CALL( SCIPcreateVar(scip, var, name, lb, ub, obj, vartype, initial, removable,
varDelorigObj, varTransObj, varDeltransObj, varCopyObj, vardata) ); /*lint !e429*/
return SCIP_OKAY; /*lint !e429*/
}
/** gets user variable data object for given problem variable
* Warning! This method should only be called after a variable was created with SCIPcreateObjVar().
* Otherwise, a segmentation fault may arise, or an undefined pointer is returned.
*/
scip::ObjVardata* SCIPgetObjVardata(
SCIP* scip, /**< SCIP data structure */
SCIP_VAR* var /**< problem variable */
)
{
SCIP_VARDATA* vardata;
vardata = SCIPvarGetData(var);
assert(vardata != NULL);
return vardata->objvardata;
}
| 32.767773 | 142 | 0.562048 | [
"object"
] |
83ae9de7a6b241ec7aaa6fb29d815e60fad3bd06 | 37,257 | cc | C++ | libtailslide/passes/mono/script_compiler.cc | SaladDais/sling | 77e93f5b04679e7c3ffcd361944abb242cff9b5f | [
"MIT"
] | 1 | 2022-03-29T07:26:13.000Z | 2022-03-29T07:26:13.000Z | libtailslide/passes/mono/script_compiler.cc | SaladDais/sling | 77e93f5b04679e7c3ffcd361944abb242cff9b5f | [
"MIT"
] | 3 | 2022-03-30T04:56:49.000Z | 2022-03-31T23:32:40.000Z | libtailslide/passes/mono/script_compiler.cc | SaladDais/tailslide | 22156d8f65a2699811f671f11649647033c8cdad | [
"MIT"
] | null | null | null | #include "script_compiler.hh"
#include "../desugaring.hh"
#include <iomanip>
namespace Tailslide {
static const char *CIL_USERSCRIPT_CLASS = "class [LslUserScript]LindenLab.SecondLife.LslUserScript";
static const char *CIL_LSL_RUNTIME_CLASS = "class [LslLibrary]LindenLab.SecondLife.LslRunTime";
static const char *CIL_LSL_LIBRARY_CLASS = "class [LslLibrary]LindenLab.SecondLife.Library";
static const std::string CIL_LIST_INITIALIZER = std::string("call ") + CIL_TYPE_NAMES[LST_LIST] + " " + CIL_USERSCRIPT_CLASS + "::CreateList()";
/// compiles to the text representation of CIL assembly, based on analysis
/// of the output of LL's lscript LSL->CIL compiler circa 2009 (when public
/// lscript source had its last functional update.)
bool MonoScriptCompiler::visit(LSLScript *script) {
LLConformantDeSugaringVisitor de_sugaring_visitor(_mAllocator, true);
script->visit(&de_sugaring_visitor);
MonoResourceVisitor resource_visitor(&_mSymData);
script->visit(&resource_visitor);
_mScriptClassName = "LSL_00000000_0000_0000_0000_000000000000";
mCIL << ".assembly extern mscorlib {.ver 1:0:5000:0}\n"
".assembly extern LslLibrary {.ver 0:1:0:0}\n"
".assembly extern LslUserScript {.ver 0:1:0:0}\n"
".assembly extern ScriptTypes {.ver 0:1:0:0}\n"
".assembly '" << _mScriptClassName << "' {.ver 0:0:0:0}\n"
".class public auto ansi serializable beforefieldinit " << _mScriptClassName << " extends " << CIL_USERSCRIPT_CLASS << "\n"
"{\n";
// declare the global variables first
auto *globals = script->getGlobals();
for (auto *global : *globals) {
if (global->getNodeType() != NODE_GLOBAL_VARIABLE)
continue;
auto *id = ((LSLGlobalVariable *) global)->getIdentifier();
mCIL << ".field public " << CIL_TYPE_NAMES[id->getIType()] << " '" << id->getName() << "'\n";
}
// now define the globals' values in the ctor for the script
mCIL << ".method public hidebysig specialname rtspecialname instance default void .ctor () cil managed\n"
"{\n"
".maxstack 500\n";
_mInGlobalExpr = true;
for (auto *global: *globals) {
if (global->getNodeType() != NODE_GLOBAL_VARIABLE)
continue;
global->visit(this);
}
_mInGlobalExpr = false;
// call the base constructor for the script class and return
mCIL << "ldarg.0\n"
"call instance void " << CIL_USERSCRIPT_CLASS << "::.ctor()\n"
"ret\n"
"}\n";
// now go over the globals _again_ to pick up all the functions
for (auto *global : *globals) {
if (global->getNodeType() != NODE_GLOBAL_FUNCTION)
continue;
global->visit(this);
}
// now look at the event handlers
script->getStates()->visit(this);
mCIL << "}\n";
return false;
}
bool MonoScriptCompiler::visit(LSLGlobalVariable *glob_var) {
// push a reference to `this` for the later stfld
mCIL << "ldarg.0\n";
auto *sym = glob_var->getSymbol();
if (auto *initializer = glob_var->getInitializer()) {
initializer->visit(this);
} else {
pushConstant(sym->getType()->getDefaultValue());
}
mCIL << "stfld " << getGlobalVarSpecifier(sym) << "\n";
return false;
}
/// Push things that need to be on the stack before we can read or write the ultimate
/// target of the lvalue (reference to `this`, the containing object for accessors, etc.)
void MonoScriptCompiler::pushLValueContainer(LSLLValueExpression *lvalue) {
auto *sym = lvalue->getSymbol();
if (sym->getSubType() == SYM_GLOBAL) {
// push a reference to `this` since this is an attribute of the class
// and we'll need to `ldfld`
mCIL << "ldarg.0\n";
}
// have an accessor, we need to push the containing object's address!
if (lvalue->getMember()) {
if (sym->getSubType() == SYM_GLOBAL) {
mCIL << "ldflda " << getGlobalVarSpecifier(sym) << "\n";
} else if (sym->getSubType() == SYM_LOCAL) {
mCIL << "ldloca.s " << _mSymData[sym].index << "\n";
} else {
// event or function param
mCIL << "ldarga.s '" << sym->getName() << "'\n";
}
}
}
/// push the actual value of an lvalue onto the stack
void MonoScriptCompiler::pushLValue(LSLLValueExpression *lvalue) {
pushLValueContainer(lvalue);
auto *sym = lvalue->getSymbol();
if (lvalue->getMember()) {
// accessor case, containing object is already on the stack and
// we just have to load the field.
mCIL << "ldfld " << getLValueAccessorSpecifier(lvalue) << "\n";
} else {
if (sym->getSubType() == SYM_GLOBAL) {
// LslUserScript `this` should already on the stack, load the given field from `this`.
mCIL << "ldfld " << getGlobalVarSpecifier(sym) << "\n";
} else if (sym->getSubType() == SYM_LOCAL) {
// must be a local, reference by index
// Seems that UThreadInjector may rewrite these to ldloc.0, ldloc.1, ...
// but we aren't aiming for conformance with its output, only lscript's.
mCIL << "ldloc.s " << _mSymData[sym].index << "\n";
} else {
// event or function param
mCIL << "ldarg.s '" << sym->getName() << "'\n";
}
}
}
void MonoScriptCompiler::pushConstant(LSLConstant *cv) {
if (!cv)
return;
switch(cv->getIType()) {
case LST_INTEGER: {
auto int_val = ((LSLIntegerConstant *) cv)->getValue();
// These values have a single-byte push form
if (int_val >= 0 && int_val <= 8)
mCIL << "ldc.i4." << int_val << '\n';
else if (int_val == -1)
mCIL << "ldc.i4.m1\n";
// can use the single-byte operand version of ldc.i4
else if (int_val >= -128 && int_val <= 127)
mCIL << "ldc.i4.s " << int_val << '\n';
else
mCIL << "ldc.i4 " << int_val << "\n";
return;
}
case LST_FLOATINGPOINT:
pushFloatLiteral(((LSLFloatConstant *) cv)->getValue());
return;
case LST_STRING:
mCIL << "ldstr \"" << escape_string(((LSLStringConstant *) cv)->getValue()) << "\"\n";
return;
case LST_KEY:
mCIL << "ldstr \"" << escape_string(((LSLKeyConstant *) cv)->getValue()) << "\"\n";
mCIL << "call " << CIL_TYPE_NAMES[LST_KEY] << " " << CIL_USERSCRIPT_CLASS << "::'CreateKey'(string)\n";
return;
case LST_VECTOR: {
auto *vec_val = ((LSLVectorConstant *) cv)->getValue();
pushFloatLiteral(vec_val->x);
pushFloatLiteral(vec_val->y);
pushFloatLiteral(vec_val->z);
mCIL << "call " << CIL_TYPE_NAMES[LST_VECTOR] << " " << CIL_USERSCRIPT_CLASS << "::'CreateVector'(float32, float32, float32)\n";
return;
}
case LST_QUATERNION: {
auto *vec_val = ((LSLQuaternionConstant *) cv)->getValue();
pushFloatLiteral(vec_val->x);
pushFloatLiteral(vec_val->y);
pushFloatLiteral(vec_val->z);
pushFloatLiteral(vec_val->s);
mCIL << "call " << CIL_TYPE_NAMES[LST_QUATERNION] << " " << CIL_USERSCRIPT_CLASS << "::'CreateQuaternion'(float32, float32, float32, float32)\n";
return;
}
case LST_LIST: {
// only know how to write the default empty list as a constant
auto *list_val = (LSLListConstant *) cv;
assert(!list_val->getLength());
mCIL << "call " << CIL_TYPE_NAMES[LST_LIST] << " " << CIL_USERSCRIPT_CLASS << "::CreateList()\n";
return;
}
default:
assert(0);
}
}
/// used for a number of cases, including pushing float constants and vec/quat components
void MonoScriptCompiler::pushFloatLiteral(float value) {
// pushed as a double for some reason
// use the binary hex form specified in the ECMA standard to preserve precision
auto d_val = (double)value;
auto *b_val = reinterpret_cast<uint8_t *>(&d_val);
// enough room for all of the octets plus null. much less annoying than
// the stringstream form and no C++20 so we don't have std::format
const size_t s_val_len = 3 * 8;
char s_val[s_val_len] = {0};
snprintf(
(char *)&s_val,
s_val_len,
"%02x %02x %02x %02x %02x %02x %02x %02x",
b_val[0], b_val[1], b_val[2], b_val[3], b_val[4], b_val[5], b_val[6], b_val[7]
);
mCIL << "ldc.r8 (" << (const char*)&s_val << ")\n";
}
void MonoScriptCompiler::storeToLValue(LSLLValueExpression *lvalue, bool push_result) {
auto *sym = lvalue->getSymbol();
// coordinate accessor case
if (lvalue->getMember()) {
mCIL << "stfld " << getLValueAccessorSpecifier(lvalue) << "\n";
// Expression assignments need to return their result, load what we just stored onto the stack
// TODO: This seems really wasteful in many cases, but this is how LL's compiler does it.
// I guess `dup` isn't an option because of the `this` reference, but wouldn't creating a
// scratch local be better?
if (push_result)
pushLValue(lvalue);
} else if (sym->getSubType() == SYM_GLOBAL) {
mCIL << "stfld " << getGlobalVarSpecifier(lvalue->getSymbol()) << "\n";
// same caveat as above
if (push_result)
pushLValue(lvalue);
} else {
// We can avoid reloading the lvalue from its storage container in these cases by just duplicating
// the result of the expression on the stack. All we need on the stack for these stores is the value.
if (push_result)
mCIL << "dup\n";
if (sym->getSubType() == SYM_LOCAL) {
mCIL << "stloc.s " << _mSymData[sym].index << "\n";
} else {
// event or function param
mCIL << "starg.s '" << sym->getName() << "'\n";
}
}
}
void MonoScriptCompiler::castTopOfStack(LSLIType from_type, LSLIType to_type) {
if (from_type == to_type)
return;
switch(to_type) {
case LST_INTEGER:
switch(from_type) {
case LST_FLOATINGPOINT:
mCIL << "call int32 " << CIL_LSL_RUNTIME_CLASS << "::ToInteger(float32)\n";
return;
case LST_STRING:
mCIL << "call int32 " << CIL_LSL_RUNTIME_CLASS << "::StringToInt(string)\n";
return;
default:
assert(0);
}
case LST_FLOATINGPOINT:
switch(from_type) {
case LST_INTEGER:
mCIL << "conv.r8\n";
return;
case LST_STRING:
mCIL << "call float32 " << CIL_LSL_RUNTIME_CLASS << "::StringToFloat(string)\n";
return;
default:
assert(0);
}
case LST_STRING:
switch (from_type) {
case LST_LIST:
mCIL << "call string " << CIL_LSL_RUNTIME_CLASS << "::ListToString(" << CIL_TYPE_NAMES[LST_LIST] << ")\n";
return;
case LST_INTEGER:
mCIL << "call string class [mscorlib]System.Convert::ToString(" << CIL_TYPE_NAMES[LST_INTEGER] << ")\n";
return;
case LST_FLOATINGPOINT:
mCIL << "call string " << CIL_LSL_RUNTIME_CLASS << "::'ToString'(" << CIL_TYPE_NAMES[from_type] << ")\n";
return;
default:
mCIL << "call string " << CIL_USERSCRIPT_CLASS << "::'ToString'(" << CIL_VALUE_TYPE_NAMES[from_type] << ")\n";
return;
}
case LST_KEY:
if (from_type == LST_STRING)
mCIL << "call " << CIL_TYPE_NAMES[LST_KEY] << " " << CIL_USERSCRIPT_CLASS << "::'CreateKey'(string)\n";
return;
case LST_VECTOR:
if (from_type == LST_STRING)
mCIL << "call " << CIL_TYPE_NAMES[LST_VECTOR] << " " << CIL_USERSCRIPT_CLASS << "::'ParseVector'(string)\n";
return;
case LST_QUATERNION:
if (from_type == LST_STRING)
mCIL << "call " << CIL_TYPE_NAMES[LST_QUATERNION] << " " << CIL_USERSCRIPT_CLASS << "::'ParseQuaternion'(string)\n";
return;
case LST_LIST:
// All casts to list are the same, box if necessary and then `CreateList(object)`.
mCIL << CIL_BOXING_INSTRUCTIONS[from_type];
mCIL << "call " << CIL_TYPE_NAMES[LST_LIST] << " " << CIL_USERSCRIPT_CLASS << "::CreateList(object)\n";
return;
default:
assert(0);
}
}
std::string MonoScriptCompiler::getGlobalVarSpecifier(LSLSymbol *sym) {
std::stringstream ss;
ss << CIL_TYPE_NAMES[sym->getIType()] << " " << _mScriptClassName << "::'" << sym->getName() << "'";
return ss.str();
}
/// return a specifier that allows referencing the field for the accessor with ldfld or stfld
std::string MonoScriptCompiler::getLValueAccessorSpecifier(LSLLValueExpression *lvalue) {
auto *accessor_type_name = CIL_TYPE_NAMES[lvalue->getIType()];
auto *obj_type_name = CIL_TYPE_NAMES[lvalue->getSymbol()->getIType()];
auto *accessor_name = lvalue->getMember()->getName();
return std::string(accessor_type_name) + " " + obj_type_name + "::" + accessor_name;
}
bool MonoScriptCompiler::visit(LSLEventHandler *handler) {
// Need a reference to the state this belongs to for conformant name mangling
// We're parented to a node list which is parented to the state.
auto *state_sym = handler->getParent()->getParent()->getSymbol();
mCIL << ".method public hidebysig instance default void e" << state_sym->getName() << CIL_HANDLER_NAMES[handler->getSymbol()->getName()];
// parameter list will be handled by `buildFunction()`
buildFunction(handler);
return false;
}
bool MonoScriptCompiler::visit(LSLGlobalFunction *glob_func) {
auto *node_sym = glob_func->getSymbol();
mCIL << ".method public hidebysig instance default " << CIL_TYPE_NAMES[glob_func->getIdentifier()->getIType()]
<< " 'g" << node_sym->getName() << "'";
buildFunction(glob_func);
return false;
}
void MonoScriptCompiler::buildFunction(LSLASTNode *func) {
// write out the parameter list
auto *func_sym = func->getSymbol();
auto *func_decl = func_sym->getFunctionDecl();
mCIL << "(";
for (auto *func_param : *func_decl) {
auto *param_sym = func_param->getSymbol();
mCIL << CIL_TYPE_NAMES[param_sym->getIType()] << " '" << param_sym->getName() << "'";
if (func_param->getNext())
mCIL << ", ";
}
mCIL << ") cil managed\n";
mCIL << "{\n";
mCIL << ".maxstack 500\n";
std::string locals_string;
for (auto param_type : _mSymData[func_sym].locals) {
if (!locals_string.empty()) {
locals_string += ", ";
}
locals_string += CIL_TYPE_NAMES[param_type];
}
if (!locals_string.empty())
mCIL << ".locals init (" << locals_string << ")\n";
_mCurrentFuncSym = func->getSymbol();
visitChildren(func);
_mCurrentFuncSym = nullptr;
if (!func_sym->getAllPathsReturn())
mCIL << "ret\n";
mCIL << "}\n";
}
bool MonoScriptCompiler::visit(LSLDeclaration *decl_stmt) {
auto *sym = decl_stmt->getSymbol();
if (auto *initializer = decl_stmt->getInitializer()) {
initializer->visit(this);
} else {
pushConstant(sym->getType()->getDefaultValue());
}
mCIL << "stloc.s " << _mSymData[sym].index << "\n";
return false;
}
bool MonoScriptCompiler::visit(LSLExpressionStatement *expr_stmt) {
auto *expr = expr_stmt->getExpr();
expr->visit(this);
if (expr->getIType() && !_mPushOmitted)
mCIL << "pop\n";
_mPushOmitted = false;
return false;
}
bool MonoScriptCompiler::visit(LSLReturnStatement *ret_stmt) {
if (auto *expr = ret_stmt->getExpr())
expr->visit(this);
mCIL << "ret\n";
return false;
}
bool MonoScriptCompiler::visit(LSLLabel *label_stmt) {
// TODO: right now this roughly matches LL's behavior, but label names
// should be mangled to prevent collisions.
mCIL << "'ul" << label_stmt->getSymbol()->getName() << "':\n";
return false;
}
bool MonoScriptCompiler::visit(LSLJumpStatement*jump_stmt) {
// TODO: right now this roughly matches LL's behavior, but label names
// should be mangled to prevent collisions.
mCIL << "br 'ul" << jump_stmt->getSymbol()->getName() << "'\n";
return false;
}
bool MonoScriptCompiler::visit(LSLIfStatement*if_stmt) {
auto jump_past_true_num = _mJumpNum++;
uint32_t jump_past_false_num = 0;
auto *false_node = if_stmt->getFalseBranch();
if (false_node)
jump_past_false_num = _mJumpNum++;
if_stmt->getCheckExpr()->visit(this);
mCIL << "brfalse LabelTempJump" << jump_past_true_num << "\n";
if_stmt->getTrueBranch()->visit(this);
if (false_node) {
mCIL << "br LabelTempJump" << jump_past_false_num << "\n";
mCIL << "LabelTempJump" << jump_past_true_num << ":\n";
false_node->visit(this);
mCIL << "LabelTempJump" << jump_past_false_num << ":\n";
} else {
mCIL << "LabelTempJump" << jump_past_true_num << ":\n";
}
return false;
}
bool MonoScriptCompiler::visit(LSLForStatement*for_stmt) {
// execute instructions to initialize vars
for(auto *init_expr : *for_stmt->getInitExprs()) {
init_expr->visit(this);
if (init_expr->getIType() && !_mPushOmitted)
mCIL << "pop\n";
_mPushOmitted = false;
}
auto jump_to_start_num = _mJumpNum++;
auto jump_to_end_num = _mJumpNum++;
mCIL << "LabelTempJump" << jump_to_start_num << ":\n";
// run the check expression, exiting the loop if it fails
for_stmt->getCheckExpr()->visit(this);
mCIL << "brfalse LabelTempJump" << jump_to_end_num << "\n";
// run the body of the loop
for_stmt->getBody()->visit(this);
// run the increment expressions
for(auto *incr_expr : *for_stmt->getIncrExprs()) {
incr_expr->visit(this);
if (incr_expr->getIType() && !_mPushOmitted)
mCIL << "pop\n";
_mPushOmitted = false;
}
// jump back up to the check expression at the top
mCIL << "br LabelTempJump" << jump_to_start_num << "\n";
mCIL << "LabelTempJump" << jump_to_end_num << ":\n";
return false;
}
bool MonoScriptCompiler::visit(LSLWhileStatement*while_stmt) {
auto jump_to_start_num = _mJumpNum++;
auto jump_to_end_num = _mJumpNum++;
mCIL << "LabelTempJump" << jump_to_start_num << ":\n";
// run the check expression, exiting the loop if it fails
while_stmt->getCheckExpr()->visit(this);
mCIL << "brfalse LabelTempJump" << jump_to_end_num << "\n";
// run the body of the loop
while_stmt->getBody()->visit(this);
// jump back up to the check expression at the top
mCIL << "br LabelTempJump" << jump_to_start_num << "\n";
mCIL << "LabelTempJump" << jump_to_end_num << ":\n";
return false;
}
bool MonoScriptCompiler::visit(LSLDoStatement*do_stmt) {
auto jump_to_start_num = _mJumpNum++;
mCIL << "LabelTempJump" << jump_to_start_num << ":\n";
// run the body of the loop
do_stmt->getBody()->visit(this);
// run the check expression, jumping back up if it succeeds
do_stmt->getCheckExpr()->visit(this);
mCIL << "brtrue LabelTempJump" << jump_to_start_num << "\n";
return false;
}
bool MonoScriptCompiler::visit(LSLStateStatement *state_stmt) {
mCIL << "ldarg.0\n"
<< "ldstr \"" << escape_string(state_stmt->getSymbol()->getName()) << "\"\n"
<< "call instance void " << CIL_USERSCRIPT_CLASS << "::ChangeState(string)\n";
pushConstant(_mCurrentFuncSym->getType()->getDefaultValue());
mCIL << "ret\n";
return false;
}
bool MonoScriptCompiler::visit(LSLConstantExpression *constant_expr) {
pushConstant(constant_expr->getConstantValue());
return false;
}
bool MonoScriptCompiler::visit(LSLTypecastExpression *cast_expr) {
auto *child_expr = cast_expr->getChildExpr();
assert(child_expr);
child_expr->visit(this);
castTopOfStack(child_expr->getIType(), cast_expr->getIType());
return false;
}
bool MonoScriptCompiler::visit(LSLBoolConversionExpression *bool_expr) {
auto *child_expr = bool_expr->getChildExpr();
auto type = child_expr->getIType();
child_expr->visit(this);
switch(type) {
case LST_INTEGER:
return false;
case LST_FLOATINGPOINT:
pushConstant(TYPE(LST_FLOATINGPOINT)->getDefaultValue());
mCIL << "ceq\n"
// TODO: LL's compiler does this, is it necessary?
<< "ldc.i4.0\n"
<< "ceq\n";
return false;
case LST_STRING:
pushConstant(TYPE(LST_STRING)->getDefaultValue());
mCIL << "call bool string::op_Equality(string, string)\n"
// TODO: LL's compiler does this, is it necessary?
<< "ldc.i4.0\n"
<< "ceq\n";
return false;
case LST_VECTOR:
case LST_QUATERNION:
pushConstant(TYPE(type)->getDefaultValue());
mCIL << "call bool " << CIL_USERSCRIPT_CLASS << "::'Equals'(" << CIL_TYPE_NAMES[type] << ", " << CIL_TYPE_NAMES[type] << ")\n"
// TODO: LL's compiler does this, is it necessary?
<< "ldc.i4.0\n"
<< "ceq\n";
return false;
case LST_KEY:
mCIL << "call bool " << CIL_USERSCRIPT_CLASS <<"::'IsNonNullUuid'(" << CIL_TYPE_NAMES[LST_KEY] << ")\n";
return false;
case LST_LIST:
pushConstant(TYPE(LST_LIST)->getDefaultValue());
mCIL << "call bool " << CIL_USERSCRIPT_CLASS << "::'Equals'(" << CIL_TYPE_NAMES[LST_LIST] << ", " << CIL_TYPE_NAMES[LST_LIST] << ")\n"
<< "ldc.i4.0\n"
<< "ceq\n";
return false;
default:
assert(0);
}
return false;
}
bool MonoScriptCompiler::visit(LSLVectorExpression *vec_expr) {
visitChildren(vec_expr);
mCIL << "call " << CIL_TYPE_NAMES[LST_VECTOR] << " " << CIL_USERSCRIPT_CLASS << "::'CreateVector'(float32, float32, float32)\n";
return false;
}
bool MonoScriptCompiler::visit(LSLQuaternionExpression *quat_expr) {
visitChildren(quat_expr);
mCIL << "call " << CIL_TYPE_NAMES[LST_QUATERNION] << " " << CIL_USERSCRIPT_CLASS << "::'CreateQuaternion'(float32, float32, float32, float32)\n";
return false;
}
bool MonoScriptCompiler::visit(LSLLValueExpression *lvalue) {
pushLValue(lvalue);
return false;
}
bool MonoScriptCompiler::visit(LSLListExpression *list_expr) {
// LL's compiler pushes lists in a different order in globexprs for some reason,
// maybe something about order of evaluation being important there.
// match their behavior so it's less annoying to compare output.
if (_mInGlobalExpr) {
mCIL << CIL_LIST_INITIALIZER << "\n";
for (auto child : *list_expr) {
child->visit(this);
mCIL << CIL_BOXING_INSTRUCTIONS[child->getIType()]
<< "call " << CIL_TYPE_NAMES[LST_LIST] << " " << CIL_USERSCRIPT_CLASS << "::Append(" << CIL_TYPE_NAMES[LST_LIST] << ", object)\n";
}
} else {
// list elements get evaluated and pushed FIRST
size_t num_children = 0;
for (auto *child : *list_expr) {
child->visit(this);
mCIL << CIL_BOXING_INSTRUCTIONS[child->getIType()];
++num_children;
}
// then they get added to the list
mCIL << CIL_LIST_INITIALIZER << "\n";
for (size_t i=0; i<num_children; ++i) {
mCIL << "call " << CIL_TYPE_NAMES[LST_LIST] << " " << CIL_USERSCRIPT_CLASS << "::Prepend(object, " << CIL_TYPE_NAMES[LST_LIST] << ")\n";
}
}
return false;
}
bool MonoScriptCompiler::visit(LSLFunctionExpression *func_expr) {
auto *func_sym = func_expr->getSymbol();
// this will be a method on the script instance, push `this` onto the stack
if (func_sym->getSubType() != SYM_BUILTIN)
mCIL << "ldarg.0\n";
// push the arguments onto the stack
for (auto *child_expr : *func_expr->getArguments()) {
child_expr->visit(this);
}
if (func_sym->getSubType() == SYM_BUILTIN) {
mCIL << "call " << CIL_TYPE_NAMES[func_expr->getIType()] << " "
<< CIL_LSL_LIBRARY_CLASS << "::'" << func_sym->getName() << "'";
} else {
mCIL << "call instance " << CIL_TYPE_NAMES[func_expr->getIType()] << " class "
<< _mScriptClassName + "::'g" + func_sym->getName() + "'";
}
// write in the functions' expected parameter types
auto *func_decl = func_sym->getFunctionDecl();
mCIL << "(";
for (auto *func_param : *func_decl) {
mCIL << CIL_TYPE_NAMES[func_param->getIType()];
if (func_param->getNext())
mCIL << ", ";
}
mCIL << ")\n";
return false;
}
/// An operation that is performed via a method call on the UserScript class
typedef struct {
LSLIType left;
LSLIType right;
} SimpleBinaryOperationInfo;
/// Cases where the operation is performed via a method call on the UserScript class with
/// a well-known operation name for the method, and operator overloading for the various types.
/// Return value is inferred by looking at the return value of the actual expression node.
const std::map<int, std::pair<const char *, std::vector<SimpleBinaryOperationInfo> > > SIMPLE_BINARY_OPS = {
{'+', {"Add", {
{LST_STRING, LST_STRING},
{LST_VECTOR, LST_VECTOR},
{LST_QUATERNION, LST_QUATERNION},
}}},
{'-', {"Subtract", {
// not done because we have an optional optimization we can do
// {LST_INTEGER, LST_INTEGER},
// not simple, float64 args and return!
// {LST_FLOATINGPOINT, LST_FLOATINGPOINT},
{LST_VECTOR, LST_VECTOR},
{LST_QUATERNION, LST_QUATERNION},
}}},
{'*', {"Multiply", {
{LST_VECTOR, LST_FLOATINGPOINT},
{LST_FLOATINGPOINT, LST_VECTOR},
{LST_VECTOR, LST_VECTOR},
{LST_VECTOR, LST_QUATERNION},
{LST_QUATERNION, LST_QUATERNION},
}}},
{'/', {"Divide", {
{LST_INTEGER, LST_INTEGER},
// not simple, float64 args and return!
// {LST_FLOATINGPOINT, LST_FLOATINGPOINT},
{LST_VECTOR, LST_FLOATINGPOINT},
{LST_VECTOR, LST_QUATERNION},
{LST_QUATERNION, LST_QUATERNION},
}}},
{'%', {"Modulo", {
{LST_INTEGER, LST_INTEGER},
{LST_VECTOR, LST_VECTOR},
}}},
{OP_EQ, {"Equals", {
{LST_VECTOR, LST_VECTOR},
{LST_QUATERNION, LST_QUATERNION},
{LST_LIST, LST_LIST},
}}},
{OP_NEQ, {"NotEquals", {
// TODO: desugar `a != b` to `!(a == b)` where possible?
{LST_LIST, LST_LIST},
}}},
{OP_SHIFT_LEFT, {"ShiftLeft", {
{LST_INTEGER, LST_INTEGER},
}}},
{OP_SHIFT_RIGHT, {"ShiftRight", {
{LST_INTEGER, LST_INTEGER},
}}},
};
bool MonoScriptCompiler::visit(LSLBinaryExpression *bin_expr) {
LSLOperator op = bin_expr->getOperation();
auto *left = bin_expr->getLHS();
auto *right = bin_expr->getRHS();
if (op == '=') {
// we're going to store, so we may need a reference to `this` on top of the stack
auto *lvalue = (LSLLValueExpression *) left;
pushLValueContainer(lvalue);
right->visit(this);
// store to the lvalue and push the lvalue back onto the stack
// if we're assigning in an expression context. For something in
// an expressionstatement context like `foo = 1` we omit the push.
storeToLValue(lvalue, maybeOmitPush(bin_expr));
return false;
} else if (op == OP_MUL_ASSIGN) {
// The only expression that gets left as a MUL_ASSIGN is the busted `int *= float` case,
// all others get desugared to `lvalue = lvalue * rhs` in an earlier compile pass.
// That expression is busted and not the same as `int = int * float`, obviously,
// but we need to support it.
auto *lvalue = (LSLLValueExpression *) left;
pushLValueContainer(lvalue);
right->visit(this);
lvalue->visit(this);
// cast the integer lvalue to a float first
castTopOfStack(LST_INTEGER, LST_FLOATINGPOINT);
mCIL << "mul\n";
// cast the result to an integer so we can store it in the lvalue
castTopOfStack(LST_FLOATINGPOINT, LST_INTEGER);
// This will return the wrong type because things expect this expression to return a float.
// Use of the retval will probably cause a crash.
storeToLValue(lvalue, maybeOmitPush(bin_expr));
return false;
}
compileBinaryExpression(op, left, right, bin_expr->getIType());
return false;
}
void MonoScriptCompiler::compileBinaryExpression(LSLOperator op, LSLExpression *left, LSLExpression *right, LSLIType ret_type) {
auto left_type = left->getIType();
auto right_type = right->getIType();
auto simple_op = SIMPLE_BINARY_OPS.find(op);
// this is an operation that uses the simplified method call form
if (simple_op != SIMPLE_BINARY_OPS.end()) {
// walk through the type pairs this operation has a method call form for
for (auto simple_op_combo : ((*simple_op).second.second)) {
if (left_type != simple_op_combo.left || right_type != simple_op_combo.right)
continue;
right->visit(this);
left->visit(this);
// right is first argument due to reversed order of evaluation in LSL
mCIL << "call " << CIL_TYPE_NAMES[ret_type] << " " << CIL_USERSCRIPT_CLASS << "::'"
<< simple_op->second.first << "'(" << CIL_TYPE_NAMES[right_type] << ", " << CIL_TYPE_NAMES[left_type] << ")\n";
return;
}
}
// handle all the operations that couldn't be handled via templating together a method call
switch(op) {
case '+': {
right->visit(this);
left->visit(this);
if (right_type == LST_LIST && left_type != LST_LIST) {
// prepend whatever this is to the right list
mCIL << CIL_BOXING_INSTRUCTIONS[left_type];
mCIL << "call " << CIL_TYPE_NAMES[LST_LIST] << " " << CIL_USERSCRIPT_CLASS << "::Prepend(" << CIL_TYPE_NAMES[LST_LIST] << ", object)\n";
return;
} else if (left_type == LST_LIST) {
// append to the left list (will also join lists)
mCIL << "call " << CIL_TYPE_NAMES[LST_LIST] << " " << CIL_USERSCRIPT_CLASS << "::Append("
<< CIL_VALUE_TYPE_NAMES[right_type] << ", " << CIL_VALUE_TYPE_NAMES[LST_LIST] << ")\n";
return;
}
switch (left_type) {
case LST_INTEGER:
case LST_FLOATINGPOINT:
mCIL << "add\n";
return;
default:
assert(0);
return;
}
}
case '-': {
if (_mOptions.optimize_sutractions) {
// LSL usually evaluates expressions from right to left, so arguments are
// often in the wrong order on the stack for CIL's primitive binary operations.
// LL gets around that by calling methods with the argument orders reversed that
// call the math operations internally with the correct order. This bit of nastiness
// is hard to avoid without using a scratch local and a decent amount of bytecode to
// swap the top two elements of the stack in place.
//
// Logically, lhs - rhs is equivalent to (-rhs) + lhs, so do it that way
// rather than calling the Subtract method with the reversed arguments.
// Skimming through the IEEE-754 spec there shouldn't be any semantic
// difference. It's faster and serializes to fewer bytes.
right->visit(this);
mCIL << "neg\n";
left->visit(this);
switch (left_type) {
case LST_FLOATINGPOINT:
case LST_INTEGER:
mCIL << "add\n";
return;
default:
assert(0);
return;
}
} else {
right->visit(this);
left->visit(this);
switch (left_type) {
case LST_FLOATINGPOINT:
mCIL << "call float64 " << CIL_USERSCRIPT_CLASS << "::'Subtract'(float64, float64)\n";
return;
case LST_INTEGER:
mCIL << "call int32 " << CIL_USERSCRIPT_CLASS << "::'Subtract'(int32, int32)\n";
return;
default:
assert(0);
return;
}
}
}
case '*': {
right->visit(this);
left->visit(this);
switch (left_type) {
case LST_INTEGER:
case LST_FLOATINGPOINT:
mCIL << "mul\n";
return;
default:
assert(0);
return;
}
}
case '/': {
right->visit(this);
left->visit(this);
switch (left_type) {
case LST_FLOATINGPOINT:
mCIL << "call float64 " << CIL_USERSCRIPT_CLASS << "::'Divide'(float64, float64)\n";
return;
default:
assert(0);
return;
}
}
case OP_EQ: {
right->visit(this);
left->visit(this);
switch (right_type) {
case LST_INTEGER:
case LST_FLOATINGPOINT:
mCIL << "ceq\n";
return;
case LST_STRING:
// note the key == string and string == key asymmetry here...
// left is top of stack, so convert left to a string if it isn't one already
castTopOfStack(left_type, right_type);
mCIL << "call bool valuetype [mscorlib]System.String::op_Equality(string, string)\n";
return;
case LST_KEY:
// these really should have been pre-casted if necessary, but this is what LL's compiler does
castTopOfStack(left_type, right_type);
mCIL << "call int32 " << CIL_USERSCRIPT_CLASS << "::'Equals'(" << CIL_TYPE_NAMES[LST_KEY] << ", " << CIL_TYPE_NAMES[LST_KEY] << ")\n";
return;
default:
assert(0);
return;
}
}
case OP_NEQ:
// EQ will visit right and left in the correct order for us
compileBinaryExpression(OP_EQ, left, right, ret_type);
// check if result == 0
mCIL << "ldc.i4.0\n"
<< "ceq\n";
return;
case OP_GEQ:
right->visit(this);
left->visit(this);
// not very nice, but operands are swapped from how CIL would like them
mCIL << "cgt\n"
<< "ldc.i4.0\n"
<< "ceq\n";
return;
case OP_LEQ:
right->visit(this);
left->visit(this);
mCIL << "clt\n"
<< "ldc.i4.0\n"
<< "ceq\n";
return;
case '>':
right->visit(this);
left->visit(this);
mCIL << "clt\n";
return;
case '<':
right->visit(this);
left->visit(this);
mCIL << "cgt\n";
return;
case OP_BOOLEAN_AND:
// We need to interleave our codegen with the code of the expressions,
// so just visit right to start
right->visit(this);
// push whether this returned false
// necessary because everything EXCEPT 0 is truthy!
mCIL << "ldc.i4.0\n"
<< "ceq\n";
left->visit(this);
mCIL << "ldc.i4.0\n"
<< "ceq\n";
// binary OR the results together and compare against zero
// will push whether neither had the false bit set
mCIL << "or\n"
<< "ldc.i4.0\n"
<< "ceq\n";
return;
case OP_BOOLEAN_OR:
right->visit(this);
left->visit(this);
// binary OR the sides together and compare against zero
mCIL << "or\n"
<< "ldc.i4.0\n"
<< "ceq\n"
// TODO: LL's codegen compares against zero again. Copy & paste error in their code?
<< "ldc.i4.0\n"
<< "ceq\n";
return;
case '&':
right->visit(this);
left->visit(this);
mCIL << "and\n";
return;
case '|':
right->visit(this);
left->visit(this);
mCIL << "or\n";
return;
case '^':
right->visit(this);
left->visit(this);
mCIL << "xor\n";
return;
default:
assert(0);
}
assert(0);
}
bool MonoScriptCompiler::visit(LSLUnaryExpression *unary_expr) {
auto *child_expr = unary_expr->getChildExpr();
LSLOperator op = unary_expr->getOperation();
if (op == OP_POST_DECR || op == OP_POST_INCR) {
auto *lvalue = (LSLLValueExpression *) child_expr;
// We need to keep the original value of the expression on the stack,
// but only if the result of the expr will actually be used
if (maybeOmitPush(unary_expr))
pushLValue(lvalue);
// may need the containing object ref for for the subsequent store
pushLValueContainer(lvalue);
// then load another copy of the value to do the operation (wasteful!)
pushLValue(lvalue);
// push "one" for the given type
pushConstant(lvalue->getType()->getOneValue());
if (op == OP_POST_DECR) {
mCIL << "sub\n";
} else {
mCIL << "add\n";
}
// This store + push, then subsequent pop is totally unnecessary, but matches what LL's
// compiler does. Only do it if we're not allowed to omit pushes.
if (!_mOptions.omit_unnecessary_pushes) {
storeToLValue(lvalue, true);
mCIL << "pop\n";
}
return false;
} else if (op == OP_PRE_INCR || op == OP_PRE_DECR) {
// This appears to generate different code from `lvalue = lvalue + 1`,
// so it isn't desugared.
auto *lvalue = (LSLLValueExpression *) child_expr;
pushLValueContainer(lvalue);
pushLValue(lvalue);
pushConstant(lvalue->getType()->getOneValue());
if (op == OP_PRE_DECR) {
mCIL << "sub\n";
} else {
mCIL << "add\n";
}
storeToLValue(lvalue, maybeOmitPush(unary_expr));
return false;
}
auto child_type = child_expr->getIType();
child_expr->visit(this);
switch (op) {
case '-':
switch(child_type) {
case LST_INTEGER:
case LST_FLOATINGPOINT:
mCIL << "neg\n";
return false;
case LST_QUATERNION:
case LST_VECTOR:
mCIL << "call " << CIL_TYPE_NAMES[child_type] << " " << CIL_USERSCRIPT_CLASS << "::'Negate'(" << CIL_TYPE_NAMES[child_type] << ")\n";
return false;
default:
assert(0);
return false;
}
case '!': {
mCIL << "ldc.i4.0\n"
<< "ceq\n";
return false;
}
case '~': {
mCIL << "not\n";
return false;
}
default:
assert(0);
return false;
}
assert(0);
return false;
}
bool MonoScriptCompiler::visit(LSLPrintExpression *print_expr) {
auto *child_expr = print_expr->getChildExpr();
child_expr->visit(this);
castTopOfStack(child_expr->getIType(), LST_STRING);
mCIL << "call void " << CIL_LSL_LIBRARY_CLASS << "::Print(string)\n";
return false;
}
}
| 35.720997 | 151 | 0.623695 | [
"object",
"vector"
] |
83b2b161454afaa2e0b129306b9c40c87ef3af75 | 36,740 | hpp | C++ | ISO639.hpp | pedrovernetti/omnglot | bb085bcb2c815b47a40e568e11d7f0b48f36c5dd | [
"MIT"
] | null | null | null | ISO639.hpp | pedrovernetti/omnglot | bb085bcb2c815b47a40e568e11d7f0b48f36c5dd | [
"MIT"
] | null | null | null | ISO639.hpp | pedrovernetti/omnglot | bb085bcb2c815b47a40e568e11d7f0b48f36c5dd | [
"MIT"
] | null | null | null |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright (c) 2019 Pedro Vernetti G.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#pragma once
#ifndef _OMN_ISO639_INCLUDED
#define _OMN_ISO639_INCLUDED
#include "globalUtilities.hpp"
namespace omn
{
enum ISO6391LanguageCode : byte
{
aa = 1, // Afar
ab, // Abkhazian
af, // Afrikaans
ak, // Akan
sq, // Albanian
am, // Amharic
ar, // Arabic
an, // Aragonese
hy, // Armenian
as, // Assamese
av, // Avaric
ae, // Avestan
ay, // Aymara
az, // Azerbaijani / Azeri
ba, // Bashkir
bm, // Bambara
eu, // Basque
be, // Belarusian
bn, // Bengali
bh, // Bihari languages
bi, // Bislama
bs, // Bosnian
br, // Breton
bg, // Bulgarian
my, // Burmese
ca, // Catalan / Valencian
ch, // Chamorro
ce, // Chechen
zh, // Chinese
cu, // Old Church Slavonic
cv, // Chuvash
kw, // Cornish
co, // Corsican
cr, // Cree
cs, // Czech
da, // Danish
dv, // Divehi
nl, // Dutch
dz, // Dzongkha
en, // English
eo, // Esperanto
et, // Estonian
ee, // Ewe
fo, // Faroese
fj, // Fijian
fi, // Finnish
fr, // French
fy, // Western Frisian
ff, // Fulah
ka, // Georgian
de, // German
gd, // Scottish Gaelic
ga, // Irish
gl, // Galician
gv, // Manx
el, // Greek
gn, // Guarani
gu, // Gujarati
ht, // Haitian Creole
ha, // Hausa
he, // Hebrew
hz, // Herero
hi, // Hindi
ho, // Hiri Motu
hr, // Croatian
hu, // Hungarian
ig, // Igbo
is, // Icelandic
io, // Ido
ii, // Sichuan Yi / Nuosu
iu, // Inuktitut
ie, // Interlingue
ia, // Interlingua
id, // Indonesian
ik, // Inupiaq
it, // Italian
jv, // Javanese
ja, // Japanese
kl, // Greenlandic
kn, // Kannada
ks, // Kashmiri
kr, // Kanuri
kk, // Kazakh
km, // Khmer
ki, // Kikuyu
rw, // Kinyarwanda
ky, // Kyrgyz
kv, // Komi
kg, // Kongo
ko, // Korean
kj, // Kwanyama
ku, // Kurdish
lo, // Lao
la, // Latin
lv, // Latvian
li, // Limburgish
ln, // Lingala
lt, // Lithuanian
lb, // Luxembourgish
lu, // Luba-Katanga
lg, // Ganda
mk, // Macedonian
mh, // Marshallese
ml, // Malayalam
mi, // Maori
mr, // Marathi
ms, // Malay
mg, // Malagasy
mt, // Maltese
mn, // Mongolian
na, // Nauru
nv, // Navajo
nr, // Southern Ndebele
nd, // Northern Ndebele
ng, // Ndonga
ne, // Nepali
no, // Norwegian
ny, // Chichewa
oc, // Occitan
oj, // Ojibwa
or_, // Oriya
om, // Oromo
os, // Ossetian
pa, // Punjabi
fa, // Persian
pi, // Pali
pl, // Polish
pt, // Portuguese
ps, // Pashto
qu, // Quechua
rm, // Romansh
ro, // Romanian
rn, // Rundi
ru, // Russian
sg, // Sango
sa, // Sanskrit
si, // Sinhalese
sk, // Slovak
sl, // Slovenian
se, // Northern Sami
sm, // Samoan
sn, // Shona
sd, // Sindhi
so, // Somali
st, // Sotho
es, // Spanish
sc, // Sardinian
sr, // Serbian
ss, // Swati
su, // Sundanese
sw, // Swahili
sv, // Swedish
ty, // Tahitian
ta, // Tamil
tt, // Tatar
te, // Telugu
tg, // Tajik
tl, // Tagalog
th, // Thai
bo, // Tibetan
ti, // Tigrinya
to, // Tonga
tn, // Tswana
ts, // Tsonga
tk, // Turkmen
tr, // Turkish
tw, // Twi
ug, // Uighur
uk, // Ukrainian
ur, // Urdu
uz, // Uzbek
ve, // Venda
vi, // Vietnamese
vo, // Volapuk
cy, // Welsh
wa, // Walloon
wo, // Wolof
xh, // Xhosa
yi, // Yiddish
yo, // Yoruba
za, // Zhuang
zu // Zulu
};
enum ISO6392LanguageCode : uint16_t
{
und = ((uint16_t)(-1)), // undefined
zxx = 0, // no linguistic content
aar = ISO6391LanguageCode::aa, // Afar
abk = ISO6391LanguageCode::ab, // Abkhazian
afr = ISO6391LanguageCode::af, // Afrikaans
aka = ISO6391LanguageCode::ak, // Akan
alb = ISO6391LanguageCode::sq, // Albanian [B-code]
amh = ISO6391LanguageCode::am, // Amharic
ara = ISO6391LanguageCode::ar, // Arabic
arg = ISO6391LanguageCode::an, // Aragonese
arm = ISO6391LanguageCode::hy, // Armenian [B-code]
asm_ = ISO6391LanguageCode::as, // Assamese
ava = ISO6391LanguageCode::av, // Avaric
ave = ISO6391LanguageCode::ae, // Avestan
aym = ISO6391LanguageCode::ay, // Aymara
aze = ISO6391LanguageCode::az, // Azerbaijani / Azeri
bak = ISO6391LanguageCode::ba, // Bashkir
bam = ISO6391LanguageCode::bm, // Bambara
baq = ISO6391LanguageCode::eu, // Basque [B-code]
bel = ISO6391LanguageCode::be, // Belarusian
ben = ISO6391LanguageCode::bn, // Bengali
bih = ISO6391LanguageCode::bh, // Bihari languages
bis = ISO6391LanguageCode::bi, // Bislama
bos = ISO6391LanguageCode::bs, // Bosnian
bre = ISO6391LanguageCode::br, // Breton
bul = ISO6391LanguageCode::bg, // Bulgarian
bur = ISO6391LanguageCode::my, // Burmese [B-code]
cat = ISO6391LanguageCode::ca, // Catalan / Valencian
cha = ISO6391LanguageCode::ch, // Chamorro
che = ISO6391LanguageCode::ce, // Chechen
chi = ISO6391LanguageCode::zh, // Chinese [B-code]
chu = ISO6391LanguageCode::cu, // Old Church Slavonic
chv = ISO6391LanguageCode::cv, // Chuvash
cor = ISO6391LanguageCode::kw, // Cornish
cos = ISO6391LanguageCode::co, // Corsican
cre = ISO6391LanguageCode::cr, // Cree
cze = ISO6391LanguageCode::cs, // Czech [B-code]
dan = ISO6391LanguageCode::da, // Danish
div = ISO6391LanguageCode::dv, // Divehi
dut = ISO6391LanguageCode::nl, // Dutch [B-code]
dzo = ISO6391LanguageCode::dz, // Dzongkha
eng = ISO6391LanguageCode::en, // English
epo = ISO6391LanguageCode::eo, // Esperanto
est = ISO6391LanguageCode::et, // Estonian
ewe = ISO6391LanguageCode::ee, // Ewe
fao = ISO6391LanguageCode::fo, // Faroese
fij = ISO6391LanguageCode::fj, // Fijian
fin = ISO6391LanguageCode::fi, // Finnish
fre = ISO6391LanguageCode::fr, // French [B-code]
fry = ISO6391LanguageCode::fy, // Western Frisian
ful = ISO6391LanguageCode::ff, // Fulah
geo = ISO6391LanguageCode::ka, // Georgian [B-code]
ger = ISO6391LanguageCode::de, // German [B-code]
gla = ISO6391LanguageCode::gd, // Scottish Gaelic
gle = ISO6391LanguageCode::ga, // Irish
glg = ISO6391LanguageCode::gl, // Galician
glv = ISO6391LanguageCode::gv, // Manx
gre = ISO6391LanguageCode::el, // Greek [B-code]
grn = ISO6391LanguageCode::gn, // Guarani
guj = ISO6391LanguageCode::gu, // Gujarati
hat = ISO6391LanguageCode::ht, // Haitian Creole
hau = ISO6391LanguageCode::ha, // Hausa
heb = ISO6391LanguageCode::he, // Hebrew
her = ISO6391LanguageCode::hz, // Herero
hin = ISO6391LanguageCode::hi, // Hindi
hmo = ISO6391LanguageCode::ho, // Hiri Motu
hrv = ISO6391LanguageCode::hr, // Croatian
hun = ISO6391LanguageCode::hu, // Hungarian
ibo = ISO6391LanguageCode::ig, // Igbo
ice = ISO6391LanguageCode::is, // Icelandic [B-code]
ido = ISO6391LanguageCode::io, // Ido
iii = ISO6391LanguageCode::ii, // Sichuan Yi / Nuosu
iku = ISO6391LanguageCode::iu, // Inuktitut
ile = ISO6391LanguageCode::ie, // Interlingue
ina = ISO6391LanguageCode::ia, // Interlingua
ind = ISO6391LanguageCode::id, // Indonesian
ipk = ISO6391LanguageCode::ik, // Inupiaq
ita = ISO6391LanguageCode::it, // Italian
jav = ISO6391LanguageCode::jv, // Javanese
jpn = ISO6391LanguageCode::ja, // Japanese
kal = ISO6391LanguageCode::kl, // Greenlandic
kan = ISO6391LanguageCode::kn, // Kannada
kas = ISO6391LanguageCode::ks, // Kashmiri
kau = ISO6391LanguageCode::kr, // Kanuri
kaz = ISO6391LanguageCode::kk, // Kazakh
khm = ISO6391LanguageCode::km, // Khmer
kik = ISO6391LanguageCode::ki, // Kikuyu
kin = ISO6391LanguageCode::rw, // Kinyarwanda
kir = ISO6391LanguageCode::ky, // Kyrgyz
kom = ISO6391LanguageCode::kv, // Komi
kon = ISO6391LanguageCode::kg, // Kongo
kor = ISO6391LanguageCode::ko, // Korean
kua = ISO6391LanguageCode::kj, // Kwanyama
kur = ISO6391LanguageCode::ku, // Kurdish
lao = ISO6391LanguageCode::lo, // Lao
lat = ISO6391LanguageCode::la, // Latin
lav = ISO6391LanguageCode::lv, // Latvian
lim = ISO6391LanguageCode::li, // Limburgish
lin = ISO6391LanguageCode::ln, // Lingala
lit = ISO6391LanguageCode::lt, // Lithuanian
ltz = ISO6391LanguageCode::lb, // Luxembourgish
lub = ISO6391LanguageCode::lu, // Luba-Katanga
lug = ISO6391LanguageCode::lg, // Ganda
mac = ISO6391LanguageCode::mk, // Macedonian [B-code]
mah = ISO6391LanguageCode::mh, // Marshallese
mal = ISO6391LanguageCode::ml, // Malayalam
mao = ISO6391LanguageCode::mi, // Maori [B-code]
mar = ISO6391LanguageCode::mr, // Marathi
may = ISO6391LanguageCode::ms, // Malay [B-code]
mlg = ISO6391LanguageCode::mg, // Malagasy
mlt = ISO6391LanguageCode::mt, // Maltese
mon = ISO6391LanguageCode::mn, // Mongolian
nau = ISO6391LanguageCode::na, // Nauru
nav = ISO6391LanguageCode::nv, // Navajo
nbl = ISO6391LanguageCode::nr, // Southern Ndebele
nde = ISO6391LanguageCode::nd, // Northern Ndebele
ndo = ISO6391LanguageCode::ng, // Ndonga
nep = ISO6391LanguageCode::ne, // Nepali
nor = ISO6391LanguageCode::no, // Norwegian
nya = ISO6391LanguageCode::ny, // Chichewa
oci = ISO6391LanguageCode::oc, // Occitan
oji = ISO6391LanguageCode::oj, // Ojibwa
ori = ISO6391LanguageCode::or_, // Oriya
orm = ISO6391LanguageCode::om, // Oromo
oss = ISO6391LanguageCode::os, // Ossetian
pan = ISO6391LanguageCode::pa, // Punjabi
per = ISO6391LanguageCode::fa, // Persian [B-code]
pli = ISO6391LanguageCode::pi, // Pali
pol = ISO6391LanguageCode::pl, // Polish
por = ISO6391LanguageCode::pt, // Portuguese
pus = ISO6391LanguageCode::ps, // Pashto
que = ISO6391LanguageCode::qu, // Quechua
roh = ISO6391LanguageCode::rm, // Romansh
rum = ISO6391LanguageCode::ro, // Romanian [B-code]
run = ISO6391LanguageCode::rn, // Rundi
rus = ISO6391LanguageCode::ru, // Russian
sag = ISO6391LanguageCode::sg, // Sango
san = ISO6391LanguageCode::sa, // Sanskrit
sin = ISO6391LanguageCode::si, // Sinhalese
slo = ISO6391LanguageCode::sk, // Slovak [B-code]
slv = ISO6391LanguageCode::sl, // Slovenian
sme = ISO6391LanguageCode::se, // Northern Sami
smo = ISO6391LanguageCode::sm, // Samoan
sna = ISO6391LanguageCode::sn, // Shona
snd = ISO6391LanguageCode::sd, // Sindhi
som = ISO6391LanguageCode::so, // Somali
sot = ISO6391LanguageCode::st, // Sotho
spa = ISO6391LanguageCode::es, // Spanish
srd = ISO6391LanguageCode::sc, // Sardinian
srp = ISO6391LanguageCode::sr, // Serbian
ssw = ISO6391LanguageCode::ss, // Swati
sun = ISO6391LanguageCode::su, // Sundanese
swa = ISO6391LanguageCode::sw, // Swahili
swe = ISO6391LanguageCode::sv, // Swedish
tah = ISO6391LanguageCode::ty, // Tahitian
tam = ISO6391LanguageCode::ta, // Tamil
tat = ISO6391LanguageCode::tt, // Tatar
tel = ISO6391LanguageCode::te, // Telugu
tgk = ISO6391LanguageCode::tg, // Tajik
tgl = ISO6391LanguageCode::tl, // Tagalog
tha = ISO6391LanguageCode::th, // Thai
tib = ISO6391LanguageCode::bo, // Tibetan [B-code]
tir = ISO6391LanguageCode::ti, // Tigrinya
ton = ISO6391LanguageCode::to, // Tonga
tsn = ISO6391LanguageCode::tn, // Tswana
tso = ISO6391LanguageCode::ts, // Tsonga
tuk = ISO6391LanguageCode::tk, // Turkmen
tur = ISO6391LanguageCode::tr, // Turkish
twi = ISO6391LanguageCode::tw, // Twi
uig = ISO6391LanguageCode::ug, // Uighur
ukr = ISO6391LanguageCode::uk, // Ukrainian
urd = ISO6391LanguageCode::ur, // Urdu
uzb = ISO6391LanguageCode::uz, // Uzbek
ven = ISO6391LanguageCode::ve, // Venda
vie = ISO6391LanguageCode::vi, // Vietnamese
vol = ISO6391LanguageCode::vo, // Volapuk
wel = ISO6391LanguageCode::cy, // Welsh [B-code]
wln = ISO6391LanguageCode::wa, // Walloon
wol = ISO6391LanguageCode::wo, // Wolof
xho = ISO6391LanguageCode::xh, // Xhosa
yid = ISO6391LanguageCode::yi, // Yiddish
yor = ISO6391LanguageCode::yo, // Yoruba
zha = ISO6391LanguageCode::za, // Zhuang
zul = ISO6391LanguageCode::zu, // Zulu
ace, // Achinese
ach, // Acoli
ada, // Adangme
ady, // Adyghe
afh, // Afrihili
ain, // Ainu
akk, // Akkadian
ale, // Aleut
alg, // Algonquian languages
alt, // Southern Altai
ang, // Old English
anp, // Angika
apa, // Apache languages
arc, // Official Aramaic / Imperial Aramaic
arn, // Mapudungun
arp, // Arapaho
arw, // Arawak
ast, // Asturian / Leonese
ath, // Athapascan languages
aus, // Australian languages
awa, // Awadhi
bad, // Banda languages
bai, // Bamileke languages
bal, // Baluchi
ban, // Balinese
bas, // Basa
bej, // Beja
bem, // Bemba
ber, // Berber languages
bho, // Bhojpuri
bik, // Bikol
bin, // Bini / Edo
bla, // Siksika
bra, // Braj
btk, // Batak languages
bua, // Buriat
bug, // Buginese
byn, // Bilin
cad, // Caddo
cai, // Mesoamerican languages
car, // Carib
ceb, // Cebuano
chb, // Chibcha
chg, // Chagatai
chk, // Chuukese
chm, // Mari
chn, // Chinook jargon
cho, // Choctaw
chp, // Chipewyan
chr, // Cherokee
chy, // Cheyenne
cmc, // Chamic languages
cnr, // Montenegrin
cop, // Coptic
cpe, // English creoles
cpf, // French creoles
cpp, // Portuguese creoles
crh, // Crimean Tatar
csb, // Kashubian
dak, // Dakota
dar, // Dargwa
day, // Land Dayak languages
del, // Delaware
den, // Slavey
dgr, // Dogrib
din, // Dinka
doi, // Dogri
dsb, // Lower Sorbian
dua, // Duala
dum, // Middle Dutch
dyu, // Dyula
efi, // Efik
egy, // Egyptian
eka, // Ekajuk
elx, // Elamite
enm, // Middle English
ewo, // Ewondo
fan, // Fang
fat, // Fanti
fon, // Fon
frm, // Middle French
fro, // Old French
frr, // Northern Frisian
frs, // Eastern Frisian
fur, // Friulian
gaa, // Ga
gay, // Gayo
gba, // Gbaya
gez, // Geez
gil, // Gilbertese
gmh, // Middle High German
goh, // Old High German
gon, // Gondi
gor, // Gorontalo
got, // Gothic
grb, // Grebo
grc, // Ancient Greek
gsw, // Swiss German / Alemannic
gwi, // Gwich'in
hai, // Haida
haw, // Hawaiian
hil, // Hiligaynon
him, // Himachali languages
hit, // Hittite
hmn, // Hmong
hsb, // Upper Sorbian
hup, // Hupa
iba, // Iban
ijo, // Ijo languages
ilo, // Iloko
inh, // Ingush
iro, // Iroquoian languages
jbo, // Lojban
jpr, // Judeo-Persian
jrb, // Judeo-Arabic
kaa, // Kara-Kalpak
kab, // Kabyle
kac, // Kachin / Jingpho
kam, // Kamba
kar, // Karen languages
kaw, // Kawi
kbd, // Kabardian
kha, // Khasi
khi, // Khoisan languages
kho, // Khotanese / Sakan
kmb, // Kimbundu
kok, // Konkani
kos, // Kosraean
kpe, // Kpelle
krc, // Karachay-Balkar
krl, // Karelian
kro, // Kru languages
kru, // Kurukh
kum, // Kumyk
kut, // Kutenai
lad, // Ladino
lah, // Lahnda
lam, // Lamba
lez, // Lezghian
lol, // Mongo
loz, // Lozi
lua, // Luba-Lulua
lui, // Luiseno
lun, // Lunda
luo, // Luo
lus, // Lushai
mad, // Madurese
mag, // Magahi
mai, // Maithili
mak, // Makasar
man, // Mandingo
mas, // Masai
mdf, // Moksha
mdr, // Mandar
men, // Mende
mga, // Middle Irish
mic, // Micmac
min, // Minangkabau
mis, // uncoded languages
mkh, // Mon-Khmer languages
mnc, // Manchu
mni, // Manipuri
mno, // Manobo languages
moh, // Mohawk
mos, // Mossi
mul, // multiple languages
mun, // Munda languages
mus, // Creek
mwl, // Mirandese
mwr, // Marwari
myn, // Mayan languages
myv, // Erzya
nah, // Nahuatl languages
nai, // Indigenous North American languages
nap, // Neapolitan
nds, // Low German / Low Saxon
new_, // Newari
nia, // Nias
niu, // Niuean
nog, // Nogai
non, // Old Norse
nqo, // N'Ko
nso, // Sepedi / Northern Sotho
nub, // Nubian languages
nwc, // Old Newari / Classical Newari
nym, // Nyamwezi
nyn, // Nyankole
nyo, // Nyoro
nzi, // Nzima
osa, // Osage
ota, // Ottoman Turkish
oto, // Otomian languages
paa, // Papuan languages
pag, // Pangasinan
pal, // Pahlavi
pam, // Pampanga
pap, // Papiamento
pau, // Palauan
peo, // Old Persian
phi, // Philippine languages
phn, // Phoenician
pon, // Pohnpeian
pra, // Prakrit languages
pro, // Old Occitan / Old Provencal
raj, // Rajasthani
rap, // Rapanui
rar, // Rarotongan / Cook Islands Maori
rom, // Romany
rup, // Aromanian
sad, // Sandawe
sah, // Yakut
sai, // Indigenous South American language
sal, // Salishan languages
sam, // Samaritan
sas, // Sasak
sat, // Santali
scn, // Sicilian
sco, // Scots
sel, // Selkup
sga, // Old Irish
shn, // Shan
sid, // Sidamo
sio, // Siouan languages
sma, // Southern Sami
smj, // Lule Sami
smn, // Inari Sami
sms, // Skolt Sami
snk, // Soninke
sog, // Sogdian
son, // Songhai languages
srn, // Sranan Tongo
srr, // Serer
suk, // Sukuma
sus, // Susu
sux, // Sumerian
syc, // Classical Syriac
syr, // Syriac
tai, // Tai languages
tem, // Timne
ter, // Tereno
tet, // Tetum
tig, // Tigre
tiv, // Tiv
tkl, // Tokelau
tlh, // Klingon
tli, // Tlingit
tmh, // Tamashek
tog, // Tonga (Nyasa)
tpi, // Tok Pisin
tsi, // Tsimshian
tum, // Tumbuka
tup, // Tupi languages
tut, // Altaic languages
tvl, // Tuvalu
tyv, // Tuvinian
udm, // Udmurt
uga, // Ugaritic
umb, // Umbundu
vai, // Vai
vot, // Votic
wak, // Wakashan languages
wal, // Walamo
war, // Waray
was, // Washo
wen, // Sorbian languages
xal, // Kalmyk / Oirat
yao, // Yao
yap, // Yapese
ypk, // Yupik languages
zap, // Zapotec
zbl, // Blissymbols
zen, // Zenaga
zgh, // Tamazight
znd, // Zande languages
zun, // Zuni
zza, // Zaza / Dimili / Kirdki / Zazaki
// Alternative terminological codes (T-codes)
bod = tib, // Tibetan
ces = cze, // Czech
cym = wel, // Welsh
deu = ger, // German
ell = gre, // Greek
eus = baq, // Basque
fas = per, // Persian
fra = fre, // French
hye = arm, // Armenian
isl = ice, // Icelandic
kat = geo, // Georgian
mkd = mac, // Macedonian
mri = mao, // Maori
msa = may, // Malay
mya = bur, // Burmese
nld = dut, // Dutch
ron = rum, // Romanian
slk = slo, // Slovak
sqi = alb, // Albanian
zho = chi, // Chinese
// Languages treated here as being the same
fil = tgl // Filipino / Tagalog
};
using language = ISO6392LanguageCode;
}
namespace // internal parts
{
constexpr const uint16_t ISO6391CodesCount = omn::ISO6391LanguageCode::zu + 1;
constexpr const omn::unicode::UTF8Character * ISO6391CodeStrings[ISO6391CodesCount] =
{
u8"aa",
u8"ab",
u8"af",
u8"ak",
u8"sq",
u8"am",
u8"ar",
u8"an",
u8"hy",
u8"as",
u8"av",
u8"ae",
u8"ay",
u8"az",
u8"ba",
u8"bm",
u8"eu",
u8"be",
u8"bn",
u8"bh",
u8"bi",
u8"bs",
u8"br",
u8"bg",
u8"my",
u8"ca",
u8"ch",
u8"ce",
u8"zh",
u8"cu",
u8"cv",
u8"kw",
u8"co",
u8"cr",
u8"cs",
u8"da",
u8"dv",
u8"nl",
u8"dz",
u8"en",
u8"eo",
u8"et",
u8"ee",
u8"fo",
u8"fj",
u8"fi",
u8"fr",
u8"fy",
u8"ff",
u8"ka",
u8"de",
u8"gd",
u8"ga",
u8"gl",
u8"gv",
u8"el",
u8"gn",
u8"gu",
u8"ht",
u8"ha",
u8"he",
u8"hz",
u8"hi",
u8"ho",
u8"hr",
u8"hu",
u8"ig",
u8"is",
u8"io",
u8"ii",
u8"iu",
u8"ie",
u8"ia",
u8"id",
u8"ik",
u8"it",
u8"jv",
u8"ja",
u8"kl",
u8"kn",
u8"ks",
u8"kr",
u8"kk",
u8"km",
u8"ki",
u8"rw",
u8"ky",
u8"kv",
u8"kg",
u8"ko",
u8"kj",
u8"ku",
u8"lo",
u8"la",
u8"lv",
u8"li",
u8"ln",
u8"lt",
u8"lb",
u8"lu",
u8"lg",
u8"mk",
u8"mh",
u8"ml",
u8"mi",
u8"mr",
u8"ms",
u8"mg",
u8"mt",
u8"mn",
u8"na",
u8"nv",
u8"nr",
u8"nd",
u8"ng",
u8"ne",
u8"no",
u8"ny",
u8"oc",
u8"oj",
u8"or",
u8"om",
u8"os",
u8"pa",
u8"fa",
u8"pi",
u8"pl",
u8"pt",
u8"ps",
u8"qu",
u8"rm",
u8"ro",
u8"rn",
u8"ru",
u8"sg",
u8"sa",
u8"si",
u8"sk",
u8"sl",
u8"se",
u8"sm",
u8"sn",
u8"sd",
u8"so",
u8"st",
u8"es",
u8"sc",
u8"sr",
u8"ss",
u8"su",
u8"sw",
u8"sv",
u8"ty",
u8"ta",
u8"tt",
u8"te",
u8"tg",
u8"tl",
u8"th",
u8"bo",
u8"ti",
u8"to",
u8"tn",
u8"ts",
u8"tk",
u8"tr",
u8"tw",
u8"ug",
u8"uk",
u8"ur",
u8"uz",
u8"ve",
u8"vi",
u8"vo",
u8"cy",
u8"wa",
u8"wo",
u8"xh",
u8"yi",
u8"yo",
u8"za",
u8"zu"
};
constexpr const uint16_t ISO6392CodesCount = omn::ISO6392LanguageCode::zza + 2;
constexpr const omn::unicode::UTF8Character * ISO6392CodeStrings[ISO6392CodesCount] =
{
u8"zxx",
u8"aar",
u8"abk",
u8"afr",
u8"aka",
u8"alb",
u8"amh",
u8"ara",
u8"arg",
u8"arm",
u8"asm",
u8"ava",
u8"ave",
u8"aym",
u8"aze",
u8"bak",
u8"bam",
u8"baq",
u8"bel",
u8"ben",
u8"bih",
u8"bis",
u8"bos",
u8"bre",
u8"bul",
u8"bur",
u8"cat",
u8"cha",
u8"che",
u8"chi",
u8"chu",
u8"chv",
u8"cor",
u8"cos",
u8"cre",
u8"cze",
u8"dan",
u8"div",
u8"dut",
u8"dzo",
u8"eng",
u8"epo",
u8"est",
u8"ewe",
u8"fao",
u8"fij",
u8"fin",
u8"fre",
u8"fry",
u8"ful",
u8"geo",
u8"ger",
u8"gla",
u8"gle",
u8"glg",
u8"glv",
u8"gre",
u8"grn",
u8"guj",
u8"hat",
u8"hau",
u8"heb",
u8"her",
u8"hin",
u8"hmo",
u8"hrv",
u8"hun",
u8"ibo",
u8"ice",
u8"ido",
u8"iii",
u8"iku",
u8"ile",
u8"ina",
u8"ind",
u8"ipk",
u8"ita",
u8"jav",
u8"jpn",
u8"kal",
u8"kan",
u8"kas",
u8"kau",
u8"kaz",
u8"khm",
u8"kik",
u8"kin",
u8"kir",
u8"kom",
u8"kon",
u8"kor",
u8"kua",
u8"kur",
u8"lao",
u8"lat",
u8"lav",
u8"lim",
u8"lin",
u8"lit",
u8"ltz",
u8"lub",
u8"lug",
u8"mac",
u8"mah",
u8"mal",
u8"mao",
u8"mar",
u8"may",
u8"mlg",
u8"mlt",
u8"mon",
u8"nau",
u8"nav",
u8"nbl",
u8"nde",
u8"ndo",
u8"nep",
u8"nor",
u8"nya",
u8"oci",
u8"oji",
u8"ori",
u8"orm",
u8"oss",
u8"pan",
u8"per",
u8"pli",
u8"pol",
u8"por",
u8"pus",
u8"que",
u8"roh",
u8"rum",
u8"run",
u8"rus",
u8"sag",
u8"san",
u8"sin",
u8"slo",
u8"slv",
u8"sme",
u8"smo",
u8"sna",
u8"snd",
u8"som",
u8"sot",
u8"spa",
u8"srd",
u8"srp",
u8"ssw",
u8"sun",
u8"swa",
u8"swe",
u8"tah",
u8"tam",
u8"tat",
u8"tel",
u8"tgk",
u8"tgl",
u8"tha",
u8"tib",
u8"tir",
u8"ton",
u8"tsn",
u8"tso",
u8"tuk",
u8"tur",
u8"twi",
u8"uig",
u8"ukr",
u8"urd",
u8"uzb",
u8"ven",
u8"vie",
u8"vol",
u8"wel",
u8"wln",
u8"wol",
u8"xho",
u8"yid",
u8"yor",
u8"zha",
u8"zul",
u8"ace",
u8"ach",
u8"ada",
u8"ady",
u8"afh",
u8"ain",
u8"akk",
u8"ale",
u8"alg",
u8"alt",
u8"ang",
u8"anp",
u8"apa",
u8"arc",
u8"arn",
u8"arp",
u8"arw",
u8"ast",
u8"ath",
u8"aus",
u8"awa",
u8"bad",
u8"bai",
u8"bal",
u8"ban",
u8"bas",
u8"bej",
u8"bem",
u8"ber",
u8"bho",
u8"bik",
u8"bin",
u8"bla",
u8"bra",
u8"btk",
u8"bua",
u8"bug",
u8"byn",
u8"cad",
u8"cai",
u8"car",
u8"ceb",
u8"chb",
u8"chg",
u8"chk",
u8"chm",
u8"chn",
u8"cho",
u8"chp",
u8"chr",
u8"chy",
u8"cmc",
u8"cnr",
u8"cop",
u8"cpe",
u8"cpf",
u8"cpp",
u8"crh",
u8"csb",
u8"dak",
u8"dar",
u8"day",
u8"del",
u8"den",
u8"dgr",
u8"din",
u8"doi",
u8"dsb",
u8"dua",
u8"dum",
u8"dyu",
u8"efi",
u8"egy",
u8"eka",
u8"elx",
u8"enm",
u8"ewo",
u8"fan",
u8"fat",
u8"fon",
u8"frm",
u8"fro",
u8"frr",
u8"frs",
u8"fur",
u8"gaa",
u8"gay",
u8"gba",
u8"gez",
u8"gil",
u8"gmh",
u8"goh",
u8"gon",
u8"gor",
u8"got",
u8"grb",
u8"grc",
u8"gsw",
u8"gwi",
u8"hai",
u8"haw",
u8"hil",
u8"him",
u8"hit",
u8"hmn",
u8"hsb",
u8"hup",
u8"iba",
u8"ijo",
u8"ilo",
u8"inh",
u8"iro",
u8"jbo",
u8"jpr",
u8"jrb",
u8"kaa",
u8"kab",
u8"kac",
u8"kam",
u8"kar",
u8"kaw",
u8"kbd",
u8"kha",
u8"khi",
u8"kho",
u8"kmb",
u8"kok",
u8"kos",
u8"kpe",
u8"krc",
u8"krl",
u8"kro",
u8"kru",
u8"kum",
u8"kut",
u8"lad",
u8"lah",
u8"lam",
u8"lez",
u8"lol",
u8"loz",
u8"lua",
u8"lui",
u8"lun",
u8"luo",
u8"lus",
u8"mad",
u8"mag",
u8"mai",
u8"mak",
u8"man",
u8"mas",
u8"mdf",
u8"mdr",
u8"men",
u8"mga",
u8"mic",
u8"min",
u8"mis",
u8"mkh",
u8"mnc",
u8"mni",
u8"mno",
u8"moh",
u8"mos",
u8"mul",
u8"mun",
u8"mus",
u8"mwl",
u8"mwr",
u8"myn",
u8"myv",
u8"nah",
u8"nai",
u8"nap",
u8"nds",
u8"new",
u8"nia",
u8"niu",
u8"nog",
u8"non",
u8"nqo",
u8"nso",
u8"nub",
u8"nwc",
u8"nym",
u8"nyn",
u8"nyo",
u8"nzi",
u8"osa",
u8"ota",
u8"oto",
u8"paa",
u8"pag",
u8"pal",
u8"pam",
u8"pap",
u8"pau",
u8"peo",
u8"phi",
u8"phn",
u8"pon",
u8"pra",
u8"pro",
u8"raj",
u8"rap",
u8"rar",
u8"rom",
u8"rup",
u8"sad",
u8"sah",
u8"sai",
u8"sal",
u8"sam",
u8"sas",
u8"sat",
u8"scn",
u8"sco",
u8"sel",
u8"sga",
u8"shn",
u8"sid",
u8"sio",
u8"sma",
u8"smj",
u8"smn",
u8"sms",
u8"snk",
u8"sog",
u8"son",
u8"srn",
u8"srr",
u8"suk",
u8"sus",
u8"sux",
u8"syc",
u8"syr",
u8"tai",
u8"tem",
u8"ter",
u8"tet",
u8"tig",
u8"tiv",
u8"tkl",
u8"tlh",
u8"tli",
u8"tmh",
u8"tog",
u8"tpi",
u8"tsi",
u8"tum",
u8"tup",
u8"tut",
u8"tvl",
u8"tyv",
u8"udm",
u8"uga",
u8"umb",
u8"vai",
u8"vot",
u8"wak",
u8"wal",
u8"war",
u8"was",
u8"wen",
u8"xal",
u8"yao",
u8"yap",
u8"ypk",
u8"zap",
u8"zbl",
u8"zen",
u8"zgh",
u8"znd",
u8"zun",
u8"zza",
u8"und"
};
}
namespace omn
{
constexpr const unicode::UTF8Character * ISO6391CodeString( ISO6391LanguageCode code )
{
return ISO6391CodeStrings[(code % ISO6391CodesCount)];
}
constexpr const unicode::UTF8Character * ISO6392CodeString( ISO6392LanguageCode code )
{
return ISO6392CodeStrings[((code >= ISO6392CodesCount) ? (ISO6392CodesCount - 1) : code)];
}
}
namespace std
{
inline string to_string( const omn::ISO6391LanguageCode code )
{
return omn::ISO6391CodeString(code);
}
inline ostream & operator << ( ostream & os, const omn::ISO6391LanguageCode code )
{
os << omn::ISO6391CodeString(code);
return os;
}
inline string to_string( const omn::ISO6392LanguageCode code )
{
return omn::ISO6392CodeString(code);
}
inline ostream & operator << ( ostream & os, const omn::ISO6392LanguageCode code )
{
os << omn::ISO6392CodeString(code);
return os;
}
}
#endif // _OMN_ISO639_INCLUDED
| 26.149466 | 98 | 0.442352 | [
"cad"
] |
83b9ef959f422821e4bddaa187b5447a8f27a356 | 1,161 | hpp | C++ | willow/include/popart/op/shapeddropout.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/include/popart/op/shapeddropout.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/include/popart/op/shapeddropout.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#ifndef GUARD_NEURALNET_SHAPEDDROPOUT_HPP
#define GUARD_NEURALNET_SHAPEDDROPOUT_HPP
#include <popart/op/dropoutbase.hpp>
namespace popart {
class ShapedDropoutOp : public DropoutBaseOp {
public:
ShapedDropoutOp(const OperatorIdentifier &_opid,
float ratio_,
const Shape &shape_,
const Op::Settings &settings_);
const std::vector<int64_t> &getShape() const { return shape; }
std::unique_ptr<Op> clone() const override;
std::vector<std::unique_ptr<Op>> getGradOps() override;
void setup() override;
void appendOutlineAttributes(OpSerialiserBase &) const override;
private:
std::vector<int64_t> shape;
};
class ShapedDropoutGradOp : public ShapedDropoutOp {
public:
ShapedDropoutGradOp(const ShapedDropoutOp &fwdOp);
std::unique_ptr<Op> clone() const override;
const std::vector<GradInOutMapper> &gradInputInfo() const override;
const std::map<int, int> &gradOutToNonGradIn() const override;
static InIndex getGradInIndex() { return 0; }
static OutIndex getOutIndex() { return 0; }
};
} // namespace popart
#endif
| 27 | 69 | 0.725237 | [
"shape",
"vector"
] |
83bc2f7804923a17b68dc1a4c5f567368364947d | 108,249 | cpp | C++ | database/L3/src/sw/gqe_aggr.cpp | Geekdude/Vitis_Libraries | bca52cee88c07e9ccbec90c00e6df98f4b450ec1 | [
"Apache-2.0"
] | 1 | 2021-04-19T20:40:02.000Z | 2021-04-19T20:40:02.000Z | database/L3/src/sw/gqe_aggr.cpp | Geekdude/Vitis_Libraries | bca52cee88c07e9ccbec90c00e6df98f4b450ec1 | [
"Apache-2.0"
] | null | null | null | database/L3/src/sw/gqe_aggr.cpp | Geekdude/Vitis_Libraries | bca52cee88c07e9ccbec90c00e6df98f4b450ec1 | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2020 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <unordered_map>
// L2
#include "xf_database/meta_table.hpp"
#include "xf_database/gqe_utils.hpp"
// L3
#include "xf_database/gqe_aggr.hpp"
namespace xf {
namespace database {
namespace gqe {
Aggregator::Aggregator(std::string xclbin) {
xclbin_path = xclbin;
err = xf::database::gqe::init_hardware(&ctx, &dev_id, &cq,
CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE);
if (err != CL_SUCCESS) {
fprintf(stderr, "ERROR: fail to init hardware\n");
exit(1);
}
err = xf::database::gqe::load_binary(&prg, ctx, dev_id, xclbin_path.c_str());
if (err != CL_SUCCESS) {
fprintf(stderr, "ERROR: fail to program PL\n");
exit(1);
}
}
Aggregator::~Aggregator() {
err = clReleaseProgram(prg);
if (err != CL_SUCCESS) {
std::cout << "deconstructor" << std::endl;
exit(1);
}
clReleaseCommandQueue(cq);
clReleaseContext(ctx);
};
ErrCode Aggregator::aggregate(Table& tab_in,
std::vector<EvaluationInfo> evals_info,
std::string filter_str,
std::string group_keys_str,
std::string output_str,
Table& tab_out,
AggrStrategyBase* strategyimp) {
// strategy
bool new_s = false;
if (strategyimp == nullptr) {
strategyimp = new AggrStrategyBase();
new_s = true;
}
auto params = strategyimp->getSolutionParams(tab_in);
// for deug
// cfg
AggrConfig aggr_config(tab_in, evals_info, filter_str, group_keys_str, output_str, (params[0] == 1));
// join
ErrCode err = aggr_all(tab_in, tab_out, aggr_config, params);
if (new_s) delete strategyimp;
return err;
}
ErrCode Aggregator::aggr_all(Table& tab_in, Table& tab_out, AggrConfig& aggr_cfg, std::vector<size_t> params) {
ErrCode err;
size_t _solution = params[0];
if (_solution == 0) {
std::cout << "direct aggregate" << std::endl;
err = aggr_sol0(tab_in, tab_out, aggr_cfg, params);
} else if (_solution == 1) {
std::cout << "pipelined aggregate" << std::endl;
err = aggr_sol1(tab_in, tab_out, aggr_cfg, params);
} else if (_solution == 2) {
std::cout << "partition + pipelined aggregate" << std::endl;
err = aggr_sol2(tab_in, tab_out, aggr_cfg, params);
} else {
return PARAM_ERROR;
}
return err;
}
ErrCode Aggregator::aggr_sol0(Table& tab_in, Table& tab_out, AggrConfig& aggr_cfg, std::vector<size_t> params) {
const int size_of_apu512 = sizeof(ap_uint<512>);
const int VEC_LEN = size_of_apu512 / sizeof(int);
int tab_in_col_num = tab_in.getColNum();
int tab_in_row_num = tab_in.getRowNum();
int tab_out_col_num = tab_out.getColNum();
int result_nrow = tab_out.getRowNum();
int tb_in_col_depth = (tab_in_row_num + VEC_LEN - 1) / VEC_LEN;
int tb_in_col_size = size_of_apu512 * tb_in_col_depth;
int* tab_in_col_type = new int[tab_in_col_num];
int* tab_out_col_type = new int[tab_out_col_num];
for (int i = 0; i < tab_in_col_num; i++) {
tab_in_col_type[i] = tab_in.getColTypeSize(i);
}
for (int i = 0; i < tab_out_col_num; i++) {
tab_out_col_type[i] = tab_out.getColTypeSize(i);
}
gqe::utils::MM mm;
//--------------- get sw scan input host bufer -----------------
std::vector<int8_t> scan_list = aggr_cfg.getScanList();
#ifdef USER_DEBUG
std::cout << "table in info: " << tab_in_row_num << " rows, " << tab_in_col_num << " cols." << std::endl;
std::cout << "table out info: " << result_nrow << " rows, " << tab_out_col_num << " cols." << std::endl;
std::cout << "scan_list:" << std::endl;
for (size_t i = 0; i < scan_list.size(); i++) {
std::cout << (int)scan_list[i] << " ";
}
std::cout << std::endl;
#endif
char* table_in_col[8];
for (int i = 0; i < tab_in_col_num; i++) {
table_in_col[i] = tab_in.getColPointer(scan_list[i]);
}
for (int i = tab_in_col_num; i < 8; i++) table_in_col[i] = mm.aligned_alloc<char>(tb_in_col_size);
//--------------- get output host bufer -----------------
size_t table_result_depth = (result_nrow + VEC_LEN - 1) / VEC_LEN;
size_t table_result_size = table_result_depth * size_of_apu512;
char* table_out_col[16];
for (int i = 0; i < 16; i++) {
table_out_col[i] = mm.aligned_alloc<char>(table_result_size);
}
MetaTable meta_aggr_in;
meta_aggr_in.setColNum(tab_in_col_num);
for (int i = 0; i < tab_in_col_num; i++) {
meta_aggr_in.setCol(i, i, tab_in_row_num);
}
MetaTable meta_aggr_out;
meta_aggr_out.setColNum(8);
for (int i = 0; i < 8; i++) {
meta_aggr_out.setCol(i, i, result_nrow);
}
ap_uint<32>* table_cfg = aggr_cfg.getAggrConfigBits();
ap_uint<32>* table_cfg_out = aggr_cfg.getAggrConfigOutBits();
// build kernel
cl_kernel agg_kernel = clCreateKernel(prg, "gqeAggr", &err);
if (err != CL_SUCCESS) {
fprintf(stderr, "ERROR: failed to create kernel.\n");
exit(1);
}
std::cout << "Kernel has been created\n";
#ifdef USER_DEBUG
std::cout << "debug 0" << std::endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
std::cout << table_cfg[i].range(j * 8 + 7, j * 8) << " ";
}
}
std::cout << std::endl;
#endif
//--------------- get output host bufer -----------------
cl_mem_ext_ptr_t mext_table_in_col[8];
cl_mem_ext_ptr_t mext_meta_aggr_in, mext_meta_aggr_out, mext_cfg, mext_cfg_out;
cl_mem_ext_ptr_t mext_table_out[16], memExt[8];
int agg_i = 0;
for (int i = 0; i < 8; i++) {
mext_table_in_col[i] = {agg_i++, table_in_col[i], agg_kernel};
}
mext_meta_aggr_in = {agg_i++, meta_aggr_in.meta(), agg_kernel};
mext_meta_aggr_out = {agg_i++, meta_aggr_out.meta(), agg_kernel};
for (int i = 0; i < 16; ++i) {
mext_table_out[i] = {agg_i++, table_out_col[i], agg_kernel};
}
mext_cfg = {agg_i++, table_cfg, agg_kernel};
mext_cfg_out = {agg_i++, table_cfg_out, agg_kernel};
for (int i = 0; i < 8; i++) {
memExt[i] = {agg_i++, nullptr, agg_kernel};
}
cl_mem buf_tb_in_col[8];
for (int i = 0; i < 8; ++i) {
buf_tb_in_col[i] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
tb_in_col_size, &mext_table_in_col[i], &err);
}
cl_mem buf_meta_aggr_in = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_in, &err);
cl_mem buf_meta_aggr_out = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_out, &err);
cl_mem buf_cfg = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_t(4 * 128), &mext_cfg, &err);
cl_mem buf_cfg_out = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
size_t(4 * 128), &mext_cfg_out, &err);
cl_mem buf_tb_out_col[16];
for (int i = 0; i < 16; ++i) {
buf_tb_out_col[i] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
table_result_size, &mext_table_out[i], &err);
}
cl_mem buf_tmp[8];
for (int i = 0; i < 8; i++) {
buf_tmp[i] = clCreateBuffer(ctx, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS | CL_MEM_EXT_PTR_XILINX,
(size_t)(8 * S_BUFF_DEPTH), &memExt[i], &err);
}
// set args and enqueue kernel
int j = 0;
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[0]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[1]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[2]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[3]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[4]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[5]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[6]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_in_col[7]);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_meta_aggr_in);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_meta_aggr_out);
for (int k = 0; k < 16; k++) {
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tb_out_col[k]);
}
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_cfg);
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_cfg_out);
for (int k = 0; k < 8; k++) {
clSetKernelArg(agg_kernel, j++, sizeof(cl_mem), &buf_tmp[k]);
}
std::vector<cl_mem> in_vec;
for (int i = 0; i < tab_in_col_num; i++) {
in_vec.push_back(buf_tb_in_col[i]);
}
in_vec.push_back(buf_meta_aggr_in);
in_vec.push_back(buf_meta_aggr_out);
in_vec.push_back(buf_cfg);
std::vector<cl_mem> out_vec;
for (int i = 0; i < 16; ++i) {
out_vec.push_back(buf_tb_out_col[i]);
}
out_vec.push_back(buf_meta_aggr_out);
std::array<cl_event, 1> evt_h2d;
std::array<cl_event, 1> evt_krn;
std::array<cl_event, 1> evt_d2h;
// step 1 h2d
clEnqueueMigrateMemObjects(cq, in_vec.size(), in_vec.data(), 0, 0, nullptr, &evt_h2d[0]);
// step 2 run kernel
clEnqueueTask(cq, agg_kernel, 1, evt_h2d.data(), &evt_krn[0]);
// step 3 d2h
clEnqueueMigrateMemObjects(cq, out_vec.size(), out_vec.data(), CL_MIGRATE_MEM_OBJECT_HOST, 1, evt_krn.data(),
&evt_d2h[0]);
clFinish(cq);
std::cout << "finished data transfer d2h" << std::endl;
int nrow = meta_aggr_out.getColLen();
std::cout << "After Aggr Row Num:" << nrow << std::endl;
std::vector<std::vector<int> > merge_info;
int output_col_num = aggr_cfg.getOutputColNum();
#ifdef USER_DEBUG
std::cout << "Merging into " << output_col_num << " cols, info:" << std::endl;
#endif
for (int i = 0; i < output_col_num; i++) {
merge_info.push_back(aggr_cfg.getResults(i));
}
double l_input_memcpy_size = 0;
double l_output_memcpy_size = 0;
for (int i = 0; i < tab_in_col_num; i++) {
l_input_memcpy_size += (double)tab_in_row_num * tab_in_col_type[i];
}
for (int i = 0; i < tab_out_col_num; i++) {
l_output_memcpy_size += (double)nrow * tab_out_col_type[i];
}
l_input_memcpy_size = (double)l_input_memcpy_size / 1024 / 1024;
l_output_memcpy_size = (double)l_output_memcpy_size / 1024 / 1024;
std::cout << "-----------------------Data Transfer Info-----------------------" << std::endl;
std::cout << "H2D size = " << l_input_memcpy_size << " MB" << std::endl;
std::cout << "D2H size = " << l_output_memcpy_size << " MB" << std::endl;
std::cout << "------------------------Performance Info------------------------" << std::endl;
cl_ulong start1, end1;
clGetEventProfilingInfo(evt_krn[0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start1, NULL);
clGetEventProfilingInfo(evt_krn[0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end1, NULL);
long kerneltime1 = (end1 - start1) / 1000000;
std::cout << std::dec << "Kernel execution time " << kerneltime1 << " ms" << std::endl;
char** cos_of_table_out = new char*[output_col_num];
std::cout << "output_col_num:" << output_col_num << std::endl;
for (int i = 0; i < output_col_num; i++) {
cos_of_table_out[i] = tab_out.getColPointer(i);
}
for (int j = 0; j < nrow; j++) {
for (int i = 0; i < output_col_num; i++) {
std::vector<int> index = merge_info[i];
int col_size = sizeof(int);
if (index.size() == 1) {
int tmp = 0;
memcpy(&tmp, table_out_col[index[0]] + j * col_size, col_size);
int64_t tmp_64b = tmp;
memcpy(cos_of_table_out[i] + j * tab_out_col_type[i], &tmp_64b, tab_out_col_type[j]);
} else if (index.size() == 2) {
ap_uint<32> low_bits = 0;
ap_uint<32> high_bits = 0;
memcpy(&low_bits, table_out_col[index[0]] + j * col_size, col_size);
memcpy(&high_bits, table_out_col[index[1]] + j * col_size, col_size);
uint64_t merge_result = (ap_uint<64>)(high_bits, low_bits);
memcpy(cos_of_table_out[i] + j * tab_out_col_type[i], &merge_result, tab_out_col_type[j]);
} else {
std::cout << "Error:Invalid Result index" << std::endl;
exit(1);
}
}
}
tab_out.setRowNum(nrow);
std::cout << "Aggr done, table saved: " << tab_out.getRowNum() << " rows," << tab_out.getColNum() << " cols"
<< std::endl;
return SUCCESS;
}
struct queue_struct {
// the sec index
int sec;
// the partition index
int p;
// the nrow setup of MetaTable, only the last round nrow is different to per_slice_nrow in probe
int meta_nrow;
// updating meta info (nrow) for each partition&slice, due to async, this change is done in threads
MetaTable* meta;
// dependency event num
int num_event_wait_list;
// dependency events
cl_event* event_wait_list;
// user event to trace current memcpy operation
cl_event* event;
// memcpy src locations
char* ptr_src[16];
// ----- part o memcpy in used -----
// data size of memcpy in
int size;
// memcpy dst locations
char* ptr_dst[16];
// ----- part o memcpy out used -----
int partition_num;
// the allocated size (nrow) of each partititon out buffer
int part_max_nrow_512;
// memcpy dst locations, used in part memcpy out
char*** part_ptr_dst;
// ----- probe memcpy used -----
int slice;
// the nrow of first (slice_num - 1) rounds, only valid in probe memcpy in
int per_slice_nrow;
int* tab_col_type_size;
int* tab_part_sec_nrow;
// for contiguous cols, input
//
//------------------------add by changg----------------------//
int valid_col_num;
int key_num;
int pld_num;
std::vector<bool> write_flag;
std::vector<std::vector<int> > merge_info;
};
class threading_pool_for_aggr_pip {
public:
std::thread part_l_in_ping_t;
std::thread part_l_in_pong_t;
std::thread part_l_out_ping_t;
std::thread part_l_out_pong_t;
std::thread aggr_in_ping_t;
std::thread aggr_in_pong_t;
std::thread aggr_out_ping_t;
std::thread aggr_out_pong_t;
std::queue<queue_struct> q1_ping; // aggr memcpy in used queue
std::queue<queue_struct> q1_pong; // aggr memcpy in used queue
std::queue<queue_struct> q2_ping; // aggr memcpy out queue
std::queue<queue_struct> q2_pong; // aggr memcpy out queue
// the flag indicate each thread is running
std::atomic<bool> q1_ping_run;
std::atomic<bool> q1_pong_run;
std::atomic<bool> q2_ping_run;
std::atomic<bool> q2_pong_run;
//------------------------add by changg----------------------//
std::unordered_map<Key, Payloads, KeyHasher> ping_merge_map;
std::unordered_map<Key, Payloads, KeyHasher> pong_merge_map;
// the total aggr num
std::atomic<int64_t> aggr_sum_nrow;
// constructor
threading_pool_for_aggr_pip() { aggr_sum_nrow = 0; };
void aggr_memcpy_in_ping_t() {
while (q1_ping_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q1_ping.empty()) {
queue_struct q = q1_ping.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.ptr_dst[i], q.ptr_src[i], q.size);
}
q.meta->setColNum(q.valid_col_num);
for (int i = 0; i < q.valid_col_num; i++) {
q.meta->setCol(i, i, q.meta_nrow);
}
q.meta->meta();
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q1_ping.pop();
}
}
};
void aggr_memcpy_in_pong_t() {
while (q1_pong_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q1_pong.empty()) {
queue_struct q = q1_pong.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.ptr_dst[i], q.ptr_src[i], q.size);
}
q.meta->setColNum(q.valid_col_num);
for (int i = 0; i < q.valid_col_num; i++) {
q.meta->setCol(i, i, q.meta_nrow);
}
q.meta->meta();
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q1_pong.pop();
}
}
};
// aggr memcpy out thread
// int nrow = q.meta->getColLen();
// for (int c = 0; c < 16; c++) {
// if (c != 7)
// memcpy(tab_aggr_res_col[c] + aggr_sum_nrow, reinterpret_cast<int*>(tab_aggr_out_col[c][kid]),
// nrow * sizeof(int));
// }
// aggr_sum_nrow += nrow;
// std::cout << "output nrow[" << p << "] = " << nrow << std::endl;
void aggr_memcpy_out_ping_t() {
while (q2_ping_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q2_ping.empty()) {
queue_struct q = q2_ping.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
int nrow = q.meta->getColLen();
std::cout << "output nrow[" << q.p << "] = " << nrow << std::endl;
char* tab_aggr_res_col[16];
for (int c = 0; c < 16; c++) {
if (q.write_flag[c]) tab_aggr_res_col[c] = q.ptr_src[c];
}
for (int i = 0; i < nrow; i++) {
Key key;
key.key_num = q.key_num;
for (int k = 0; k < key.key_num; k++) {
std::vector<int> index = q.merge_info[k];
if (index.size() > 1) {
std::cout << "please ensure grp keys in first cols" << std::endl;
exit(1);
}
// memcpy(&key.keys[k], tab_aggr_res_col[index[0]] + i * q.tab_col_type_size[k],
// q.tab_col_type_size[k]);
uint32_t tmp = 0;
memcpy(&(tmp), tab_aggr_res_col[index[0]] + i * sizeof(int), sizeof(int));
key.keys[k] = tmp;
}
if (ping_merge_map.find(key) != ping_merge_map.end()) {
for (int p = 0; p < q.pld_num; p++) {
// int col_size = q.tab_col_type_size[p - key.key_num];
int col_size = sizeof(int);
std::vector<int> index = q.merge_info[p + q.key_num];
if (index.size() == 1) {
uint32_t tmp = 0;
memcpy(&tmp, tab_aggr_res_col[index[0]] + i * col_size, col_size);
ping_merge_map[key].values[p] += tmp;
} else if (index.size() == 2 || index.size() == 3) {
ap_uint<32> low_bits = 0;
ap_uint<32> high_bits = 0;
memcpy(&high_bits, tab_aggr_res_col[index[1]] + i * col_size, col_size);
memcpy(&low_bits, tab_aggr_res_col[index[0]] + i * col_size, col_size);
ping_merge_map[key].values[p] += (ap_uint<64>)(high_bits, low_bits);
}
}
} else {
Payloads pld;
for (int p = 0; p < q.pld_num; p++) {
// int col_size = q.tab_col_type_size[p - key.key_num];
int col_size = sizeof(int);
std::vector<int> index = q.merge_info[p + q.key_num];
if (index.size() == 1) {
uint32_t tmp = 0;
memcpy(&tmp, tab_aggr_res_col[index[0]] + i * col_size, col_size);
pld.values[p] = tmp;
} else if (index.size() == 2 || index.size() == 3) {
ap_uint<32> low_bits = 0;
ap_uint<32> high_bits = 0;
memcpy(&high_bits, tab_aggr_res_col[index[1]] + i * col_size, col_size);
memcpy(&low_bits, tab_aggr_res_col[index[0]] + i * col_size, col_size);
pld.values[p] = (ap_uint<64>)(high_bits, low_bits);
}
}
ping_merge_map.insert(std::make_pair(key, pld));
}
}
aggr_sum_nrow += nrow;
std::cout << "output aggr_sum_nrow[" << q.p << "] = " << aggr_sum_nrow << std::endl;
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q2_ping.pop();
}
}
}
void aggr_memcpy_out_pong_t() {
while (q2_pong_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q2_pong.empty()) {
queue_struct q = q2_pong.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
int nrow = q.meta->getColLen();
std::cout << "output nrow[" << q.p << "] = " << nrow << std::endl;
char* tab_aggr_res_col[16];
for (int c = 0; c < 16; c++) {
if (q.write_flag[c]) tab_aggr_res_col[c] = q.ptr_src[c];
}
// std::cout << "&&&&&&&&&&" << q.key_num << std::endl;
for (int i = 0; i < nrow; i++) {
Key key;
key.key_num = q.key_num;
for (int k = 0; k < key.key_num; k++) {
std::vector<int> index = q.merge_info[k];
if (index.size() > 1) {
std::cout << "please ensure grp keys in first cols" << std::endl;
exit(1);
}
// memcpy(&key.keys[k], tab_aggr_res_col[index[0]] + i * q.tab_col_type_size[k],
// q.tab_col_type_size[k]);
uint32_t tmp = 0;
memcpy(&tmp, tab_aggr_res_col[index[0]] + i * sizeof(int), sizeof(int));
key.keys[k] = tmp;
}
if (pong_merge_map.find(key) != pong_merge_map.end()) {
for (int p = 0; p < q.pld_num; p++) {
std::vector<int> index = q.merge_info[p + q.key_num];
// int col_size = q.tab_col_type_size[p - key.key_num];
int col_size = sizeof(int);
if (index.size() == 1) {
uint32_t tmp = 0;
memcpy(&tmp, tab_aggr_res_col[index[0]] + i * col_size, col_size);
pong_merge_map[key].values[p] += tmp;
} else if (index.size() == 2 || index.size() == 3) {
ap_uint<32> low_bits;
ap_uint<32> high_bits;
memcpy(&high_bits, tab_aggr_res_col[index[1]] + i * col_size, col_size);
memcpy(&low_bits, tab_aggr_res_col[index[0]] + i * col_size, col_size);
pong_merge_map[key].values[p] += (ap_uint<64>)(high_bits, low_bits);
}
}
} else {
Payloads pld;
for (int p = 0; p < q.pld_num; p++) {
std::vector<int> index = q.merge_info[p + q.key_num];
// int col_size = q.tab_col_type_size[p - key.key_num];
int col_size = sizeof(int);
if (index.size() == 1) {
uint32_t tmp = 0;
memcpy(&tmp, tab_aggr_res_col[index[0]] + i * col_size, col_size);
pld.values[p] = tmp;
} else if (index.size() == 2 || index.size() == 3) {
ap_uint<32> low_bits = 0;
ap_uint<32> high_bits = 0;
memcpy(&high_bits, tab_aggr_res_col[index[1]] + i * col_size, col_size);
memcpy(&low_bits, tab_aggr_res_col[index[0]] + i * col_size, col_size);
pld.values[p] = (ap_uint<64>)(high_bits, low_bits);
}
}
pong_merge_map.insert(std::make_pair(key, pld));
}
}
aggr_sum_nrow += nrow;
std::cout << "output aggr_sum_nrow[" << q.p << "] = " << aggr_sum_nrow << std::endl;
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q2_pong.pop();
}
}
}
// initialize the table L aggr threads
void aggr_init() {
aggr_sum_nrow = 0;
// start the part o memcpy in thread and non-stop running
q1_ping_run = 1;
aggr_in_ping_t = std::thread(&threading_pool_for_aggr_pip::aggr_memcpy_in_ping_t, this);
// start the part o memcpy in thread and non-stop running
q1_pong_run = 1;
aggr_in_pong_t = std::thread(&threading_pool_for_aggr_pip::aggr_memcpy_in_pong_t, this);
// start the part o memcpy in thread and non-stop running
q2_ping_run = 1;
aggr_out_ping_t = std::thread(&threading_pool_for_aggr_pip::aggr_memcpy_out_ping_t, this);
// start the part o memcpy in thread and non-stop running
q2_pong_run = 1;
aggr_out_pong_t = std::thread(&threading_pool_for_aggr_pip::aggr_memcpy_out_pong_t, this);
}
};
ErrCode Aggregator::aggr_sol1(Table& tab_in, Table& tab_out, AggrConfig& aggr_cfg, std::vector<size_t> params) {
const int VEC_LEN = 16;
const int size_of_apu512 = sizeof(ap_uint<512>);
const int sec_num = params[2];
int l_nrow = tab_in.getRowNum();
int l_ncol = tab_in.getColNum();
#ifdef USER_DEBUG
std::cout << "tab_in info: " << l_nrow << " rows, " << l_ncol << " cols." << std::endl;
#endif
// start threading pool threads
gqe::utils::MM mm;
threading_pool_for_aggr_pip pool;
pool.aggr_init();
// aggr kernel
cl_kernel aggrkernel[2];
aggrkernel[0] = clCreateKernel(prg, "gqeAggr", &err);
aggrkernel[1] = clCreateKernel(prg, "gqeAggr", &err);
// divide table L into many sections
// the col nrow of each section
int tab_sec_nrow_each = (l_nrow + sec_num - 1) / sec_num;
if (tab_sec_nrow_each < sec_num) {
std::cerr << "Error: Table L section size is smaller than section number!!!";
std::cerr << "sec size of Table L: " << tab_sec_nrow_each << ", ";
std::cerr << "sec number of Table L: " << sec_num << std::endl;
exit(1);
}
int* tab_in_col_size = new int[l_ncol];
int* tab_sec_size = new int[l_ncol];
for (int i = 0; i < l_ncol; i++) {
tab_in_col_size[i] = tab_in.getColTypeSize(i);
tab_sec_size[i] = tab_sec_nrow_each * tab_in_col_size[i];
}
int tab_sec_nrow[sec_num];
for (int sec = 0; sec < sec_num - 1; sec++) {
tab_sec_nrow[sec] = tab_sec_nrow_each;
}
tab_sec_nrow[sec_num - 1] = l_nrow - tab_sec_nrow_each * (sec_num - 1);
// define and load lineitem table
// data load from disk. due to table size, data read into several sections
std::vector<int8_t> scan_list = aggr_cfg.getScanList();
char* tab_in_user_col_sec[8][sec_num];
for (int i = 0; i < 8; i++) {
if (i < l_ncol) {
for (int j = 0; j < sec_num; j++) {
tab_in_user_col_sec[i][j] = tab_in.getColPointer(scan_list[i], sec_num, j);
}
} else {
for (int j = 0; j < sec_num; j++) {
tab_in_user_col_sec[i][j] = mm.aligned_alloc<char>(VEC_LEN);
}
}
}
// L host side pinned buffers for aggr kernel
char* tab_in_col[8][2];
for (int i = 0; i < 8; i++) {
if (i < l_ncol) {
tab_in_col[i][0] = mm.aligned_alloc<char>(tab_sec_size[i]);
tab_in_col[i][1] = mm.aligned_alloc<char>(tab_sec_size[i]);
memset(tab_in_col[i][0], 0, tab_sec_size[i]);
memset(tab_in_col[i][1], 0, tab_sec_size[i]);
} else {
tab_in_col[i][0] = mm.aligned_alloc<char>(VEC_LEN);
tab_in_col[i][1] = mm.aligned_alloc<char>(VEC_LEN);
}
}
// define the nrow of aggr result
// int aggr_result_nrow = tab_sec_nrow_each;
int aggr_result_nrow = tab_out.getRowNum();
int out_ncol = aggr_cfg.getOutputColNum();
int* tab_out_col_type = new int[out_ncol];
for (int i = 0; i < out_ncol; i++) {
tab_out_col_type[i] = tab_out.getColTypeSize(i);
}
int key_num = aggr_cfg.getGrpKeyNum();
std::vector<std::vector<int> > merge_info;
for (int i = 0; i < out_ncol; i++) {
merge_info.push_back(aggr_cfg.getResults(i));
}
std::vector<bool> write_flag = aggr_cfg.getWriteFlag();
#ifdef USER_DEBUG
for (auto l : write_flag) {
std::cout << l << " ";
}
for (int kk = 0; kk < write_flag.size(); kk++) {
std::cout << write_flag[kk] << " ";
}
std::cout << std::endl;
#endif
size_t aggr_result_nrow_512 = (aggr_result_nrow + VEC_LEN - 1) / VEC_LEN;
size_t aggr_result_nrow_512_size = aggr_result_nrow_512 * size_of_apu512;
char* tab_aggr_out_col[16][2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 16; i++) {
if (write_flag[i]) {
tab_aggr_out_col[i][k] = mm.aligned_alloc<char>(aggr_result_nrow_512_size);
memset(tab_aggr_out_col[i][k], 0, aggr_result_nrow_512_size);
} else {
tab_aggr_out_col[i][k] = mm.aligned_alloc<char>(VEC_LEN);
}
}
}
ap_uint<32>* cfg_aggr = aggr_cfg.getAggrConfigBits();
ap_uint<32>* cfg_aggr_out = aggr_cfg.getAggrConfigOutBits();
//--------------- meta setup -----------------
// setup meta input and output
MetaTable meta_aggr_in[2];
for (int i = 0; i < 2; i++) {
meta_aggr_in[i].setColNum(l_ncol);
for (int j = 0; j < l_ncol; j++) {
meta_aggr_in[i].setCol(j, j, tab_sec_nrow_each);
}
meta_aggr_in[i].meta();
}
MetaTable meta_aggr_out[2];
meta_aggr_out[0].setColNum(16);
meta_aggr_out[1].setColNum(16);
for (int c = 0; c < 16; c++) {
meta_aggr_out[0].setCol(c, c, aggr_result_nrow_512);
meta_aggr_out[1].setCol(c, c, aggr_result_nrow_512);
}
meta_aggr_out[0].meta();
meta_aggr_out[1].meta();
cl_mem_ext_ptr_t mext_tab_aggr_in_col[8][2];
cl_mem_ext_ptr_t mext_meta_aggr_in[2], mext_meta_aggr_out[2];
cl_mem_ext_ptr_t mext_cfg_aggr, mext_cfg_aggr_out;
cl_mem_ext_ptr_t mext_tab_aggr_out[16][2];
cl_mem_ext_ptr_t mext_aggr_tmp[8];
int agg_i = 0;
for (int k = 0; k < 2; k++) {
agg_i = 0;
for (int c = 0; c < 8; c++) {
mext_tab_aggr_in_col[c][k] = {agg_i++, tab_in_col[c][k], aggrkernel[k]};
}
mext_meta_aggr_in[k] = {agg_i++, meta_aggr_in[k].meta(), aggrkernel[k]};
mext_meta_aggr_out[k] = {agg_i++, meta_aggr_out[k].meta(), aggrkernel[k]};
}
for (int k = 0; k < 2; k++) {
agg_i = 10;
for (int i = 0; i < 16; ++i) {
mext_tab_aggr_out[i][k] = {agg_i++, tab_aggr_out_col[i][k], aggrkernel[k]};
}
}
mext_cfg_aggr = {agg_i++, cfg_aggr, aggrkernel[0]};
mext_cfg_aggr_out = {agg_i++, cfg_aggr_out, aggrkernel[0]};
for (int c = 0; c < 8; c++) {
mext_aggr_tmp[c] = {agg_i++, nullptr, aggrkernel[0]};
}
cl_mem buf_tab_aggr_in_col[8][2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 8; ++i) {
if (i < l_ncol) {
buf_tab_aggr_in_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, tab_sec_size[i],
&mext_tab_aggr_in_col[i][k], &err);
} else {
buf_tab_aggr_in_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, VEC_LEN,
&mext_tab_aggr_in_col[i][k], &err);
}
}
}
cl_mem buf_aggr_tmp[8];
for (int i = 0; i < 8; i++) {
buf_aggr_tmp[i] = clCreateBuffer(ctx, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS | CL_MEM_EXT_PTR_XILINX,
(size_t)(8 * S_BUFF_DEPTH), &mext_aggr_tmp[i], &err);
}
cl_mem buf_meta_aggr_in[2];
cl_mem buf_meta_aggr_out[2];
for (int i = 0; i < 2; i++) {
buf_meta_aggr_in[i] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_in[i], &err);
buf_meta_aggr_out[i] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_out[i], &err);
}
cl_mem buf_cfg_aggr = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_t(4 * 128), &mext_cfg_aggr, &err);
cl_mem buf_cfg_aggr_out = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
size_t(4 * 128), &mext_cfg_aggr_out, &err);
cl_mem buf_tab_aggr_out_col[16][2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 16; ++i) {
if (write_flag[i])
buf_tab_aggr_out_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
aggr_result_nrow_512_size, &mext_tab_aggr_out[i][k], &err);
else
buf_tab_aggr_out_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, VEC_LEN,
&mext_tab_aggr_out[i][k], &err);
}
}
// set args and enqueue kernel
for (int k = 0; k < 2; k++) {
int j = 0;
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[0][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[1][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[2][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[3][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[4][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[5][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[6][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[7][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_meta_aggr_in[k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_meta_aggr_out[k]);
for (int c = 0; c < 16; c++) {
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_out_col[c][k]);
}
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_cfg_aggr);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_cfg_aggr_out);
for (int c = 0; c < 8; c++) {
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_aggr_tmp[c]);
}
}
clEnqueueMigrateMemObjects(cq, 1, &buf_meta_aggr_out[0], 0, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, 1, &buf_meta_aggr_out[1], 0, 0, nullptr, nullptr);
std::vector<cl_mem> aggr_in_vec[2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < l_ncol; i++) {
aggr_in_vec[k].push_back(buf_tab_aggr_in_col[i][k]);
}
aggr_in_vec[k].push_back(buf_meta_aggr_in[k]);
aggr_in_vec[k].push_back(buf_cfg_aggr);
}
std::vector<cl_mem> aggr_out_vec[2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 16; ++i) {
aggr_out_vec[k].push_back(buf_tab_aggr_out_col[i][k]);
}
aggr_out_vec[k].push_back(buf_meta_aggr_out[k]);
}
clEnqueueMigrateMemObjects(cq, aggr_in_vec[0].size(), aggr_in_vec[0].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, aggr_in_vec[1].size(), aggr_in_vec[1].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, aggr_out_vec[0].size(), aggr_out_vec[0].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, aggr_out_vec[1].size(), aggr_out_vec[1].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
std::vector<std::vector<cl_event> > evt_aggr_memcpy_in(sec_num);
std::vector<std::vector<cl_event> > evt_aggr_h2d(sec_num);
std::vector<std::vector<cl_event> > evt_aggr_krn(sec_num);
std::vector<std::vector<cl_event> > evt_aggr_d2h(sec_num);
std::vector<std::vector<cl_event> > evt_aggr_memcpy_out(sec_num);
for (int p = 0; p < sec_num; p++) {
evt_aggr_memcpy_in[p].resize(1);
evt_aggr_h2d[p].resize(1);
evt_aggr_krn[p].resize(1);
evt_aggr_d2h[p].resize(1);
evt_aggr_memcpy_out[p].resize(1);
evt_aggr_memcpy_in[p][0] = clCreateUserEvent(ctx, &err);
evt_aggr_memcpy_out[p][0] = clCreateUserEvent(ctx, &err);
}
std::vector<std::vector<cl_event> > evt_aggr_h2d_dep(sec_num);
evt_aggr_h2d_dep[0].resize(1);
for (int i = 1; i < sec_num; ++i) {
if (i == 1)
evt_aggr_h2d_dep[i].resize(1);
else
evt_aggr_h2d_dep[i].resize(2);
}
std::vector<std::vector<cl_event> > evt_aggr_krn_dep(sec_num);
evt_aggr_krn_dep[0].resize(1);
for (int i = 1; i < sec_num; ++i) {
if (i == 1)
evt_aggr_krn_dep[i].resize(2);
else
evt_aggr_krn_dep[i].resize(3);
}
std::vector<std::vector<cl_event> > evt_aggr_d2h_dep(sec_num);
evt_aggr_d2h_dep[0].resize(1);
for (int i = 1; i < sec_num; ++i) {
if (i == 1)
evt_aggr_d2h_dep[i].resize(1);
else
evt_aggr_d2h_dep[i].resize(2);
}
queue_struct aggr_min[sec_num];
queue_struct aggr_mout[sec_num];
// because pure device buf is used in aggr kernel, the kernel needs to be run invalid for 1 round
{
std::cout << "xxxxxxxxxxxxxxxxxxxxxx invalid below xxxxxxxxxxxxxxxxxxxxxxxx" << std::endl;
meta_aggr_in[0].setColNum(1);
meta_aggr_in[0].setCol(0, 0, 15);
meta_aggr_in[0].meta();
clEnqueueMigrateMemObjects(cq, aggr_in_vec[0].size(), aggr_in_vec[0].data(), 0, 0, nullptr,
&evt_aggr_h2d[0][0]);
clEnqueueTask(cq, aggrkernel[0], evt_aggr_h2d[0].size(), evt_aggr_h2d[0].data(), nullptr);
clFinish(cq);
std::cout << "xxxxxxxxxxxxxxxxxxxxxx invalid above xxxxxxxxxxxxxxxxxxxxxxxx" << std::endl;
}
gqe::utils::Timer timer_aggr;
timer_aggr.add(); // 0
// aggr loop run
for (int p = 0; p < sec_num; p++) {
int kid = p % 2;
// 1)memcpy in, copy the data from tab_part_new_col[partition_num][8][l_new_part_nrow_512] to
// tab_aggr_in_col0-7
aggr_min[p].p = p;
aggr_min[p].valid_col_num = l_ncol;
aggr_min[p].size = tab_sec_size[p];
aggr_min[p].event = &evt_aggr_memcpy_in[p][0];
aggr_min[p].meta = &meta_aggr_in[kid];
aggr_min[p].meta_nrow = tab_sec_nrow[p];
for (int i = 0; i < l_ncol; i++) {
aggr_min[p].ptr_src[i] = tab_in_user_col_sec[i][p];
aggr_min[p].ptr_dst[i] = tab_in_col[i][kid];
}
if (p > 1) {
aggr_min[p].num_event_wait_list = evt_aggr_h2d[p - 2].size();
aggr_min[p].event_wait_list = evt_aggr_h2d[p - 2].data();
} else {
aggr_min[p].num_event_wait_list = 0;
aggr_min[p].event_wait_list = nullptr;
}
if (kid == 0) pool.q1_ping.push(aggr_min[p]);
if (kid == 1) pool.q1_pong.push(aggr_min[p]);
// 2)h2d
evt_aggr_h2d_dep[p][0] = evt_aggr_memcpy_in[p][0];
if (p > 1) {
evt_aggr_h2d_dep[p][1] = evt_aggr_krn[p - 2][0];
}
clEnqueueMigrateMemObjects(cq, aggr_in_vec[kid].size(), aggr_in_vec[kid].data(), 0, evt_aggr_h2d_dep[p].size(),
evt_aggr_h2d_dep[p].data(), &evt_aggr_h2d[p][0]);
// 3)aggr kernel
evt_aggr_krn_dep[p][0] = evt_aggr_h2d[p][0];
if (p > 0) {
evt_aggr_krn_dep[p][1] = evt_aggr_krn[p - 1][0];
}
if (p > 1) {
evt_aggr_krn_dep[p][2] = evt_aggr_d2h[p - 2][0];
}
clEnqueueTask(cq, aggrkernel[kid], evt_aggr_krn_dep[p].size(), evt_aggr_krn_dep[p].data(), &evt_aggr_krn[p][0]);
// 4)d2h
evt_aggr_d2h_dep[p][0] = evt_aggr_krn[p][0];
if (p > 1) {
evt_aggr_d2h_dep[p][1] = evt_aggr_memcpy_out[p - 2][0];
}
clEnqueueMigrateMemObjects(cq, aggr_out_vec[kid].size(), aggr_out_vec[kid].data(), CL_MIGRATE_MEM_OBJECT_HOST,
evt_aggr_d2h_dep[p].size(), evt_aggr_d2h_dep[p].data(), &evt_aggr_d2h[p][0]);
// 5)memcpy out
aggr_mout[p].p = p;
aggr_mout[p].write_flag = write_flag;
aggr_mout[p].merge_info = merge_info;
aggr_mout[p].tab_col_type_size = tab_out_col_type;
aggr_mout[p].key_num = key_num;
aggr_mout[p].pld_num = out_ncol - key_num;
aggr_mout[p].event = &evt_aggr_memcpy_out[p][0];
aggr_mout[p].meta = &meta_aggr_out[kid];
for (int c = 0; c < 16; c++) {
if (write_flag[c]) {
aggr_mout[p].ptr_src[c] = tab_aggr_out_col[c][kid];
}
}
aggr_mout[p].num_event_wait_list = evt_aggr_d2h[p].size();
aggr_mout[p].event_wait_list = evt_aggr_d2h[p].data();
if (kid == 0) pool.q2_ping.push(aggr_mout[p]);
if (kid == 1) pool.q2_pong.push(aggr_mout[p]);
}
clWaitForEvents(evt_aggr_memcpy_out[sec_num - 1].size(), evt_aggr_memcpy_out[sec_num - 1].data());
if (sec_num > 1) {
clWaitForEvents(evt_aggr_memcpy_out[sec_num - 2].size(), evt_aggr_memcpy_out[sec_num - 2].data());
}
timer_aggr.add(); // 1
#ifdef AGGR_PERF_PROFILE
cl_ulong start, end;
long evt_ns;
for (int p = 0; p < sec_num; p++) {
double input_memcpy_size = 0;
for (int ii = 0; ii < l_ncol; ii++) {
input_memcpy_size += (double)tab_sec_nrow[p] * tab_in_col_type[ii];
}
input_memcpy_size = input_memcpy_size / 1024 / 1024;
clGetEventProfilingInfo(evt_aggr_h2d[p][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_aggr_h2d[p][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
std::cout << "Sec: " << p << ", h2d, size: " << input_memcpy_size << " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << input_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
clGetEventProfilingInfo(evt_aggr_krn[p][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_aggr_krn[p][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
std::cout << "Part: " << p << ", krn, size: " << input_memcpy_size << " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << input_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
clGetEventProfilingInfo(evt_aggr_d2h[p][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_aggr_d2h[p][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
double output_memcpy_size = (double)aggr_result_nrow_512_size * out_ncol / 1024 / 1024;
std::cout << "Part: " << p << ", d2h, size: " << output_memcpy_size << " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << output_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
}
std::cout << "output aggr_sum_nrow = " << pool.aggr_sum_nrow << std::endl;
std::cout << "ping merge map size = " << pool.ping_merge_map.size() << std::endl;
std::cout << "pong merge map size = " << pool.pong_merge_map.size() << std::endl;
std::cout << "-----------------------------------------------------" << std::endl;
#endif
double tvtime_aggr = timer_aggr.getMilliSec();
pool.q1_ping_run = 0;
pool.q1_pong_run = 0;
pool.q2_ping_run = 0;
pool.q2_pong_run = 0;
pool.aggr_in_ping_t.join();
pool.aggr_in_pong_t.join();
pool.aggr_out_ping_t.join();
pool.aggr_out_pong_t.join();
// when merging the application (0: low bit, 1: high bit, 0~1 sum, 2: count)
std::unordered_map<Key, int, KeyHasher> key_map;
std::vector<bool> route_list(merge_info.size());
std::vector<std::vector<int> > route_info(merge_info.size());
// merge_info size = output size,
// route_list get which key needs combination
// key_map save all the sum locations, using (high,low)->index, using it to find the sum location in
for (size_t i = 0; i < merge_info.size(); i++) {
std::vector<int> index = merge_info[i];
if (index.size() <= 2) {
route_list[i] = false;
Key key;
key.key_num = index.size();
for (size_t ii = 0; ii < index.size(); ii++) {
key.keys[ii] = index[ii];
}
key_map.insert(std::make_pair(key, i));
} else {
route_list[i] = true;
}
}
for (size_t i = 0; i < merge_info.size(); i++) {
std::vector<int> index = merge_info[i];
if (index.size() == 3) {
Key key_sum;
key_sum.key_num = 2;
for (int ii = 0; ii < 2; ii++) {
key_sum.keys[ii] = index[ii];
}
Key key_counter;
key_counter.key_num = 1;
key_counter.keys[0] = index[2];
int sum_ind = i;
int sum_counter = i;
if (key_map.find(key_sum) != key_map.end()) {
sum_ind = key_map[key_sum];
}
if (key_map.find(key_counter) != key_map.end()) {
sum_counter = key_map[key_counter];
}
route_info[i] = {sum_ind, sum_counter};
}
}
gqe::utils::Timer timer_merge;
timer_merge.add(); // 0
for (auto it = pool.pong_merge_map.begin(); it != pool.pong_merge_map.end(); it++) {
Key key = it->first;
Payloads pld = it->second;
if (pool.ping_merge_map.find(key) != pool.ping_merge_map.end()) {
for (int i = 0; i < out_ncol - key_num; i++) {
pool.ping_merge_map[key].values[i] += pld.values[i];
}
} else {
for (int i = 0; i < out_ncol - key_num; i++) {
pool.ping_merge_map[key].values[i] = pld.values[i];
}
pool.ping_merge_map.insert(std::make_pair(key, pld));
}
}
char** output_ptr = new char*[out_ncol];
for (int i = 0; i < out_ncol; i++) {
output_ptr[i] = tab_out.getColPointer(i);
}
tab_out.setRowNum(pool.ping_merge_map.size());
int32_t row_counter = 0;
for (auto it = pool.ping_merge_map.begin(); it != pool.ping_merge_map.end(); it++) {
Key key = it->first;
for (size_t i = 0; i < merge_info.size(); i++) {
if (route_list[i] == true) {
int sum_ind = route_info[i][0];
int sum_counter = route_info[i][1];
pool.ping_merge_map[key].values[i - key.key_num] =
pool.ping_merge_map[key].values[sum_ind - key.key_num] /
pool.ping_merge_map[key].values[sum_counter - key.key_num];
}
if (i < (size_t)key.key_num) {
// std::cout << key.keys[i] << std::endl;
int64_t key_v = key.keys[i];
memcpy(output_ptr[i] + row_counter * tab_out_col_type[i], &key_v, tab_out_col_type[i]);
} else {
memcpy(output_ptr[i] + row_counter * tab_out_col_type[i - key.key_num],
&(pool.ping_merge_map[key].values[i - key.key_num]), tab_out_col_type[i - key.key_num]);
}
}
row_counter++;
}
timer_merge.add(); // 1
std::cout << merge_info.size() << " cols," << row_counter << " rows" << std::endl;
double in1_bytes = (double)l_nrow * sizeof(int) * l_ncol / 1024 / 1024;
double out_bytes = (double)pool.ping_merge_map.size() * sizeof(int) * out_ncol / 1024 / 1024;
std::cout << "-----------------------Data Transfer Info-----------------------" << std::endl;
std::cout << "H2D size = " << in1_bytes << " MB" << std::endl;
std::cout << "D2H size = " << out_bytes << " MB" << std::endl;
std::cout << "-----------------------Performance Info-----------------------" << std::endl;
double tvtime_merge = timer_merge.getMilliSec();
std::cout << "All time: " << (double)(tvtime_aggr + tvtime_merge) / 1000
<< " ms, throughput: " << in1_bytes / 1024 / ((double)(tvtime_aggr + tvtime_merge) / 1000000) << " GB/s"
<< std::endl;
std::cout << "Output number = " << pool.ping_merge_map.size() << std::endl;
std::cout << "Aggr done, table saved: " << tab_out.getRowNum() << " rows," << tab_out.getColNum() << " cols"
<< std::endl;
return SUCCESS;
}
class threading_pool_for_aggr_part {
public:
std::thread part_l_in_ping_t;
std::thread part_l_in_pong_t;
std::thread part_l_out_ping_t;
std::thread part_l_out_pong_t;
std::thread aggr_in_ping_t;
std::thread aggr_in_pong_t;
std::thread aggr_out_ping_t;
std::thread aggr_out_pong_t;
std::queue<queue_struct> q2_ping; // part l memcpy in used queue
std::queue<queue_struct> q2_pong; // part l memcpy in used queue
std::queue<queue_struct> q3_ping; // part l memcpy out used queue
std::queue<queue_struct> q3_pong; // part l memcpy out used queue
std::queue<queue_struct> q7_ping; // aggr memcpy in used queue
std::queue<queue_struct> q7_pong; // aggr memcpy in used queue
std::queue<queue_struct> q8_ping; // aggr memcpy out queue
std::queue<queue_struct> q8_pong; // aggr memcpy out queue
// the flag indicate each thread is running
std::atomic<bool> q2_ping_run;
std::atomic<bool> q2_pong_run;
std::atomic<bool> q3_ping_run;
std::atomic<bool> q3_pong_run;
std::atomic<bool> q4_run;
std::atomic<bool> q5_run_ping;
std::atomic<bool> q5_run_pong;
std::atomic<bool> q6_run;
std::atomic<bool> q7_ping_run;
std::atomic<bool> q7_pong_run;
std::atomic<bool> q8_ping_run;
std::atomic<bool> q8_pong_run;
// the nrow of each partition
std::atomic<int> l_new_part_offset[256];
int toutrow[256][32];
// the total aggr num
std::atomic<int64_t> aggr_sum_nrow;
// the buffer size of each output partition of Tab L.
int l_partition_out_col_part_nrow_max;
// constructor
threading_pool_for_aggr_part() { aggr_sum_nrow = 0; };
// table L memcpy in thread
void part_l_memcpy_in_ping_t() {
while (q2_ping_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q2_ping.empty()) {
queue_struct q = q2_ping.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.ptr_dst[i], q.ptr_src[i], q.meta_nrow * q.tab_col_type_size[i]);
}
q.meta->setColNum(q.valid_col_num);
for (int i = 0; i < q.valid_col_num; i++) {
q.meta->setCol(i, i, q.meta_nrow);
}
q.meta->meta();
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q2_ping.pop();
}
}
};
// table L memcpy in thread
void part_l_memcpy_in_pong_t() {
while (q2_pong_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q2_pong.empty()) {
queue_struct q = q2_pong.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.ptr_dst[i], q.ptr_src[i], q.meta_nrow * q.tab_col_type_size[i]);
}
q.meta->setColNum(q.valid_col_num);
for (int i = 0; i < q.valid_col_num; i++) {
q.meta->setCol(i, i, q.meta_nrow);
}
q.meta->meta();
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q2_pong.pop();
}
}
};
// table L memcpy out thread
void part_l_memcpy_out_ping_t() {
while (q3_ping_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q3_ping.empty()) {
queue_struct q = q3_ping.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
int l_partition_out_col_part_depth = q.part_max_nrow_512;
int* nrow_per_part_l = q.meta->getPartLen();
for (int p = 0; p < q.partition_num; ++p) {
int sec_partitioned_res_part_nrow = nrow_per_part_l[p];
if (sec_partitioned_res_part_nrow > l_partition_out_col_part_nrow_max) {
std::cerr << "partition out nrow: " << sec_partitioned_res_part_nrow
<< ", buffer size: " << l_partition_out_col_part_nrow_max << std::endl;
std::cerr << "ERROR: Table L output partition size is smaller than required!" << std::endl;
exit(1);
}
int offset = l_new_part_offset[p];
l_new_part_offset[p] += sec_partitioned_res_part_nrow;
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.part_ptr_dst[p][i] + offset * q.tab_col_type_size[i],
q.ptr_src[i] + p * l_partition_out_col_part_depth * sizeof(ap_uint<512>),
q.tab_col_type_size[i] * sec_partitioned_res_part_nrow);
}
}
clSetUserEventStatus(q.event[0], CL_COMPLETE);
q3_ping.pop();
}
}
};
// table L memcpy out thread
void part_l_memcpy_out_pong_t() {
while (q3_pong_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q3_pong.empty()) {
queue_struct q = q3_pong.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
int l_partition_out_col_part_depth = q.part_max_nrow_512;
int* nrow_per_part_l = q.meta->getPartLen();
for (int p = 0; p < q.partition_num; ++p) {
int sec_partitioned_res_part_nrow = nrow_per_part_l[p];
if (sec_partitioned_res_part_nrow > l_partition_out_col_part_nrow_max) {
std::cerr << "partition out nrow: " << sec_partitioned_res_part_nrow
<< ", buffer size: " << l_partition_out_col_part_nrow_max << std::endl;
std::cerr << "ERROR: Table L output partition size is smaller than required!" << std::endl;
exit(1);
}
int offset = l_new_part_offset[p];
l_new_part_offset[p] += sec_partitioned_res_part_nrow;
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.part_ptr_dst[p][i] + offset * q.tab_col_type_size[i],
q.ptr_src[i] + p * l_partition_out_col_part_depth * sizeof(ap_uint<512>),
q.tab_col_type_size[i] * sec_partitioned_res_part_nrow);
}
}
clSetUserEventStatus(q.event[0], CL_COMPLETE);
q3_pong.pop();
}
}
};
void aggr_memcpy_in_ping_t() {
while (q7_ping_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q7_ping.empty()) {
queue_struct q = q7_ping.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.ptr_dst[i], q.ptr_src[i], q.meta_nrow * q.tab_col_type_size[i]);
}
q.meta->setColNum(q.valid_col_num);
for (int i = 0; i < q.valid_col_num; i++) {
q.meta->setCol(i, i, q.meta_nrow);
}
q.meta->meta();
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q7_ping.pop();
}
}
};
void aggr_memcpy_in_pong_t() {
while (q7_pong_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q7_pong.empty()) {
queue_struct q = q7_pong.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
for (int i = 0; i < q.valid_col_num; i++) {
memcpy(q.ptr_dst[i], q.ptr_src[i], q.meta_nrow * q.tab_col_type_size[i]);
}
q.meta->setColNum(q.valid_col_num);
for (int i = 0; i < q.valid_col_num; i++) {
q.meta->setCol(i, i, q.meta_nrow);
}
q.meta->meta();
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q7_pong.pop();
}
}
};
void aggr_memcpy_out_ping_t() {
while (q8_ping_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q8_ping.empty()) {
queue_struct q = q8_ping.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
int nrow = q.meta->getColLen();
std::cout << "output nrow[" << q.p << "] = " << nrow << std::endl;
// in int32 imp, suppose all the col are int32, after aggr, when int64, use the
// tab_out.tab_col_type_size
for (int c = 0; c < 16; c++) {
if (q.write_flag[c])
memcpy(q.ptr_dst[c] + aggr_sum_nrow * sizeof(int), q.ptr_src[c], nrow * sizeof(int));
}
aggr_sum_nrow += nrow;
std::cout << "output aggr_sum_nrow[" << q.p << "] = " << aggr_sum_nrow << std::endl;
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q8_ping.pop();
}
}
}
void aggr_memcpy_out_pong_t() {
while (q8_pong_run) {
#ifdef Valgrind_debug
sleep(1);
#endif
while (!q8_pong.empty()) {
queue_struct q = q8_pong.front();
clWaitForEvents(q.num_event_wait_list, q.event_wait_list);
int nrow = q.meta->getColLen();
std::cout << "output nrow[" << q.p << "] = " << nrow << std::endl;
for (int c = 0; c < 16; c++) {
if (q.write_flag[c])
memcpy(q.ptr_dst[c] + aggr_sum_nrow * sizeof(int), (q.ptr_src[c]), nrow * sizeof(int));
}
aggr_sum_nrow += nrow;
std::cout << "output aggr_sum_nrow[" << q.p << "] = " << aggr_sum_nrow << std::endl;
clSetUserEventStatus(q.event[0], CL_COMPLETE);
// remove the first element after processing it.
q8_pong.pop();
}
}
}
// initialize the table L partition threads
void partl_init() {
memset(l_new_part_offset, 0, sizeof(int) * 256);
for (int i = 0; i < 256; i++) {
memset(toutrow[i], 0, sizeof(int) * 32);
}
// start the part o memcpy in thread and non-stop running
q2_ping_run = 1;
part_l_in_ping_t = std::thread(&threading_pool_for_aggr_part::part_l_memcpy_in_ping_t, this);
// start the part o memcpy in thread and non-stop running
q2_pong_run = 1;
part_l_in_pong_t = std::thread(&threading_pool_for_aggr_part::part_l_memcpy_in_pong_t, this);
// start the part o memcpy in thread and non-stop running
q3_ping_run = 1;
part_l_out_ping_t = std::thread(&threading_pool_for_aggr_part::part_l_memcpy_out_ping_t, this);
// start the part o memcpy in thread and non-stop running
q3_pong_run = 1;
part_l_out_pong_t = std::thread(&threading_pool_for_aggr_part::part_l_memcpy_out_pong_t, this);
};
void aggr_init() {
aggr_sum_nrow = 0;
// start the part o memcpy in thread and non-stop running
q7_ping_run = 1;
aggr_in_ping_t = std::thread(&threading_pool_for_aggr_part::aggr_memcpy_in_ping_t, this);
// start the part o memcpy in thread and non-stop running
q7_pong_run = 1;
aggr_in_pong_t = std::thread(&threading_pool_for_aggr_part::aggr_memcpy_in_pong_t, this);
// start the part o memcpy in thread and non-stop running
q8_ping_run = 1;
aggr_out_ping_t = std::thread(&threading_pool_for_aggr_part::aggr_memcpy_out_ping_t, this);
// start the part o memcpy in thread and non-stop running
q8_pong_run = 1;
aggr_out_pong_t = std::thread(&threading_pool_for_aggr_part::aggr_memcpy_out_pong_t, this);
}
};
inline void zipInt64(void* dest, const void* low, const void* high, size_t n) {
int64_t* dptr = (int64_t*)dest;
if (high == nullptr) {
for (size_t i = 0; i < n; ++i) {
int64_t tmp = *((const int32_t*)low + i); // sign-ext 32b to 64b
*(dptr + i) = tmp;
}
} else {
// zip two 32b to one 64b
for (size_t i = 0; i < n; ++i) {
uint64_t tmp = *((const uint32_t*)low + i); // zero-ext 32b to 64b
tmp |= (uint64_t)(*((const uint32_t*)high + i)) << 32;
*(dptr + i) = (int64_t)tmp; // cast unsigned to signed
}
}
}
ErrCode Aggregator::aggr_sol2(Table& tab_in, Table& tab_out, AggrConfig& aggr_cfg, std::vector<size_t> params) {
const int VEC_LEN = 16;
const int size_of_apu512 = sizeof(ap_uint<512>);
gqe::utils::MM mm;
int l_nrow = tab_in.getRowNum();
int l_ncol = tab_in.getColNum();
const int tab_part_sec_num = params[1];
int log_partition_num = params[3];
#ifdef USER_DEBUG
std::cout << "tab_in info: " << l_nrow << " rows, " << l_ncol << " cols." << std::endl;
#endif
threading_pool_for_aggr_part pool;
pool.partl_init();
// partition kernel
cl_kernel partkernel[2];
partkernel[0] = clCreateKernel(prg, "gqePart", &err);
partkernel[1] = clCreateKernel(prg, "gqePart", &err);
cl_kernel aggrkernel[2];
aggrkernel[0] = clCreateKernel(prg, "gqeAggr", &err);
aggrkernel[1] = clCreateKernel(prg, "gqeAggr", &err);
// ------------------------------------------
// --------- partitioning Table L ----------
// partition setups
const int k_depth = 512;
const int partition_num = 1 << log_partition_num;
// divide table L into many sections
// the col nrow of each section
int tab_part_sec_nrow_each = (l_nrow + tab_part_sec_num - 1) / tab_part_sec_num;
if (tab_part_sec_nrow_each < tab_part_sec_num) {
std::cerr << "Error: Table L section size is smaller than section number!!!";
std::cerr << "sec size of Table L: " << tab_part_sec_nrow_each << ", ";
std::cerr << "sec number of Table L: " << tab_part_sec_num << std::endl;
exit(1);
}
int tab_part_sec_nrow[tab_part_sec_num];
for (int sec = 0; sec < tab_part_sec_num - 1; sec++) {
tab_part_sec_nrow[sec] = tab_part_sec_nrow_each;
}
tab_part_sec_nrow[tab_part_sec_num - 1] = l_nrow - tab_part_sec_nrow_each * (tab_part_sec_num - 1);
int* tab_in_col_size = new int[l_ncol];
int* tab_part_sec_size = new int[l_ncol];
for (int i = 0; i < l_ncol; i++) {
tab_in_col_size[i] = tab_in.getColTypeSize(i);
tab_part_sec_size[i] = tab_part_sec_nrow_each * tab_in_col_size[i];
}
// todo: change config
std::vector<int8_t> scan_list = aggr_cfg.getScanList();
std::vector<int8_t> part_list = aggr_cfg.getPartList();
char* tab_part_in_user_col_sec[8][tab_part_sec_num];
for (int i = 0; i < 8; i++) {
if (i < l_ncol) {
for (int j = 0; j < tab_part_sec_num; j++) {
tab_part_in_user_col_sec[i][j] = tab_in.getColPointer(i, tab_part_sec_num, j);
}
} else {
for (int j = 0; j < tab_part_sec_num; j++) {
tab_part_in_user_col_sec[i][j] = mm.aligned_alloc<char>(VEC_LEN);
}
}
}
char* tab_part_in_col[8][2];
for (int i = 0; i < 8; i++) {
if (i < l_ncol) {
tab_part_in_col[i][0] = mm.aligned_alloc<char>(tab_part_sec_size[i]);
tab_part_in_col[i][1] = mm.aligned_alloc<char>(tab_part_sec_size[i]);
memset(tab_part_in_col[i][0], 0, tab_part_sec_size[i]);
memset(tab_part_in_col[i][1], 0, tab_part_sec_size[i]);
} else {
tab_part_in_col[i][0] = mm.aligned_alloc<char>(VEC_LEN);
tab_part_in_col[i][1] = mm.aligned_alloc<char>(VEC_LEN);
}
}
// partition output data
int tab_part_out_col_nrow_512_init = tab_part_sec_nrow_each * 4 / VEC_LEN;
assert(tab_part_out_col_nrow_512_init > 0 && "Error: table output col size must be greater than 0");
// the depth of each partition in each col
int tab_part_out_col_eachpart_nrow_512 = (tab_part_out_col_nrow_512_init + partition_num - 1) / partition_num;
pool.l_partition_out_col_part_nrow_max = tab_part_out_col_eachpart_nrow_512 * 16;
// update depth to make sure the buffer size is aligned by parttion_num * tab_part_out_col_eachpart_nrow_512
int tab_part_out_col_nrow_512 = partition_num * tab_part_out_col_eachpart_nrow_512;
int tab_part_out_col_size = tab_part_out_col_nrow_512 * size_of_apu512;
// partition_output data
char* tab_part_out_col[8][2];
for (int i = 0; i < 8; i++) {
if (i < l_ncol) {
tab_part_out_col[i][0] = mm.aligned_alloc<char>(tab_part_out_col_size);
tab_part_out_col[i][1] = mm.aligned_alloc<char>(tab_part_out_col_size);
} else {
tab_part_out_col[i][0] = mm.aligned_alloc<char>(VEC_LEN);
tab_part_out_col[i][1] = mm.aligned_alloc<char>(VEC_LEN);
}
}
ap_uint<512>* cfg_part = aggr_cfg.getPartConfigBits();
//--------------- metabuffer setup L -----------------
MetaTable meta_part_in[2];
for (int k = 0; k < 2; k++) {
meta_part_in[k].setColNum(l_ncol);
for (int j = 0; j < l_ncol; j++) {
meta_part_in[k].setCol(j, j, tab_part_sec_nrow_each);
}
meta_part_in[k].meta();
}
// setup partition kernel used meta output
MetaTable meta_part_out[2];
for (int k = 0; k < 2; k++) {
meta_part_out[k].setColNum(l_ncol);
meta_part_out[k].setPartition(partition_num, tab_part_out_col_eachpart_nrow_512);
for (int j = 0; j < l_ncol; j++) {
meta_part_out[k].setCol(j, j, tab_part_out_col_nrow_512);
}
meta_part_out[k].meta();
}
cl_mem_ext_ptr_t mext_tab_part_in_col[8][2];
cl_mem_ext_ptr_t mext_meta_part_in[2], mext_meta_part_out[2];
cl_mem_ext_ptr_t mext_tab_part_out_col[8][2];
int part_i = 3;
for (int i = 0; i < 8; ++i) {
mext_tab_part_in_col[i][0] = {part_i, tab_part_in_col[i][0], partkernel[0]};
mext_tab_part_in_col[i][1] = {part_i++, tab_part_in_col[i][1], partkernel[1]};
}
mext_meta_part_in[0] = {part_i, meta_part_in[0].meta(), partkernel[0]};
mext_meta_part_in[1] = {part_i++, meta_part_in[1].meta(), partkernel[1]};
mext_meta_part_out[0] = {part_i, meta_part_out[0].meta(), partkernel[0]};
mext_meta_part_out[1] = {part_i++, meta_part_out[1].meta(), partkernel[1]};
for (int i = 0; i < 8; ++i) {
mext_tab_part_out_col[i][0] = {part_i, tab_part_out_col[i][0], partkernel[0]};
mext_tab_part_out_col[i][1] = {part_i++, tab_part_out_col[i][1], partkernel[1]};
}
cl_mem_ext_ptr_t mext_cfg_part = {part_i++, cfg_part, partkernel[0]};
// dev buffers, part in
cl_mem buf_tab_part_in_col[8][2];
for (int k = 0; k < 2; k++) {
for (int c = 0; c < 8; c++) {
if (c < l_ncol) {
buf_tab_part_in_col[c][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
tab_part_sec_size[c], &mext_tab_part_in_col[c][k], &err);
} else {
buf_tab_part_in_col[c][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, VEC_LEN,
&mext_tab_part_in_col[c][k], &err);
}
}
}
// dev buffers, part out
cl_mem buf_tab_part_out_col[8][2];
for (int k = 0; k < 2; k++) {
for (int c = 0; c < 8; c++) {
if (c < l_ncol) {
buf_tab_part_out_col[c][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
tab_part_out_col_size, &mext_tab_part_out_col[c][k], &err);
} else {
buf_tab_part_out_col[c][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, VEC_LEN,
&mext_tab_part_out_col[c][k], &err);
}
}
}
cl_mem buf_cfg_part = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 9), &mext_cfg_part, &err);
cl_mem buf_meta_part_in[2];
buf_meta_part_in[0] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 8), &mext_meta_part_in[0], &err);
buf_meta_part_in[1] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 8), &mext_meta_part_in[1], &err);
cl_mem buf_meta_part_out[2];
buf_meta_part_out[0] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
(sizeof(ap_uint<512>) * 24), &mext_meta_part_out[0], &err);
buf_meta_part_out[1] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
(sizeof(ap_uint<512>) * 24), &mext_meta_part_out[1], &err);
// create user partition res cols
// all sections partition 0 output to same 8-col buffers
// ap_uint<512> tab_part_new_col[partition_num][8][l_new_part_nrow_512]
char*** tab_part_new_col = new char**[partition_num];
// combine sec0_partition0, sec1_parttion0, ...secN_partition0 in 1 buffer. the depth is
// int l_new_part_nrow_512 = tab_part_out_col_eachpart_nrow_512 * tab_part_sec_num;
int l_new_part_nrow_512_size = tab_part_out_col_eachpart_nrow_512 * tab_part_sec_num * size_of_apu512;
for (int p = 0; p < partition_num; ++p) {
tab_part_new_col[p] = new char*[8];
for (int i = 0; i < 8; ++i) {
tab_part_new_col[p][i] = mm.aligned_alloc<char>(l_new_part_nrow_512_size);
memset(tab_part_new_col[p][i], 0, l_new_part_nrow_512_size);
}
}
//----------------------partition L run-----------------------------
std::cout << "------------------- Partitioning L table -----------------" << std::endl;
const int idx = 0;
int j = 0;
for (int k = 0; k < 2; k++) {
j = 0;
clSetKernelArg(partkernel[k], j++, sizeof(int), &k_depth);
clSetKernelArg(partkernel[k], j++, sizeof(int), &idx);
clSetKernelArg(partkernel[k], j++, sizeof(int), &log_partition_num);
for (int vv = 0; vv < l_ncol; vv++) {
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_tab_part_in_col[part_list[vv]][k]);
// clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_tab_part_in_col[vv][k]);
}
for (int vv = l_ncol; vv < 8; vv++) {
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_tab_part_in_col[vv][k]);
}
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_meta_part_in[k]);
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_meta_part_out[k]);
for (int vv = 0; vv < l_ncol; vv++) {
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_tab_part_out_col[part_list[vv]][k]);
// clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_tab_part_in_col[vv]][k]);
}
for (int vv = l_ncol; vv < 8; vv++) {
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_tab_part_out_col[vv][k]);
}
clSetKernelArg(partkernel[k], j++, sizeof(cl_mem), &buf_cfg_part);
}
// partition h2d
std::vector<cl_mem> part_in_vec[2];
for (int k = 0; k < 2; k++) {
for (int j = 0; j < l_ncol; j++) {
part_in_vec[k].push_back(buf_tab_part_in_col[j][k]);
}
part_in_vec[k].push_back(buf_meta_part_in[k]);
part_in_vec[k].push_back(buf_cfg_part);
}
// partition d2h
std::vector<cl_mem> part_out_vec[2];
for (int k = 0; k < 2; k++) {
for (int j = 0; j < l_ncol; j++) {
part_out_vec[k].push_back(buf_tab_part_out_col[j][k]);
}
part_out_vec[k].push_back(buf_meta_part_out[k]);
}
clEnqueueMigrateMemObjects(cq, 1, &buf_meta_part_out[0], 0, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, 1, &buf_meta_part_out[1], 0, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, part_in_vec[0].size(), part_in_vec[0].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, part_in_vec[1].size(), part_in_vec[1].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, part_out_vec[0].size(), part_out_vec[0].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, part_out_vec[1].size(), part_out_vec[1].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
std::vector<std::vector<cl_event> > evt_part_h2d(tab_part_sec_num);
std::vector<std::vector<cl_event> > evt_part_krn(tab_part_sec_num);
std::vector<std::vector<cl_event> > evt_part_d2h(tab_part_sec_num);
for (int sec = 0; sec < tab_part_sec_num; sec++) {
evt_part_h2d[sec].resize(1);
evt_part_krn[sec].resize(1);
evt_part_d2h[sec].resize(1);
}
std::vector<std::vector<cl_event> > evt_part_h2d_dep(tab_part_sec_num);
evt_part_h2d_dep[0].resize(1);
for (int i = 1; i < tab_part_sec_num; ++i) {
if (i == 1)
evt_part_h2d_dep[i].resize(1);
else
evt_part_h2d_dep[i].resize(2);
}
std::vector<std::vector<cl_event> > evt_part_krn_dep(tab_part_sec_num);
evt_part_krn_dep[0].resize(1);
for (int i = 1; i < tab_part_sec_num; ++i) {
if (i == 1)
evt_part_krn_dep[i].resize(2);
else
evt_part_krn_dep[i].resize(3);
}
std::vector<std::vector<cl_event> > evt_part_d2h_dep(tab_part_sec_num);
evt_part_d2h_dep[0].resize(1);
for (int i = 1; i < tab_part_sec_num; ++i) {
if (i == 1)
evt_part_d2h_dep[i].resize(1);
else
evt_part_d2h_dep[i].resize(2);
}
// define partl memcpy in user events
std::vector<std::vector<cl_event> > evt_part_memcpy_in(tab_part_sec_num);
for (int i = 0; i < tab_part_sec_num; i++) {
evt_part_memcpy_in[i].resize(1);
evt_part_memcpy_in[i][0] = clCreateUserEvent(ctx, &err);
}
std::vector<std::vector<cl_event> > evt_part_memcpy_out(tab_part_sec_num);
for (int i = 0; i < tab_part_sec_num; i++) {
evt_part_memcpy_out[i].resize(1);
evt_part_memcpy_out[i][0] = clCreateUserEvent(ctx, &err);
}
queue_struct part_min[tab_part_sec_num];
queue_struct part_mout[tab_part_sec_num];
std::cout << "=================" << std::endl;
gqe::utils::Timer timer_part;
timer_part.add();
for (int sec = 0; sec < tab_part_sec_num; sec++) {
int kid = sec % 2;
// 1) memcpy in
part_min[sec].sec = sec;
part_min[sec].valid_col_num = l_ncol;
part_min[sec].tab_col_type_size = tab_in_col_size;
part_min[sec].event = &evt_part_memcpy_in[sec][0];
part_min[sec].meta_nrow = tab_part_sec_nrow[sec];
part_min[sec].meta = &meta_part_in[kid];
for (int i = 0; i < l_ncol; i++) {
part_min[sec].ptr_src[i] = tab_part_in_user_col_sec[i][sec];
part_min[sec].ptr_dst[i] = tab_part_in_col[i][kid];
}
if (sec > 1) {
part_min[sec].num_event_wait_list = evt_part_h2d[sec - 2].size();
part_min[sec].event_wait_list = evt_part_h2d[sec - 2].data();
} else {
part_min[sec].num_event_wait_list = 0;
part_min[sec].event_wait_list = nullptr;
}
if (kid == 0) pool.q2_ping.push(part_min[sec]);
if (kid == 1) pool.q2_pong.push(part_min[sec]);
// 2) h2d
evt_part_h2d_dep[sec][0] = evt_part_memcpy_in[sec][0];
if (sec > 1) {
evt_part_h2d_dep[sec][1] = evt_part_krn[sec - 2][0];
}
clEnqueueMigrateMemObjects(cq, part_in_vec[kid].size(), part_in_vec[kid].data(), 0,
evt_part_h2d_dep[sec].size(), evt_part_h2d_dep[sec].data(), &evt_part_h2d[sec][0]);
// 3) kernel
evt_part_krn_dep[sec][0] = evt_part_h2d[sec][0];
if (sec > 0) {
evt_part_krn_dep[sec][1] = evt_part_krn[sec - 1][0];
}
if (sec > 1) {
evt_part_krn_dep[sec][2] = evt_part_d2h[sec - 2][0];
}
clEnqueueTask(cq, partkernel[kid], evt_part_krn_dep[sec].size(), evt_part_krn_dep[sec].data(),
&evt_part_krn[sec][0]);
// 4) d2h, transfer partiton results back
evt_part_d2h_dep[sec][0] = evt_part_krn[sec][0];
if (sec > 1) {
evt_part_d2h_dep[sec][1] = evt_part_memcpy_out[sec - 2][0];
}
clEnqueueMigrateMemObjects(cq, part_out_vec[kid].size(), part_out_vec[kid].data(), 1,
evt_part_d2h_dep[sec].size(), evt_part_d2h_dep[sec].data(), &evt_part_d2h[sec][0]);
// 5) memcpy out
part_mout[sec].sec = sec;
part_mout[sec].valid_col_num = l_ncol;
part_mout[sec].tab_col_type_size = tab_in_col_size;
part_mout[sec].partition_num = partition_num;
part_mout[sec].part_max_nrow_512 = tab_part_out_col_eachpart_nrow_512;
part_mout[sec].event = &evt_part_memcpy_out[sec][0];
part_mout[sec].meta = &meta_part_out[kid];
for (int i = 0; i < l_ncol; i++) {
part_mout[sec].ptr_src[i] = tab_part_out_col[i][kid];
}
part_mout[sec].part_ptr_dst = tab_part_new_col;
part_mout[sec].num_event_wait_list = evt_part_d2h[sec].size();
part_mout[sec].event_wait_list = evt_part_d2h[sec].data();
if (kid == 0) pool.q3_ping.push(part_mout[sec]);
if (kid == 1) pool.q3_pong.push(part_mout[sec]);
}
clWaitForEvents(evt_part_memcpy_out[tab_part_sec_num - 1].size(), evt_part_memcpy_out[tab_part_sec_num - 1].data());
if (tab_part_sec_num > 1) {
clWaitForEvents(evt_part_memcpy_out[tab_part_sec_num - 2].size(),
evt_part_memcpy_out[tab_part_sec_num - 2].data());
}
timer_part.add();
pool.q2_ping_run = 0;
pool.q2_pong_run = 0;
pool.q3_ping_run = 0;
pool.q3_pong_run = 0;
pool.part_l_in_ping_t.join();
pool.part_l_in_pong_t.join();
pool.part_l_out_ping_t.join();
pool.part_l_out_pong_t.join();
#ifdef XDEBUG
// print new_part column data
for (int p = 0; p < partition_num; p++) {
int part_nrow = pool.l_new_part_offset[p];
std::cout << "----------------------------------" << std::endl;
std::cout << "Tab L, p: " << p << ", nrow = " << part_nrow << std::endl;
for (int c = 0; c < 7; c++) {
std::cout << "col: " << c << std::endl;
int nrow_16 = std::min((part_nrow + 15) / 16, 10);
for (int ss = 0; ss < nrow_16; ss++) {
for (int m = 0; m < 16; m++) {
std::cout << tab_part_new_col[p][c][ss](32 * m + 31, 32 * m) << ", ";
}
std::cout << std::endl;
}
}
}
std::cout << "-------------------------------------------------------------" << std::endl;
#endif
#ifdef AGGR_PERF_PROFILE
cl_ulong start, end;
long evt_ns;
for (int sec = 0; sec < tab_part_sec_num; sec++) {
double input_memcpy_size = 0;
for (int i = 0; i < l_ncol; i++) {
input_memcpy_size += tab_part_sec_size[i];
}
input_memcpy_size = input_memcpy_size / 1024 / 1024;
clGetEventProfilingInfo(evt_part_h2d[sec][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_part_h2d[sec][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
std::cout << "Tab L sec: " << sec << ", h2d, size: " << input_memcpy_size
<< " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << input_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
clGetEventProfilingInfo(evt_part_krn[sec][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_part_krn[sec][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
std::cout << "Tab L sec: " << sec << ", krn, size: " << input_memcpy_size
<< " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << input_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
clGetEventProfilingInfo(evt_part_d2h[sec][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_part_d2h[sec][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
double output_memcpy_size = (double)tab_part_out_col_size * l_ncol / 1024 / 1024;
std::cout << "Tab L sec: " << sec << ", d2h, size: " << output_memcpy_size
<< " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << output_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
}
for (int p = 0; p < partition_num; ++p) {
std::cout << "Tab L, p: " << p << ", nrow = " << pool.l_new_part_offset[p] << std::endl;
}
#endif
double tvtime_part = timer_part.getMilliSec();
//=====================================================
//==================== group aggr =====================
//=====================================================
pool.aggr_init();
ap_uint<32>* cfg_aggr = aggr_cfg.getAggrConfigBits();
ap_uint<32>* cfg_aggr_out = aggr_cfg.getAggrConfigOutBits();
int out_ncol = aggr_cfg.getOutputColNum();
if (out_ncol < (int)tab_out.getColNum()) {
std::cout << "Coumn number of Out table should >= " << out_ncol << std::endl;
exit(1);
}
int* tab_out_col_size = new int[out_ncol];
for (int i = 0; i < out_ncol; i++) {
tab_out_col_size[i] = tab_out.getColTypeSize(i);
}
int key_num = aggr_cfg.getGrpKeyNum();
std::vector<std::vector<int> > merge_info;
#ifdef USER_DEBUG
std::cout << "Merging into " << out_ncol << " cols, info:" << std::endl;
#endif
for (int i = 0; i < out_ncol; i++) {
merge_info.push_back(aggr_cfg.getResults(i));
}
std::vector<bool> write_flag = aggr_cfg.getWriteFlag();
// aggr input hbuf
int aggr_in_nrow_max = 0;
int aggr_in_nrow[partition_num];
for (int p = 0; p < partition_num; p++) {
aggr_in_nrow[p] = pool.l_new_part_offset[p];
aggr_in_nrow_max = std::max(aggr_in_nrow_max, aggr_in_nrow[p]);
}
std::cout << "aggr_in_nrow_max = " << aggr_in_nrow_max << std::endl;
int* aggr_in_nrow_max_size = new int[l_ncol];
for (int i = 0; i < l_ncol; i++) {
aggr_in_nrow_max_size[i] = aggr_in_nrow_max * tab_in_col_size[i];
}
char* tab_aggr_in_col[8][2];
for (int k = 0; k < 2; k++) {
for (int c = 0; c < 8; c++) {
if (c < l_ncol)
tab_aggr_in_col[c][k] = mm.aligned_alloc<char>(aggr_in_nrow_max_size[c]);
else
tab_aggr_in_col[c][k] = mm.aligned_alloc<char>(VEC_LEN);
}
}
// define the nrow of aggr result
int aggr_result_nrow = aggr_in_nrow_max;
size_t aggr_result_nrow_512 = (aggr_result_nrow + VEC_LEN - 1) / VEC_LEN;
size_t aggr_result_nrow_512_size = aggr_result_nrow_512 * sizeof(ap_uint<512>);
// in int32 imp, suppose all the data bit is 32 bit
char* tab_aggr_out_col[16][2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 16; i++) {
if (write_flag[i]) {
tab_aggr_out_col[i][k] = mm.aligned_alloc<char>(aggr_result_nrow_512_size);
memset(tab_aggr_out_col[i][k], 0, aggr_result_nrow_512_size);
} else {
tab_aggr_out_col[i][k] = mm.aligned_alloc<char>(VEC_LEN);
}
}
}
//--------------- meta setup -----------------
// setup meta input and output
MetaTable meta_aggr_in[2];
MetaTable meta_aggr_out[2];
for (int i = 0; i < 2; i++) {
meta_aggr_in[i].setColNum(l_ncol);
for (int j = 0; j < l_ncol; j++) {
// meta_aggr_in[i].setCol(j, j, (aggr_in_nrow_max + 15) / 16);
meta_aggr_in[i].setCol(j, j, aggr_in_nrow_max);
}
meta_aggr_in[i].meta();
}
meta_aggr_out[0].setColNum(16);
meta_aggr_out[1].setColNum(16);
for (int c = 0; c < 16; c++) {
meta_aggr_out[0].setCol(c, c, aggr_result_nrow_512);
meta_aggr_out[1].setCol(c, c, aggr_result_nrow_512);
}
meta_aggr_out[0].meta();
meta_aggr_out[1].meta();
// setCol invalid now since kernel code is comment out
//---------------------------------------------
cl_mem_ext_ptr_t mext_tab_aggr_in_col[8][2];
cl_mem_ext_ptr_t mext_meta_aggr_in[2], mext_meta_aggr_out[2];
cl_mem_ext_ptr_t mext_cfg_aggr, mext_cfg_aggr_out;
cl_mem_ext_ptr_t mext_tab_aggr_out[16][2];
cl_mem_ext_ptr_t mext_aggr_tmp[8];
int agg_i = 0;
for (int k = 0; k < 2; k++) {
agg_i = 0;
for (int c = 0; c < 8; c++) {
mext_tab_aggr_in_col[c][k] = {agg_i++, tab_aggr_in_col[c][k], aggrkernel[k]};
}
mext_meta_aggr_in[k] = {agg_i++, meta_aggr_in[k].meta(), aggrkernel[k]};
mext_meta_aggr_out[k] = {agg_i++, meta_aggr_out[k].meta(), aggrkernel[k]};
}
for (int k = 0; k < 2; k++) {
agg_i = 10;
for (int i = 0; i < 16; ++i) {
mext_tab_aggr_out[i][k] = {agg_i++, tab_aggr_out_col[i][k], aggrkernel[k]};
}
}
mext_cfg_aggr = {agg_i++, cfg_aggr, aggrkernel[0]};
mext_cfg_aggr_out = {agg_i++, cfg_aggr_out, aggrkernel[0]};
for (int c = 0; c < 8; c++) {
mext_aggr_tmp[c] = {agg_i++, nullptr, aggrkernel[0]};
}
cl_mem buf_tab_aggr_in_col[8][2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 8; ++i) {
if (i < l_ncol) {
buf_tab_aggr_in_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
aggr_in_nrow_max_size[i], &mext_tab_aggr_in_col[i][k], &err);
} else {
buf_tab_aggr_in_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, VEC_LEN,
&mext_tab_aggr_in_col[i][k], &err);
}
}
}
cl_mem buf_aggr_tmp[8];
for (int i = 0; i < 8; i++) {
buf_aggr_tmp[i] = clCreateBuffer(ctx, CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS | CL_MEM_EXT_PTR_XILINX,
(size_t)(8 * S_BUFF_DEPTH), &mext_aggr_tmp[i], &err);
}
cl_mem buf_meta_aggr_in[2];
buf_meta_aggr_in[0] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_in[0], &err);
buf_meta_aggr_in[1] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_in[1], &err);
cl_mem buf_meta_aggr_out[2];
buf_meta_aggr_out[0] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_out[0], &err);
buf_meta_aggr_out[1] = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
(sizeof(ap_uint<512>) * 24), &mext_meta_aggr_out[1], &err);
cl_mem buf_cfg_aggr = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_t(4 * 128), &mext_cfg_aggr, &err);
cl_mem buf_cfg_aggr_out = clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
size_t(4 * 128), &mext_cfg_aggr_out, &err);
cl_mem buf_tab_aggr_out_col[16][2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 16; ++i) {
if (write_flag[i])
buf_tab_aggr_out_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE,
aggr_result_nrow_512_size, &mext_tab_aggr_out[i][k], &err);
else
buf_tab_aggr_out_col[i][k] =
clCreateBuffer(ctx, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, VEC_LEN,
&mext_tab_aggr_out[i][k], &err);
}
}
// set args and enqueue kernel
for (int k = 0; k < 2; k++) {
j = 0;
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[0][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[1][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[2][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[3][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[4][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[5][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[6][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_in_col[7][k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_meta_aggr_in[k]);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_meta_aggr_out[k]);
for (int c = 0; c < 16; c++) {
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_tab_aggr_out_col[c][k]);
}
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_cfg_aggr);
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_cfg_aggr_out);
for (int c = 0; c < 8; c++) {
clSetKernelArg(aggrkernel[k], j++, sizeof(cl_mem), &buf_aggr_tmp[c]);
}
}
clEnqueueMigrateMemObjects(cq, 1, &buf_meta_aggr_out[0], 0, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, 1, &buf_meta_aggr_out[1], 0, 0, nullptr, nullptr);
std::vector<cl_mem> aggr_in_vec[2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < l_ncol; i++) {
aggr_in_vec[k].push_back(buf_tab_aggr_in_col[i][k]);
}
aggr_in_vec[k].push_back(buf_meta_aggr_in[k]);
aggr_in_vec[k].push_back(buf_cfg_aggr);
}
std::vector<cl_mem> aggr_out_vec[2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < 16; ++i) {
aggr_out_vec[k].push_back(buf_tab_aggr_out_col[i][k]);
}
aggr_out_vec[k].push_back(buf_meta_aggr_out[k]);
}
clEnqueueMigrateMemObjects(cq, aggr_in_vec[0].size(), aggr_in_vec[0].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, aggr_in_vec[1].size(), aggr_in_vec[1].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, aggr_out_vec[0].size(), aggr_out_vec[0].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
clEnqueueMigrateMemObjects(cq, aggr_out_vec[1].size(), aggr_out_vec[1].data(),
CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED, 0, nullptr, nullptr);
std::vector<std::vector<cl_event> > evt_aggr_memcpy_in(partition_num);
std::vector<std::vector<cl_event> > evt_aggr_h2d(partition_num);
std::vector<std::vector<cl_event> > evt_aggr_krn(partition_num);
std::vector<std::vector<cl_event> > evt_aggr_d2h(partition_num);
std::vector<std::vector<cl_event> > evt_aggr_memcpy_out(partition_num);
for (int p = 0; p < partition_num; p++) {
evt_aggr_memcpy_in[p].resize(1);
evt_aggr_h2d[p].resize(1);
evt_aggr_krn[p].resize(1);
evt_aggr_d2h[p].resize(1);
evt_aggr_memcpy_out[p].resize(1);
evt_aggr_memcpy_in[p][0] = clCreateUserEvent(ctx, &err);
evt_aggr_memcpy_out[p][0] = clCreateUserEvent(ctx, &err);
}
std::vector<std::vector<cl_event> > evt_aggr_h2d_dep(partition_num);
evt_aggr_h2d_dep[0].resize(1);
for (int i = 1; i < partition_num; ++i) {
if (i == 1)
evt_aggr_h2d_dep[i].resize(1);
else
evt_aggr_h2d_dep[i].resize(2);
}
std::vector<std::vector<cl_event> > evt_aggr_krn_dep(partition_num);
std::vector<std::vector<cl_event> > evt_aggr_d2h_dep(partition_num);
// the collection of each partition aggr results
// in int32 imp, suppose all the data bit is 32 bit
char* tab_aggr_res_col[16];
for (int i = 0; i < 16; i++) {
void* ptr = nullptr;
if (posix_memalign(&ptr, 4096, aggr_result_nrow_512_size)) throw std::bad_alloc();
tab_aggr_res_col[i] = reinterpret_cast<char*>(ptr);
}
queue_struct aggr_min[partition_num];
queue_struct aggr_mout[partition_num];
// because pure device buf is used in aggr kernel, the kernel needs to be run invalid for 1 round
{
std::cout << "xxxxxxxxxxxxxxxxxxxxxx invalid below xxxxxxxxxxxxxxxxxxxxxxxx" << std::endl;
meta_aggr_in[0].setColNum(1);
meta_aggr_in[0].setCol(0, 0, 15);
meta_aggr_in[0].meta();
clEnqueueMigrateMemObjects(cq, aggr_in_vec[0].size(), aggr_in_vec[0].data(), 0, 0, nullptr,
&evt_aggr_h2d[0][0]);
clEnqueueTask(cq, aggrkernel[0], evt_aggr_h2d[0].size(), evt_aggr_h2d[0].data(), nullptr);
clFinish(cq);
std::cout << "xxxxxxxxxxxxxxxxxxxxxx invalid above xxxxxxxxxxxxxxxxxxxxxxxx" << std::endl;
}
gqe::utils::Timer timer_aggr;
timer_aggr.add();
// aggr loop run
for (int p = 0; p < partition_num; p++) {
int kid = p % 2;
// 1)memcpy in, copy the data from tab_part_new_col[partition_num][8][l_new_part_nrow_512] to
// tab_aggr_in_col0-7
aggr_min[p].p = p;
aggr_min[p].valid_col_num = l_ncol;
aggr_min[p].tab_col_type_size = tab_in_col_size;
aggr_min[p].event = &evt_aggr_memcpy_in[p][0];
aggr_min[p].meta = &meta_aggr_in[kid];
aggr_min[p].meta_nrow = aggr_in_nrow[p];
for (int i = 0; i < l_ncol; i++) {
aggr_min[p].ptr_src[i] = tab_part_new_col[p][scan_list[i]];
aggr_min[p].ptr_dst[i] = tab_aggr_in_col[i][kid];
}
if (p > 1) {
aggr_min[p].num_event_wait_list = evt_aggr_h2d[p - 2].size();
aggr_min[p].event_wait_list = evt_aggr_h2d[p - 2].data();
} else {
aggr_min[p].num_event_wait_list = 0;
aggr_min[p].event_wait_list = nullptr;
}
if (kid == 0) pool.q7_ping.push(aggr_min[p]);
if (kid == 1) pool.q7_pong.push(aggr_min[p]);
// 2)h2d
evt_aggr_h2d_dep[p][0] = evt_aggr_memcpy_in[p][0];
if (p > 1) {
evt_aggr_h2d_dep[p][1] = evt_aggr_krn[p - 2][0];
}
clEnqueueMigrateMemObjects(cq, aggr_in_vec[kid].size(), aggr_in_vec[kid].data(), 0, evt_aggr_h2d_dep[p].size(),
evt_aggr_h2d_dep[p].data(), &evt_aggr_h2d[p][0]);
// 3)aggr kernel
evt_aggr_krn_dep[p].push_back(evt_aggr_h2d[p][0]);
if (p > 0) {
evt_aggr_krn_dep[p].push_back(evt_aggr_krn[p - 1][0]);
}
if (p > 1) {
evt_aggr_krn_dep[p].push_back(evt_aggr_d2h[p - 2][0]);
}
clEnqueueTask(cq, aggrkernel[kid], evt_aggr_krn_dep[p].size(), evt_aggr_krn_dep[p].data(), &evt_aggr_krn[p][0]);
// 4)d2h
evt_aggr_d2h_dep[p].push_back(evt_aggr_krn[p][0]);
if (p > 1) {
evt_aggr_d2h_dep[p].push_back(evt_aggr_memcpy_out[p - 2][0]);
}
clEnqueueMigrateMemObjects(cq, aggr_out_vec[kid].size(), aggr_out_vec[kid].data(), CL_MIGRATE_MEM_OBJECT_HOST,
evt_aggr_d2h_dep[p].size(), evt_aggr_d2h_dep[p].data(), &evt_aggr_d2h[p][0]);
// 5)memcpy out
aggr_mout[p].p = p;
aggr_mout[p].valid_col_num = out_ncol;
// did work in 64bit impl
aggr_mout[p].tab_col_type_size = tab_out_col_size;
aggr_mout[p].write_flag = write_flag;
aggr_mout[p].merge_info = merge_info;
aggr_mout[p].key_num = key_num;
aggr_mout[p].pld_num = out_ncol - key_num;
aggr_mout[p].event = &evt_aggr_memcpy_out[p][0];
aggr_mout[p].meta = &meta_aggr_out[kid];
for (int c = 0; c < 16; c++) {
if (write_flag[c]) {
aggr_mout[p].ptr_src[c] = tab_aggr_out_col[c][kid];
aggr_mout[p].ptr_dst[c] = tab_aggr_res_col[c];
}
}
aggr_mout[p].num_event_wait_list = evt_aggr_d2h[p].size();
aggr_mout[p].event_wait_list = evt_aggr_d2h[p].data();
if (kid == 0) pool.q8_ping.push(aggr_mout[p]);
if (kid == 1) pool.q8_pong.push(aggr_mout[p]);
}
// clFinish(cq);
clWaitForEvents(evt_aggr_memcpy_out[partition_num - 1].size(), evt_aggr_memcpy_out[partition_num - 1].data());
if (partition_num > 1) {
clWaitForEvents(evt_aggr_memcpy_out[partition_num - 2].size(), evt_aggr_memcpy_out[partition_num - 2].data());
}
timer_aggr.add();
#ifdef AGGR_PERF_PROFILE
for (int p = 0; p < partition_num; p++) {
double input_memcpy_size = 0;
for (int pp = 0; pp < l_ncol; pp++) {
input_memcpy_size += (double)aggr_in_nrow[p] * tab_in_col_size[pp];
}
input_memcpy_size = input_memcpy_size / 1024 / 1024;
clGetEventProfilingInfo(evt_aggr_h2d[p][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_aggr_h2d[p][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
std::cout << "Part: " << p << ", h2d, size: " << input_memcpy_size << " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << input_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
clGetEventProfilingInfo(evt_aggr_krn[p][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_aggr_krn[p][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
std::cout << "Part: " << p << ", krn, size: " << input_memcpy_size << " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << input_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
clGetEventProfilingInfo(evt_aggr_d2h[p][0], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(evt_aggr_d2h[p][0], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
evt_ns = end - start;
double output_memcpy_size = 0;
for (int pp = 0; pp < 16; pp++) {
if (write_flag[pp]) output_memcpy_size += (double)aggr_result_nrow_512_size;
}
output_memcpy_size = output_memcpy_size / 1024 / 1024;
std::cout << "Part: " << p << ", d2h, size: " << output_memcpy_size << " MB, time: " << double(evt_ns) / 1000000
<< " ms, throughput: " << output_memcpy_size / 1024 / ((double)evt_ns / 1000000000) << " GB/s "
<< std::endl;
}
#endif
pool.q7_ping_run = 0;
pool.q7_pong_run = 0;
pool.q8_ping_run = 0;
pool.q8_pong_run = 0;
pool.aggr_in_ping_t.join();
pool.aggr_in_pong_t.join();
pool.aggr_out_ping_t.join();
pool.aggr_out_pong_t.join();
double l_input_memcpy_size = 0;
for (int i = 0; i < l_ncol; i++) {
l_input_memcpy_size += (double)l_nrow * tab_in_col_size[i];
}
l_input_memcpy_size = l_input_memcpy_size / 1024 / 1024;
double l_output_memcpy_size = (double)pool.aggr_sum_nrow * out_ncol * sizeof(int64_t) / 1024 / 1024;
std::cout << "-----------------------Data Transfer Info-----------------------" << std::endl;
std::cout << "H2D size = " << l_input_memcpy_size << " MB" << std::endl;
std::cout << "D2H size = " << l_output_memcpy_size << " MB" << std::endl;
double tvtime_aggr = timer_aggr.getMilliSec();
std::cout << "------------------------Performance Info------------------------" << std::endl;
std::cout << "Tab L pipelined partition, time: " << (double)tvtime_part / 1000
<< " ms, throughput: " << l_input_memcpy_size / 1024 / ((double)tvtime_part / 1000000) << " GB/s"
<< std::endl;
std::cout << "aggr pipelined, time: " << (double)tvtime_aggr / 1000
<< " ms, throughput: " << l_input_memcpy_size / 1024 / ((double)tvtime_aggr / 1000000) << " GB/s"
<< std::endl;
std::cout << "All time: " << (double)(tvtime_part + tvtime_aggr) / 1000
<< " ms, throughput: " << l_input_memcpy_size / 1024 / ((double)(tvtime_part + tvtime_aggr) / 1000000)
<< " GB/s" << std::endl;
tab_out.setRowNum(pool.aggr_sum_nrow);
// tab_out.setWColNum(out_ncol);
char** cos_of_table_out = new char*[out_ncol];
for (int i = 0; i < out_ncol; i++) {
cos_of_table_out[i] = tab_out.getColPointer(i);
}
// XXX For gqeAggr v2, the high/low bits are written to different buffers for 64b output.
// This should be addressed by 64b native kernels.
for (int i = 0; i < out_ncol; ++i) {
auto index = merge_info[i];
if (index.size() == 1) {
if (tab_out_col_size[i] == 4) {
memcpy(cos_of_table_out[i], tab_aggr_res_col[index[0]], 4 * pool.aggr_sum_nrow);
} else if (tab_out_col_size[i] == 8) {
// sign extend the low
zipInt64(cos_of_table_out[i], tab_aggr_res_col[index[0]], nullptr, pool.aggr_sum_nrow);
} else {
assert(0 && "Illegal column size");
}
} else if (index.size() == 2) {
if (tab_out_col_size[i] == 4) {
// truncate and just keep the low bits.
memcpy(cos_of_table_out[i], tab_aggr_res_col[index[0]], 4 * pool.aggr_sum_nrow);
} else if (tab_out_col_size[i] == 8) {
// zip
zipInt64(cos_of_table_out[i], tab_aggr_res_col[index[0]], tab_aggr_res_col[index[1]],
pool.aggr_sum_nrow);
} else {
assert(0 && "Illegal column size");
}
} else {
assert(0 && "Unsupported output content handling");
}
}
std::cout << "Aggr done, table saved: " << tab_out.getRowNum() << " rows," << tab_out.getColNum() << " cols"
<< std::endl;
return SUCCESS;
}
} // database
} // gqe
} // xf
| 43.543443 | 120 | 0.565465 | [
"vector"
] |
83bd94f6bb3d914aae0f62188fe512ae9f7fdd60 | 1,876 | hpp | C++ | src/Pathfinding-Visualizer/Graph.hpp | joshuainovero/Pathfinding-Visualizer | da94f026d2a1c26cb5241500e8013d1e9d906543 | [
"MIT"
] | 4 | 2021-10-15T03:40:48.000Z | 2022-01-19T18:48:01.000Z | src/Pathfinding-Visualizer/Graph.hpp | joshuainovero/Pathfinding-Visualizer | da94f026d2a1c26cb5241500e8013d1e9d906543 | [
"MIT"
] | null | null | null | src/Pathfinding-Visualizer/Graph.hpp | joshuainovero/Pathfinding-Visualizer | da94f026d2a1c26cb5241500e8013d1e9d906543 | [
"MIT"
] | 2 | 2021-10-15T03:40:52.000Z | 2022-01-05T10:07:42.000Z | #ifndef GRAPH_H
#define GRAHP_H
#include "Node.hpp"
#include "Astar.hpp"
#include "Dijkstra.hpp"
#include "BFS.hpp"
#include "DFS.hpp"
#include "RecursiveMaze.hpp"
#include "RandomTerrain.hpp"
#include <vector>
#include <utility>
enum Enum_Search {ASTAR, DIJKSTRA, BFS, DFS};
enum Maze_Algorithms {RM, RAND_T};
class Graph {
public:
static constexpr float ratio_row = 0.1555555556f;
Graph(uint32_t rows, uint32_t width);
void construct_graph(uint32_t rows, uint32_t width);
void clear_graph();
void draw_grid(sf::RenderWindow *window, const bool& enable);
void draw_tiles(sf::RenderWindow *window, const bool& visualize_visiting);
void assign_start(Node* v__);
void remove_start();
void remove_end();
void assign_end(Node* v__);
void assign_curr_search_algo(Enum_Search v__);
void assign_curr_terr_algo(Maze_Algorithms v__);
void draw_ST_tiles(sf::RenderWindow* window, sf::Mouse& mousePos);
std::vector<Node*>* get_board() const;
uint32_t get_total_rows() const;
std::pair<Node*, Node*> STNodes() const;
Search_* g_curr_search_algo() const;
Algorithm_* g_curr_terr_algo() const;
Maze_Algorithms g_curr_maze_algo() const;
std::vector<Search_*> g_search_algos() const;
std::vector<Algorithm_*> g_terrain_algos() const;
sf::Vector2u rowcol_pos_click(sf::Vector2i pos);
private:
std::vector<Node*> *board;
std::vector<Algorithm_*> terrain_algorithms;
std::vector<Search_*> search_algorithms;
Maze_Algorithms current_maze_algo;
Algorithm_* current_terrain_algo;
Search_* current_search_algo;
Node* start_node;
Node* end_node;
uint32_t board_width;
uint32_t total_rows;
float tile_gap;
sf::RectangleShape horLine, vertLine;
sf::RectangleShape green_tile, red_tile;
};
#endif // GRAPH_H | 21.813953 | 78 | 0.70629 | [
"vector"
] |
83c1d2c498b4953461d9ff2718d8de77b435f0b4 | 23,608 | cpp | C++ | Modules/Contents/UI/Source/PolyUITextInput.cpp | mcclure/old-Polycode | 284d68b114da057c9468627781eca2d853d272f7 | [
"MIT"
] | 3 | 2018-04-21T16:25:21.000Z | 2022-03-28T03:36:16.000Z | Modules/Contents/UI/Source/PolyUITextInput.cpp | mcclure/old-Polycode | 284d68b114da057c9468627781eca2d853d272f7 | [
"MIT"
] | null | null | null | Modules/Contents/UI/Source/PolyUITextInput.cpp | mcclure/old-Polycode | 284d68b114da057c9468627781eca2d853d272f7 | [
"MIT"
] | 1 | 2020-04-29T03:22:50.000Z | 2020-04-29T03:22:50.000Z | /*
* PolyUITextInput.cpp
* Poly
*
* Created by Ivan Safrin on 7/30/08.
* Copyright 2008 __MyCompanyName__. All rights reserved.
*
*/
#include "PolyUITextInput.h"
using namespace Polycode;
UITextInput::UITextInput(bool multiLine, Number width, Number height) : ScreenEntity() {
this->multiLine = multiLine;
draggingSelection = false;
hasSelection = false;
doSelectToCaret = false;
caretPosition = 0;
caretImagePosition = 0;
currentLine = NULL;
lineOffset = -1;
numLines = 0;
this->positionMode = ScreenEntity::POSITION_TOPLEFT;
Config *conf = CoreServices::getInstance()->getConfig();
if(multiLine)
fontName = conf->getStringValue("Polycode", "uiTextInputFontNameMultiLine");
else
fontName = conf->getStringValue("Polycode", "uiTextInputFontName");
fontSize = conf->getNumericValue("Polycode", "uiTextInputFontSize");
Number rectHeight = height;
if(!multiLine) {
rectHeight = fontSize+12;
}
lineSpacing = conf->getNumericValue("Polycode", "textEditLineSpacing");
Number st = conf->getNumericValue("Polycode", "textBgSkinT");
Number sr = conf->getNumericValue("Polycode", "textBgSkinR");
Number sb = conf->getNumericValue("Polycode", "textBgSkinB");
Number sl = conf->getNumericValue("Polycode", "textBgSkinL");
padding = conf->getNumericValue("Polycode", "textBgSkinPadding");
inputRect = new UIBox(conf->getStringValue("Polycode", "textBgSkin"),
st,sr,sb,sl,
width+(padding*2), height+(padding*2));
addChild(inputRect);
inputRect->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);
inputRect->addEventListener(this, InputEvent::EVENT_MOUSEUP);
inputRect->addEventListener(this, InputEvent::EVENT_DOUBLECLICK);
inputRect->addEventListener(this, InputEvent::EVENT_MOUSEMOVE);
inputRect->addEventListener(this, InputEvent::EVENT_MOUSEOVER);
inputRect->addEventListener(this, InputEvent::EVENT_MOUSEOUT);
selectorRectTop = new ScreenShape(ScreenShape::SHAPE_RECT, 1,1);
selectorRectTop->setPositionMode(ScreenEntity::POSITION_TOPLEFT);
selectorRectTop->setColor(181.0f/255.0f, 213.0f/255.0f, 255.0f/255.0f, 1);
selectorRectTop->visible = false;
addChild(selectorRectTop);
selectorRectMiddle = new ScreenShape(ScreenShape::SHAPE_RECT, 1,1);
selectorRectMiddle->setPositionMode(ScreenEntity::POSITION_TOPLEFT);
selectorRectMiddle->setColor(181.0f/255.0f, 213.0f/255.0f, 255.0f/255.0f, 1);
selectorRectMiddle->visible = false;
addChild(selectorRectMiddle);
selectorRectBottom = new ScreenShape(ScreenShape::SHAPE_RECT, 1,1);
selectorRectBottom->setPositionMode(ScreenEntity::POSITION_TOPLEFT);
selectorRectBottom->setColor(181.0f/255.0f, 213.0f/255.0f, 255.0f/255.0f, 1);
selectorRectBottom->visible = false;
addChild(selectorRectBottom);
insertLine(true);
blinkerRect = new ScreenShape(ScreenShape::SHAPE_RECT, 1, fontSize,0,0);
blinkerRect->setPositionMode(ScreenEntity::POSITION_TOPLEFT);
blinkerRect->setColor(0,0,0,1);
addChild(blinkerRect);
blinkerRect->visible = false;
blinkerRect->setPosition(0,3);
blinkTimer = new Timer(true, 500);
blinkTimer->addEventListener(this, Timer::EVENT_TRIGGER);
focusable = true;
this->width = width;
this->height = rectHeight;
hitwidth = width;
hitheight = rectHeight;
updateCaretPosition();
}
void UITextInput::clearSelection() {
hasSelection = false;
selectorRectTop->visible = false;
selectorRectMiddle->visible = false;
selectorRectBottom->visible = false;
}
void UITextInput::setSelection(int lineStart, int lineEnd, int colStart, int colEnd) {
if(lineStart == lineOffset) {
selectionLine = lineEnd;
} else {
selectionLine = lineStart;
}
if(colStart == caretPosition) {
selectionCaretPosition = colEnd;
} else {
selectionCaretPosition = colStart;
}
// Logger::log("SET lineStart:%d lineEnd:%d colStart:%d colEnd:%d\n", lineStart, lineEnd, colStart, colEnd);
if(lineStart > lineEnd) {
int tmp = lineStart;
lineStart = lineEnd;
lineEnd = tmp;
tmp = colStart;
colStart = colEnd;
colEnd = tmp;
}
if(colStart > colEnd && lineStart == lineEnd) {
int tmp = colStart;
colStart = colEnd;
colEnd = tmp;
}
clearSelection();
if(lineStart > lines.size()-1)
return;
ScreenLabel *topLine = lines[lineStart];
if(colStart+1 > topLine->getText().length())
return;
Number fColEnd = colEnd;
if(colEnd > topLine->getText().length() || lineStart != lineEnd)
fColEnd = topLine->getText().length();
Number topSize, topHeight, topX;
selectorRectTop->visible = true;
topSize = topLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), topLine->getText().substr(colStart,fColEnd-colStart), fontSize) - 4;
topHeight = lineHeight+lineSpacing;
if(colStart > 0) {
topX = topLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), topLine->getText().substr(0,colStart-1), fontSize); ;
} else {
topX = 0;
}
selectorRectTop->setScale(topSize, topHeight);
selectorRectTop->setPosition(topX + padding + (topSize/2.0)+ 1, padding + (lineStart * (lineHeight+lineSpacing)) + (topHeight/2.0));
if(lineEnd > lineStart && lineEnd < lines.size()) {
ScreenLabel *bottomLine = lines[lineEnd];
selectorRectBottom->visible = true;
Number bottomSize = bottomLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), bottomLine->getText().substr(0,colEnd), fontSize) - 4;
Number bottomHeight = lineHeight+lineSpacing;
selectorRectBottom->setScale(bottomSize, bottomHeight);
selectorRectBottom->setPosition(padding + (bottomSize/2.0) + 1, padding + (lineEnd * (lineHeight+lineSpacing)) + (bottomHeight/2.0));
if(lineEnd != lineStart+1) {
// need filler
selectorRectMiddle->visible = true;
Number midSize = this->width-padding;
Number midHeight = 0;
for(int i=lineStart+1; i < lineEnd;i++) {
midHeight += lineHeight+lineSpacing;
}
selectorRectMiddle->setScale(midSize, midHeight);
selectorRectMiddle->setPosition(padding + (midSize/2.0), padding + ((lineStart+1) * (lineHeight+lineSpacing)) + (midHeight/2.0));
}
}
hasSelection = true;
selectionTop = lineStart;
selectionBottom = lineEnd;
selectionL = colStart;
selectionR = colEnd;
}
void UITextInput::deleteSelection() {
if(selectionTop == selectionBottom) {
String ctext = lines[selectionTop]->getText();
String newText = ctext.substr(0, selectionL);
int rside = selectionR;
if(rside > ctext.length()-1)
rside = ctext.length() - 1;
newText += ctext.substr(rside,ctext.length() - selectionR);
lines[selectionTop]->setText(newText);
} else {
String ctext = lines[selectionTop]->getText();
String newText = ctext.substr(0, selectionL);
lines[selectionTop]->setText(newText);
ScreenLabel *bottomLine = lines[selectionBottom];
// if whole lines to remove, do it
vector<ScreenLabel*> linesToRemove;
if(selectionBottom > selectionTop + 1) {
for(int i=selectionTop+1; i < selectionBottom; i++) {
linesToRemove.push_back(lines[i]);
}
for(int i=0; i < linesToRemove.size(); i++) {
removeLine(linesToRemove[i]);
}
}
ctext = bottomLine->getText();
int rside = selectionR;
if(rside > ctext.length()-1)
rside = ctext.length() - 1;
newText = ctext.substr(rside,ctext.length() - selectionR);
lineOffset = selectionTop;
selectLineFromOffset();
caretPosition = currentLine->getText().length();
updateCaretPosition();
currentLine->setText(currentLine->getText() + newText);
removeLine(bottomLine);
}
clearSelection();
caretPosition = selectionL;
updateCaretPosition();
}
void UITextInput::Resize(int x, int y) {
inputRect->resizeBox(x, y);
}
int UITextInput::insertLine(bool after) {
numLines++;
ScreenLabel *newLine = new ScreenLabel(fontName, L"", fontSize, Label::ANTIALIAS_FULL);
newLine->setColor(0,0,0,1);
lineHeight = newLine->getHeight();
addChild(newLine);
if(after) {
if(currentLine) {
String ctext = currentLine->getText();
String text2 = ctext.substr(caretPosition, ctext.length()-caretPosition);
ctext = ctext.substr(0,caretPosition);
currentLine->setText(ctext);
newLine->setText(text2);
caretPosition=0;
}
currentLine = newLine;
vector<ScreenLabel*>::iterator it;
it = lines.begin();
for(int i=0; i < lineOffset+1; i++) {
it++;
}
lineOffset = lineOffset + 1;
lines.insert(it,newLine);
restructLines();
} else {
// do we even need that? I don't think so.
}
return 1;
}
void UITextInput::restructLines() {
for(int i=0; i < lines.size(); i++) {
lines[i]->setPosition(padding,padding + (i*(lineHeight+lineSpacing)) ,0.0f);
}
}
void UITextInput::setText(String text) {
if(!multiLine) {
currentLine->setText(text);
} else {
}
// this->text = text;
// currentLine->setText(text);
}
void UITextInput::onLoseFocus() {
blinkerRect->visible = false;
}
String UITextInput::getText() {
if(!multiLine) {
return currentLine->getText();
} else {
String totalText = L"";
for(int i=0; i < lines.size(); i++) {
totalText += lines[i]->getText();
totalText += L"\n";
}
return totalText;
}
}
void UITextInput::updateCaretPosition() {
caretImagePosition = padding;
if(caretPosition == 0) {
caretImagePosition = padding;
} else if(caretPosition > currentLine->getText().length()) {
caretPosition = currentLine->getText().length();
String caretSubString = currentLine->getText().substr(0,caretPosition);
caretImagePosition = currentLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), caretSubString, fontSize);
caretImagePosition = caretImagePosition - 4.0f + padding;
} else {
String caretSubString = currentLine->getText().substr(0,caretPosition);
caretImagePosition = currentLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), caretSubString, fontSize);
caretImagePosition = caretImagePosition - 4.0f + padding;
}
blinkerRect->visible = true;
blinkTimer->Reset();
if(doSelectToCaret) {
doSelectToCaret = false;
}
}
void UITextInput::selectLineFromOffset() {
for(int i=0; i < lines.size(); i++) {
if(i == lineOffset) {
currentLine = lines[i];
return;
}
}
}
void UITextInput::dragSelectionTo(Number x, Number y) {
x -= padding;
y -= padding;
int lineOffset = y / (lineHeight+lineSpacing);
if(lineOffset > lines.size()-1)
lineOffset = lines.size()-1;
ScreenLabel *selectToLine = lines[lineOffset];
int len = selectToLine->getText().length();
Number slen;
int caretPosition = selectToLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), selectToLine->getText().substr(0,len), fontSize);
for(int i=0; i < len; i++) {
slen = selectToLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), selectToLine->getText().substr(0,i), fontSize);
if(slen > x) {
caretPosition = i;
break;
}
}
if(x > slen)
caretPosition = len;
if(caretPosition < 0)
caretPosition = 0;
setSelection(this->lineOffset, lineOffset, this->caretPosition, caretPosition);
}
int UITextInput::caretSkipWordBack(int caretLine, int caretPosition) {
for(int i=caretPosition; i > 0; i--) {
String bit = lines[caretLine]->getText().substr(i,1);
wchar_t chr = ((wchar_t*)bit.c_str())[0];
if(((chr > 0 && chr < 48) || (chr > 57 && chr < 65) || (chr > 90 && chr < 97) || (chr > 122 && chr < 127)) && i < caretPosition-1) {
return i+1;
}
}
return 0;
}
int UITextInput::caretSkipWordForward(int caretLine, int caretPosition) {
int len = lines[caretLine]->getText().length();
for(int i=caretPosition; i < len; i++) {
String bit = lines[caretLine]->getText().substr(i,1);
wchar_t chr = ((wchar_t*)bit.c_str())[0];
if(((chr > 0 && chr < 48) || (chr > 57 && chr < 65) || (chr > 90 && chr < 97) || (chr > 122 && chr < 127)) && i > caretPosition) {
return i;
}
}
return lines[caretLine]->getText().length();
}
void UITextInput::selectWordAtCaret() {
int selectStart = 0;
int len = currentLine->getText().length();
int selectEnd = len;
for(int i=this->caretPosition; i > 0; i--) {
String bit = currentLine->getText().substr(i,1);
wchar_t chr = ((wchar_t*)bit.c_str())[0];
if( (chr > 0 && chr < 48) || (chr > 57 && chr < 65) || (chr > 90 && chr < 97) || (chr > 122 && chr < 127)) {
selectStart = i+1;
break;
}
}
for(int i=this->caretPosition; i < len; i++) {
String bit = currentLine->getText().substr(i,1);
wchar_t chr = ((wchar_t*)bit.c_str())[0];
if( (chr > 0 && chr < 48) || (chr > 57 && chr < 65) || (chr > 90 && chr < 97) || (chr > 122 && chr < 127)) {
selectEnd = i;
break;
}
}
setSelection(this->lineOffset, this->lineOffset, selectStart, selectEnd);
}
void UITextInput::setCaretToMouse(Number x, Number y) {
clearSelection();
x -= padding;
y -= padding;
//if(lines.size() > 1) {
lineOffset = y / (lineHeight+lineSpacing);
if(lineOffset > lines.size()-1)
lineOffset = lines.size()-1;
selectLineFromOffset();
//}
int len = currentLine->getText().length();
Number slen;
for(int i=0; i < len; i++) {
slen = currentLine->getLabel()->getTextWidth(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), currentLine->getText().substr(0,i), fontSize);
if(slen > x) {
caretPosition = i;
break;
}
}
if(x > slen)
caretPosition = len;
updateCaretPosition();
}
void UITextInput::removeLine(ScreenLabel *line) {
for(int i=0;i<lines.size();i++) {
if(lines[i] == line) {
lines.erase(lines.begin()+i);
}
}
removeChild(line);
delete line;
restructLines();
}
void UITextInput::selectAll() {
setSelection(0, lines.size()-1, 0, lines[lines.size()-1]->getText().length());
}
void UITextInput::insertText(String text) {
vector<String> strings = text.split("\n");
int numLines = lines.size();
for(int i=0; i < strings.size(); i++) {
if(i < numLines) {
lines[i]->setText(strings[i]);
} else {
numLines++;
ScreenLabel *newLine = new ScreenLabel(fontName, L"", fontSize, Label::ANTIALIAS_FULL);
newLine->setColor(0,0,0,1);
addChild(newLine);
lines.push_back(newLine);
newLine->setText(strings[i]);
}
}
restructLines();
}
String UITextInput::getSelectionText() {
String totalText = L"";
if(selectionTop == selectionBottom) {
totalText = lines[selectionTop]->getText().substr(selectionL, selectionR-selectionL);
return totalText;
} else {
totalText += lines[selectionTop]->getText().substr(selectionL, lines[selectionTop]->getText().length()-selectionL);
totalText += L"\n";
}
if(selectionBottom > selectionTop+1) {
for(int i=selectionTop+1; i <= selectionBottom; i++) {
totalText += lines[i]->getText();
totalText += L"\n";
}
}
totalText += lines[selectionBottom]->getText().substr(0, selectionL);
return totalText;
}
void UITextInput::onKeyDown(TAUKey key, wchar_t charCode) {
if(!hasFocus)
return;
// Logger::log("UCHAR: %d\n", charCode);
CoreInput *input = CoreServices::getInstance()->getCore()->getInput();
if(key == KEY_a && (input->getKeyState(KEY_LSUPER) || input->getKeyState(KEY_RSUPER))) {
selectAll();
return;
}
if(key == KEY_c && (input->getKeyState(KEY_LSUPER) || input->getKeyState(KEY_RSUPER))) {
CoreServices::getInstance()->getCore()->copyStringToClipboard(getSelectionText());
return;
}
if(key == KEY_x && (input->getKeyState(KEY_LSUPER) || input->getKeyState(KEY_RSUPER))) {
return;
}
if(key == KEY_v && (input->getKeyState(KEY_LSUPER) || input->getKeyState(KEY_RSUPER))) {
insertText(CoreServices::getInstance()->getCore()->getClipboardString());
return;
}
if(key == KEY_LEFT) {
if(input->getKeyState(KEY_LSUPER) || input->getKeyState(KEY_RSUPER)) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
setSelection(this->lineOffset, selectionLine, this->caretPosition, 0);
} else {
setSelection(this->lineOffset, this->lineOffset, this->caretPosition, 0);
}
} else {
caretPosition = 0;
clearSelection();
updateCaretPosition();
}
} else if (input->getKeyState(KEY_LALT) || input->getKeyState(KEY_RALT)) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
setSelection(this->lineOffset, selectionLine, this->caretPosition, caretSkipWordBack(selectionLine, selectionCaretPosition));
} else {
setSelection(this->lineOffset, this->lineOffset, this->caretPosition, caretSkipWordBack(this->lineOffset, caretPosition));
}
} else {
caretPosition = caretSkipWordBack(this->lineOffset,caretPosition);
clearSelection();
updateCaretPosition();
}
} else {
if(caretPosition > 0) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
if(selectionCaretPosition > 0)
setSelection(this->lineOffset, selectionLine, this->caretPosition, selectionCaretPosition-1);
} else {
setSelection(this->lineOffset, this->lineOffset, this->caretPosition, caretPosition-1);
}
} else {
caretPosition--;
clearSelection();
updateCaretPosition();
}
}
}
return;
}
if(key == KEY_RIGHT) {
if(caretPosition < currentLine->getText().length()) {
if(input->getKeyState(KEY_LSUPER) || input->getKeyState(KEY_RSUPER)) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
setSelection(this->lineOffset, selectionLine, this->caretPosition, lines[selectionLine]->getText().length());
} else {
setSelection(this->lineOffset, this->lineOffset, this->caretPosition, currentLine->getText().length());
}
} else {
caretPosition = currentLine->getText().length();
clearSelection();
}
} else if (input->getKeyState(KEY_LALT) || input->getKeyState(KEY_RALT)) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
setSelection(this->lineOffset, selectionLine, this->caretPosition, caretSkipWordForward(selectionLine, selectionCaretPosition));
} else {
setSelection(this->lineOffset, this->lineOffset, this->caretPosition, caretSkipWordForward(this->lineOffset, caretPosition));
}
} else {
caretPosition = caretSkipWordForward(this->lineOffset,caretPosition);
clearSelection();
}
} else {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
setSelection(this->lineOffset, selectionLine, this->caretPosition, selectionCaretPosition+1);
} else {
setSelection(this->lineOffset, this->lineOffset, this->caretPosition, caretPosition+1);
}
} else {
caretPosition++;
clearSelection();
}
}
updateCaretPosition();
}
return;
}
if(key == KEY_UP) {
if(multiLine) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
if(selectionLine > 0)
setSelection(this->lineOffset, selectionLine-1, this->caretPosition, selectionCaretPosition);
} else {
if(this->lineOffset > 0)
setSelection(this->lineOffset, this->lineOffset-1, this->caretPosition, caretPosition);
}
} else {
clearSelection();
if(lineOffset > 0) {
lineOffset--;
selectLineFromOffset();
updateCaretPosition();
}
}
}
blinkerRect->visible = true;
return;
}
if(key == KEY_DOWN) {
if(multiLine) {
if(input->getKeyState(KEY_LSHIFT) || input->getKeyState(KEY_RSHIFT)) {
if(hasSelection) {
if(selectionLine < lines.size()-1)
setSelection(this->lineOffset, selectionLine+1, this->caretPosition, selectionCaretPosition);
} else {
if(this->lineOffset < lines.size()-1)
setSelection(this->lineOffset, this->lineOffset+1, this->caretPosition, caretPosition);
}
} else {
clearSelection();
if(lineOffset < lines.size()-1) {
lineOffset++;
selectLineFromOffset();
updateCaretPosition();
}
}
}
blinkerRect->visible = true;
return;
}
if(key == KEY_RETURN) {
if(hasSelection)
deleteSelection();
if(multiLine) {
insertLine(true);
updateCaretPosition();
}
return;
}
String ctext = currentLine->getText();
// if(1) {
if((charCode > 31 && charCode < 127) || charCode > 127) {
if(hasSelection)
deleteSelection();
ctext = currentLine->getText();
String text2 = ctext.substr(caretPosition, ctext.length()-caretPosition);
ctext = ctext.substr(0,caretPosition);
ctext += charCode + text2;
caretPosition++;
}
if(key == KEY_TAB && multiLine) {
if(hasSelection)
deleteSelection();
ctext = currentLine->getText();
String text2 = ctext.substr(caretPosition, ctext.length()-caretPosition);
ctext = ctext.substr(0,caretPosition);
ctext += (wchar_t)'\t' + text2;
caretPosition++;
}
if(key == KEY_BACKSPACE) {
if(hasSelection) {
deleteSelection();
return;
} else {
ctext = currentLine->getText();
if(caretPosition > 0) {
if(ctext.length() > 0) {
String text2 = ctext.substr(caretPosition, ctext.length()-caretPosition);
ctext = ctext.substr(0,caretPosition-1);
ctext += text2;
caretPosition--;
}
} else {
if(lineOffset > 0) {
ScreenLabel *lineToRemove = currentLine;
lineOffset--;
selectLineFromOffset();
caretPosition = currentLine->getText().length();
updateCaretPosition();
currentLine->setText(currentLine->getText() + ctext);
removeLine(lineToRemove);
return;
}
}
}
}
currentLine->setText(ctext);
updateCaretPosition();
}
void UITextInput::Update() {
if(hasSelection) {
blinkerRect->visible = false;
}
blinkerRect->setPosition(caretImagePosition,currentLine->getPosition2D().y);
if(hasFocus) {
// inputRect->setStrokeColor(1.0f, 1.0f, 1.0f, 0.25f);
} else {
blinkerRect->visible = false;
// inputRect->setStrokeColor(1.0f, 1.0f, 1.0f, 0.1f);
}
}
UITextInput::~UITextInput() {
}
void UITextInput::handleEvent(Event *event) {
if(event->getDispatcher() == inputRect) {
switch(event->getEventCode()) {
case InputEvent::EVENT_MOUSEDOWN:
if(parentEntity) {
((ScreenEntity*)parentEntity)->focusChild(this);
} else {
hasFocus = true;
}
setCaretToMouse(((InputEvent*)event)->mousePosition.x, ((InputEvent*)event)->mousePosition.y);
draggingSelection = true;
break;
case InputEvent::EVENT_MOUSEUP:
draggingSelection = false;
break;
case InputEvent::EVENT_DOUBLECLICK:
selectWordAtCaret();
break;
case InputEvent::EVENT_MOUSEMOVE:
if(draggingSelection) {
dragSelectionTo(((InputEvent*)event)->mousePosition.x, ((InputEvent*)event)->mousePosition.y);
}
break;
case InputEvent::EVENT_MOUSEOVER:
CoreServices::getInstance()->getCore()->setCursor(CURSOR_TEXT);
break;
case InputEvent::EVENT_MOUSEOUT:
CoreServices::getInstance()->getCore()->setCursor(CURSOR_ARROW);
break;
}
}
if(event->getDispatcher() == blinkTimer) {
if(hasSelection || draggingSelection) {
blinkerRect->visible = false;
} else {
if(hasFocus)
blinkerRect->visible = !blinkerRect->visible;
else
blinkerRect->visible = false;
}
}
} | 28.860636 | 186 | 0.672738 | [
"vector"
] |
83c2196eee3344f1d5c72b4217a32f525f4d9f09 | 5,006 | cpp | C++ | sstd/src/file/csv.cpp | admiswalker/SubStandardLibrary-SSTD- | d0e7c754f4437fc57e8c4ab56fbbf2aa871b00ff | [
"MIT"
] | null | null | null | sstd/src/file/csv.cpp | admiswalker/SubStandardLibrary-SSTD- | d0e7c754f4437fc57e8c4ab56fbbf2aa871b00ff | [
"MIT"
] | null | null | null | sstd/src/file/csv.cpp | admiswalker/SubStandardLibrary-SSTD- | d0e7c754f4437fc57e8c4ab56fbbf2aa871b00ff | [
"MIT"
] | null | null | null | #include "./csv.hpp"
#include "./file.hpp"
#include "./path.hpp"
#include "./read_write.hpp"
#include "../tinyInterpreter.hpp"
#include "../string/strEdit.hpp"
// erasing empty element(s) in the tail of vector
void eraseEmptyTail(std::vector<std::string>& inOut){
uint cols = inOut.size();
for(uint p=cols-1; p!=0; --p){
if(inOut[p].size()==0){ inOut.erase(inOut.begin()+p);
} else { break; }
}
}
// erasing empty element(s) in the tail of vector
void eraseEmptyTail(std::vector<std::vector<std::string>>& inOut){
uint rows = inOut.size();
for(uint p=rows-1; p!=0; --p){
if(inOut[p].size()==1 && inOut[p][0].size()==0){ inOut.erase(inOut.begin()+p);
} else { break; }
}
}
bool isEmpty(std::string& token, struct debugInformation& dbgInf){
if(token.size()!=0){
for(uint i=0; i<token.size(); ++i){
if(token[i]!=' '){ printf("ERROR: %s: Line(%u): There is a invalid value (%c) between ',' and '\"'.\n", dbgInf.FileName.c_str(), dbgInf.LineNum, token[i]); return false; }
}
}
return true;
}
bool go2comma(const uchar*& str, uint& r, struct debugInformation& dbgInf){
for(; str[r]!=0; ++r){
if(str[r]==','){ break; }
if(str[r]==0x0D && str[r+1]==0x0A){ ++r; break; } // Line feed code (Windows)
if(str[r]==0x0A){ break; } // Line feed code (Unix)
if(str[r]!=' '){ printf("ERROR: %s: Line(%u): There is a invalid value (%c) between '\"' and ','.\n", dbgInf.FileName.c_str(), dbgInf.LineNum, str[r]); return false; }
}
return true;
}
bool go2doubleQuotation(std::string& token, const uchar*& str, uint& r, struct debugInformation& dbgInf){
if(isEmpty(token, dbgInf)==false){ return false; }
++r;
for(; str[r]!=0; ++r){
if(str[r]=='"' && str[r+1]=='"'){ ++r; token += str[r]; continue; } // "" is treated as a escape of ".
if(str[r]=='"'){ ++r; if(go2comma(str, r, dbgInf)==false){ return false; } break; }
if(str[r]==0x0D && str[r+1]==0x0A){ ++r; } // Line feed code (Windows): ignore '0x0D'
if(str[r]==0x0A){ ++dbgInf.LineNum; } // Line feed code (Unix)
token += str[r]; // Both of the line feed codes (CR+LF or LF) are added as a LF.
}
if(str[r]==0){ printf("ERROR: %s: Line(%u): Command of '\"\"' is not closed. ('\"' is required).\n", dbgInf.FileName.c_str(), dbgInf.LineNum); return false; }
return true;
}
std::vector<std::string> getLine(bool& result, const uchar* str, uint& r, struct debugInformation& dbgInf){
result=true;
std::vector<std::string> line;
std::string token;
for(; str[r]!=0; ){
if(str[r]==' '){ if(token.size()==0){ ++r; continue; } } // skip ' ' just after ','
if(str[r]==','){
line.push_back(std::move(token));
token.clear();
++r;
continue;
}
if(str[r]=='"'){ if(go2doubleQuotation(token, str, r, dbgInf)==false){ result=false; return std::vector<std::string>(0); } continue; } // Command of '""'.
if(str[r]==0x0D && str[r+1]==0x0A){ r+=2; break; } // Line feed code (Windows)
if(str[r]==0x0A){ ++dbgInf.LineNum; ++r; break; } // Line feed code (Unix)
token += str[r];
++r;
}
line.push_back(std::move(token));
return line;
}
std::vector<std::vector<std::string>> sstd::csv2vvec(const char* pReadFile){
// r: read place
uint r=0;
// std::string str = sstd::read(pReadFile);
// ignoreBOM(str, r); // Ignore BOM (BOM: byte order mark)
std::string str = sstd::read_withoutBOM(pReadFile);
std::vector<std::vector<std::string>> ret;
struct debugInformation dbgInf;
dbgInf.FileName = sstd::getFileName(pReadFile);
dbgInf.LineNum = 1;
bool result;
for(; str[r]!=0; ){
std::vector<std::string> line = getLine(result, (uchar*)&str[0], r, dbgInf);
eraseEmptyTail(line);
ret.push_back(std::move(line));
if(result==false){ return std::vector<std::vector<std::string>>(0); }
}
eraseEmptyTail(ret);
return ret;
}
std::vector<std::vector<std::string>> sstd::csv2vvec(const std::string& readFile){
return sstd::csv2vvec(readFile.c_str());
}
//-----
bool sstd::vvec2csv(const char* pSavePath, const std::vector<std::vector<std::string>>& vecCSV){
std::string str;
for(uint r=0; r<vecCSV.size(); ++r){
for(uint c=0; c<vecCSV[r].size(); ++c){
str += '\"' + vecCSV[r][c] + "\",";
}
str += '\n';
}
sstd::file fp;
if(!fp.fopen(pSavePath, "wb")){ return false; }
if(fp.fwrite(str.c_str(), sizeof(char), str.size())!=(size_t)str.size()){ return false; }
return true;
}
bool sstd::vvec2csv(const std::string& savePath, const std::vector<std::vector<std::string>>& vecCSV){
return sstd::vvec2csv(savePath.c_str(), vecCSV);
}
| 37.358209 | 183 | 0.552537 | [
"vector"
] |
83c741ada5b1ac4b6e8ed53d67cb7b9c05fc5c08 | 1,195 | hpp | C++ | include/PluginRegistry.hpp | flagarde/FlakedTuna | 25d2f81be27506090339d539205e7a2710343e4b | [
"MIT"
] | 3 | 2021-01-06T12:11:04.000Z | 2021-05-21T16:37:54.000Z | include/PluginRegistry.hpp | flagarde/FlakedTuna | 25d2f81be27506090339d539205e7a2710343e4b | [
"MIT"
] | 4 | 2021-05-14T19:48:29.000Z | 2021-05-15T05:03:32.000Z | include/PluginRegistry.hpp | flagarde/FlakedTuna | 25d2f81be27506090339d539205e7a2710343e4b | [
"MIT"
] | 1 | 2021-01-15T12:27:19.000Z | 2021-01-15T12:27:19.000Z | #pragma once
#include <exception>
#include <functional>
#include <memory>
#include <typeindex>
#include <map>
// TODO: Look at supporting constructors with parameters
namespace FlakedTuna
{
class PluginRegistry
{
private:
std::multimap<std::type_index,std::function<std::shared_ptr<void>()>> _plugins;
public:
template<typename T, typename BaseT> void RegisterPlugin()
{
_plugins.emplace(std::type_index(typeid(BaseT)), [this]() { return std::make_shared<T>(); });
}
template <class BaseT> std::vector<std::shared_ptr<BaseT>> ResolvePlugin()
{
std::vector<std::shared_ptr<BaseT>> return_plugins;
std::pair<std::multimap<std::type_index, std::function<std::shared_ptr<void>()>>::iterator, std::multimap<std::type_index, std::function<std::shared_ptr<void>()>>::iterator> ret ;
ret = _plugins.equal_range(std::type_index(typeid(BaseT)));
for(std::multimap<std::type_index, std::function<std::shared_ptr<void>()>>::iterator it=ret.first; it!=ret.second; ++it)
{
return_plugins.push_back( std::static_pointer_cast<BaseT>( (it->second)() ) );
}
return return_plugins;
}
};
} // namespace FlakedTuna
| 31.447368 | 185 | 0.676987 | [
"vector"
] |
83c7c5de2f38e0936e88d4e6aaa5b7f6baae3f53 | 9,840 | cpp | C++ | source/engine/render/backend/vulkan/device.cpp | aviktorov/pbr-sandbox | 66a71c741dac2d2dd46668a506d02de88f05e399 | [
"MIT"
] | 19 | 2020-02-11T19:57:41.000Z | 2022-02-20T14:11:33.000Z | source/engine/render/backend/vulkan/device.cpp | aviktorov/pbr-sandbox | 66a71c741dac2d2dd46668a506d02de88f05e399 | [
"MIT"
] | null | null | null | source/engine/render/backend/vulkan/device.cpp | aviktorov/pbr-sandbox | 66a71c741dac2d2dd46668a506d02de88f05e399 | [
"MIT"
] | 5 | 2019-11-05T17:38:33.000Z | 2022-03-04T12:49:58.000Z | #include "render/backend/vulkan/Device.h"
#include "render/backend/vulkan/Platform.h"
#include "render/backend/vulkan/Utils.h"
#define VMA_IMPLEMENTATION
#include <vk_mem_alloc.h>
#include <array>
#include <vector>
#include <iostream>
#include <set>
namespace render::backend::vulkan
{
/*
*/
static int maxCombinedImageSamplers = 32;
static int maxUniformBuffers = 32;
static int maxDescriptorSets = 512;
/*
*/
static std::vector<const char*> requiredInstanceExtensions = {
VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
VK_KHR_SURFACE_EXTENSION_NAME,
};
/*
*/
static std::vector<const char*> requiredPhysicalDeviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
#ifdef SCAPES_VULKAN_USE_VALIDATION_LAYERS
static std::vector<const char *> requiredValidationLayers = {
"VK_LAYER_KHRONOS_validation",
};
#endif
/*
*/
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
std::cerr << "Validation layer: " << pCallbackData->pMessage << std::endl;
return VK_FALSE;
}
/*
*/
void Device::init(const char *applicationName, const char *engineName)
{
if (volkInitialize() != VK_SUCCESS)
throw std::runtime_error("Can't initialize Vulkan helper library");
// Check required instance extensions
requiredInstanceExtensions.push_back(render::backend::vulkan::Platform::getInstanceExtension());
if (!Utils::checkInstanceExtensions(requiredInstanceExtensions, true))
throw std::runtime_error("This device doesn't have required Vulkan extensions");
#if SCAPES_VULKAN_USE_VALIDATION_LAYERS
// Check required instance validation layers
if (!Utils::checkInstanceValidationLayers(requiredValidationLayers, true))
throw std::runtime_error("This device doesn't have required Vulkan validation layers");
#endif
// Fill instance structures
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = applicationName;
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = engineName;
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkDebugUtilsMessengerCreateInfoEXT debugMessengerInfo = {};
debugMessengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debugMessengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
debugMessengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
debugMessengerInfo.pfnUserCallback = debugCallback;
debugMessengerInfo.pUserData = nullptr;
VkInstanceCreateInfo instanceInfo = {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pApplicationInfo = &appInfo;
instanceInfo.enabledExtensionCount = static_cast<uint32_t>(requiredInstanceExtensions.size());
instanceInfo.ppEnabledExtensionNames = requiredInstanceExtensions.data();
instanceInfo.pNext = &debugMessengerInfo;
#if SCAPES_VULKAN_USE_VALIDATION_LAYERS
instanceInfo.enabledLayerCount = static_cast<uint32_t>(requiredValidationLayers.size());
instanceInfo.ppEnabledLayerNames = requiredValidationLayers.data();
#endif
// Create Vulkan instance
VkResult result = vkCreateInstance(&instanceInfo, nullptr, &instance);
if (result != VK_SUCCESS)
throw std::runtime_error("Failed to create Vulkan instance");
volkLoadInstance(instance);
// Create Vulkan debug messenger
result = vkCreateDebugUtilsMessengerEXT(instance, &debugMessengerInfo, nullptr, &debugMessenger);
if (result != VK_SUCCESS)
throw std::runtime_error("Can't create Vulkan debug messenger");
// Enumerate physical devices
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
throw std::runtime_error("Failed to find GPUs with Vulkan support");
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
// Pick the best physical device
int estimate = -1;
for (const auto& device : devices)
{
int currentEstimate = examinePhysicalDevice(device);
if (currentEstimate == -1)
continue;
if (estimate > currentEstimate)
continue;
estimate = currentEstimate;
physicalDevice = device;
}
if (physicalDevice == VK_NULL_HANDLE)
throw std::runtime_error("Failed to find a suitable GPU");
// Create logical device
graphicsQueueFamily = Utils::getGraphicsQueueFamily(physicalDevice);
const float queuePriority = 1.0f;
VkDeviceQueueCreateInfo graphicsQueueInfo = {};
graphicsQueueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
graphicsQueueInfo.queueFamilyIndex = graphicsQueueFamily;
graphicsQueueInfo.queueCount = 1;
graphicsQueueInfo.pQueuePriorities = &queuePriority;
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.sampleRateShading = VK_TRUE;
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = &graphicsQueueInfo;
deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredPhysicalDeviceExtensions.size());
deviceCreateInfo.ppEnabledExtensionNames = requiredPhysicalDeviceExtensions.data();
// next two parameters are ignored, but it's still good to pass layers for backward compatibility
#if SCAPES_VULKAN_USE_VALIDATION_LAYERS
deviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(requiredValidationLayers.size());
deviceCreateInfo.ppEnabledLayerNames = requiredValidationLayers.data();
#endif
result = vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &device);
if (result != VK_SUCCESS)
throw std::runtime_error("Can't create logical device");
volkLoadDevice(device);
// Get graphics queue
vkGetDeviceQueue(device, graphicsQueueFamily, 0, &graphicsQueue);
if (graphicsQueue == VK_NULL_HANDLE)
throw std::runtime_error("Can't get graphics queue from logical device");
// Create command pool
VkCommandPoolCreateInfo commandPoolInfo = {};
commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
commandPoolInfo.queueFamilyIndex = graphicsQueueFamily;
commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
if (vkCreateCommandPool(device, &commandPoolInfo, nullptr, &commandPool) != VK_SUCCESS)
throw std::runtime_error("Can't create command pool");
// Create descriptor pools
std::array<VkDescriptorPoolSize, 2> descriptorPoolSizes = {};
descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorPoolSizes[0].descriptorCount = maxUniformBuffers;
descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorPoolSizes[1].descriptorCount = maxCombinedImageSamplers;
VkDescriptorPoolCreateInfo descriptorPoolInfo = {};
descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptorPoolInfo.poolSizeCount = static_cast<uint32_t>(descriptorPoolSizes.size());
descriptorPoolInfo.pPoolSizes = descriptorPoolSizes.data();
descriptorPoolInfo.maxSets = maxDescriptorSets;
descriptorPoolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
if (vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool) != VK_SUCCESS)
throw std::runtime_error("Can't create descriptor pool");
maxMSAASamples = Utils::getMaxUsableSampleCount(physicalDevice);
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.physicalDevice = physicalDevice;
allocatorInfo.device = device;
allocatorInfo.instance = instance;
if (vmaCreateAllocator(&allocatorInfo, &vram_allocator) != VK_SUCCESS)
throw std::runtime_error("Can't create VRAM allocator");
}
void Device::shutdown()
{
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
descriptorPool = VK_NULL_HANDLE;
vkDestroyCommandPool(device, commandPool, nullptr);
commandPool = VK_NULL_HANDLE;
vmaDestroyAllocator(vram_allocator);
vram_allocator = VK_NULL_HANDLE;
vkDestroyDevice(device, nullptr);
device = VK_NULL_HANDLE;
vkDestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr);
debugMessenger = VK_NULL_HANDLE;
vkDestroyInstance(instance, nullptr);
instance = VK_NULL_HANDLE;
graphicsQueueFamily = 0xFFFF;
graphicsQueue = VK_NULL_HANDLE;
maxMSAASamples = VK_SAMPLE_COUNT_1_BIT;
physicalDevice = VK_NULL_HANDLE;
}
/*
*/
int Device::examinePhysicalDevice(VkPhysicalDevice physicalDevice) const
{
if (!Utils::checkPhysicalDeviceExtensions(physicalDevice, requiredPhysicalDeviceExtensions))
return -1;
VkPhysicalDeviceProperties physicalDeviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
VkPhysicalDeviceFeatures physicalDeviceFeatures;
vkGetPhysicalDeviceFeatures(physicalDevice, &physicalDeviceFeatures);
int estimate = 0;
switch (physicalDeviceProperties.deviceType)
{
case VK_PHYSICAL_DEVICE_TYPE_OTHER:
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
case VK_PHYSICAL_DEVICE_TYPE_CPU: estimate = 10; break;
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: estimate = 100; break;
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: estimate = 1000; break;
}
// TODO: add more estimates here
if (physicalDeviceFeatures.geometryShader)
estimate++;
if (physicalDeviceFeatures.tessellationShader)
estimate++;
return estimate;
}
}
| 35.523466 | 185 | 0.79624 | [
"render",
"vector"
] |
83d14048376184794d010c270b23f0e13ec4f38a | 3,632 | cpp | C++ | src/graph.cpp | lem0nez/instanalyzer | 0bb2353ecc6d3657245d2f8053a55172da03968e | [
"Apache-2.0"
] | null | null | null | src/graph.cpp | lem0nez/instanalyzer | 0bb2353ecc6d3657245d2f8053a55172da03968e | [
"Apache-2.0"
] | null | null | null | src/graph.cpp | lem0nez/instanalyzer | 0bb2353ecc6d3657245d2f8053a55172da03968e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2019 Nikita Dudko. All rights reserved.
* Contacts: <nikita.dudko.95@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 "graph.hpp"
#include <random>
#include "boost/format.hpp"
#include "boost/regex.hpp"
using namespace std;
const vector<Graph::Colors> Graph::m_graph_styles = {
{Term::COL_RED, Term::COL_BLACK, Term::COL_RED},
{Term::COL_ORANGE, Term::COL_BLACK, Term::COL_ORANGE},
{Term::COL_YELLOW, Term::COL_BLACK, Term::COL_YELLOW},
{Term::COL_GREEN, Term::COL_BLACK, Term::COL_GREEN},
{Term::COL_BLUE, Term::COL_BLACK, Term::COL_BLUE},
{Term::COL_GRAY, Term::COL_BLACK, Term::COL_GRAY}
};
const vector<Graph::Colors> Graph::m_graph_dark_styles = {
{Term::COL_WHITE, Term::COL_BLACK, Term::COL_WHITE},
{Term::COL_CREAM, Term::COL_BLACK, Term::COL_CREAM}
};
const vector<Graph::Colors> Graph::m_graph_light_styles = {
{Term::COL_BLACK, Term::COL_WHITE, Term::COL_BLACK}
};
int Graph::draw_graphs(ostream& t_os, const vector<Graph>& t_graphs) {
using namespace boost;
static const unsigned short MAX_TERM_COLUMNS = 80;
const unsigned int term_columns = (Term::get_columns() > MAX_TERM_COLUMNS) ?
MAX_TERM_COLUMNS : Term::get_columns();
size_t idx = 0;
for (const auto& g : t_graphs) {
string percents = (format("%.1f %%") % g.get_percents()).str();
// Delete all text colors and styles.
string label = regex_replace(g.get_label(),
regex("\x1b\\[[[:digit:];]+m"), "");
// 1 is space to separate label and percents.
const int max_label_len = term_columns - percents.length() - 1;
// 4 is first character of label and three dots.
if (max_label_len < 4) {
return idx;
} else if (static_cast<size_t>(max_label_len) < label.length()) {
label = label.substr(0, max_label_len - 3) + "...";
}
const string& graph_start = Term::get_color(g.get_colors().graph, true) +
Term::get_color(g.get_colors().text_in) +
(g.is_bold_text() ? Term::bold() : "");
const size_t spaces = term_columns - label.length() - percents.length(),
graph_end_char = term_columns * (g.get_percents() / 100.0) +
graph_start.length();
string graph =
graph_start + label + string(spaces, ' ') + percents + Term::reset();
graph.insert(graph_end_char, Term::reset() + Term::get_color(
g.get_colors().text_out) + (g.is_bold_text() ? Term::bold() : ""));
t_os << graph << endl;
++idx;
}
return -1;
}
Graph::Colors Graph::get_random_style() {
vector<Colors> styles(m_graph_styles);
if (Term::is_dark_theme()) {
styles.insert(styles.cend(),
m_graph_dark_styles.cbegin(), m_graph_dark_styles.cend());
} else {
styles.insert(styles.cend(),
m_graph_light_styles.cbegin(), m_graph_light_styles.cend());
}
random_device rd;
mt19937 engine(rd());
uniform_int_distribution<int> uni(0, styles.size() - 1);
// For prevent repeat of styles one after another.
static size_t previous_idx;
size_t idx;
do {
idx = uni(rd);
} while (idx == previous_idx);
previous_idx = idx;
return styles[idx];
}
| 32.428571 | 78 | 0.672907 | [
"vector"
] |
83dd3a10eb0ce859f5da9f050254df28011d27c9 | 279 | cpp | C++ | Cpp/1619.mean-of-array-after-removing-some-elements.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | 1 | 2015-12-19T23:05:35.000Z | 2015-12-19T23:05:35.000Z | Cpp/1619.mean-of-array-after-removing-some-elements.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | Cpp/1619.mean-of-array-after-removing-some-elements.cpp | zszyellow/leetcode | 2ef6be04c3008068f8116bf28d70586e613a48c2 | [
"MIT"
] | null | null | null | class Solution {
public:
double trimMean(vector<int>& arr) {
int N = arr.size(), M = N / 20;
std::sort(arr.begin(), arr.end());
int sum = std::accumulate(arr.begin()+M, arr.begin()+(N-M), 0);
return static_cast<double>(sum) / (N-2*M);
}
}; | 31 | 71 | 0.53405 | [
"vector"
] |
83dd8c9c07582c1abd0c6150ad94915d70a9b859 | 1,437 | cpp | C++ | CCC/Stage1/14/ccc14s5.jj.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | 1 | 2017-10-01T00:51:39.000Z | 2017-10-01T00:51:39.000Z | CCC/Stage1/14/ccc14s5.jj.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | CCC/Stage1/14/ccc14s5.jj.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
int N;
typedef pair<int,int> I2;
I2 pts[2001];
int best[2001];
int pbest[2001];
double pdist[2001];
struct line
{
int a, b;
double d;
bool operator < (const line& l) const
{
return d < l.d;
}
};
int main()
{
scanf("%d",&N);
N++;
for(int i = 0;i!=N-1;i++)
scanf("%d%d",&pts[i+1].first, &pts[i+1].second);
for(int i = 0;i!=N;i++)
pdist[i] = -1;
vector<line> V;
for(int i = 0;i!=N;i++)
{
for (int j = i+1; j < N; j++)
{
line l;
l.a = i;
l.b = j;
int dx = pts[j].first - pts[i].first;
int dy = pts[j].second - pts[i].second;
l.d = sqrt(dx * dx + dy * dy);
V.push_back(l);
}
}
sort(V.begin(), V.end());
for(int i = 0;i!=V.size();i++)
{
int a = V[i].a;
int b = V[i].b;
if (V[i].d != pdist[a])
{
pbest[a] = best[a];
pdist[a] = V[i].d;
}
if (V[i].d != pdist[b])
{
pbest[best] = best[b];
pdist[b] = V[i].d;
}
if (a!=0)
{
best[a] = max(best[a], 1 + pbest[b]);
best[b] = max(best[b], 1 + pbest[a]);
}
else
{
best[a] = max(best[a], pbest[b]);
}
}
printf("%d\n", best[0] + 1);
}
| 15.451613 | 51 | 0.473904 | [
"vector"
] |
83f4fc14b5a55a42c6c331bc1b1581c537c66f7c | 4,380 | hpp | C++ | mysql-server/storage/ndb/src/common/util/parse_mask.hpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/src/common/util/parse_mask.hpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/src/common/util/parse_mask.hpp | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
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
*/
#ifndef PARSE_MASK_HPP
#define PARSE_MASK_HPP
#include <util/BaseString.hpp>
#include <util/SparseBitmask.hpp>
#include <ctype.h>
#ifndef _WIN32
#include <strings.h>
#endif
#define PARSE_END_ENTRIES 8192
#define MAX_STRING_SIZE 32
struct ParseEntries
{
const char *m_name;
unsigned int m_type;
};
struct ParseParams
{
const char *name;
enum { S_UNSIGNED, S_BITMASK, S_STRING } type;
};
struct ParamValue
{
ParamValue() { found = false;}
bool found;
char buf[MAX_STRING_SIZE];
char * string_val;
unsigned unsigned_val;
SparseBitmask mask_val;
};
class ParseThreadConfiguration
{
public:
ParseThreadConfiguration(const char *str,
const struct ParseEntries *parse_entries,
const unsigned int num_parse_entries,
const struct ParseParams *parse_params,
const unsigned int num_parse_params,
BaseString &err_msg);
~ParseThreadConfiguration();
int read_params(ParamValue values[],
unsigned int num_values,
unsigned int *type,
int *ret_code,
bool allow_empty);
private:
unsigned int get_entry_type(const char *type);
void skipblank();
unsigned int get_param_len();
int find_params(char **start, char **end);
int parse_params(char *start, ParamValue values[]);
unsigned int find_type();
int find_next();
int parse_string(char *dst);
int parse_unsigned(unsigned *dst);
int parse_bitmask(SparseBitmask& mask);
char *m_curr_str;
char *m_save_str;
const struct ParseEntries *m_parse_entries;
const unsigned int m_num_parse_entries;
const struct ParseParams *m_parse_params;
const unsigned int m_num_parse_params;
BaseString & m_err_msg;
bool m_first;
};
/**
* Parse string with numbers format
* 1,2,3-5
* @return -1 if unparsable chars found,
* -2 str has number > bitmask size
* else returns number of bits set
*/
template <typename T>
inline int
parse_mask(const char *str, T& mask)
{
int cnt = 0;
BaseString tmp(str);
Vector<BaseString> list;
if (tmp.trim().empty())
{
return 0; /* Empty bitmask allowed */
}
tmp.split(list, ",");
for (unsigned i = 0; i<list.size(); i++)
{
list[i].trim();
if (list[i].empty())
{
return -3;
}
char * delim = const_cast<char*>(strchr(list[i].c_str(), '-'));
unsigned first = 0;
unsigned last = 0;
if (delim == 0)
{
int res = sscanf(list[i].c_str(), "%u", &first);
if (res != 1)
{
return -1;
}
last = first;
}
else
{
* delim = 0;
delim++;
int res0 = sscanf(list[i].c_str(), "%u", &first);
if (res0 != 1)
{
return -1;
}
int res1 = sscanf(delim, "%u", &last);
if (res1 != 1)
{
return -1;
}
if (first > last)
{
unsigned tmp = first;
first = last;
last = tmp;
}
}
for (unsigned j = first; j<(last+1); j++)
{
if (j > mask.max_size())
{
return -2;
}
cnt++;
mask.set(j);
}
}
return cnt;
}
#endif
| 25.172414 | 79 | 0.632192 | [
"vector"
] |
83f6892ba223fa93e86ee6db66442be3887099aa | 14,540 | cpp | C++ | Sources/Graphics/OpenGL/JPEG/opengl_win32.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | 27 | 2017-12-19T09:15:36.000Z | 2021-07-30T13:02:00.000Z | Sources/Graphics/OpenGL/JPEG/opengl_win32.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | null | null | null | Sources/Graphics/OpenGL/JPEG/opengl_win32.cpp | wurui1994/test | 027cef75f98dbb252b322113dacd4a9a6997d84f | [
"MIT"
] | 29 | 2018-04-10T13:25:54.000Z | 2021-12-24T01:51:03.000Z | #define FAST_IS_JPEG
#include <jpeglib.h>
#include <jerror.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<string> vec;
int num = 0;
//================================
GLuint LoadJPEG(const char *FileName)
//================================
{
unsigned long x, y;
unsigned int texture_id;
unsigned long data_size; // length of the file
int channels; // 3 =>RGB 4 =>RGBA
unsigned int type;
unsigned char *rowptr[1]; // pointer to an array
unsigned char *jdata; // data for the image
struct jpeg_decompress_struct info; //for our jpeg info
struct jpeg_error_mgr err; //the error handler
FILE *file = fopen(FileName, "rb"); //open the file
info.err = jpeg_std_error(&err);
jpeg_create_decompress(&info); //fills info structure
//if the jpeg file doesn't load
if (!file)
{
fprintf(stderr, "Error reading JPEG file %s!", FileName);
return 0;
}
jpeg_stdio_src(&info, file);
jpeg_read_header(&info, TRUE); // read jpeg file header
info.do_fancy_upsampling = FALSE;
jpeg_start_decompress(&info); // decompress the file
//set width and height
x = info.output_width;
y = info.output_height;
channels = info.num_components;
type = GL_RGB;
if (channels == 4)
type = GL_RGBA;
data_size = x * y * 3;
//--------------------------------------------
// read scanlines one at a time & put bytes
// in jdata[] array. Assumes an RGB image
//--------------------------------------------
jdata = (unsigned char *)malloc(data_size);
while (info.output_scanline < info.output_height)
{ // loop
// Enable jpeg_read_scanlines() to fill our jdata array
rowptr[0] = (unsigned char *)jdata + // secret to method
3 * info.output_width * (info.output_height - info.output_scanline);
jpeg_read_scanlines(&info, rowptr, 1);
}
//---------------------------------------------------
jpeg_finish_decompress(&info); //finish decompressing
//----- create OpenGL tex map (omit if not needed) --------
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, x, y, GL_RGB, GL_UNSIGNED_BYTE, jdata);
fclose(file); //close the file
free(jdata);
return texture_id; // for OpenGL tex maps
}
void subimage(string &s)
{
const GLuint texGround = LoadJPEG(s.c_str());
glBindTexture(GL_TEXTURE_2D, texGround);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(-1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(-1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, -1.0f);
glEnd();
glDeleteTextures(1, &texGround);
}
void initiate()
{
//
ifstream ifs("test.txt");
string temp;
int tempr, tempt;
while (!ifs.eof())
{
getline(ifs, temp);
if (temp.length() > 4)
vec.push_back(temp);
//cout<<temp<<endl;
}
ifs.close();
//cout<<vec.size()<<endl;
}
//#include <GL/glaux.h> // Header File For The Glaux Library
HDC hDC = NULL; // Private GDI Device Context
HGLRC hRC = NULL; // Permanent Rendering Context
HWND hWnd = NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
bool keys[256]; // Array Used For The Keyboard Routine
bool active = TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen = TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height == 0)
{ // Prevent A Divide By Zero By
height = 1; // Making Height Equal One
}
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
//gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}
int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
//glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
//glClearDepth(1.0f); // Depth Buffer Setup
//glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glEnable(GL_TEXTURE_2D);
//glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
//glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
return TRUE; // Initialization Went OK
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
if (num == vec.size())
return 0;
subimage(vec[num]);
num++;
return TRUE; // Everything Went OK
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_PAINT:
//if(num==vec.size())num-=vec.size();
DrawGLScene(); // Draw The Scene
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen)
{ // Are We In Fullscreen Mode?
ChangeDisplaySettings(NULL, 0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC)
{ // Do We Have A Rendering Context?
if (!wglMakeCurrent(NULL, NULL))
{ // Are We Able To Release The DC And RC Contexts?
MessageBox(NULL, "Release Of DC And RC Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC))
{ // Are We Able To Delete The RC?
MessageBox(NULL, "Release Rendering Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
hRC = NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd, hDC))
{ // Are We Able To Release The DC
MessageBox(NULL, "Release Device Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hDC = NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd))
{ // Are We Able To Destroy The Window?
MessageBox(NULL, "Could Not Release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hWnd = NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL", hInstance))
{ // Are We Able To Unregister Class
MessageBox(NULL, "Could Not Unregister Class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hInstance = NULL; // Set hInstance To NULL
}
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(char *title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left = (long)0; // Set Left Value To 0
WindowRect.right = (long)width; // Set Right Value To Requested Width
WindowRect.top = (long)0; // Set Top Value To 0
WindowRect.bottom = (long)height; // Set Bottom Value To Requested Height
fullscreen = fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = DefWindowProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc))
{ // Attempt To Register The Window Class
MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen)
{ // Attempt Fullscreen Mode?
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
{
fullscreen = FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL, "Program Will Now Close.", "ERROR", MB_OK | MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen)
{ // Are We Still In Fullscreen Mode?
dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
dwStyle = WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
350, 120, // Window Position
500, // Calculate Window Width
500, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL)))
{ // Dont Pass Anything To WM_CREATE
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd = {
// pfd Tells Windows How We Want Things To Be
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC = GetDC(hWnd)))
{ // Did We Get A Device Context?
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
{ // Did Windows Find A Matching Pixel Format?
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!SetPixelFormat(hDC, PixelFormat, &pfd))
{ // Are We Able To Set The Pixel Format?
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC = wglCreateContext(hDC)))
{ // Are We Able To Get A Rendering Context?
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!wglMakeCurrent(hDC, hRC))
{ // Try To Activate The Rendering Context
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd, SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL())
{ // Initialize Our Newly Created GL Window
KillGLWindow(); // Reset The Display
MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
int WINAPI WinMain(HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done = FALSE; // Bool Variable To Exit Loop
initiate();
fullscreen = FALSE; // Windowed Mode
//}
// Create Our OpenGL Window
if (!CreateGLWindow("", 640, 480, 16, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
while (1)
{
DrawGLScene(); // Draw The Scene
SwapBuffers(hDC); // Swap Buffers (Double
if (num == vec.size())
return 0;
}
// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}
| 33.735499 | 173 | 0.669257 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.