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
fd47c55ddf2b1536e3d62e30d25463b951b6c842
3,140
cc
C++
reid_cloud/src/model/DescribeHeatMapResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
reid_cloud/src/model/DescribeHeatMapResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
reid_cloud/src/model/DescribeHeatMapResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/reid_cloud/model/DescribeHeatMapResult.h> #include <json/json.h> using namespace AlibabaCloud::Reid_cloud; using namespace AlibabaCloud::Reid_cloud::Model; DescribeHeatMapResult::DescribeHeatMapResult() : ServiceResult() {} DescribeHeatMapResult::DescribeHeatMapResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeHeatMapResult::~DescribeHeatMapResult() {} void DescribeHeatMapResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allHeatMapPointsNode = value["HeatMapPoints"]["HeatMapPoint"]; for (auto valueHeatMapPointsHeatMapPoint : allHeatMapPointsNode) { HeatMapPoint heatMapPointsObject; if(!valueHeatMapPointsHeatMapPoint["Y"].isNull()) heatMapPointsObject.y = std::stof(valueHeatMapPointsHeatMapPoint["Y"].asString()); if(!valueHeatMapPointsHeatMapPoint["Weight"].isNull()) heatMapPointsObject.weight = std::stoi(valueHeatMapPointsHeatMapPoint["Weight"].asString()); if(!valueHeatMapPointsHeatMapPoint["X"].isNull()) heatMapPointsObject.x = std::stof(valueHeatMapPointsHeatMapPoint["X"].asString()); heatMapPoints_.push_back(heatMapPointsObject); } if(!value["ErrorCode"].isNull()) errorCode_ = value["ErrorCode"].asString(); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["DynamicCode"].isNull()) dynamicCode_ = value["DynamicCode"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["DynamicMessage"].isNull()) dynamicMessage_ = value["DynamicMessage"].asString(); } std::string DescribeHeatMapResult::getMessage()const { return message_; } std::string DescribeHeatMapResult::getDynamicCode()const { return dynamicCode_; } std::string DescribeHeatMapResult::getErrorCode()const { return errorCode_; } std::string DescribeHeatMapResult::getDynamicMessage()const { return dynamicMessage_; } std::string DescribeHeatMapResult::getErrorMessage()const { return errorMessage_; } std::string DescribeHeatMapResult::getCode()const { return code_; } std::vector<DescribeHeatMapResult::HeatMapPoint> DescribeHeatMapResult::getHeatMapPoints()const { return heatMapPoints_; } bool DescribeHeatMapResult::getSuccess()const { return success_; }
28.288288
95
0.756369
[ "vector", "model" ]
fd4f30e125fa4353595bef3d8e351d3c71d49eea
555
cpp
C++
Red/Debug/Darwin/DarwinProcess.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
1
2018-01-29T02:49:05.000Z
2018-01-29T02:49:05.000Z
Red/Debug/Darwin/DarwinProcess.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
26
2017-05-08T22:57:14.000Z
2018-05-15T20:55:26.000Z
Red/Debug/Darwin/DarwinProcess.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2018 Andrew Depke */ #include "DarwinProcess.h" #include <mach-o/dyld.h> #include <string.h> namespace Red { bool GetProcessModules(std::vector<ProcessModule>* Output) { unsigned int ModuleCount = _dyld_image_count(); if (ModuleCount == 0) { return false; } for (unsigned int Iter = 0; Iter < ModuleCount; ++Iter) { ProcessModule Module; Module.Name = _dyld_get_image_name(Iter); Module.BaseAddress = ""; Module.FileSize = 0; Output->push_back(Module); } return true; } } // namespace Red
17.34375
59
0.67027
[ "vector" ]
fd517adafc67095b26e4f816e5ed8b471ed7eb18
7,330
cc
C++
v0_1_5/tests/vector-test.cc
AdvantechRISC/apq8016_external_marisa-trie
629ed059b1e85cd8e4de363d8b3dc53c15c3e08a
[ "BSD-3-Clause" ]
null
null
null
v0_1_5/tests/vector-test.cc
AdvantechRISC/apq8016_external_marisa-trie
629ed059b1e85cd8e4de363d8b3dc53c15c3e08a
[ "BSD-3-Clause" ]
null
null
null
v0_1_5/tests/vector-test.cc
AdvantechRISC/apq8016_external_marisa-trie
629ed059b1e85cd8e4de363d8b3dc53c15c3e08a
[ "BSD-3-Clause" ]
null
null
null
#include <cstdlib> #include <ctime> #include <sstream> #include <string> #include <vector> #include <marisa_alpha/vector.h> #include <marisa_alpha/intvector.h> #include <marisa_alpha/bitvector.h> #include "assert.h" namespace { void TestVector() { TEST_START(); std::vector<int> values; for (std::size_t i = 0; i < 1000; ++i) { values.push_back(std::rand()); } marisa_alpha::Vector<int> vec; ASSERT(vec.max_size() == MARISA_ALPHA_UINT32_MAX); ASSERT(vec.size() == 0); ASSERT(vec.capacity() == 0); ASSERT(!vec.fixed()); ASSERT(vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32)); for (std::size_t i = 0; i < values.size(); ++i) { vec.push_back(values[i]); ASSERT(vec[i] == values[i]); ASSERT(static_cast<const marisa_alpha::Vector<int> &>(vec)[i] == values[i]); } ASSERT(vec.size() == values.size()); ASSERT(vec.capacity() >= vec.size()); ASSERT(!vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32) + ((sizeof(int) * values.size()))); ASSERT(static_cast<const marisa_alpha::Vector<int> &>(vec).front() == values.front()); ASSERT(static_cast<const marisa_alpha::Vector<int> &>(vec).back() == values.back()); ASSERT(vec.front() == values.front()); ASSERT(vec.back() == values.back()); vec.shrink(); ASSERT(vec.size() == values.size()); ASSERT(vec.capacity() == vec.size()); for (std::size_t i = 0; i < values.size(); ++i) { ASSERT(vec[i] == values[i]); ASSERT(static_cast<const marisa_alpha::Vector<int> &>(vec)[i] == values[i]); } vec.save("vector-test.dat"); vec.clear(); ASSERT(vec.empty()); ASSERT(vec.capacity() == 0); marisa_alpha::Mapper mapper; vec.mmap(&mapper, "vector-test.dat"); ASSERT(mapper.is_open()); ASSERT(vec.size() == values.size()); ASSERT(vec.capacity() == 0); ASSERT(vec.fixed()); ASSERT(!vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32) + ((sizeof(int) * values.size()))); for (std::size_t i = 0; i < values.size(); ++i) { ASSERT(static_cast<const marisa_alpha::Vector<int> &>(vec)[i] == values[i]); } vec.clear(); vec.load("vector-test.dat"); ASSERT(vec.size() == values.size()); ASSERT(vec.capacity() == vec.size()); ASSERT(!vec.fixed()); ASSERT(!vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32) + ((sizeof(int) * values.size()))); for (std::size_t i = 0; i < values.size(); ++i) { ASSERT(vec[i] == values[i]); ASSERT(static_cast<const marisa_alpha::Vector<int> &>(vec)[i] == values[i]); } vec.clear(); vec.push_back(0); ASSERT(vec.capacity() == 1); vec.push_back(1); ASSERT(vec.capacity() == 2); vec.push_back(2); ASSERT(vec.capacity() == 4); vec.resize(5); ASSERT(vec.capacity() == 8); vec.resize(100); ASSERT(vec.capacity() == 100); vec.fix(); ASSERT(vec.fixed()); EXCEPT(vec.fix(), MARISA_ALPHA_STATE_ERROR); EXCEPT(vec.push_back(0), MARISA_ALPHA_STATE_ERROR); EXCEPT(vec.resize(0), MARISA_ALPHA_STATE_ERROR); EXCEPT(vec.reserve(0), MARISA_ALPHA_STATE_ERROR); TEST_END(); } void TestIntVector() { TEST_START(); marisa_alpha::IntVector vec; ASSERT(vec.num_bits_per_int() == 0); ASSERT(vec.mask() == 0); ASSERT(vec.size() == 0); ASSERT(vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32) * 4); marisa_alpha::Vector<marisa_alpha::UInt32> values; vec.build(values); ASSERT(vec.num_bits_per_int() == 1); ASSERT(vec.mask() == 1); ASSERT(vec.size() == 0); ASSERT(vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32) * 4); values.push_back(0); vec.build(values); ASSERT(vec.num_bits_per_int() == 1); ASSERT(vec.mask() == 1); ASSERT(vec.size() == 1); ASSERT(!vec.empty()); ASSERT(vec.total_size() == sizeof(marisa_alpha::UInt32) * 5); ASSERT(vec[0] == 0); values.push_back(255); vec.build(values); ASSERT(vec.num_bits_per_int() == 8); ASSERT(vec.mask() == 0xFF); ASSERT(vec.size() == 2); ASSERT(vec[0] == 0); ASSERT(vec[1] == 255); values.push_back(65536); vec.build(values); ASSERT(vec.num_bits_per_int() == 17); ASSERT(vec.mask() == 0x1FFFF); ASSERT(vec.size() == 3); ASSERT(vec[0] == 0); ASSERT(vec[1] == 255); ASSERT(vec[2] == 65536); vec.save("vector-test.dat"); vec.clear(); ASSERT(vec.num_bits_per_int() == 0); ASSERT(vec.mask() == 0); ASSERT(vec.size() == 0); marisa_alpha::Mapper mapper; vec.mmap(&mapper, "vector-test.dat"); ASSERT(mapper.is_open()); ASSERT(vec.num_bits_per_int() == 17); ASSERT(vec.mask() == 0x1FFFF); ASSERT(vec.size() == 3); ASSERT(vec[0] == 0); ASSERT(vec[1] == 255); ASSERT(vec[2] == 65536); vec.clear(); vec.load("vector-test.dat"); ASSERT(vec.num_bits_per_int() == 17); ASSERT(vec.mask() == 0x1FFFF); ASSERT(vec.size() == 3); ASSERT(vec[0] == 0); ASSERT(vec[1] == 255); ASSERT(vec[2] == 65536); values.clear(); for (std::size_t i = 0; i < 500; ++i) { values.push_back(std::rand()); } vec.build(values); ASSERT(vec.size() == values.size()); for (std::size_t i = 0; i < vec.size(); ++i) { ASSERT(vec[i] == values[i]); } TEST_END(); } void TestBitVector(marisa_alpha::UInt32 size) { marisa_alpha::BitVector bv; ASSERT(bv.size() == 0); ASSERT(bv.empty()); ASSERT(bv.total_size() == sizeof(marisa_alpha::UInt32) * 5); std::vector<bool> bits(size); std::vector<marisa_alpha::UInt32> zeros, ones; for (marisa_alpha::UInt32 i = 0; i < size; ++i) { const bool bit = (std::rand() % 2) == 0; bits[i] = bit; bv.push_back(bit); (bit ? ones : zeros).push_back(i); ASSERT(bv[i] == bits[i]); } ASSERT(bv.size() == bits.size()); ASSERT((size == 0) || !bv.empty()); bv.build(); marisa_alpha::UInt32 num_zeros = 0, num_ones = 0; for (marisa_alpha::UInt32 i = 0; i < bits.size(); ++i) { ASSERT(bv[i] == bits[i]); ASSERT(bv.rank0(i) == num_zeros); ASSERT(bv.rank1(i) == num_ones); ++(bv[i] ? num_ones : num_zeros); } for (marisa_alpha::UInt32 i = 0; i < zeros.size(); ++i) { ASSERT(bv.select0(i) == zeros[i]); } for (marisa_alpha::UInt32 i = 0; i < ones.size(); ++i) { ASSERT(bv.select1(i) == ones[i]); } std::stringstream stream; bv.write(stream); bv.clear(); ASSERT(bv.size() == 0); ASSERT(bv.empty()); ASSERT(bv.total_size() == sizeof(marisa_alpha::UInt32) * 5); bv.read(stream); ASSERT(bv.size() == bits.size()); num_zeros = 0, num_ones = 0; for (marisa_alpha::UInt32 i = 0; i < bits.size(); ++i) { ASSERT(bv[i] == bits[i]); ASSERT(bv.rank0(i) == num_zeros); ASSERT(bv.rank1(i) == num_ones); ++(bv[i] ? num_ones : num_zeros); } for (marisa_alpha::UInt32 i = 0; i < zeros.size(); ++i) { ASSERT(bv.select0(i) == zeros[i]); } for (marisa_alpha::UInt32 i = 0; i < ones.size(); ++i) { ASSERT(bv.select1(i) == ones[i]); } } void TestBitVector() { TEST_START(); TestBitVector(0); TestBitVector(1); TestBitVector(511); TestBitVector(512); TestBitVector(513); for (marisa_alpha::UInt32 i = 0; i < 100; ++i) { TestBitVector(std::rand() % 4096); } TEST_END(); } } // namespace int main() { std::srand((unsigned int)time(NULL)); TestVector(); TestIntVector(); TestBitVector(); return 0; }
24.111842
68
0.602456
[ "vector" ]
fd57b9220af65c576bad8bda564ad474def7cb05
1,810
cpp
C++
src/mesh.cpp
SirBob01/OpenGL-Experimenting
bdf4aae4c1d7c1e2c96d0066e2b3bd196b4dd3a4
[ "MIT" ]
null
null
null
src/mesh.cpp
SirBob01/OpenGL-Experimenting
bdf4aae4c1d7c1e2c96d0066e2b3bd196b4dd3a4
[ "MIT" ]
null
null
null
src/mesh.cpp
SirBob01/OpenGL-Experimenting
bdf4aae4c1d7c1e2c96d0066e2b3bd196b4dd3a4
[ "MIT" ]
null
null
null
#include "mesh.h" Mesh::Mesh(std::vector<Vertex> &vertices, std::vector<uint32_t> &indices) { generate_buffers(vertices, indices); } Mesh::Mesh(std::vector<glm::vec3> &positions, std::vector<glm::vec3> &normals, std::vector<uint32_t> &indices) { std::vector<Vertex> vertices; for (int i = 0; i < positions.size(); i++) { vertices.push_back({positions[i], normals[i], glm::vec2(0, 0)}); } generate_buffers(vertices, indices); } Mesh::Mesh(std::vector<glm::vec3> &positions, std::vector<glm::vec2> &texture_coordinates, std::vector<uint32_t> &indices) { std::vector<Vertex> vertices; for (int i = 0; i < positions.size(); i++) { vertices.push_back( {positions[i], glm::vec3(0, 0, 0), texture_coordinates[i]}); } generate_buffers(vertices, indices); } Mesh::Mesh(std::vector<glm::vec3> &positions) { std::vector<Vertex> vertices; for (int i = 0; i < positions.size(); i++) { vertices.push_back({positions[i], glm::vec3(0, 0, 0), glm::vec2(0, 0)}); } std::vector<uint32_t> indices; generate_buffers(vertices, indices); } void Mesh::generate_buffers(std::vector<Vertex> &vertices, std::vector<uint32_t> &indices) { if (indices.size() == 0) { for (int i = 0; i < vertices.size(); i++) { indices.push_back(i); } } index_count_ = indices.size(); vertex_buffer_ = std::make_unique<Buffer<Vertex>>( vertices, BufferType::Vertex, BufferUsage::StaticDraw); index_buffer_ = std::make_unique<Buffer<uint32_t>>( indices, BufferType::Index, BufferUsage::StaticDraw); } void Mesh::bind() { vertex_buffer_->bind(); index_buffer_->bind(); } size_t Mesh::get_index_count() { return index_count_; }
32.321429
80
0.613812
[ "mesh", "vector" ]
fd59598938e770ef45b0b91a65d8c7bcd5e37483
4,059
hpp
C++
src/graph/flow_network.hpp
Fa2019-3460-635/net-flow-and-circ
cb9de5d1a69193854231e4d01379e4d40b22ae86
[ "MIT" ]
1
2019-10-26T18:07:53.000Z
2019-10-26T18:07:53.000Z
src/graph/flow_network.hpp
Fa2019-3460-635/net-flow-and-circ
cb9de5d1a69193854231e4d01379e4d40b22ae86
[ "MIT" ]
25
2019-08-29T22:06:50.000Z
2019-10-04T13:44:17.000Z
src/graph/flow_network.hpp
Fa2019-3460-635/net-flow-and-circ
cb9de5d1a69193854231e4d01379e4d40b22ae86
[ "MIT" ]
null
null
null
#pragma once #include "graph.hpp" #include <map> namespace graph { class FlowNetwork : public Graph { //============================================================================== // Constructors //============================================================================== public: FlowNetwork () : Graph() {} /** * @param adj_list: an adjacency list representation of a graph */ FlowNetwork (Graph::AdjacencyList const & adj_list) : Graph(adj_list) { // initialize flow along all edges to 0 for (auto const & node : adj_list) for (auto const & edge : node) m_flow[edge] = 0; } //============================================================================== // Static Utility Methods //============================================================================== public: /** * @brief Get the residual graph based on the original graph, the augmenting path, and * the increased flow along the path * @param G: graph to augment * @param p: augmenting path * @param f: flow along augmenting path * @return Gf, the residual graph. */ static FlowNetwork get_residual_graph (const FlowNetwork & G, std::vector<int> p, int f); //============================================================================== // Public Methods //============================================================================== public: /** * @brief This function finds the sum of the capacity leaving a node * * @param node: the node in question */ int total_capacity_out (int node); /** * @brief The source will have no edges pointing to it * * This method assumes that the graph contains a single source */ virtual int find_source(); /** * @brief The sink points to nothing * * This method assumes that the graph contains a single sink */ virtual int find_sink(); /** * @brief Reduce the capacity of the edge between the given nodes * * @param start_node * @param end_node * @param amount: The amount by which to reduce the capacity of the edge. */ void reduce_edge_capacity (int start_node, int end_node, int amount); /** * @brief Increases the capacity of the edge between the given nodes * * @param start_node * @param end_node * @param amount: The amount by which to increase the capacity of the edge. */ void increase_edge_capacity (int start_node, int end_node, int amount); /** * @brief Transform the given graph which potentially has multiple sources/sinks to * one that has a single source/sink. * * @param G: The graph to transform * @return A new graph that has one source and one sink */ static FlowNetwork transform_to_single_source_sink (const FlowNetwork & G); /** * @brief Find the sources for this graph * @return a list of source-node indicies. */ virtual std::vector<int> get_sources (); /** * @brief Find the sinks for this graph * @return a list of sink-node indicies. */ virtual std::vector<int> get_sinks (); //============================================================================== // Implementation Details //============================================================================== private: /** * Comparator functor so that we can use Graph::edge instances as keys * in an associative array that maps edges to their flows. */ struct EdgeComparator { bool operator () (Graph::edge const & e1, Graph::edge const & e2) const { return &e1 < &e2; } }; //============================================================================== // Private Attributes //============================================================================== private: std::vector<int> m_sources; std::vector<int> m_sinks; std::map<Graph::edge, int, EdgeComparator> m_flow; }; } // namespace graph
28.384615
93
0.50037
[ "vector", "transform" ]
fd5af461f4288bf714b54ac6ca9c8ba9acf516f0
11,915
cpp
C++
src/material/material.cpp
mfirmin/audio-demo
767e2fc1b7afb53cd5aafad90ae562661a154373
[ "MIT" ]
1
2021-09-13T20:22:29.000Z
2021-09-13T20:22:29.000Z
src/material/material.cpp
mfirmin/audio-demo
767e2fc1b7afb53cd5aafad90ae562661a154373
[ "MIT" ]
null
null
null
src/material/material.cpp
mfirmin/audio-demo
767e2fc1b7afb53cd5aafad90ae562661a154373
[ "MIT" ]
1
2021-09-13T20:22:31.000Z
2021-09-13T20:22:31.000Z
#include "material.hpp" #include "gl/shaderUtils.hpp" #include "light/light.hpp" #include <GL/glew.h> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <string> #include <sstream> Material::Material(glm::vec3 color, float specularCoefficient, float shininess) : color(color), specularCoefficient(specularCoefficient), shininess(shininess) {} void Material::create() { if (getProgram() != 0) { // already initialized return; } std::string vertexShaderSource = R"( #version 330 layout(location = 0) in vec3 position; layout(location = 1) in vec3 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; out vec3 vNormalEyespace; out vec4 vPositionEyespace; void main() { vNormalEyespace = (transpose(inverse(viewMatrix * modelMatrix)) * vec4(normal, 0.0)).xyz; vPositionEyespace = viewMatrix * modelMatrix * vec4(position, 1.0); gl_Position = projectionMatrix * vPositionEyespace; } )"; std::string fragmentShaderSource = R"( #version 330 #define MAX_LIGHTS 10 out vec4 fColor; uniform mat4 viewMatrix; uniform vec3 color; uniform float shininess; uniform vec3 emissiveColor; uniform float emissiveStrength; uniform float emissiveEnabled; uniform float blinnEnabled; uniform float specularCoefficient; in vec3 vNormalEyespace; in vec4 vPositionEyespace; uniform int numLights; uniform struct Light { vec4 position; vec3 color; float intensity; float ambientCoefficient; float attenuation; float enabled; // spotlight only float coneAngle; vec3 coneDirection; } lights[MAX_LIGHTS]; vec3 illuminate(vec3 inColor, vec3 P, vec3 N, vec3 E) { vec3 outColor = vec3(0.0); for (int i = 0; i < numLights; i++) { Light light = lights[i]; if (light.enabled < 0.5) { continue; } vec3 L; float attenuation; if (light.position.w == 0.0) { // directional light // convert the direction into eyespace L = normalize((viewMatrix * light.position).xyz); // directional lights don't support attenuation attenuation = 1.0; } else { vec3 lightPositionEyespace = (viewMatrix * light.position).xyz; L = normalize(lightPositionEyespace - P); float distance = length(lightPositionEyespace - P); attenuation = 1.0 / (1.0 + light.attenuation * pow(distance, 2)); } // TODO: Spotlights vec3 H = normalize(L + E); vec3 ambient = light.ambientCoefficient * inColor * light.color * light.intensity; float diffuseCoefficient = max(0.0, dot(N, L)); vec3 diffuse = diffuseCoefficient * inColor * light.color * light.intensity; float specularTerm = 0.0; if (diffuseCoefficient > 0.0) { float dir = 0.0; if (blinnEnabled > 0.5f) { dir = dot(N, H); } else { dir = dot( E, reflect(-L, N) ); } specularTerm = pow( max( 0.0, dir ), shininess ); } vec3 specular = specularCoefficient * specularTerm * inColor * light.color * light.intensity; // TODO: Shadows outColor += ambient + attenuation * (diffuse + specular); } // TODO: Gamma correction if (emissiveEnabled > 0.5f) { outColor += emissiveStrength * emissiveColor; } return outColor; } void main() { vec3 N = normalize(vNormalEyespace); vec3 E = normalize(-vPositionEyespace.xyz); if (dot(N, E) < 0.0) { N = -N; } fColor = vec4(illuminate(color, vPositionEyespace.xyz, N, E), 1.0); } )"; if (!compile(vertexShaderSource, fragmentShaderSource)) { return; } GLuint shader = getProgram(); glUseProgram(shader); auto projectionMatrixLocation = glGetUniformLocation(shader, "projectionMatrix"); auto viewMatrixLocation = glGetUniformLocation(shader, "viewMatrix"); auto modelMatrixLocation = glGetUniformLocation(shader, "modelMatrix"); auto colorLocation = glGetUniformLocation(shader, "color"); auto shininessLocation = glGetUniformLocation(shader, "shininess"); auto specularCoefficientLocation = glGetUniformLocation(shader, "specularCoefficient"); auto emissiveColorLocation = glGetUniformLocation(shader, "emissiveColor"); auto emissiveStrengthLocation = glGetUniformLocation(shader, "emissiveStrength"); auto emissiveEnabledLocation = glGetUniformLocation(shader, "emissiveEnabled"); auto blinnEnabledLocation = glGetUniformLocation(shader, "blinnEnabled"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0))); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0))); glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0))); glUniform3fv(colorLocation, 1, glm::value_ptr(color)); glUniform1f(shininessLocation, shininess); glUniform1f(specularCoefficientLocation, specularCoefficient); glUniform3fv(emissiveColorLocation, 1, glm::value_ptr(color)); glUniform1f(emissiveStrengthLocation, 0.0f); glUniform1f(emissiveEnabledLocation, 0.0f); glUniform1f(blinnEnabledLocation, 1.0f); glUseProgram(0); } Material::~Material() {} bool Material::compile(std::string vertexShader, std::string fragmentShader) { program = ShaderUtils::compile(vertexShader, fragmentShader); return program != 0; } void Material::setColor(glm::vec3 color) { glUseProgram(program); auto colorLocation = glGetUniformLocation(program, "color"); glUniform3fv(colorLocation, 1, glm::value_ptr(color)); glUseProgram(0); } void Material::setEmissiveColorAndStrength(glm::vec3 color, float strength) { glUseProgram(program); auto emissiveColorLocation = glGetUniformLocation(program, "emissiveColor"); auto emissiveStrengthLocation = glGetUniformLocation(program, "emissiveStrength"); glUniform3fv(emissiveColorLocation, 1, glm::value_ptr(color)); glUniform1f(emissiveStrengthLocation, strength); glUseProgram(0); } void Material::setEmissiveColor(glm::vec3 color) { glUseProgram(program); auto emissiveColorLocation = glGetUniformLocation(program, "emissiveColor"); glUniform3fv(emissiveColorLocation, 1, glm::value_ptr(color)); glUseProgram(0); } void Material::setEmissiveStrength(float strength) { glUseProgram(program); auto emissiveStrengthLocation = glGetUniformLocation(program, "emissiveStrength"); glUniform1f(emissiveStrengthLocation, strength); glUseProgram(0); } void Material::setShininess(float shininess) { glUseProgram(program); auto shininessLocation = glGetUniformLocation(program, "shininess"); glUniform1f(shininessLocation, shininess); glUseProgram(0); } void Material::setLights(const std::vector<std::shared_ptr<Light>>& lights) { std::size_t lightIndex = 0; glUseProgram(program); glUniform1i(glGetUniformLocation(program, "numLights"), lights.size()); for (const auto& light : lights) { auto lightInfo = light->getLightInfo(); // position std::ostringstream positionLocation; std::ostringstream colorLocation; std::ostringstream intensityLocation; std::ostringstream attenuationLocation; std::ostringstream ambientCoefficientLocation; std::ostringstream enabledLocation; std::ostringstream coneAngleLocation; std::ostringstream coneDirectionLocation; positionLocation << "lights[" << lightIndex << "].position"; colorLocation << "lights[" << lightIndex << "].color"; intensityLocation << "lights[" << lightIndex << "].intensity"; attenuationLocation << "lights[" << lightIndex << "].attenuation"; ambientCoefficientLocation << "lights[" << lightIndex << "].ambientCoefficient"; enabledLocation << "lights[" << lightIndex << "].enabled"; coneAngleLocation << "lights[" << lightIndex << "].coneAngle"; coneDirectionLocation << "lights[" << lightIndex << "].coneDirection"; glUniform4fv( glGetUniformLocation(program, positionLocation.str().c_str()), 1, glm::value_ptr(lightInfo.position) ); glUniform3fv( glGetUniformLocation(program, colorLocation.str().c_str()), 1, glm::value_ptr(lightInfo.color) ); glUniform1f( glGetUniformLocation(program, intensityLocation.str().c_str()), lightInfo.intensity ); glUniform1f( glGetUniformLocation(program, attenuationLocation.str().c_str()), lightInfo.attenuation ); glUniform1f( glGetUniformLocation(program, ambientCoefficientLocation.str().c_str()), lightInfo.ambientCoefficient ); glUniform1f( glGetUniformLocation(program, enabledLocation.str().c_str()), lightInfo.enabled ? 1.0f : 0.0f ); glUniform1f( glGetUniformLocation(program, coneAngleLocation.str().c_str()), lightInfo.coneAngle ); glUniform3fv( glGetUniformLocation(program, coneDirectionLocation.str().c_str()), 1, glm::value_ptr(lightInfo.coneDirection) ); lightIndex++; } glUseProgram(0); } void Material::setModelMatrix(const glm::mat4& modelMatrix) { glUseProgram(program); auto modelMatrixLocation = glGetUniformLocation(program, "modelMatrix"); glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(modelMatrix)); glUseProgram(0); } void Material::setProjectionAndViewMatrices( const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix ) { glUseProgram(program); auto projectionMatrixLocation = glGetUniformLocation(program, "projectionMatrix"); auto viewMatrixLocation = glGetUniformLocation(program, "viewMatrix"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix)); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix)); glUseProgram(0); } void Material::setMatrices( const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix, const glm::mat4& modelMatrix ) { glUseProgram(program); auto projectionMatrixLocation = glGetUniformLocation(program, "projectionMatrix"); auto viewMatrixLocation = glGetUniformLocation(program, "viewMatrix"); auto modelMatrixLocation = glGetUniformLocation(program, "modelMatrix"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix)); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(viewMatrix)); glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(modelMatrix)); glUseProgram(0); }
34.536232
109
0.625346
[ "vector" ]
fd5bdc4018fde20d74187edbfde5eeaa68435e38
2,866
hh
C++
src/bie/bimat_interface.hh
XiaoMaResearch/hybrid_tsunamic_plane_stress
574988edfcd4839f680b85cde2bf818936e86b78
[ "MIT" ]
6
2019-04-12T19:51:23.000Z
2021-09-16T07:12:57.000Z
src/bie/bimat_interface.hh
XiaoMaResearch/hybrid_tsunamic_plane_stress
574988edfcd4839f680b85cde2bf818936e86b78
[ "MIT" ]
null
null
null
src/bie/bimat_interface.hh
XiaoMaResearch/hybrid_tsunamic_plane_stress
574988edfcd4839f680b85cde2bf818936e86b78
[ "MIT" ]
1
2019-07-07T07:23:58.000Z
2019-07-07T07:23:58.000Z
/** * @file bimat_interface.hh * * @author David S. Kammer <kammer@cornell.edu> * * @date creation: Mon Oct 09 2017 * @date last modification: Mon Oct 09 2017 * * @brief * * @section LICENSE * * MIT License * Copyright (c) 2017 David S. Kammer * */ #ifndef __BIMAT_INTERFACE_H__ #define __BIMAT_INTERFACE_H__ /* -------------------------------------------------------------------------- */ #include "half_space.hh" #include "interface_law.hh" #include "interface.hh" class BimatInterface : public Interface { /* ------------------------------------------------------------------------ */ /* Constructors/Destructors */ /* ------------------------------------------------------------------------ */ public: BimatInterface(double length, unsigned int nb_nodes, Material * top_material, Kernel * top_H11, Kernel * top_H12, Kernel * top_H22, Material * bot_material, Kernel * bot_H11, Kernel * bot_H12, Kernel * bot_H22, InterfaceLaw * law); virtual ~BimatInterface(); /* ------------------------------------------------------------------------ */ /* Methods */ /* ------------------------------------------------------------------------ */ public: // get (limiting) stable time step virtual double getStableTimeStep(); // initiate interface model and half spaces virtual void init(); // functions used during time stepping for each half-space virtual void computeDisplacement(); virtual void forwardFFT(); virtual void computeStressFourierCoeff(); virtual void backwardFFT(); virtual void computeResidual(); virtual void computeVelocity(); // compute force needed to close normal gap virtual void closingNormalGapForce(NodalField * close_force); // compute force needed to maintain current shear gap virtual void maintainShearGapForce(NodalField * maintain_force); // compute gap in displacement virtual void computeGap1(NodalField * gap_1); virtual void computeGap2(NodalField * gap_2); // dumper function virtual void registerDumpField(const std::string & field_name); /* ------------------------------------------------------------------------ */ /* Accessors */ /* ------------------------------------------------------------------------ */ public: virtual void setTimeStep(double time_step); /* ------------------------------------------------------------------------ */ /* Class Members */ /* ------------------------------------------------------------------------ */ private: // half spaces HalfSpace top; HalfSpace bot; }; //#include "bimat_interface_impl.cc" #endif /* __BIMAT_INTERFACE_H__ */
32.568182
80
0.480461
[ "model" ]
5b73de2c3ad24592b2d48ee2c92eab8af658bfe5
8,575
cpp
C++
sp/src/game/server/firefightreloaded/weapon_sniper_rifle.cpp
FIREFIGHT-RELOADED/mapbase-source-sdk-2013
652bc5e3a6adb9045c88f239cc88cb6e89d9eabf
[ "Unlicense" ]
null
null
null
sp/src/game/server/firefightreloaded/weapon_sniper_rifle.cpp
FIREFIGHT-RELOADED/mapbase-source-sdk-2013
652bc5e3a6adb9045c88f239cc88cb6e89d9eabf
[ "Unlicense" ]
2
2020-11-23T19:36:30.000Z
2020-11-26T11:41:42.000Z
sp/src/game/server/firefightreloaded/weapon_sniper_rifle.cpp
FIREFIGHT-RELOADED/mapbase-source-sdk-2013
652bc5e3a6adb9045c88f239cc88cb6e89d9eabf
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Sniper Rifle // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "npcevent.h" #include "basehlcombatweapon.h" #include "basecombatcharacter.h" #include "ai_basenpc.h" #include "player.h" #include "gamerules.h" #include "in_buttons.h" #include "soundent.h" #include "game.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "te_effect_dispatch.h" #include "gamestats.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // CWeaponSniperRifle //----------------------------------------------------------------------------- class CWeaponSniperRifle : public CBaseHLCombatWeapon { DECLARE_CLASS( CWeaponSniperRifle, CBaseHLCombatWeapon ); public: CWeaponSniperRifle( void ); void PrimaryAttack( void ); void SecondaryAttack( void ); void ItemPostFrame( void ); void ItemBusyFrame( void ); void Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ); bool Reload(void); void Drop(const Vector &vecVelocity); bool Holster(CBaseCombatWeapon *pSwitchingTo = NULL); virtual const Vector& GetBulletSpread( void ) { static const Vector cone = VECTOR_CONE_3DEGREES; static const Vector zoomcone = VECTOR_CONE_1DEGREES; if (m_bInZoom) { return zoomcone; } return cone; } float WeaponAutoAimScale() { return 0.6f; } DECLARE_SERVERCLASS(); DECLARE_DATADESC(); DECLARE_ACTTABLE(); private: void CheckZoomToggle( void ); void ToggleZoom( void ); private: bool m_bInZoom; }; acttable_t CWeaponSniperRifle::m_acttable[] = { { ACT_HL2MP_IDLE, ACT_HL2MP_IDLE_AR2, false }, { ACT_HL2MP_RUN, ACT_HL2MP_RUN_AR2, false }, { ACT_HL2MP_IDLE_CROUCH, ACT_HL2MP_IDLE_CROUCH_AR2, false }, { ACT_HL2MP_WALK_CROUCH, ACT_HL2MP_WALK_CROUCH_AR2, false }, { ACT_HL2MP_GESTURE_RANGE_ATTACK, ACT_HL2MP_GESTURE_RANGE_ATTACK_AR2, false }, { ACT_HL2MP_GESTURE_RELOAD, ACT_GESTURE_RELOAD_SMG1, false }, { ACT_HL2MP_JUMP, ACT_HL2MP_JUMP_AR2, false }, { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_AR2, false }, }; IMPLEMENT_ACTTABLE(CWeaponSniperRifle); LINK_ENTITY_TO_CLASS( weapon_sniper_rifle, CWeaponSniperRifle ); PRECACHE_WEAPON_REGISTER( weapon_sniper_rifle ); IMPLEMENT_SERVERCLASS_ST( CWeaponSniperRifle, DT_WeaponSniperRifle ) END_SEND_TABLE() BEGIN_DATADESC( CWeaponSniperRifle ) DEFINE_FIELD( m_bInZoom, FIELD_BOOLEAN ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CWeaponSniperRifle::CWeaponSniperRifle( void ) { m_bReloadsSingly = false; m_bFiresUnderwater = false; m_bInZoom = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ) { switch( pEvent->event ) { case EVENT_WEAPON_RELOAD: { CBasePlayer *pOwner = ToBasePlayer(GetOwner()); CEffectData data; for (int i = 0; i < 2; i++) { data.m_vOrigin = pOwner->WorldSpaceCenter() + RandomVector(-4, 4); data.m_vAngles = QAngle(90, random->RandomInt(0, 360), 0); data.m_nEntIndex = entindex(); DispatchEffect("ShellEject", data); } } break; default: BaseClass::Operator_HandleAnimEvent(pEvent, pOperator); break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::PrimaryAttack( void ) { // Only the player fires this way so we can cast CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( !pPlayer ) { return; } if ( m_iClip1 <= 0 ) { if ( !m_bFireOnEmpty ) { Reload(); } else { WeaponSound( EMPTY ); m_flNextPrimaryAttack = 0.15; } return; } m_flNextPrimaryAttack = gpGlobals->curtime + 0.85; m_iPrimaryAttacks++; gamestats->Event_WeaponFired( pPlayer, true, GetClassname() ); WeaponSound( SINGLE ); pPlayer->DoMuzzleFlash(); SendWeaponAnim( ACT_VM_PRIMARYATTACK ); pPlayer->SetAnimation( PLAYER_ATTACK1 ); if (GetWpnData().m_bUseMuzzleSmoke) { DispatchParticleEffect("weapon_muzzle_smoke", PATTACH_POINT_FOLLOW, pPlayer->GetViewModel(), "muzzle", true); } m_iClip1--; Vector vecSrc = pPlayer->Weapon_ShootPosition(); Vector vecAiming = pPlayer->GetAutoaimVector( AUTOAIM_SCALE_DEFAULT ); pPlayer->FireBullets( 1, vecSrc, vecAiming, vec3_origin, MAX_TRACE_LENGTH, m_iPrimaryAmmoType, 0 ); pPlayer->SetMuzzleFlashTime( gpGlobals->curtime + 0.5 ); //Disorient the player QAngle angles = pPlayer->GetLocalAngles(); angles.x += random->RandomInt( -1, 1 ); angles.y += random->RandomInt( -1, 1 ); angles.z = 0; pPlayer->SnapEyeAngles( angles ); pPlayer->ViewPunch( QAngle( -8, random->RandomFloat( -2, 2 ), 0 ) ); CSoundEnt::InsertSound( SOUND_COMBAT, GetAbsOrigin(), 600, 0.2, GetOwner() ); if ( !m_iClip1 && pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) <= 0 ) { // HEV suit - indicate out of ammo condition pPlayer->SetSuitUpdate( "!HEV_AMO0", FALSE, 0 ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::SecondaryAttack( void ) { //NOTENOTE: The zooming is handled by the post/busy frames } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CWeaponSniperRifle::Reload(void) { CBasePlayer *pPlayer = ToBasePlayer(GetOwner()); if (m_bInZoom) { if (pPlayer->SetFOV(this, 0, 0.2f)) { WeaponSound(SPECIAL1); m_bInZoom = false; } } return BaseClass::Reload(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::CheckZoomToggle( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if (!IsIronsighted()) { if (pPlayer->m_afButtonPressed & IN_ATTACK2) { ToggleZoom(); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::ItemBusyFrame( void ) { // Allow zoom toggling even when we're reloading CheckZoomToggle(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::ItemPostFrame( void ) { // Allow zoom toggling CheckZoomToggle(); BaseClass::ItemPostFrame(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pSwitchingTo - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CWeaponSniperRifle::Holster(CBaseCombatWeapon *pSwitchingTo) { CBasePlayer *pPlayer = ToBasePlayer(GetOwner()); if (m_bInZoom) { if (pPlayer->SetFOV(this, 0, 0.2f)) { WeaponSound(SPECIAL1); m_bInZoom = false; } } return BaseClass::Holster(pSwitchingTo); } void CWeaponSniperRifle::Drop(const Vector &vecVelocity) { CBasePlayer *pPlayer = ToBasePlayer(GetOwner()); if (m_bInZoom) { if (pPlayer->SetFOV(this, 0, 0.2f)) { WeaponSound(SPECIAL1); m_bInZoom = false; } } BaseClass::Drop(vecVelocity); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSniperRifle::ToggleZoom( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( pPlayer == NULL ) return; if ( m_bInZoom ) { if ( pPlayer->SetFOV( this, 0, 0.2f ) ) { WeaponSound(SPECIAL1); m_bInZoom = false; } } else { if ( pPlayer->SetFOV( this, 20, 0.05f ) ) { WeaponSound(SPECIAL1); m_bInZoom = true; } } }
25.445104
111
0.555335
[ "vector" ]
5b81a33c5eef6297c1840d17dc026e77fa241f43
1,694
cpp
C++
lab2021-2022f/lab04/inheritance3.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
14
2019-04-23T13:45:10.000Z
2022-03-12T18:26:47.000Z
lab2020-2021/lab03/inheritance3.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
null
null
null
lab2020-2021/lab03/inheritance3.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
9
2019-09-01T15:17:45.000Z
2020-11-13T20:31:36.000Z
// παράδειγμα με χρήση abstract class, pure virtual function #include <iostream> #include <string> #include <vector> using namespace std; class pet { protected: string _name; public: pet(string name) : _name(name) {} virtual string sound() const = 0; virtual void make_sound() const { cout << _name << ": " << sound() << "!\n"; } }; class dog : public pet { public: dog(string name) : pet(name) {} string sound() const { return "woof"; } void make_sound() const { pet::make_sound(); cout << '(' << _name << " wags tail)\n"; } }; class cat : public pet { public: cat(string name) : pet(name) {} virtual string sound() const { return "miao"; } }; // αν η παράμετρος της συνάρτησης δεν ήταν reference, τότε το πέρασμα θα γινόταν με τιμή και θα δημιουργούταν // ένα νέο αντικείμενο pet. Ωστόσο, ο compiler δεν επιτρέπει τη μεταγλώττιση καθώς η κλάση pet είναι abstract // και συνεπώς δεν μπορεί να δημιουργεί αντικείμενα. void make_sound_twice(const pet& a_pet) { a_pet.make_sound(); a_pet.make_sound(); } int main() { // pet p; // object of abstract class type "pet" is not allowed: -- function "pet::sound" is a pure virtual function dog a_dog("Alf"); cat a_cat("Tom"); make_sound_twice(a_dog); make_sound_twice(a_cat); cout << "Vector with pets" << endl; vector<pet *> pets; pets.push_back(&a_dog); pets.push_back(&a_cat); for (size_t i = 0; i < pets.size(); i++) { pets[i]->make_sound(); } } /* έξοδος Alf: woof! (Alf wags tail) Alf: woof! (Alf wags tail) Tom: miao! Tom: miao! Vector with pets Alf: woof! (Alf wags tail) Tom: miao! */
20.409639
120
0.625148
[ "object", "vector" ]
5b86187df3ba6aba90065ffcc7a8de7758ec1aa3
1,468
cpp
C++
Leetcode Solution/Tree/Medium/95. Unique Binary Search Trees II.cpp
piyushn28/Placement-Preparation
585643400ebf814d12aacbcce39c3b87b2570963
[ "MIT" ]
1
2021-06-15T03:34:26.000Z
2021-06-15T03:34:26.000Z
Leetcode Solution/Tree/Medium/95. Unique Binary Search Trees II.cpp
piyushn28/Placement-Preparation
585643400ebf814d12aacbcce39c3b87b2570963
[ "MIT" ]
null
null
null
Leetcode Solution/Tree/Medium/95. Unique Binary Search Trees II.cpp
piyushn28/Placement-Preparation
585643400ebf814d12aacbcce39c3b87b2570963
[ "MIT" ]
1
2021-06-02T17:28:53.000Z
2021-06-02T17:28:53.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode* >helper(int start,int end) { vector<TreeNode* > res; if(start>end) { res.push_back(NULL); return res; } for(int i=start;i<=end;i++) { vector<TreeNode* > lefts=helper(start,i-1); vector<TreeNode* > rights=helper(i+1,end); for(int j=0;j<(int)lefts.size();j++) { for(int k=0;k<(int)rights.size();k++) { TreeNode* root = new TreeNode(i); root->left = lefts[j]; root->right = rights[k]; res.push_back(root); } } } return res; } vector<TreeNode*> generateTrees(int n) { if(n==0) return vector<TreeNode* >(0); return helper(1,n); } };
30.583333
71
0.330381
[ "vector" ]
5b8f42d4d64835e78b67fe7782e5bf4daaf9f81b
1,501
hpp
C++
src/repository/importFileBase.hpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/repository/importFileBase.hpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/repository/importFileBase.hpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> #include <vector> #include <memory> #include <cstdint> #include "../queries/queryStatus.hpp" #include "../mapping/indexDefinitionManager.hpp" namespace tools { class GenDefinitionBase; } namespace repository { class ImportFileBase; typedef struct { std::string index; std::string_view lines; ImportFileBase *t; } WorkerInitParam; class ImportFileBase { public: ImportFileBase(std::string _path,std::string _index,std::shared_ptr<queries::QueryStatus> &_queryStatus); bool openFile(); bool initImport(); bool estimateLineWorkSize(); bool doImport(); bool allocBuffers(); virtual bool fetch() = 0; virtual bool decodeHeader() = 0; virtual ~ImportFileBase() = default; friend class tools::GenDefinitionBase; protected: uint32_t processor_count = 1; WorkerInitParam * workerInitParams = nullptr; std::vector<pthread_t> threads; int64_t len = 0; char *buffer0 = nullptr; char *buffer1 = nullptr; char *buffers[2] {}; size_t usefullBufferSize[2]{}; uint32_t workingBuffer = 0; uint32_t lines_per_thread = 0; int fd = 0; size_t position = 0; uint32_t toSkip = 0; uint32_t lineSize = 0; std::string path; std::string index; size_t pos = 0; std::shared_ptr<queries::QueryStatus> queryStatus; std::shared_ptr<mapping::IndexDefinition> id; static void * InternalThreadEntryFunc(void * p) { auto *o = (WorkerInitParam*)p; o->t->processingLoop(o); return nullptr; } void processingLoop(WorkerInitParam *o); }; }
22.073529
106
0.725516
[ "vector" ]
5b9543941e3d21cca566e678c79cf97aed869126
7,938
cc
C++
tests/aff4_map_tests.cc
gonmator/c-aff4
e5e148960d4e0155df376b376ac7162b97829961
[ "Apache-2.0" ]
146
2018-03-21T15:51:09.000Z
2022-02-18T00:36:11.000Z
tests/aff4_map_tests.cc
gonmator/c-aff4
e5e148960d4e0155df376b376ac7162b97829961
[ "Apache-2.0" ]
84
2018-03-29T04:58:39.000Z
2021-06-08T18:44:44.000Z
tests/aff4_map_tests.cc
gonmator/c-aff4
e5e148960d4e0155df376b376ac7162b97829961
[ "Apache-2.0" ]
29
2018-05-11T05:40:43.000Z
2021-11-22T10:54:55.000Z
#include <gtest/gtest.h> #include "aff4/libaff4.h" #include <unistd.h> #include <glog/logging.h> #include "utils.h" namespace aff4 { class AFF4MapTest: public ::testing::Test { protected: std::string filename = "/tmp/aff4_test.zip"; std::string source_filename = "/tmp/source.txt"; std::string image_name = "image.dd"; URN volume_urn; URN image_urn; URN image_urn_streamed; // Remove the file on teardown. virtual void TearDown() { unlink(filename.c_str()); unlink(source_filename.c_str()); } // Create a sparse AFF4Map stream with some data in it. virtual void SetUp() { MemoryDataStore resolver; AFF4Flusher<AFF4Stream> file; AFF4Flusher<ZipFile> zip; EXPECT_OK(NewFileBackedObject(&resolver, filename, "truncate", file)); EXPECT_OK(ZipFile::NewZipFile(&resolver, std::move(file), zip)); // Store the URN for the test to use. volume_urn = zip->urn; image_urn = volume_urn.Append(image_name); // Write Map image sequentially (Seek/Write method). { AFF4Flusher<AFF4Stream> data_stream; EXPECT_OK(AFF4Image::NewAFF4Image( &resolver, image_urn.Append("data"), zip.get(), data_stream)); AFF4Flusher<AFF4Map> image; EXPECT_OK(AFF4Map::NewAFF4Map( &resolver, image_urn, zip.get(), data_stream.get(), image)); resolver.logger->debug("Datastream urn {}", data_stream->urn); // Maps are written in random order. image->Seek(50, SEEK_SET); image->Write("XX - This is the position."); image->Seek(0, SEEK_SET); image->Write("00 - This is the position."); // We can "overwrite" data by writing the same range again. image->Seek(50, SEEK_SET); image->Write("50"); } // Test the Stream method. { image_urn_streamed = image_urn.Append("streamed"); // First create a stream and add some data in it. AFF4Flusher<AFF4Stream> source(new StringIO(&resolver)); // Fill it with data. source->Write("AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHH"); // Make a temporary map that defines our plan. AFF4Flusher<AFF4Map> helper_map(new AFF4Map(&resolver)); helper_map->AddRange(4, 0, 4, source.get()); // 0000AAAA helper_map->AddRange(0, 12, 4, source.get()); // DDDDAAAA helper_map->AddRange(12, 16, 4, source.get()); // DDDDAAAA0000EEEE AFF4Flusher<AFF4Map> image; EXPECT_OK(AFF4Map::NewAFF4Map( &resolver, image_urn_streamed, zip.get(), nullptr, image)); // Now we create the real map by copying the temporary map stream. DefaultProgress default_progress(&resolver); EXPECT_OK( AFF4Map::CopyStreamFromMap(helper_map.get(), image.get(), &default_progress)); } } }; TEST_F(AFF4MapTest, TestAddRange) { MemoryDataStore resolver; AFF4Flusher<AFF4Stream> file; AFF4Flusher<AFF4Volume> zip; EXPECT_OK(NewFileBackedObject(&resolver, filename, "read", file)); EXPECT_OK(ZipFile::OpenZipFile(&resolver, std::move(file), zip)); AFF4Flusher<AFF4Stream> a(new StringIO(&resolver)); AFF4Flusher<AFF4Stream> b(new StringIO(&resolver)); AFF4Flusher<AFF4Stream> devnul(new StringIO(&resolver)); AFF4Flusher<AFF4Map> map; EXPECT_OK(AFF4Map::NewAFF4Map( &resolver, image_urn, zip.get(), devnul.get(), map)); // First test - overlapping regions: map->AddRange(0, 0, 100, a.get()); map->AddRange(10, 10, 100, a.get()); // Should be merged into a single range. auto ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 1); EXPECT_EQ(ranges[0].length, 110); map->Clear(); // Repeating regions - should not be merged but first region should be // truncated. map->AddRange(0, 0, 100, a.get()); map->AddRange(50, 0, 100, a.get()); ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 2); EXPECT_EQ(ranges[0].length, 50); // Inserted region. Should split existing region into three. map->Clear(); map->AddRange(0, 0, 100, a.get()); map->AddRange(50, 0, 10, b.get()); ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 3); EXPECT_EQ(ranges[0].length, 50); EXPECT_EQ(ranges[0].target_id, 0); EXPECT_EQ(ranges[1].length, 10); EXPECT_EQ(ranges[1].target_id, 1); EXPECT_EQ(ranges[2].length, 40); EXPECT_EQ(ranges[2].target_id, 0); // New range overwrites all the old ranges. map->AddRange(0, 0, 100, b.get()); ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 1); EXPECT_EQ(ranges[0].length, 100); EXPECT_EQ(ranges[0].target_id, 1); // Simulate writing contiguous regions. These should be merged into a single // region automatically. map->Clear(); map->AddRange(0, 100, 10, a.get()); map->AddRange(10, 110, 10, a.get()); map->AddRange(20, 120, 10, a.get()); map->AddRange(30, 130, 10, a.get()); ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 1); EXPECT_EQ(ranges[0].length, 40); EXPECT_EQ(ranges[0].target_id, 0); // Writing sparse image. map->Clear(); map->AddRange(0, 100, 10, a.get()); map->AddRange(30, 130, 10, a.get()); ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 2); EXPECT_EQ(ranges[0].length, 10); EXPECT_EQ(ranges[0].target_id, 0); EXPECT_EQ(ranges[1].length, 10); EXPECT_EQ(ranges[1].map_offset, 30); EXPECT_EQ(ranges[1].target_id, 0); // Now merge. Adding the missing region makes the image not sparse. map->AddRange(10, 110, 20, a.get()); ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 1); EXPECT_EQ(ranges[0].length, 40); } TEST_F(AFF4MapTest, CreateMapStream) { MemoryDataStore resolver; AFF4Flusher<AFF4Stream> file; AFF4Flusher<AFF4Volume> zip; EXPECT_OK(NewFileBackedObject(&resolver, filename, "read", file)); EXPECT_OK(ZipFile::OpenZipFile(&resolver, std::move(file), zip)); VolumeGroup volumes(&resolver); volumes.AddVolume(std::move(zip)); AFF4Flusher<AFF4Map> map; EXPECT_OK(AFF4Map::OpenAFF4Map( &resolver, image_urn, &volumes, map)); map->Seek(50, SEEK_SET); EXPECT_STREQ(map->Read(2).c_str(), "50"); map->Seek(0, SEEK_SET); EXPECT_STREQ(map->Read(2).c_str(), "00"); std::vector<Range> ranges = map->GetRanges(); EXPECT_EQ(ranges.size(), 3); EXPECT_EQ(ranges[0].length, 26); EXPECT_EQ(ranges[0].map_offset, 0); EXPECT_EQ(ranges[0].target_offset, 26); // This is the extra "overwritten" 2 bytes which were appended to the end of // the target stream and occupy the map range from 50-52. EXPECT_EQ(ranges[1].length, 2); EXPECT_EQ(ranges[1].map_offset, 50); EXPECT_EQ(ranges[1].target_offset, 52); EXPECT_EQ(ranges[2].length, 24); EXPECT_EQ(ranges[2].map_offset, 52); EXPECT_EQ(ranges[2].target_offset, 2); // Test that reads outside the ranges null pad correctly. map->Seek(48, SEEK_SET); std::string read_string = map->Read(4); EXPECT_EQ(read_string[0], 0); EXPECT_EQ(read_string[1], 0); EXPECT_EQ(read_string[2], '5'); EXPECT_EQ(read_string[3], '0'); { AFF4Flusher<AFF4Map> streamed_map; EXPECT_OK(AFF4Map::OpenAFF4Map( &resolver, image_urn_streamed, &volumes, streamed_map)); EXPECT_EQ(streamed_map->Size(), 16); read_string = streamed_map->Read(1000); EXPECT_EQ(read_string, std::string("DDDDAAAA\0\0\0\0EEEE", 16)); } // Check the untransformed data stream - it is written in the same order as // the ranges are given. { AFF4Flusher<AFF4Image> map_data; EXPECT_OK(AFF4Image::OpenAFF4Image( &resolver, image_urn.Append("streamed").Append("data"), &volumes, map_data)); std::string read_string = map_data->Read(1000); EXPECT_STREQ(read_string.c_str(), "DDDDAAAAEEEE"); } } } // namespace aff4
29.730337
78
0.643361
[ "vector" ]
5b9a31da1ddc2c7017a6590c3eb4881ff25bb54b
8,358
cpp
C++
core/conn/odbc/src/odbc/EventMsgs/odbceventmsgutil.cpp
CoderSong2015/Apache-Trafodion
889631aae9cdcd38fca92418d633f2dedc0be619
[ "Apache-2.0" ]
148
2015-06-18T21:26:04.000Z
2017-12-25T01:47:01.000Z
core/conn/odbc/src/odbc/EventMsgs/odbceventmsgutil.cpp
CoderSong2015/Apache-Trafodion
889631aae9cdcd38fca92418d633f2dedc0be619
[ "Apache-2.0" ]
1,352
2015-06-20T03:05:01.000Z
2017-12-25T14:13:18.000Z
core/conn/odbc/src/odbc/EventMsgs/odbceventmsgutil.cpp
CoderSong2015/Apache-Trafodion
889631aae9cdcd38fca92418d633f2dedc0be619
[ "Apache-2.0" ]
166
2015-06-19T18:52:10.000Z
2017-12-27T06:19:32.000Z
/************************************************************************* * // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ **************************************************************************/ // // FILE: odbcEventMsgUtil.cpp // #include "tdm_logevent.h" #include "tdm_odbcSrvrMsg.h" #include "odbcEventMsgUtil.h" #define EVENTMSG_ERROR_MSGBOX_TITLE "ODBC/MX Event Message Handling Error" LogEvent *EventLogPtr = NULL; ////////////////////////////////////////////////////////////////////////// // // Name: DllMain // // Purpose: Initialize the logging class // // Input: None // // Output: TRUE for success // FALSE for failure // ////////////////////////////////////////////////////////////////////////// BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { HMODULE msgHandle = (HMODULE)(INVALID_HANDLE_VALUE); const char evSource[] = { "ODBC/MX" }; char msgFile[MAX_PATH+1]; BOOL result; DWORD retLength; msgFile[0] = '\0'; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // Create an instance of the LogEvent class. EventLogPtr = new LogEvent(); // Ensure that the new operation is successful. if (!EventLogPtr) return TRUE; // Get a handle to our message DLL. msgHandle = LoadLibrary("tdm_odbcSrvrMsg_intl.dll"); if (!msgHandle) { PVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL); ///////////////////////////////////////////////////////////////////////// // Note: MessageBox call is a temporary solution for now. // We need to change this call later when ODBC is starting as a service. ///////////////////////////////////////////////////////////////////////// #ifdef _DEBUG MessageBox(NULL, (const char*) lpMsgBuf, EVENTMSG_ERROR_MSGBOX_TITLE, MB_TASKMODAL | MB_SERVICE_NOTIFICATION); MessageBox(NULL, "Load Library of tdm_odbcSevrMsg_init.dll failed", EVENTMSG_ERROR_MSGBOX_TITLE, MB_TASKMODAL | MB_SERVICE_NOTIFICATION); #endif LocalFree(lpMsgBuf); } else { if ((retLength = GetModuleFileName(msgHandle, msgFile, sizeof(msgFile))) == 0) { PVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL); ///////////////////////////////////////////////////////////////////////// // Note: MessageBox call is a temporary solution for now. // We need to change this call later when ODBC is starting as a service. ///////////////////////////////////////////////////////////////////////// #ifdef _DEBUG MessageBox(NULL, (const char*) lpMsgBuf, EVENTMSG_ERROR_MSGBOX_TITLE, MB_TASKMODAL | MB_SERVICE_NOTIFICATION); MessageBox(NULL, "GetModuleFileName failed", EVENTMSG_ERROR_MSGBOX_TITLE, MB_TASKMODAL | MB_SERVICE_NOTIFICATION); #endif LocalFree(lpMsgBuf); } else { // Don't be tempted to close the DLL handle -- bad things happen. // Now register the event source with this DLL as the message store // If Registration fails in the debug mode, a message box will be displayed. if (!(result = EventLogPtr->Registration( msgFile , evSource ))) { #ifdef _DEBUG MessageBox(NULL, "Registration of tdm_odbcSevrMsg_init.dll failed", EVENTMSG_ERROR_MSGBOX_TITLE, MB_TASKMODAL | MB_SERVICE_NOTIFICATION); #endif delete EventLogPtr; EventLogPtr = NULL; } } } return TRUE; case DLL_PROCESS_DETACH: if (EventLogPtr) { // Finally, before the program terminates, it's nice to clean up. EventLogPtr->DeRegister(); delete EventLogPtr; EventLogPtr = NULL; } return TRUE; default: return TRUE; } } ////////////////////////////////////////////////////////////////////////// // // Name: SendODBCEventMsg // // Purpose: Add a specified type of parameter to an event. // This logs a message with (any) token parameters previously // specified by the Add* methods. // // Note: Parameters in event messages are specified in the message // template by using the form "%n", where "n" indicates the // relative call to AddToken which supplies the value for the // parameter. Thus, the first AddToken call will provide the // value for token %1, the second for token %2, etc. // The maximum number of tokens is defined in teventlog.h. // Token is a null-terminated string that becomes the parameter // value. // // Input: EventId - numeric value for the event. This corresponds // to the value defined by the message compiler for // the event. // EventLogType - The type of the event being logged // (e.g., EVENTLOG_INFORMATION_TYPE, // EVENTLOG_WARNING_TYPE, and // EVENTLOG_ERROR_TYPE) // Pid - Process ID // ComponentName - ODBC/MX Component (e.g., Association Server) // ObjectRef - Object Reference // nToken - Number of additional tokens // // Output: None // ////////////////////////////////////////////////////////////////////////// extern "C" void SendODBCEventMsg(DWORD EventId, short EventLogType, DWORD Pid, char *ComponentName, char *ObjectRef, char *ClusterName, int NodeId, short nToken, va_list vl) { BOOL result = FALSE; char *TokenPtr; if (!EventLogPtr) return; // Provide an EventID number to be used with the "logging resumed" // event. This event is posted if logging becomes enabled after it had been // previously disabled due to a resource constraint, such as the log being full. // If not invoked, then no event is generated under these conditions. EventLogPtr->SetResumeEvent(LogEventLoggingResumed); ////////////////////////////////////////////////////////// // Note: // AddInteger and AddToken will display a message box // for the debug version if an error occurred. // Therefore, we do not need to show the reason here; // we can just simply "return." ////////////////////////////////////////////////////////// // Pid is %1. if (Pid != 0) { if (!(result = EventLogPtr->AddInteger(Pid))) return; } // ComponentName is %2. if (ComponentName != NULL) { if (!(result = EventLogPtr->AddToken(ComponentName))) return; } // ObjectRef is %3. if (ObjectRef != NULL) { if (!(result = EventLogPtr->AddToken(ObjectRef))) return; } // ClusterName is %4. if (ClusterName!= NULL) { if (!(result = EventLogPtr->AddToken(ClusterName))) return; } // NodeId is %5 if (NodeId != -1) { if (!(result = EventLogPtr->AddInteger(NodeId))) return; } else { char szNodeId[20]; strcpy(szNodeId, "Unknown"); if (!(result = EventLogPtr->AddToken(szNodeId))) return; } for (int i = 0; i<nToken; i++) { // Process additional tokens. // Start with %6, ... TokenPtr = va_arg(vl, char *); if (!(result = EventLogPtr->AddToken( TokenPtr))) { // An error has occurred. va_end(vl); return; } } // Now log the event. EventLogPtr->Send( EventId, EventLogType ); va_end(vl); }
29.223776
84
0.59105
[ "object" ]
5b9d974e390178d7339dd5ef007d9201c7155214
9,346
c++
C++
src/extern/inventor/apps/examples/Toolmaker/04.Actions/GetVolumeAction.c++
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/extern/inventor/apps/examples/Toolmaker/04.Actions/GetVolumeAction.c++
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/extern/inventor/apps/examples/Toolmaker/04.Actions/GetVolumeAction.c++
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /*-------------------------------------------------------------- * This is an example from the Inventor Toolmaker, * chapter 4, example 2. * * Source file for "GetVolumeAction" action. *------------------------------------------------------------*/ #include <Inventor/elements/SoComplexityElement.h> #include <Inventor/elements/SoComplexityTypeElement.h> #include <Inventor/elements/SoCoordinateElement.h> #include <Inventor/elements/SoElements.h> #include <Inventor/elements/SoFontNameElement.h> #include <Inventor/elements/SoFontSizeElement.h> #include <Inventor/elements/SoModelMatrixElement.h> #include <Inventor/elements/SoProfileCoordinateElement.h> #include <Inventor/elements/SoProfileElement.h> #include <Inventor/elements/SoSwitchElement.h> #include <Inventor/elements/SoUnitsElement.h> #include <Inventor/elements/SoViewVolumeElement.h> #include <Inventor/elements/SoViewingMatrixElement.h> #include <Inventor/elements/SoViewportRegionElement.h> #include <Inventor/nodes/SoCamera.h> #include <Inventor/nodes/SoComplexity.h> #include <Inventor/nodes/SoCoordinate3.h> #include <Inventor/nodes/SoCoordinate4.h> #include <Inventor/nodes/SoCube.h> #include <Inventor/nodes/SoFont.h> #include <Inventor/nodes/SoGroup.h> #include <Inventor/nodes/SoProfile.h> #include <Inventor/nodes/SoProfileCoordinate2.h> #include <Inventor/nodes/SoProfileCoordinate3.h> #include <Inventor/nodes/SoSphere.h> #include <Inventor/nodes/SoTransformation.h> #include "GetVolumeAction.h" SO_ACTION_SOURCE(GetVolumeAction); // // Initializes the GetVolumeAction class. This is a one-time // thing that is done after database initialization and before // any instance of this class is constructed. // void GetVolumeAction::initClass() { // Initialize the run-time type variables SO_ACTION_INIT_CLASS(GetVolumeAction, SoAction); // Enable elements that are involved in volume computation. // Most of these deal with geometrix properties // (coordinates, profiles) or transformations (model matrix, // units). Some are needed for certain groups (switches, // level-of-detail) to function correctly. SO_ENABLE(GetVolumeAction, SoModelMatrixElement); SO_ENABLE(GetVolumeAction, SoComplexityElement); SO_ENABLE(GetVolumeAction, SoComplexityTypeElement); SO_ENABLE(GetVolumeAction, SoCoordinateElement); SO_ENABLE(GetVolumeAction, SoFontNameElement); SO_ENABLE(GetVolumeAction, SoFontSizeElement); SO_ENABLE(GetVolumeAction, SoProfileCoordinateElement); SO_ENABLE(GetVolumeAction, SoProfileElement); SO_ENABLE(GetVolumeAction, SoSwitchElement); SO_ENABLE(GetVolumeAction, SoUnitsElement); SO_ENABLE(GetVolumeAction, SoViewVolumeElement); SO_ENABLE(GetVolumeAction, SoViewingMatrixElement); SO_ENABLE(GetVolumeAction, SoViewportRegionElement); // Now we need to register methods to implement this action // for various node classes. We have created implementations // for two specific shape nodes, SoCube and SoSphere, so we // can register specific methods for those two classes. We // also want to make sure that group classes traverse their // children correctly for this action, so we will use a // method that calls doAction() to handle groups. Finally, // we need to make sure that relevant property nodes set up // the state correctly; we can use the same method that // calls doAction() for these classes, as well. We will use // the SO_ACTION_ADD_METHOD() macro to make this easier. // This registers a method to call for SoNode, so it will be // used for any node class that does not have a more // specific method registered for it. This makes sure that // there is always a method to call for any node. The // "nullAction" method is defined on SoAction for use in // cases like this. SO_ACTION_ADD_METHOD(SoNode, nullAction); // These register methods for the two shapes that can // really handle the action SO_ACTION_ADD_METHOD(SoCube, cubeVolume); SO_ACTION_ADD_METHOD(SoSphere, sphereVolume); // Register the method that calls doAction() for all group // classes and for relevant properties (transformations, // coordinates, profiles, and so on). SO_ACTION_ADD_METHOD(SoCamera, callDoAction); SO_ACTION_ADD_METHOD(SoComplexity, callDoAction); SO_ACTION_ADD_METHOD(SoCoordinate3, callDoAction); SO_ACTION_ADD_METHOD(SoCoordinate4, callDoAction); SO_ACTION_ADD_METHOD(SoFont, callDoAction); SO_ACTION_ADD_METHOD(SoGroup, callDoAction); SO_ACTION_ADD_METHOD(SoProfile, callDoAction); SO_ACTION_ADD_METHOD(SoProfileCoordinate2, callDoAction); SO_ACTION_ADD_METHOD(SoProfileCoordinate3, callDoAction); SO_ACTION_ADD_METHOD(SoTransformation, callDoAction); } // // Constructor // GetVolumeAction::GetVolumeAction() { SO_ACTION_CONSTRUCTOR(GetVolumeAction); } // // Destructor. Does nothing. // GetVolumeAction::~GetVolumeAction() { } // // Initiates action on a graph. This is called when the action // is applied to a node, a path, or a path list. It gives us a // chance to initialize things before beginning traversal. // void GetVolumeAction::beginTraversal(SoNode *node) { // Initialize volume to 0 volume = 0.0; // Begin traversal at the given root node. traverse(node); } // // This method implements the action for an SoCube node. // void GetVolumeAction::cubeVolume(SoAction *action, SoNode *node) { // The action is really an instance of GetVolumeAction GetVolumeAction *volumeAct = (GetVolumeAction *) action; // And the node pointer is really a cube: const SoCube *cube = (const SoCube *) node; // Find the dimensions of the cube float width = (cube->width.isIgnored() ? 2.0 : cube->width.getValue()); float height = (cube->height.isIgnored() ? 2.0 : cube->height.getValue()); float depth = (cube->depth.isIgnored() ? 2.0 : cube->depth.getValue()); // ...and the volume float cubeVol = width * height * depth; // Add the volume to the accumulated volume in the action volumeAct->addVolume(cubeVol); } // // This method implements the action for an SoSphere node. // void GetVolumeAction::sphereVolume(SoAction *action, SoNode *node) { // The action is really an instance of GetVolumeAction GetVolumeAction *volumeAct = (GetVolumeAction *) action; // And the node pointer is really a sphere: const SoSphere *sphere = (const SoSphere *) node; // Find the radius of the sphere float radius = (sphere->radius.isIgnored() ? 1.0 : sphere->radius.getValue()); // Compute the volume using our favorite formula that we all // remember from our math classes, right? float sphereVol = 4./3. * M_PI * radius * radius * radius; // Add the volume to the accumulated volume in the action volumeAct->addVolume(sphereVol); } // // This method implements the action for all of the relevant // non-shape node classes. // void GetVolumeAction::callDoAction(SoAction *action, SoNode *node) { node->doAction(action); } // // This adds the given object-space volume to the total, first // converting it to world space using the current model matrix. // void GetVolumeAction::addVolume(float objectSpaceVolume) { // Find the current modeling matrix const SbMatrix &modelMatrix = SoModelMatrixElement::get(state); // The determinant of the upper-left 3x3 of this matrix is // the conversion factor we need to go from object-space // volume to world space. Pretty cool, indeed. float objectToWorldFactor = modelMatrix.det3(); // Add in the converted volume to our current volume volume += objectToWorldFactor * objectSpaceVolume; }
35.671756
77
0.720415
[ "object", "shape", "model" ]
5ba2996410490772999c1eeaf6d86c26c4384e6d
2,388
cpp
C++
helper/main.cpp
yak1ex/UTF8-Win32API
a320d71ff8d04f1b7a3d28222e832648eca97480
[ "BSD-2-Clause" ]
2
2015-12-01T14:56:09.000Z
2017-04-29T20:05:26.000Z
helper/main.cpp
yak1ex/UTF8-Win32API
a320d71ff8d04f1b7a3d28222e832648eca97480
[ "BSD-2-Clause" ]
null
null
null
helper/main.cpp
yak1ex/UTF8-Win32API
a320d71ff8d04f1b7a3d28222e832648eca97480
[ "BSD-2-Clause" ]
null
null
null
#include <windows.h> #include "helper/win32u_helper.hpp" #include <vector> int _umain_stub() { return 0; } extern "C" int _umain(...) __attribute__((weak, alias("_Z11_umain_stubv"))); extern int _umain() __attribute__((weak, alias("_Z11_umain_stubv"))); extern int _umain(int argc) __attribute__((weak, alias("_Z11_umain_stubv"))); extern int _umain(int argc, char ** argv) __attribute__((weak, alias("_Z11_umain_stubv"))); extern int _umain(int argc, char ** argv, char **envp) __attribute__((weak, alias("_Z11_umain_stubv"))); static int(*ptr_umain)(...) = static_cast<int(*)(...)>(_umain); static int(*ptr_umain0)() = static_cast<int(*)()>(_umain); static int(*ptr_umain1)(int) = static_cast<int(*)(int)>(_umain); static int(*ptr_umain2)(int, char**) = static_cast<int(*)(int, char**)>(_umain); static int(*ptr_umain3)(int, char**, char**) = static_cast<int(*)(int, char**, char**)>(_umain); extern LPSTR* _uenviron; extern void UpdateEnviron(); template<typename T> static inline bool is_target(T t) { return t != reinterpret_cast<T>(_umain_stub); } int main(void) { // NOTE: A static initializer calls CreateEnviron(), thus the below line is not required. // UpdateEnviron(); // No arguments if(is_target(ptr_umain0)) { return ptr_umain0(); } // 1 argument int argc; LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); if(is_target(ptr_umain1)) { return ptr_umain1(argc); } // 2 arguments std::vector<std::size_t> uargv_idx; std::vector<char> uargv_body; int nLen = 0; for(int i = 0; i < argc; ++i) { uargv_idx.push_back(nLen); nLen += win32u::UTF8Length(argv[i]); } uargv_idx.push_back(nLen); uargv_body.reserve(nLen); for(int i = 0; i < argc; ++i) { uargv_body.resize(uargv_idx[i+1]); win32u::ToUTF8(&uargv_body[0] + uargv_idx[i], uargv_idx[i+1] - uargv_idx[i], argv[i]); } std::vector<char*> uargv; for(int i = 0; i < argc; ++i) { uargv.push_back(&uargv_body[0] + uargv_idx[i]); } uargv.push_back(0); if(is_target(ptr_umain2)) { return ptr_umain2(argc, &uargv[0]); } // 3 arguments if(is_target(ptr_umain3)) { return ptr_umain3(argc, &uargv[0], _uenviron); } if(is_target(ptr_umain)) { return ptr_umain(argc, &uargv[0], _uenviron); } return -1; // Not reached }
29.121951
105
0.640704
[ "vector" ]
5baaebae3a5ad9afcd76e0bcfa6908217877a9d3
1,800
cpp
C++
project-template/lib/app/GuiBuilder.cpp
nerudaj/dgm-sdk
3d0366487a2f4377ba52ab577f990fd8a4bd3e91
[ "Apache-2.0" ]
null
null
null
project-template/lib/app/GuiBuilder.cpp
nerudaj/dgm-sdk
3d0366487a2f4377ba52ab577f990fd8a4bd3e91
[ "Apache-2.0" ]
null
null
null
project-template/lib/app/GuiBuilder.cpp
nerudaj/dgm-sdk
3d0366487a2f4377ba52ab577f990fd8a4bd3e91
[ "Apache-2.0" ]
null
null
null
#include "GuiBuilder.hpp" tgui::Label::Ptr WidgetCreator::createLabel(const std::string& text, unsigned fontSize) { auto label = tgui::Label::create(text); label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Left); label->setVerticalAlignment(tgui::Label::VerticalAlignment::Center); label->setAutoSize(false); label->setTextSize(fontSize); return label; } tgui::CheckBox::Ptr WidgetCreator::createCheckbox(bool checked, std::function<void(bool)> onChange) { auto checkbox = tgui::CheckBox::create(); checkbox->setChecked(checked); checkbox->connect("Changed", onChange); return checkbox; } tgui::Slider::Ptr WidgetCreator::createSlider(float value, std::function<void(void)> onChange, float lo, float hi, float step) { auto slider = tgui::Slider::create(lo, hi); slider->setStep(step); slider->setValue(value); slider->connect("ValueChanged", onChange); return slider; } tgui::ComboBox::Ptr WidgetCreator::createDropdown(const std::vector<std::string>& items, const std::string& selected, std::function<void(void)> onSelect) { auto dropdown = tgui::ComboBox::create(); for (auto& item : items) { dropdown->addItem(item, item); } dropdown->setSelectedItem(selected); dropdown->connect("ItemSelected", onSelect); return dropdown; } void GuiOptionsBuilder::build() { auto size = rowContainer->getSize(); labelFontSize = size.y / rowsToBuild.size() * 0.8f; for (auto&& [name, id, widget] : rowsToBuild) { auto row = tgui::HorizontalLayout::create(); rowContainer->add(row); auto label = WidgetCreator::createLabel(name, labelFontSize); row->add(label); row->setRatio(0, 0.5f); row->add(widget, id); if (id.starts_with("Checkbox")) { row->setRatio(1, 0.1f); row->insertSpace(2, 0.4f); } else { row->setRatio(1, 0.5f); } } }
28.571429
155
0.711667
[ "vector" ]
5bae5f82ccefa4dd4e73a8e3279c965aee57dd58
5,144
cpp
C++
modules/Components/Scene.cpp
xenginez/XE
7f536c906460c7062cad5b8e09a644812cabf6d3
[ "MIT" ]
2
2019-06-10T06:51:27.000Z
2021-11-20T19:57:46.000Z
modules/Components/Scene.cpp
xenginez/XE
7f536c906460c7062cad5b8e09a644812cabf6d3
[ "MIT" ]
1
2019-07-12T03:05:02.000Z
2019-08-12T12:01:06.000Z
modules/Components/Scene.cpp
xenginez/XE
7f536c906460c7062cad5b8e09a644812cabf6d3
[ "MIT" ]
null
null
null
#include "Scene.h" #include "World.h" #include "GameObject.h" BEG_META( Components::Scene ) REG_PROPERTY( "Children", &Components::Scene::_Children )->Attribute( XE::NonEditorAttribute() ); REG_PROPERTY( "Transform", &Components::Scene::_Transform ); END_META() Components::Scene::Scene() { } Components::Scene::~Scene() { } XE::AABB Components::Scene::GetBoundingBox() { XE::AABB boundbox; for( auto & child : _Children ) { boundbox.Merge( child->GetBoundingBox() ); } return boundbox; } Components::ScenePtr Components::Scene::GetRoot() { if( auto parent = GetParent() ) { return parent->GetRoot(); } return XE_THIS( Components::Scene ); } Components::ScenePtr Components::Scene::GetParent() const { return _Parent.lock(); } const XE::Transform & Components::Scene::GetTransform() const { return _Transform; } const XE::Array< Components::ScenePtr > & Components::Scene::GetChildren() const { return _Children; } void Components::Scene::Translate( const XE::Vec3f & val ) { _Transform.Translate( val ); } void Components::Scene::Rotate( const XE::Quat & val ) { _Transform.Rotate( val ); } void Components::Scene::Scale( const XE::Vec3f & val ) { _Transform.Scale( val ); } XE::Vec3d Components::Scene::GetWorldPosition() const { return _Transform.GetWorldPosition(); } void Components::Scene::SetWorldPosition( const XE::Vec3d & val ) { _Transform.SetWorldPosition( val ); } XE::Quat Components::Scene::GetWorldRotation() const { return _Transform.GetWorldRotation(); } void Components::Scene::SetWorldRotation( const XE::Quat & val ) { _Transform.SetWorldRotation( val ); } XE::Vec3d Components::Scene::GetWorldScale() const { return _Transform.GetWorldScale(); } void Components::Scene::SetWorldScale( const XE::Vec3d & val ) { _Transform.SetWorldScale( val ); } XE::Mat4x4d Components::Scene::GetWorldTransform() const { return _Transform.GetWorldTransform(); } void Components::Scene::SetWorldTransform( const XE::Mat4x4d & val ) { _Transform.SetWorldTransform( val ); } const XE::Vec3f & Components::Scene::GetRelativePosition() const { return _Transform.GetRelativePosition(); } void Components::Scene::SetRelativePosition( const XE::Vec3f & val ) { _Transform.SetRelativePosition( val ); } const XE::Quat & Components::Scene::GetRelativeRotation() const { return _Transform.GetRelativeRotation(); } void Components::Scene::SetRelativeRotation( const XE::Quat & val ) { _Transform.SetRelativeRotation( val ); } const XE::Vec3f & Components::Scene::GetRelativeScale() const { return _Transform.GetRelativeScale(); } void Components::Scene::SetRelativeScale( const XE::Vec3f & val ) { _Transform.SetRelativeScale( val ); } const XE::Mat4x4f & Components::Scene::GetRelativeTransform() const { return _Transform.GetRelativeTransform(); } void Components::Scene::SetRelativeTransform( const XE::Mat4x4f & val ) { _Transform.SetRelativeTransform( val ); } Components::ScenePtr Components::Scene::FindChild( const XE::String & val ) const { for( auto child : _Children ) { if( child->GetName() == val ) { return child; } } return nullptr; } Components::ScenePtr Components::Scene::FindChild( XE::MetaClassPtr val ) const { for( auto child : _Children ) { if( child->GetMetaClass()->CanConvert( val ) ) { return child; } } return nullptr; } Components::ScenePtr Components::Scene::FindChild( Components::ComponentHandle val ) const { for( auto child : _Children ) { if( child->GetHandle() == val ) { return child; } } return nullptr; } Components::ScenePtr Components::Scene::FindChildFromTree( const XE::String & val ) const { if( auto child = FindChild( val ) ) { return child; } for( auto child : _Children ) { if( auto ret = child->FindChildFromTree( val ) ) { return ret; } } return nullptr; } Components::ScenePtr Components::Scene::FindChildFromTree( XE::MetaClassPtr val ) const { if( auto child = FindChild( val ) ) { return child; } for( auto child : _Children ) { if( auto ret = child->FindChildFromTree( val ) ) { return ret; } } return nullptr; } Components::ScenePtr Components::Scene::FindChildFromTree( Components::ComponentHandle val ) const { if( auto child = FindChild( val ) ) { return child; } for( auto child : _Children ) { if( auto ret = child->FindChildFromTree( val ) ) { return ret; } } return nullptr; } void Components::Scene::Startup() { for( auto child : _Children ) { child->_Parent = XE_THIS( Components::Scene ); child->_Transform.SetParent( &_Transform ); } Super::Startup(); for( auto child : _Children ) { child->Startup(); } } void Components::Scene::Update( XE::float32 dt ) { if( GetEnabled() == false ) { return; } OnUpdate( dt ); for( auto child : _Children ) { child->Update( dt ); } } void Components::Scene::LateUpdate( XE::float32 dt ) { if( GetEnabled() == false ) { return; } OnLateUpdate( dt ); for( auto child : _Children ) { child->LateUpdate( dt ); } } void Components::Scene::Clearup() { for( auto child : _Children ) { child->Clearup(); } Super::Clearup(); }
17.033113
98
0.688764
[ "transform" ]
5bb3f9b3941acaab62669df96bce2297a00d2839
5,877
hpp
C++
MuPad/MuPadConvert.hpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
2
2015-04-02T21:45:49.000Z
2018-09-19T01:59:02.000Z
MuPad/MuPadConvert.hpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
null
null
null
MuPad/MuPadConvert.hpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
null
null
null
/* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2004 Michael Stevens * See accompanying Bayes++.html for terms and conditions of use. */ /* * Bayesian_filter_matrix <-> MuPAD conversions * Many MuPAD function use long, we assume long === int */ namespace MuPAD_convert { template <class FilterMatrix> MTcell List(const FilterMatrix& M) /* * Convert Filter Matrix into a MuPAD list */ { MTcell mpList = MFnewList(M.size1()); // creates a MuPAD list of lists for (unsigned r = 0; r < M.size1(); ++r) { // creates a MuPAD list MTcell colList = MFnewList(M.size2()); for (unsigned c = 0; c < M.size2(); ++c) { MFsetList( &colList, c, MFdouble(M(r,c))); } MFsig(colList); MFsetList (&mpList, r, colList); } MFsig (mpList); // calculates the signature of the list return mpList; } template <> MTcell List(const Bayesian_filter_matrix::Vec& V) /* * Convert Vector into a MuPAD list */ { MTcell mpList = MFnewList(V.size()); // creates a MuPAD list for (unsigned r = 0; r < V.size(); ++r) { MFsetList (&mpList, r, MFdouble(V[r]) ); } MFsig (mpList); // calculates the signature of the list return mpList; } template <class FilterMatrix> MTcell ListTranspose(const FilterMatrix& M) /* * Convert Filter Matrix's transpose into a MuPAD list */ { MTcell mpList = MFnewList(M.size2()); // creates a MuPAD list of lists for (unsigned r = 0; r < M.size2(); ++r) { // creates a MuPAD list MTcell colList = MFnewList(M.size1()); for (unsigned c = 0; c < M.size1(); ++c) { MFsetList( &colList, c, MFdouble(M(c,r))); } MFsig(colList); MFsetList (&mpList, r, colList); } MFsig (mpList); // calculates the signature of the list return mpList; } template <class FilterMatrix> MTcell Array(const FilterMatrix& M) /* * Convert Filter Matrix into a MuPAD Array */ { MTcell mpList = List(M); // Convert to array MTcell mpArray = MFlist2array(mpList, M.size1(),M.size2()); MFfree(mpList); return mpArray; } template <> MTcell Array(const Bayesian_filter_matrix::Vec& V) /* * Convert Vector into a MuPAD Array */ { MTcell mpList = List(V); // Convert to array MTcell mpArray = MFlist2array(mpList, V.size()); MFfree(mpList); return mpArray; } template <class FilterMatrix> MTcell ArrayTranspose(const FilterMatrix& M) /* * Convert Filter Matrix's transpose into a MuPAD Array */ { MTcell mpList = ListTranspose(M); // Convert to array MTcell mpArray = MFlist2array(mpList, M.size2(),M.size1()); MFfree(mpList); return mpArray; } template <class Dummy> Bayesian_filter_matrix::Vec Vector(Dummy); template <> Bayesian_filter_matrix::Vec Vector(MTcell aorl) /* * Convert MuPAD list OR array to a Filter Vector */ { // Check type if (MFisList(aorl)) { // list is simple int size = MFnops(aorl); Bayesian_filter_matrix::Vec V(size); for (int i = 0; i < size; ++i) { V[i] = MFdouble (MFgetList(&aorl,i)); } return V; } else { // not a list, accept 1 dim arrays if (!MFisArray(aorl)) MFerror( "array or list expected" ); int dim = MFdimArray(aorl); if (dim == 1 || dim == 2) { // 1d row Array or 2d col Array long lb, ub; MFrangeArray(aorl, 1, &lb, &ub); int size = (ub-lb+1); if (dim == 2) { MFrangeArray(aorl, 2, &lb, &ub); if ((ub-lb+1) != 1) MFerror( "2d array with 1 column required for vector" ); } MTcell list = MFarray2list(aorl); // extract list into Matrix Bayesian_filter_matrix::Vec V(size); for (int j = 0; j < size; ++j) { V[j] = MFdouble (MFgetList(&list,j)); } MFfree (list); // free list return V; } else { MFerror( "1d or 2d array required for vector" ); // Unreachable Bayesian_filter_matrix::Vec V(Bayesian_filter_matrix::Empty); return V; } } }; template <class Dummy> Bayesian_filter_matrix::Matrix Matrix_from_list(Dummy); template <> Bayesian_filter_matrix::Matrix Matrix_from_list(MTcell list) /* * Convert MuPAD list to a Filter Matrix */ { bool conversionFailed = false; // find size and check all sub-lists of same size? int rows = MFnops(list); int cols; if (MFisList(list)) { if (rows == 0) { cols = 0; } else { cols = MFnops( MFgetList(&list,0) ); for (int i = 0; i < rows && !conversionFailed; ++i) { if (!MFisList(MFgetList(&list,i)) || !MFnops (MFgetList(&list,i)) == cols) { conversionFailed = true; } } } } else conversionFailed = true; if (conversionFailed) MFerror( "Conversion of list of list to Matrix failed" ); Bayesian_filter_matrix::Matrix M(rows, cols); for (int i = 0; i < rows; ++i) { MTcell sublist = MFgetList(&list,i); for (int j = 0; j < cols; ++j) { M(i,j) = MFdouble (MFgetList(&sublist,j)); } } return M; } template <class Dummy> Bayesian_filter_matrix::Matrix Matrix(Dummy); template <> Bayesian_filter_matrix::Matrix Matrix(MTcell aorl) /* * Convert MuPAD list OR array to a Filter Matrix */ { // Check type if (MFisList(aorl)) { // list is simple Bayesian_filter_matrix::Matrix& M = Matrix_from_list(aorl); return M; } else { // not a list, accept 2 dim arrays if (!MFisArray(aorl)) MFerror( "array or list expected" ); int dim = MFdimArray(aorl); if (dim != 2) MFerror( "2d array expected" ); long lb, ub; MFrangeArray(aorl, 1, &lb, &ub); int cols = (ub-lb+1); MFrangeArray(aorl, 2, &lb, &ub); int rows = (ub-lb+1); // convert into list MTcell list = MFarray2list(aorl); // extract list into Matrix Bayesian_filter_matrix::Matrix M(rows, cols); int listit = 0; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { M(i,j) = MFdouble (MFgetList(&list,listit++)); } } MFfree (list); // free list return M; } }; }//namespace MuPAD_convert
20.33564
80
0.631445
[ "vector" ]
5bc0db00c1cebd46e0c909b44119d7f7c4f2727b
754
cpp
C++
Spectrum/Spectrum/Main.cpp
rnsheehan/Spectrum
f5a3db2c7aa9d7197a202d7aa2539950f44b7885
[ "MIT" ]
null
null
null
Spectrum/Spectrum/Main.cpp
rnsheehan/Spectrum
f5a3db2c7aa9d7197a202d7aa2539950f44b7885
[ "MIT" ]
null
null
null
Spectrum/Spectrum/Main.cpp
rnsheehan/Spectrum
f5a3db2c7aa9d7197a202d7aa2539950f44b7885
[ "MIT" ]
null
null
null
#ifndef ATTACH_H #include "Attach.h" #endif // !ATTACH_H // The aim of this project is to implement the code needed to compute the FFT of an arbitrary data set // The data I have in mind is that obtained from a high speed oscilloscope // Generally, the data will be of the form (time_value, voltage_value) // The code for computing the FFT is taken from NRinC, this code adapts an existing code to run using std::vector<double> // One of the tasks required is to determine the SNR of the FFT from the trace data // R. Sheehan 5 - 12 - 2018 int main() { //testing::sample_FFT_calculation(); //testing::laser_FFT(); testing::laser_LLM(); testing::compute_FFT_test(); std::cout << "Press enter to close\n"; std::cin.get(); return 0; }
27.925926
121
0.713528
[ "vector" ]
5bc3c92ec391c1af3f43f6bb05db21a8e9cbbc91
1,523
cpp
C++
c++/sqrt_tree.cpp
forgotter/Snippets
bb4e39cafe7ef2c1ef3ac24b450a72df350a248b
[ "MIT" ]
38
2018-09-17T18:16:24.000Z
2022-02-10T10:26:23.000Z
c++/sqrt_tree.cpp
forgotter/Snippets
bb4e39cafe7ef2c1ef3ac24b450a72df350a248b
[ "MIT" ]
1
2020-10-01T10:48:45.000Z
2020-10-04T11:27:44.000Z
c++/sqrt_tree.cpp
forgotter/Snippets
bb4e39cafe7ef2c1ef3ac24b450a72df350a248b
[ "MIT" ]
12
2018-11-13T13:36:41.000Z
2021-05-02T10:07:44.000Z
/// Name: SQRTTREE /// Description: DS for range-query (without updates). O(1) per query, O(nlogn) for preprocessing. /// Detail: Range Query, Data Structure, Sparse Lookup Table /// Guarantee: } // SQRTTREE inline int op(int val1, int val2) { return (1LL * val1 * val2) % prime; } vector<int> arr; vector<vector<int>> prefix, suffix; void build(int n) { int layers = 0; while ((1 << layers) < n) layers++; layers++; suffix.resize(layers); prefix.resize(layers); for (int i = 0; i < layers; i++) { suffix[i].resize(n); prefix[i].resize(n); } for (int sz = 2, lev = 1; sz <= n; sz <<= 1, lev++) { for (int i = 0; i < n; i += sz) { suffix[lev][i] = arr[i]; for (int j = 1; j < sz; j++) suffix[lev][i + j] = op(suffix[lev][i + j - 1], arr[i + j]); prefix[lev][i + sz - 1] = arr[i + sz - 1]; for (int j = 1; j < sz; j++) prefix[lev][i + sz - 1 - j] = op(prefix[lev][i + sz - j], arr[i + sz - 1 - j]); } } } int query(int l, int r) { if (l == r) return arr[l]; if (l + 1 == r) return op(arr[l], arr[r]); int bit = (l ^ r); int msb = 31 - __builtin_clz(bit); if ((l + (1 << msb - 1) == r) && !((r + 1) % (1 << msb))) { return prefix[msb][l]; } else { return op(prefix[msb][l], suffix[msb][r]); } } // SQRTTREE
24.174603
99
0.443204
[ "vector" ]
5bc56866273eee12f500731fc16cf012678535e6
5,088
cpp
C++
src/main.cpp
RubyNova/Touhou-NovelRT
2ccff45b13462c275822b07fce96377e4a846afa
[ "MIT" ]
null
null
null
src/main.cpp
RubyNova/Touhou-NovelRT
2ccff45b13462c275822b07fce96377e4a846afa
[ "MIT" ]
null
null
null
src/main.cpp
RubyNova/Touhou-NovelRT
2ccff45b13462c275822b07fce96377e4a846afa
[ "MIT" ]
null
null
null
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root for more information. #include <TouhouNovelRT.h> int main(int argc, char *argv[]) { std::filesystem::path executableDirPath = NovelRT::Utilities::Misc::getExecutableDirPath(); std::filesystem::path resourcesDirPath = executableDirPath / "Resources"; std::filesystem::path imagesDirPath = resourcesDirPath / "Images"; std::filesystem::path soundsDirPath = resourcesDirPath / "Sounds"; auto borderPath = (imagesDirPath / "background/default.png"); auto bkPath = imagesDirPath / "background/default_spell1.png"; auto runner = std::make_shared<NovelRT::NovelRunner>(0, "TouhouNovelRT"); auto scene = std::make_unique<TouhouNovelRT::SceneGraph::SimpleScene>(runner, bkPath.string(), borderPath.string(), true); auto audio = runner->getAudioService(); audio.lock()->initializeAudio(); auto bgm = audio.lock()->loadMusic((soundsDirPath / "marisa.ogg").string()); auto playerTransform = NovelRT::Transform(TouhouNovelRT::SceneGraph::SimpleScene::WorldOrigin, 0.0f, NovelRT::Maths::GeoVector<float>(0.0f, 0.0f)); auto playerNode = std::make_shared<TouhouNovelRT::SceneGraph::PlayerNode>(runner, std::shared_ptr(std::move(runner->getRenderer().lock()->createImageRect(playerTransform, 3, NovelRT::Graphics::RGBAConfig(255, 255, 255, 255))))); scene->insert(playerNode); auto bossTransform = NovelRT::Transform(TouhouNovelRT::SceneGraph::SimpleScene::WorldOrigin, 0.0f, NovelRT::Maths::GeoVector<float>(0.0f, 0.0f)); bossTransform.getPosition().setX(bossTransform.getPosition().getX() + (TouhouNovelRT::SceneGraph::SimpleScene::WorldSize.getX() / 3)); auto bossNode = std::make_shared<TouhouNovelRT::SceneGraph::BossNode>(runner, std::shared_ptr(std::move(runner->getRenderer().lock()->createImageRect(bossTransform, 3, NovelRT::Graphics::RGBAConfig(255, 255, 255, 255))))); scene->insert(bossNode); auto playerBulletFactory = TouhouNovelRT::Bullets::BulletFactory(runner, NovelRT::Maths::GeoVector<float>(36.0f, 36.0f), NovelRT::Graphics::RGBAConfig(255, 255, 255, 255), 2, false, (imagesDirPath / "bullet" / "circle" / "small-17.png").string(), bossNode); auto playerBulletEmitter = std::vector<std::shared_ptr<TouhouNovelRT::Bullets::Emitter>>{ std::make_shared<TouhouNovelRT::Bullets::Emitter>(TouhouNovelRT::SceneGraph::SimpleScene::WorldSize.getX() * 0.75f, 1.0f / 15.0f, runner, playerNode, playerBulletFactory) }; auto playerSpellcardFactory = TouhouNovelRT::Bullets::BulletFactory(runner, NovelRT::Maths::GeoVector<float>(36.0f, 36.0f), NovelRT::Graphics::RGBAConfig(255, 255, 255, 255), 2, std::vector<std::string>(), bossNode); auto playerSpellcard = std::make_shared<TouhouNovelRT::Bullets::MarisaSpellcard>(std::make_shared<TouhouNovelRT::Bullets::Emitter>(400.0f, 2.0f, runner, playerNode, playerSpellcardFactory)); auto playerGun = TouhouNovelRT::Player::Gun(playerBulletEmitter, std::shared_ptr<TouhouNovelRT::Bullets::MarisaSpellcard>(playerSpellcard)); auto playerController = TouhouNovelRT::Player::Controller(playerGun, runner.get(), runner->getInteractionService(), playerNode); auto bossBulletMap = std::map<size_t, std::vector<TouhouNovelRT::Bullets::BulletInstanceConfig>>{ { 0, std::vector<TouhouNovelRT::Bullets::BulletInstanceConfig>{ TouhouNovelRT::Bullets::BulletInstanceConfig(NovelRT::Maths::GeoVector<float>(0.0f, 1.0f), NovelRT::Maths::GeoVector<float>(200.0f, 200.0f), 0.0f, 100.0f) } }, { 0, std::vector<TouhouNovelRT::Bullets::BulletInstanceConfig>{ TouhouNovelRT::Bullets::BulletInstanceConfig(NovelRT::Maths::GeoVector<float>(0.0f, 1.0f), NovelRT::Maths::GeoVector<float>(200.0f, 200.0f), 0.0f, 100.0f) } }, }; auto bossBulletFactory = TouhouNovelRT::Bullets::BulletFactory(runner, NovelRT::Maths::GeoVector<float>(36.0f, 36.0f), NovelRT::Graphics::RGBAConfig(255, 255, 255, 255), 2, false, (imagesDirPath / "bullet" / "circle" / "small-20.png").string(), playerNode); auto bossBulletEmitter = std::vector<std::shared_ptr<TouhouNovelRT::Bullets::Emitter>>{ std::make_shared<TouhouNovelRT::Bullets::Emitter>(TouhouNovelRT::SceneGraph::SimpleScene::WorldSize.getX() * 0.75f, 1.0f / 15.0f, runner, bossNode, bossBulletFactory) }; auto bossSpellcardFactory = TouhouNovelRT::Bullets::BulletFactory(runner, NovelRT::Maths::GeoVector<float>(36.0f, 36.0f), NovelRT::Graphics::RGBAConfig(255, 255, 255, 255), 2, std::vector<std::string>(), playerNode); auto bossSpellcard = std::make_shared<TouhouNovelRT::Bullets::BossSpellcard>(runner, TouhouNovelRT::Bullets::BossSpellcardBulletStageData(std::vector<TouhouNovelRT::Bullets::BulletWaveData>{TouhouNovelRT::Bullets::BulletWaveData(bossBulletMap, 1) }, bossBulletEmitter)); bossSpellcard->activate(); audio.lock()->playMusic(bgm, -1); runner->SceneConstructionRequested += [&]() { scene->drawObjects(); playerController.getGunHandler().invokeSceneConstruction(); bossSpellcard->constructBullets(); }; return runner->runNovel(); }
78.276923
272
0.742138
[ "vector", "transform" ]
5bc92216d89f0d9c2d847933d89b86113d59e4ae
22,108
cpp
C++
src/types/simulation.cpp
Wolff09/seal
c0560204743d1c5f602cfc206ffac32531ea2c06
[ "MIT" ]
7
2019-10-18T07:24:13.000Z
2022-01-07T14:01:17.000Z
src/types/simulation.cpp
Wolff09/seal
c0560204743d1c5f602cfc206ffac32531ea2c06
[ "MIT" ]
null
null
null
src/types/simulation.cpp
Wolff09/seal
c0560204743d1c5f602cfc206ffac32531ea2c06
[ "MIT" ]
1
2019-11-30T01:45:41.000Z
2019-11-30T01:45:41.000Z
#include "types/simulation.hpp" #include "types/util.hpp" #include "types/error.hpp" #include "types/assumption.hpp" #include "z3++.h" #include <set> #include <string> using namespace cola; using namespace prtypes; struct GetObservedAddressVisitor : public ObserverVisitor { // TODO: support more general observers with arbitrarily many observered addresses, but only one that is used in frees, and only free lead to accepting states const VariableDeclaration* decl; void visit(const SelfGuardVariable& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const SelfGuardVariable&)"); } void visit(const ArgumentGuardVariable& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const ArgumentGuardVariable&)"); } void visit(const TrueGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const TrueGuard&)"); } void visit(const ConjunctionGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const ConjunctionGuard&)"); } void visit(const EqGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const EqGuard&)"); } void visit(const NeqGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const NeqGuard&)"); } void visit(const State& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const State&)"); } void visit(const Transition& /*obj*/) { throw std::logic_error("Unexpected invocation: GetObservedAddressVisitor::visit(const Transition&)"); } void visit(const ThreadObserverVariable& /*obj*/) { /* do nothing */ } void visit(const ProgramObserverVariable& var) { decl = var.decl.get(); } void visit(const Observer& observer) { for (const auto& var : observer.variables) { var->accept(*this); } } const VariableDeclaration& get_ptr_var() const { assert(decl); return *decl; } }; struct TranslationUnit { z3::context context; z3::solver solver; std::map<std::string, z3::expr> name2expr; TranslationUnit() : solver(context) {} const z3::expr& variable(std::string name) { auto find = name2expr.find(name); if (find == name2expr.end()) { // add new variable auto insertion = name2expr.insert({ name, context.int_const(name.c_str()) }); assert(insertion.second); return insertion.first->second; } else { // get existing variable return find->second; } } }; struct TranslationWithPrefixVisitor : public ObserverVisitor { const std::string prefix; TranslationUnit& translation; z3::expr result; TranslationWithPrefixVisitor(std::string prefix, TranslationUnit& unit) : prefix(prefix), translation(unit), result(unit.context.bool_val(true)) {} z3::expr get_expr() { return result; } void visit(const ThreadObserverVariable& var) { result = translation.variable("oThr__" + var.name); } void visit(const ProgramObserverVariable& var) { result = translation.variable("oPtr__" + var.decl->name); } void visit(const SelfGuardVariable& /*var*/) { result = translation.variable("__self__"); } void visit(const ArgumentGuardVariable& var) { result = translation.variable(prefix + var.decl.name); } void visit(const TrueGuard& /*guard*/) { result = translation.context.bool_val(true); } void mk_equality(const ComparisonGuard& guard) { guard.lhs.accept(*this); z3::expr lhs = result; guard.rhs->accept(*this); z3::expr rhs = result; result = (lhs == rhs); } void visit(const EqGuard& guard) { mk_equality(guard); } void visit(const NeqGuard& guard) { mk_equality(guard); result = !result; } void visit(const ConjunctionGuard& guard) { z3::expr_vector conjuncts(translation.context); for (const auto& conj : guard.conjuncts) { conj->accept(*this); conjuncts.push_back(result); } result = z3::mk_and(conjuncts); } void visit(const State& /*obj*/) { throw std::logic_error("Unexpected invocation: TranslationWithPrefixVisitor::visit(const State&)"); } void visit(const Transition& /*obj*/) { throw std::logic_error("Unexpected invocation: TranslationWithPrefixVisitor::visit(const Transition&)"); } void visit(const Observer& /*obj*/) { throw std::logic_error("Unexpected invocation: TranslationWithPrefixVisitor::visit(const Observer&)"); } }; z3::expr make_formula(const Guard& guard, std::string param_prefix, TranslationUnit& unit) { TranslationWithPrefixVisitor visitor(param_prefix, unit); guard.accept(visitor); return visitor.get_expr(); } z3::expr make_relation_formula(const Function& label, const std::string& prefix, const std::string& otherPrefix, TranslationUnit& unit, const SimulationEngine::VariableDeclarationSet& skip) { z3::expr_vector conjuncts(unit.context); for (const auto& decl : label.args) { if (skip.count(*decl) == 0) { // TODO: better way to compute names that is guaranteed to be consistent with TranslationWithPrefixVisitor auto variable = unit.variable(prefix + decl->name); auto other = unit.variable(otherPrefix + decl->name); conjuncts.push_back(variable == other); } } return z3::mk_and(conjuncts); } struct NoConstraints { template<typename... Targs> z3::expr operator()(TranslationUnit& unit, const Targs&... /*args*/) { return unit.context.bool_val(true); } }; struct EqualFreeable { z3::expr operator()(TranslationUnit& unit, const Observer& observer, const Transition& match, std::string prefix, std::string otherPrefix) { GetObservedAddressVisitor visitor; observer.accept(visitor); // TODO: better way to compute names that is guaranteed to be consistent with TranslationWithPrefixVisitor auto ovar = unit.variable("oPtr__" + visitor.get_ptr_var().name); // ensure: var == ovar ==> var' == ovar z3::expr_vector conjuncts(unit.context); for (const auto& decl : match.label.args) { auto variable = unit.variable(prefix + decl->name); auto other = unit.variable(otherPrefix + decl->name); conjuncts.push_back(z3::implies(variable == ovar, other ==ovar)); } return z3::mk_and(conjuncts); } }; template<typename AdditionalConstraints> std::vector<const State*> abstract_post(const Observer& observer, const State& to_post, const Transition& match, const SimulationEngine::VariableDeclarationSet& unrelated) { static const std::string PREFIX_MATCH = "arg1__"; static const std::string PREFIX_TRANS = "arg2__"; TranslationUnit translation; z3::expr match_enc = make_formula(*match.guard, PREFIX_MATCH, translation); z3::expr relation = make_relation_formula(match.label, PREFIX_MATCH, PREFIX_TRANS, translation, unrelated); z3::expr addition = AdditionalConstraints()(translation, observer, match, PREFIX_MATCH, PREFIX_TRANS); translation.solver.add(relation); translation.solver.add(addition); translation.solver.add(match_enc); std::vector<const State*> result; bool definitely_has_post = false; for (const auto& transition : to_post.transitions) { if (&transition->label == &match.label && transition->kind == match.kind) { z3::expr trans_enc = make_formula(*transition->guard, PREFIX_TRANS, translation); translation.solver.push(); translation.solver.add(trans_enc); auto check_result = translation.solver.check(); translation.solver.pop(); switch (check_result) { case z3::unknown: throw std::logic_error("SMT solving failed: Z3 was unable to prove SAT/UNSAT, returned 'UNKNOWN'. Cannot recover."); case z3::unsat: // transition->guard is definitely not enabled break; case z3::sat: // transition->guard may be enabled result.push_back(&transition->dst); if (!definitely_has_post) { translation.solver.push(); translation.solver.add(!trans_enc); auto check_post_result = translation.solver.check(); translation.solver.pop(); definitely_has_post |= (check_post_result == z3::unsat); } } } } if (!definitely_has_post) { // only add the state back again if needed (unknown if there is an enabled outgoing transition) result.push_back(&to_post); } return result; } std::vector<const State*> abstract_post(const Observer& observer, const State& to_post, const Transition& match) { return abstract_post<NoConstraints>(observer, to_post, match, {}); } bool SimulationEngine::is_safe(const Enter& enter, const std::vector<std::reference_wrapper<const VariableDeclaration>>& params, const VariableDeclarationSet& invalid_params) const { // translate invalid parameters to function internal argument declarations VariableDeclarationSet invalid_translated; assert(enter.decl.args.size() == params.size()); for (std::size_t i = 0; i < params.size(); i++) { if (invalid_params.count(params.at(i)) != 0) { invalid_translated.insert(*enter.decl.args.at(i)); } } // chech safe for (const auto& observer : observers) { for (const auto& state : observer->states) { for (const auto& transition : state->transitions) { if (&transition->label == &enter.decl && transition->kind == Transition::INVOCATION /* TODO: && enabled(transition->guard, params) */) { const State& pre_state = transition->src; const State& post_state = transition->dst; std::vector<const State*> post_pre = abstract_post<EqualFreeable>(*observer, pre_state, *transition, invalid_translated); for (const State* to_simulate : post_pre) { if (!is_in_simulation_relation(*to_simulate, post_state)) { return false; } } } } } } return true; } bool simulation_holds(const Observer& observer, const SimulationEngine::SimulationRelation& current, const State& to_simulate, const State& simulator) { if (&to_simulate == &simulator) { auto required = std::make_pair(&to_simulate, &simulator); return current.count(required) != 0; } // handle outgoing transitions of to_simulate // TODO: does this ignore implicit transitions? for (const auto& transition : to_simulate.transitions) { auto next_to_simulate = &transition->dst; auto simulator_post = abstract_post(observer, simulator, *transition); for (const auto& next_simulator : simulator_post) { auto required = std::make_pair(next_to_simulate, next_simulator); if (current.count(required) == 0) { return false; } } } // // handle outgoing transitions of simulator (this makes it a bisimulation!) // for (const auto& transition : simulator.transitions) { // auto next_simulator = &transition->dst; // auto to_simulate_post = abstract_post(observer, to_simulate, *transition); // for (const auto& next_to_simulate : to_simulate_post) { // auto required = std::make_pair(next_to_simulate, next_simulator); // if (!current.count(required)) { // return false; // } // } // } return true; } // void debug_simulation_relation(const SimulationEngine::SimulationRelation& sim) { // std::cout << "Simulation Relation: " << std::endl; // for (const auto& [lhs, rhs] : sim) { // std::cout << " " << lhs->name << " - " << rhs->name << std::endl; // } // } void SimulationEngine::compute_simulation(const Observer& observer) { prtypes::raise_if_assumption_unsatisfied(observer); SimulationEngine::SimulationRelation result; // start with all-relation, pruned by those that are definitely in a simulation relation for (const auto& lhs : observer.states) { for (const auto& rhs : observer.states) { if (prtypes::implies(rhs->final, lhs->final)) { result.insert({ lhs.get(), rhs.get() }); } } } // remove non-simulation pairs until fixed point bool removed; do { removed = false; auto it = result.begin(); while (it != result.end()) { if (!simulation_holds(observer, result, *it->first, *it->second)) { removed = true; it = result.erase(it); // progresses it } else { it++; } } } while (removed); // store information this->observers.insert(&observer); this->all_simulations.insert(result.begin(), result.end()); // debug_simulation_relation(result); } bool SimulationEngine::is_in_simulation_relation(const State& state, const State& other) const { return all_simulations.count({ &state, &other }) > 0; } struct CallVisitor final : Visitor { void visit(const VariableDeclaration& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const VariableDeclaration&)"); } void visit(const Expression& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Expression&)"); } void visit(const BooleanValue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const BooleanValue&)"); } void visit(const NullValue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const NullValue&)"); } void visit(const EmptyValue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const EmptyValue&)"); } void visit(const MaxValue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const MaxValue&)"); } void visit(const MinValue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const MinValue&)"); } void visit(const NDetValue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const NDetValue&)"); } void visit(const VariableExpression& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const VariableExpression&)"); } void visit(const NegatedExpression& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const NegatedExpression&)"); } void visit(const BinaryExpression& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const BinaryExpression&)"); } void visit(const Dereference& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Dereference&)"); } void visit(const InvariantExpression& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const InvariantExpression&)"); } void visit(const InvariantActive& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const InvariantActive&)"); } void visit(const Sequence& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Sequence&)"); } void visit(const Scope& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Scope&)"); } void visit(const Atomic& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Atomic&)"); } void visit(const Choice& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Choice&)"); } void visit(const IfThenElse& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const IfThenElse&)"); } void visit(const Loop& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Loop&)"); } void visit(const While& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const While&)"); } void visit(const Skip& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Skip&)"); } void visit(const Break& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Break&)"); } void visit(const Continue& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Continue&)"); } void visit(const Assume& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Assume&)"); } void visit(const Assert& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Assert&)"); } void visit(const AngelChoose& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const AngelChoose&)"); } void visit(const AngelActive& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const AngelActive&)"); } void visit(const AngelContains& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const AngelContains&)"); } void visit(const Return& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Return&)"); } void visit(const Malloc& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Malloc&)"); } void visit(const Assignment& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Assignment&)"); } void visit(const Macro& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Macro&)"); } void visit(const CompareAndSwap& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const CompareAndSwap&)"); } void visit(const Function& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Function&)"); } void visit(const Program& /*node*/) override { throw std::logic_error("Unexpected invocation: CallVisitor::visit(const Program&)"); } const Function* label = nullptr; Transition::Kind kind = Transition::INVOCATION; std::pair<const Function&, Transition::Kind> convert(const AstNode& node) { node.accept(*this); assert(label); return { *label, kind }; } void visit(const Enter& node) override { this->label = &node.decl; this->kind = Transition::INVOCATION; } void visit(const Exit& node) override { this->label = &node.decl; this->kind = Transition::RESPONSE; } }; struct GuardMakerVisitor final : public ObserverVisitor { std::vector<std::unique_ptr<Guard>> guards; bool is_thread_observed; bool is_address_observed; const VariableDeclaration* decl; GuardMakerVisitor(bool is_thread_observed, bool is_address_observed, const VariableDeclaration* decl) : is_thread_observed(is_thread_observed), is_address_observed(is_address_observed), decl(decl) {} void visit(const SelfGuardVariable& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const SelfGuardVariable&)"); } void visit(const ArgumentGuardVariable& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const ArgumentGuardVariable&)"); } void visit(const TrueGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const TrueGuard&)"); } void visit(const ConjunctionGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const ConjunctionGuard&)"); } void visit(const EqGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const EqGuard&)"); } void visit(const NeqGuard& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const NeqGuard&)"); } void visit(const State& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const State&)"); } void visit(const Transition& /*obj*/) { throw std::logic_error("Unexpected invocation: GuardMakerVisitor::visit(const Transition&)"); } void visit(const Observer& observer) { for (const auto& var : observer.variables) { var->accept(*this); } } void visit(const ThreadObserverVariable& var) { if (is_thread_observed) { guards.push_back(std::make_unique<EqGuard>(var, std::make_unique<SelfGuardVariable>())); } else { guards.push_back(std::make_unique<NeqGuard>(var, std::make_unique<SelfGuardVariable>())); } } void visit(const ProgramObserverVariable& var) { assert(decl); if (is_address_observed) { guards.push_back(std::make_unique<EqGuard>(var, std::make_unique<ArgumentGuardVariable>(*decl))); } else { guards.push_back(std::make_unique<NeqGuard>(var, std::make_unique<ArgumentGuardVariable>(*decl))); } } }; bool SimulationEngine::is_repeated_execution_simulating(const std::vector<std::reference_wrapper<const Command>>& events) const { auto make_guard = [](const Observer& observer, const Function& label, bool is_address_observed, bool is_thread_observed) -> std::unique_ptr<Guard> { const VariableDeclaration* decl = nullptr; if (label.args.size() > 0) { assert(label.args.size() <= 1); assert(label.args.at(0)->type.sort == Sort::PTR); decl = label.args.at(0).get(); } GuardMakerVisitor visitor(is_thread_observed, is_address_observed, decl); observer.accept(visitor); return std::make_unique<ConjunctionGuard>(std::move(visitor.guards)); }; auto post_for_sequence = [&](const Observer& observer, std::set<const State*> reach, bool is_address_observed, bool is_thread_observed) -> std::set<const State*> { assert(reach.size() > 0); const State& dummy_state = **reach.begin(); for (const Command& cmd : events) { auto [label, kind] = CallVisitor().convert(cmd); std::set<const State*> post; Transition dummy_transition(dummy_state, dummy_state, label, kind, make_guard(observer, label, is_address_observed, is_thread_observed)); for (const State* state : reach) { auto state_post = abstract_post(observer, *state, dummy_transition); post.insert(state_post.begin(), state_post.end()); } reach = std::move(post); } return reach; }; for (const Observer* observer : this->observers) { for (const auto& source : observer->states) { for (bool is_address_observed : { true, false }) { for (bool is_thread_observed : { true, false }) { std::set<const State*> reach_once = post_for_sequence(*observer, { source.get() }, is_address_observed, is_thread_observed); std::set<const State*> reach_twice = post_for_sequence(*observer, reach_once, is_address_observed, is_thread_observed); for (const State* lhs : reach_once) { bool simulated = false; for (const State* rhs : reach_twice) { if (this->is_in_simulation_relation(*lhs, *rhs)) { simulated = true; break; } } if (!simulated) { return false; } } } } } } return true; }
46.938429
200
0.72562
[ "vector" ]
5bccf81d440d1ecc955dd0ba6b289fd741947b75
20,427
cpp
C++
Midas/src/c-compiler/vale.cpp
monarrk/Vale
2cf501ef8eef5a38fda2302f5915b0307cbdb309
[ "Apache-2.0" ]
null
null
null
Midas/src/c-compiler/vale.cpp
monarrk/Vale
2cf501ef8eef5a38fda2302f5915b0307cbdb309
[ "Apache-2.0" ]
null
null
null
Midas/src/c-compiler/vale.cpp
monarrk/Vale
2cf501ef8eef5a38fda2302f5915b0307cbdb309
[ "Apache-2.0" ]
null
null
null
#include <llvm-c/Core.h> #include <llvm-c/DebugInfo.h> #include <llvm-c/ExecutionEngine.h> #include <llvm-c/Analysis.h> #include <assert.h> #include <string> #include <vector> #include <iostream> #include <fstream> #include <nlohmann/json.hpp> #include "function/expressions/shared/shared.h" #include "struct/interface.h" #include "metal/types.h" #include "metal/ast.h" #include "metal/instructions.h" #include "function/function.h" #include "struct/struct.h" #include "metal/readjson.h" #include "error.h" #include <cstring> #include <llvm-c/Transforms/Scalar.h> #include <llvm-c/Transforms/Utils.h> #include <llvm-c/Transforms/IPO.h> #ifdef _WIN32 #define asmext "asm" #define objext "obj" #else #define asmext "s" #define objext "o" #endif // for convenience using json = nlohmann::json; void initInternalExterns(GlobalState* globalState) { { LLVMTypeRef retType = LLVMPointerType(LLVMInt8Type(), 0); LLVMTypeRef paramType = LLVMInt64Type(); LLVMTypeRef funcType = LLVMFunctionType(retType, &paramType, 1, 0); globalState->malloc = LLVMAddFunction(globalState->mod, "malloc", funcType); } { LLVMTypeRef retType = LLVMVoidType(); LLVMTypeRef paramType = LLVMPointerType(LLVMInt8Type(), 0); LLVMTypeRef funcType = LLVMFunctionType(retType, &paramType, 1, 0); globalState->free = LLVMAddFunction(globalState->mod, "free", funcType); } { LLVMTypeRef retType = LLVMVoidType(); LLVMTypeRef paramType = LLVMInt8Type(); LLVMTypeRef funcType = LLVMFunctionType(retType, &paramType, 1, 0); globalState->exit = LLVMAddFunction(globalState->mod, "exit", funcType); } { LLVMTypeRef retType = LLVMVoidType(); LLVMTypeRef paramType = LLVMInt1Type(); LLVMTypeRef funcType = LLVMFunctionType(retType, &paramType, 1, 0); globalState->assert = LLVMAddFunction(globalState->mod, "__vassert", funcType); } { LLVMTypeRef retType = LLVMVoidType(); LLVMTypeRef paramTypes[2] = { LLVMInt64Type(), LLVMInt64Type() }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes, 2, 0); globalState->assertI64Eq = LLVMAddFunction(globalState->mod, "__vassertI64Eq", funcType); } { LLVMTypeRef retType = LLVMVoidType(); LLVMTypeRef paramTypes[] = { LLVMInt64Type(), LLVMInt64Type() }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes, 2, 0); globalState->flareI64 = LLVMAddFunction(globalState->mod, "__vflare_i64", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(LLVMInt8Type(), 0) }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->printCStr = LLVMAddFunction(globalState->mod, "__vprintCStr", funcType); } { LLVMTypeRef retType = LLVMInt64Type(); LLVMTypeRef funcType = LLVMFunctionType(retType, nullptr, 0, 0); globalState->getch = LLVMAddFunction(globalState->mod, "getchar", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMInt64Type() }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->printInt = LLVMAddFunction(globalState->mod, "__vprintI64", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMInt1Type() }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->printBool = LLVMAddFunction(globalState->mod, "__vprintBool", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(globalState->stringInnerStructL, 0), LLVMPointerType(LLVMInt8Type(), 0), }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->initStr = LLVMAddFunction(globalState->mod, "__vinitStr", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(globalState->stringInnerStructL, 0), LLVMPointerType(globalState->stringInnerStructL, 0), LLVMPointerType(globalState->stringInnerStructL, 0) }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->addStr = LLVMAddFunction(globalState->mod, "__vaddStr", funcType); } { LLVMTypeRef retType = LLVMInt8Type(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(globalState->stringInnerStructL, 0), LLVMPointerType(globalState->stringInnerStructL, 0) }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->eqStr = LLVMAddFunction(globalState->mod, "__veqStr", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(globalState->stringInnerStructL, 0) }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->printVStr = LLVMAddFunction(globalState->mod, "__vprintStr", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMInt64Type(), LLVMPointerType(LLVMInt8Type(), 0), LLVMInt64Type(), }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->intToCStr = LLVMAddFunction(globalState->mod, "__vintToCStr", funcType); } { LLVMTypeRef retType = LLVMInt64Type(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(LLVMInt8Type(), 0), }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->strlen = LLVMAddFunction(globalState->mod, "strlen", funcType); } { LLVMTypeRef retType = LLVMInt64Type(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(LLVMVoidType(), 0), }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->censusContains = LLVMAddFunction(globalState->mod, "__vcensusContains", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(LLVMVoidType(), 0), }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->censusAdd = LLVMAddFunction(globalState->mod, "__vcensusAdd", funcType); } { LLVMTypeRef retType = LLVMVoidType(); std::vector<LLVMTypeRef> paramTypes = { LLVMPointerType(LLVMVoidType(), 0), }; LLVMTypeRef funcType = LLVMFunctionType(retType, paramTypes.data(), paramTypes.size(), 0); globalState->censusRemove = LLVMAddFunction(globalState->mod, "__vcensusRemove", funcType); } } void initInternalStructs(GlobalState* globalState) { { auto controlBlockStructL = LLVMStructCreateNamed( LLVMGetGlobalContext(), CONTROL_BLOCK_STRUCT_NAME); std::vector<LLVMTypeRef> memberTypesL; globalState->controlBlockTypeStrIndex = memberTypesL.size(); memberTypesL.push_back(LLVMPointerType(LLVMInt8Type(), 0)); globalState->controlBlockObjIdIndex = memberTypesL.size(); memberTypesL.push_back(LLVMInt64Type()); globalState->controlBlockRcMemberIndex = memberTypesL.size(); memberTypesL.push_back(LLVMInt64Type()); LLVMStructSetBody( controlBlockStructL, memberTypesL.data(), memberTypesL.size(), false); globalState->controlBlockStructL = controlBlockStructL; } { auto stringInnerStructL = LLVMStructCreateNamed( LLVMGetGlobalContext(), "__Str"); std::vector<LLVMTypeRef> memberTypesL; memberTypesL.push_back(LLVMInt64Type()); memberTypesL.push_back(LLVMArrayType(LLVMInt8Type(), 0)); LLVMStructSetBody( stringInnerStructL, memberTypesL.data(), memberTypesL.size(), false); globalState->stringInnerStructL = stringInnerStructL; } { auto stringWrapperStructL = LLVMStructCreateNamed( LLVMGetGlobalContext(), "__Str_rc"); std::vector<LLVMTypeRef> memberTypesL; memberTypesL.push_back(globalState->controlBlockStructL); memberTypesL.push_back(globalState->stringInnerStructL); LLVMStructSetBody( stringWrapperStructL, memberTypesL.data(), memberTypesL.size(), false); globalState->stringWrapperStructL = stringWrapperStructL; } } void compileValeCode(GlobalState* globalState, const char* filename) { std::ifstream instream(filename); std::string str(std::istreambuf_iterator<char>{instream}, {}); assert(str.size() > 0); auto programJ = json::parse(str.c_str()); auto program = readProgram(&globalState->metalCache, programJ); // Start making the entry function. We make it up here because we want its // builder for creating string constants. In a perfect world we wouldn't need // a builder for making string constants, but LLVM wants one, and it wants one // that's attached to a function. auto paramTypesL = std::vector<LLVMTypeRef>{ LLVMInt64Type(), LLVMPointerType(LLVMPointerType(LLVMInt8Type(), 0), 0) }; LLVMTypeRef functionTypeL = LLVMFunctionType( LLVMInt64Type(), paramTypesL.data(), paramTypesL.size(), 0); LLVMValueRef entryFunctionL = LLVMAddFunction(globalState->mod, "main", functionTypeL); LLVMSetLinkage(entryFunctionL, LLVMDLLExportLinkage); LLVMSetDLLStorageClass(entryFunctionL, LLVMDLLExportStorageClass); LLVMSetFunctionCallConv(entryFunctionL, LLVMX86StdcallCallConv); LLVMBuilderRef entryBuilder = LLVMCreateBuilder(); LLVMBasicBlockRef blockL = LLVMAppendBasicBlock(entryFunctionL, "thebestblock"); LLVMPositionBuilderAtEnd(entryBuilder, blockL); globalState->program = program; globalState->stringConstantBuilder = entryBuilder; globalState->liveHeapObjCounter = LLVMAddGlobal(globalState->mod, LLVMInt64Type(), "__liveHeapObjCounter"); // LLVMSetLinkage(globalState->liveHeapObjCounter, LLVMExternalLinkage); LLVMSetInitializer(globalState->liveHeapObjCounter, LLVMConstInt(LLVMInt64Type(), 0, false)); globalState->objIdCounter = LLVMAddGlobal(globalState->mod, LLVMInt64Type(), "__objIdCounter"); // LLVMSetLinkage(globalState->liveHeapObjCounter, LLVMExternalLinkage); LLVMSetInitializer(globalState->objIdCounter, LLVMConstInt(LLVMInt64Type(), 501, false)); initInternalStructs(globalState); initInternalExterns(globalState); for (auto p : program->structs) { auto name = p.first; auto structM = p.second; declareStruct(globalState, structM); } for (auto p : program->interfaces) { auto name = p.first; auto interfaceM = p.second; declareInterface(globalState, interfaceM); } for (auto p : program->structs) { auto name = p.first; auto structM = p.second; translateStruct(globalState, structM); } for (auto p : program->interfaces) { auto name = p.first; auto interfaceM = p.second; translateInterface(globalState, interfaceM); } for (auto p : program->structs) { auto name = p.first; auto structM = p.second; for (auto e : structM->edges) { declareEdge(globalState, e); } } LLVMValueRef mainL = nullptr; int numFuncs = program->functions.size(); for (auto p : program->functions) { auto name = p.first; auto function = p.second; LLVMValueRef entryFunctionL = declareFunction(globalState, function); if (function->prototype->name->name == "F(\"main\")") { mainL = entryFunctionL; } } assert(mainL != nullptr); // We translate the edges after the functions are declared because the // functions have to exist for the itables to point to them. for (auto p : program->structs) { auto name = p.first; auto structM = p.second; for (auto e : structM->edges) { translateEdge(globalState, e); } } for (auto p : program->functions) { auto name = p.first; auto function = p.second; translateFunction(globalState, function); } LLVMValueRef emptyValues[1] = {}; LLVMValueRef mainResult = LLVMBuildCall(entryBuilder, mainL, emptyValues, 0, "valeMainCall"); LLVMValueRef args[2] = { LLVMConstInt(LLVMInt64Type(), 0, false), LLVMBuildLoad(entryBuilder, globalState->liveHeapObjCounter, "numLiveObjs") }; LLVMBuildCall(entryBuilder, globalState->assertI64Eq, args, 2, ""); LLVMBuildRet(entryBuilder, mainResult); LLVMDisposeBuilder(entryBuilder); } void createModule(GlobalState *globalState) { globalState->mod = LLVMModuleCreateWithNameInContext(globalState->opt->srcDirAndNameNoExt.c_str(), globalState->context); if (!globalState->opt->release) { globalState->dibuilder = LLVMCreateDIBuilder(globalState->mod); globalState->difile = LLVMDIBuilderCreateFile(globalState->dibuilder, "main.vale", 9, ".", 1); // If theres a compile error on this line, its some sort of LLVM version issue, try commenting or uncommenting the last four args. globalState->compileUnit = LLVMDIBuilderCreateCompileUnit(globalState->dibuilder, LLVMDWARFSourceLanguageC, globalState->difile, "Vale compiler", 13, 0, "", 0, 0, "", 0, LLVMDWARFEmissionFull, 0, 0, 0/*, "isysroothere", strlen("isysroothere"), "sdkhere", strlen("sdkhere")*/); } compileValeCode(globalState, globalState->opt->srcpath); if (!globalState->opt->release) LLVMDIBuilderFinalize(globalState->dibuilder); } // Use provided options (triple, etc.) to creation a machine LLVMTargetMachineRef createMachine(ValeOptions *opt) { char *err; // LLVMInitializeAllTargetInfos(); // LLVMInitializeAllTargetMCs(); // LLVMInitializeAllTargets(); // LLVMInitializeAllAsmPrinters(); // LLVMInitializeAllAsmParsers(); LLVMInitializeX86TargetInfo(); LLVMInitializeX86TargetMC(); LLVMInitializeX86Target(); LLVMInitializeX86AsmPrinter(); LLVMInitializeX86AsmParser(); // Find target for the specified triple if (!opt->triple) opt->triple = LLVMGetDefaultTargetTriple(); LLVMTargetRef target; if (LLVMGetTargetFromTriple(opt->triple, &target, &err) != 0) { errorExit(ExitCode::LlvmSetupFailed, "Could not create target: ", err); LLVMDisposeMessage(err); return NULL; } // Create a specific target machine LLVMCodeGenOptLevel opt_level = opt->release? LLVMCodeGenLevelAggressive : LLVMCodeGenLevelNone; LLVMRelocMode reloc = (opt->pic || opt->library)? LLVMRelocPIC : LLVMRelocDefault; if (!opt->cpu) opt->cpu = "generic"; if (!opt->features) opt->features = ""; LLVMTargetMachineRef machine; if (!(machine = LLVMCreateTargetMachine(target, opt->triple, opt->cpu, opt->features, opt_level, reloc, LLVMCodeModelDefault))) { errorExit(ExitCode::LlvmSetupFailed, "Could not create target machine"); return NULL; } return machine; } // Generate requested object file void generateOutput( const char *objpath, const char *asmpath, LLVMModuleRef mod, const char *triple, LLVMTargetMachineRef machine) { char *err; LLVMSetTarget(mod, triple); LLVMTargetDataRef dataref = LLVMCreateTargetDataLayout(machine); char *layout = LLVMCopyStringRepOfTargetData(dataref); LLVMSetDataLayout(mod, layout); LLVMDisposeMessage(layout); if (asmpath) { char asmpathCStr[1024] = {0}; strncpy(asmpathCStr, asmpath, 1024); // Generate assembly file if requested if (LLVMTargetMachineEmitToFile(machine, mod, asmpathCStr, LLVMAssemblyFile, &err) != 0) { std::cerr << "Could not emit asm file: " << asmpathCStr << std::endl; LLVMDisposeMessage(err); } } char objpathCStr[1024] = { 0 }; strncpy(objpathCStr, objpath, 1024); // Generate .o or .obj file if (LLVMTargetMachineEmitToFile(machine, mod, objpathCStr, LLVMObjectFile, &err) != 0) { std::cerr << "Could not emit obj file to path " << objpathCStr << " " << err << std::endl; LLVMDisposeMessage(err); } } // Generate IR nodes into LLVM IR using LLVM void generateModule(GlobalState *globalState) { char *err; // Generate IR to LLVM IR createModule(globalState); // Serialize the LLVM IR, if requested if (globalState->opt->print_llvmir && LLVMPrintModuleToFile(globalState->mod, fileMakePath(globalState->opt->output, globalState->opt->srcNameNoExt.c_str(), "ll").c_str(), &err) != 0) { std::cerr << "Could not emit pre-ir file: " << err << std::endl; LLVMDisposeMessage(err); } // Verify generated IR if (globalState->opt->verify) { char *error = NULL; LLVMVerifyModule(globalState->mod, LLVMAbortProcessAction, &error); if (error) { if (*error) errorExit(ExitCode::VerifyFailed, "Module verification failed:\n%s", error); LLVMDisposeMessage(error); } } // Optimize the generated LLVM IR LLVMPassManagerRef passmgr = LLVMCreatePassManager(); LLVMAddPromoteMemoryToRegisterPass(passmgr); // Demote allocas to registers. LLVMAddInstructionCombiningPass(passmgr); // Do simple "peephole" and bit-twiddling optimizations LLVMAddReassociatePass(passmgr); // Reassociate expressions. LLVMAddGVNPass(passmgr); // Eliminate common subexpressions. LLVMAddCFGSimplificationPass(passmgr); // Simplify the control flow graph if (globalState->opt->release) LLVMAddFunctionInliningPass(passmgr); // Function inlining LLVMRunPassManager(passmgr, globalState->mod); LLVMDisposePassManager(passmgr); // Serialize the LLVM IR, if requested auto outputFilePath = fileMakePath(globalState->opt->output, globalState->opt->srcNameNoExt.c_str(), "opt.ll"); std::cout << "Printing file " << outputFilePath << std::endl; if (globalState->opt->print_llvmir && LLVMPrintModuleToFile(globalState->mod, outputFilePath.c_str(), &err) != 0) { std::cerr << "Could not emit ir file: " << err << std::endl; LLVMDisposeMessage(err); } // Transform IR to target's ASM and OBJ if (globalState->machine) { auto objpath = fileMakePath(globalState->opt->output, globalState->opt->srcNameNoExt.c_str(), globalState->opt->wasm ? "wasm" : objext); auto asmpath = fileMakePath(globalState->opt->output, globalState->opt->srcNameNoExt.c_str(), globalState->opt->wasm ? "wat" : asmext); generateOutput( objpath.c_str(), globalState->opt->print_asm ? asmpath.c_str() : NULL, globalState->mod, globalState->opt->triple, globalState->machine); } LLVMDisposeModule(globalState->mod); // LLVMContextDispose(gen.context); // Only need if we created a new context } // Setup LLVM generation, ensuring we know intended target void setup(GlobalState *globalState, ValeOptions *opt) { globalState->opt = opt; LLVMTargetMachineRef machine = createMachine(opt); if (!machine) exit((int)(ExitCode::BadOpts)); // Obtain data layout info, particularly pointer sizes globalState->machine = machine; globalState->dataLayout = LLVMCreateTargetDataLayout(machine); globalState->ptrSize = LLVMPointerSize(globalState->dataLayout) << 3u; // LLVM inlining bugs prevent use of LLVMContextCreate(); globalState->context = LLVMGetGlobalContext(); } void closeGlobalState(GlobalState *globalState) { LLVMDisposeTargetMachine(globalState->machine); } int main(int argc, char **argv) { ValeOptions valeOptions; // Get compiler's options from passed arguments int ok = valeOptSet(&valeOptions, &argc, argv); if (ok <= 0) { exit((int)(ok == 0 ? ExitCode::Success : ExitCode::BadOpts)); } if (argc < 2) errorExit(ExitCode::BadOpts, "Specify a Vale program to compile."); valeOptions.srcpath = argv[1]; new (&valeOptions.srcDir) std::string(fileDirectory(valeOptions.srcpath)); new (&valeOptions.srcNameNoExt) std::string(getFileNameNoExt(valeOptions.srcpath)); new (&valeOptions.srcDirAndNameNoExt) std::string(valeOptions.srcDir + valeOptions.srcNameNoExt); // We set up generation early because we need target info, e.g.: pointer size GlobalState globalState; setup(&globalState, &valeOptions); // Parse source file, do semantic analysis, and generate code // ModuleNode *modnode = NULL; // if (!errors) generateModule(&globalState); closeGlobalState(&globalState); // errorSummary(); }
34.680815
187
0.708278
[ "object", "vector", "transform" ]
5bcf9a2733341878d8800eab7aeceac94f914174
7,697
cpp
C++
cplusplus/RCF/src/RCF/test/Test.cpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
cplusplus/RCF/src/RCF/test/Test.cpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
cplusplus/RCF/src/RCF/test/Test.cpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
//****************************************************************************** // RCF - Remote Call Framework // // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved. // http://www.deltavsoft.com // // RCF is distributed under dual licenses - closed source or GPL. // Consult your particular license for conditions of use. // // If you have not purchased a commercial license, you are using RCF // under GPL terms. // // Version: 2.0 // Contact: support <at> deltavsoft.com // //****************************************************************************** #include <RCF/test/Test.hpp> #include <RCF/Tools.hpp> #include <RCF/Exception.hpp> // getcwd #ifdef _MSC_VER #include <direct.h> #else #include <unistd.h> #endif // Boost string algo is more portable than stricmp, strcasecmp, etc. #include <boost/algorithm/string.hpp> #include <fstream> namespace RCF { bool compareNoCase(const std::string & s1, const std::string & s2) { return boost::to_upper_copy(s1) == boost::to_upper_copy(s2); } TestEnv gTestEnv_; TestEnv & gTestEnv() { return gTestEnv_; } TestHierarchy::TestHierarchy() : mCaseSensitive(false), mHasTestCaseRun(false), mEnumerateOnly(false) { } void TestHierarchy::pushTestCase(const std::string & name) { mCurrentTestCase.push_back(name); } void TestHierarchy::popTestCase() { mCurrentTestCase.pop_back(); } std::string TestHierarchy::currentTestCase() { std::string s; for (std::size_t i=0; i<mCurrentTestCase.size(); ++i) { s += mCurrentTestCase[i]; if (i != mCurrentTestCase.size() - 1) { s += '/'; } } return s; } void TestHierarchy::onlyRunTestCase(const std::string & testCase, bool caseSensitive) { split(testCase, '/', mTestCaseToRun); mCaseSensitive = caseSensitive; } void TestHierarchy::enumerateTestCasesOnly() { mEnumerateOnly = true; } bool TestHierarchy::shouldCurrentTestCaseRun() { if (mEnumerateOnly) { std::cout << "Test case: " << currentTestCase() << std::endl; bool match = doesCurrentTestCaseMatch(); return match && mCurrentTestCase.size() <= mTestCaseToRun.size(); } else if (mTestCaseToRun.empty()) { return true; } else { bool matches = doesCurrentTestCaseMatch(); if (matches && mTestCaseToRun.size() == mCurrentTestCase.size()) { mHasTestCaseRun = true; } return matches; } } bool TestHierarchy::didTestCaseRun() { return mHasTestCaseRun; } void TestHierarchy::split( const std::string & s, char delim, std::vector<std::string> & elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } } bool TestHierarchy::doesCurrentTestCaseMatch() { for (std::size_t i=0; i<mCurrentTestCase.size(); ++i) { if (i < mTestCaseToRun.size()) { if (mCaseSensitive) { if (mCurrentTestCase[i] != mTestCaseToRun[i]) { return false; } } else { if (!compareNoCase(mCurrentTestCase[i], mTestCaseToRun[i])) { return false; } } } } return true; } TestCaseSentry::TestCaseSentry(const std::string & name) : mName(name), mHasRun(false) { TestHierarchy & th = gTestEnv().mTestHierarchy; th.pushTestCase(mName); mRunnable = th.shouldCurrentTestCaseRun(); if (mRunnable) { std::cout << "Entering test case " << th.currentTestCase() << "." << std::endl; } } #if defined(_MSC_VER) && _MSC_VER == 1310 // C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data #pragma warning(push) #pragma warning( disable: 4267 ) #endif TestCaseSentry::TestCaseSentry(std::size_t n) : mRunnable(false), mHasRun(false) { TestHierarchy & th = gTestEnv().mTestHierarchy; std::ostringstream os; os << n; mName = os.str(); th.pushTestCase(mName); mRunnable = th.shouldCurrentTestCaseRun(); if (mRunnable) { std::cout << "Entering test case " << th.currentTestCase() << "." << std::endl; } } #if defined(_MSC_VER) && _MSC_VER == 1310 #pragma warning(pop) #endif TestCaseSentry::~TestCaseSentry() { TestHierarchy & th = gTestEnv().mTestHierarchy; if (mRunnable) { std::cout << "Leaving test case " << th.currentTestCase() << "." << std::endl; } th.popTestCase(); } bool TestCaseSentry::shouldRun() { return mRunnable && !mHasRun; } void TestCaseSentry::setHasRun() { mHasRun = true; } #ifdef BOOST_WINDOWS void TestEnv::printTestMessage(const std::string & msg) { std::cout << msg << std::flush; OutputDebugStringA(msg.c_str()); } #else void TestEnv::printTestMessage(const std::string & msg) { std::cout << msg << std::flush; } #endif void TestEnv::reportTestFailure( const char * file, int line, const char * condition, const char * info) { std::ostringstream os; os << file << "(" << line << "): Test case: " << mTestHierarchy.currentTestCase() << std::endl; os << file << "(" << line << "): Test failed: " << condition; if (info) { os << " : " << info; } os << std::endl; printTestMessage( os.str() ); ++mFailCount; if (mAssertOnFail) { if (mPfnAssert) { mPfnAssert(file, line, condition, info); } else { #ifdef BOOST_WINDOWS // __debugbreak() is more likely to give a legible call stack. //DebugBreak(); __debugbreak(); #else assert(0); #endif } } } TestEnv::TestEnv() : mFailCount(0), mAssertOnFail(false), mPfnAssert(NULL) { } void TestEnv::setTestCaseToRun(const std::string & testCase, bool caseSensitive) { mTestHierarchy.onlyRunTestCase(testCase, caseSensitive); } void TestEnv::setEnumerationOnly() { mTestHierarchy.enumerateTestCasesOnly(); } void TestEnv::setAssertOnFail(bool assertOnFail) { mAssertOnFail = assertOnFail; } void TestEnv::setPfnAssert(PfnAssert pfnAssert) { mPfnAssert = pfnAssert; } std::size_t TestEnv::getFailCount() { return mFailCount; } bool TestEnv::didTestCaseRun() { return mTestHierarchy.didTestCaseRun(); } std::string getRelativePathToCheckoutRoot() { std::string testPath = "."; std::string testFile = testPath + "/.hgtags"; while (!std::ifstream(testFile.c_str()).good() && testPath.size() < 100) { testPath = testPath + "/.."; testFile = testPath + "/.hgtags"; } if (std::ifstream(testFile.c_str()).good()) { return testPath; } return ""; } std::string getRelativeTestDataPath() { std::string checkoutRoot = getRelativePathToCheckoutRoot(); RCF_ASSERT(checkoutRoot.size() > 0)(checkoutRoot); std::string testDataPath = checkoutRoot + "/RCF/test/data/"; return testDataPath; } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4996) // warning C4996: 'getcwd': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getcwd. See online help for details. #endif std::string getWorkingDir() { std::vector<char> vec(1024); char * szRet = getcwd(&vec[0], static_cast<int>( vec.size() )); RCF_UNUSED_VARIABLE(szRet); return std::string(&vec[0]); } #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace RCF
20.859079
182
0.598025
[ "vector" ]
5bd078529792b75fe52133c9614d8bd9da18bc9f
12,907
cxx
C++
Projects/shader_SkyBox/SkyDome_shader.cxx
Neill3d/MoPlugs
84efea03e045f820f3dc132c1a60a779fc5e34fc
[ "BSD-3-Clause" ]
23
2017-10-20T07:01:18.000Z
2022-02-25T08:46:07.000Z
Projects/shader_SkyBox/SkyDome_shader.cxx
droidoid/MoPlugs
fce52e6469408e32e94af8ac8a303840bc956e53
[ "BSD-3-Clause" ]
1
2019-11-08T04:03:38.000Z
2019-11-10T10:16:00.000Z
Projects/shader_SkyBox/SkyDome_shader.cxx
droidoid/MoPlugs
fce52e6469408e32e94af8ac8a303840bc956e53
[ "BSD-3-Clause" ]
5
2017-12-03T20:43:27.000Z
2020-01-22T16:54:13.000Z
////////////////////////////////////////////////////////////////////////////////////////////////// // // file: SkyDome_shader.cxx // // Author Sergey Solokhin (Neill3d) // // GitHub page - https://github.com/Neill3d/MoPlugs // Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE // /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef ORSDK_DLL /** \def ORSDK_DLL * Be sure that ORSDK_DLL is defined only once... */ #define ORSDK_DLL K_DLLEXPORT #endif // Class declaration #include "SkyDome_shader.h" #include <Windows.h> #include <CommDlg.h> #include <algorithm> #include <vector> #include "graphics\glslShader.h" #include "IO\FileUtils.h" //--- Registration defines #define ORSHADERSKYDOME__CLASS ORSHADERSKYDOME__CLASSNAME #define ORSHADERSKYDOME__DESC "SkyDome" //--- FiLMBOX Registration & Implementation. FBShaderImplementation( ORSHADERSKYDOME__CLASS ); FBRegisterShader ( ORSHADERSKYDOME__DESCSTR, ORSHADERSKYDOME__CLASS, ORSHADERSKYDOME__DESCSTR, ORSHADERSKYDOME__DESC, FB_DEFAULT_SDK_ICON ); //////////////////////////////////////////////////////////// static GLSLShader *gShader = nullptr; static int gShaderRef = 0; static GLint gShaderCameraLoc=0; static GLint gShaderContrastLoc=0; static GLint gShaderBrightnessLoc=0; static GLint gShaderSaturationLoc=0; static GLint gShaderGammaLoc=0; #define SKYDOME_VERTEX "\\GLSL\\skydome.vsh" #define SKYDOME_FRAGMENT "\\GLSL\\skydome.fsh" /************************************************ * FiLMBOX Constructor. ************************************************/ bool ORShaderSkyDome::FBCreate() { FBPropertyPublish( this, LayerId, "Layer Id", nullptr, nullptr ); FBPropertyPublish( this, Contrast, "Contrast", nullptr, nullptr ); FBPropertyPublish( this, Brightness, "Brightness", nullptr, nullptr ); FBPropertyPublish( this, Saturation, "Saturation", nullptr, nullptr ); FBPropertyPublish( this, Gamma, "Gamma", nullptr, nullptr ); FBPropertyPublish( this, Transparency, "Transparency", nullptr, nullptr ); FBPropertyPublish( this, TransparencyFactor, "Transparency Factor", nullptr, nullptr ); LayerId = 0; LayerId.SetMinMax( 0.0, 10.0, true, true ); Brightness = 0.0; Brightness.SetMinMax(-100.0, 100.0, true, true); Saturation = 0.0; Saturation.SetMinMax(-100.0, 100.0, true, true); Contrast = 0.0; Contrast.SetMinMax(-100.0, 100.0, true, true); Gamma = 100.0; Gamma.SetMinMax(-300.0, 300.0, true, true); Transparency = kFBAlphaSourceNoAlpha; TransparencyFactor = 100.0; TransparencyFactor.SetMinMax( 0.0, 100.0, true, true ); // RenderingPass = kFBPassPreRender; //SetShaderCapacity(kFBShaderCapacityMaterialEffect, false); //SetShaderPassActionCallback( (FBShaderPassActionCallback) (kFBShaderPassInstanceBegin | kFBShaderPassInstanceEnd | kFBShaderPassMaterialBegin | kFBShaderPassMaterialEnd) ); gShaderRef++; if (gShader == nullptr) { FBString effectPath, effectFullName; try { gShader = new GLSLShader(); if (gShader == nullptr) throw std::exception( "Failed to allocate memory for a shader" ); if (false == FindEffectLocation( SKYDOME_FRAGMENT, effectPath, effectFullName ) ) throw std::exception( "Failed to locate shader files" ); // most of shaders share the same simple vertex shader if (false == gShader->LoadShaders( FBString(effectPath, SKYDOME_VERTEX), FBString(effectPath, SKYDOME_FRAGMENT) ) ) throw std::exception( "Failed to load shader" ); // // find locations for all neede shader uniforms GLint colorLoc = gShader->findLocation( "colorSampler" ); gShaderCameraLoc = gShader->findLocation( "CameraPos" ); gShaderContrastLoc = gShader->findLocation( "contrast" ); gShaderBrightnessLoc = gShader->findLocation( "brightness" ); gShaderSaturationLoc = gShader->findLocation( "saturation" ); gShaderGammaLoc = gShader->findLocation( "gamma" ); gShader->Bind(); if (colorLoc >= 0) GLSLShader::setUniformUINT( colorLoc, 0 ); gShader->UnBind(); } catch ( const std::exception &e ) { FBMessageBox( "SkyDome Shader", e.what(), "Ok" ); if (gShader != nullptr) { delete gShader; gShader = nullptr; gShaderRef=0; } } } return true; } /************************************************ * FiLMBOX Destructor. ************************************************/ void ORShaderSkyDome::FBDestroy() { gShaderRef--; if (gShaderRef <= 0) { if (gShader) { delete gShader; gShader = nullptr; } gShaderRef = 0; } } /* void ORShaderSkyDome::ShaderPassInstanceBegin( FBRenderOptions* pRenderOptions, FBRenderingPass pPass) { glDepthMask(GL_FALSE); mCullFace = glIsEnabled(GL_CULL_FACE); glGetIntegerv( GL_CULL_FACE_MODE, &mCullFaceMode ); } void ORShaderSkyBox::ShaderPassInstanceEnd ( FBRenderOptions* pRenderOptions, FBRenderingPass pPass) { glDepthMask(GL_TRUE); if (mCullFace == GL_TRUE) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); glCullFace(mCullFaceMode); } void ORShaderSkyBox::ShaderPassMaterialBegin( FBRenderOptions* pRenderOptions, FBRenderingPass pPass, FBShaderModelInfo* pInfo) { FBMaterial *pMaterial = pInfo->GetFBMaterial(); FBModel *pModel = pInfo->GetFBModel(); if (pModel == nullptr || pMaterial == nullptr) return; FBModelCullingMode cullMode = pModel->GetCullingMode(); switch(cullMode) { case kFBCullingOff: glDisable(GL_CULL_FACE); break; case kFBCullingOnCW: glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); break; case kFBCullingOnCCW: glEnable(GL_CULL_FACE); glCullFace(GL_BACK); break; } pMaterial->OGLInit(); FBTexture *pTexture = pMaterial->GetTexture(); if (pTexture) { glEnable(GL_TEXTURE_2D); pTexture->OGLInit(pRenderOptions); } } void ORShaderSkyBox::ShaderPassMaterialEnd ( FBRenderOptions* pRenderOptions, FBRenderingPass pPass, FBShaderModelInfo* pInfo) { glDisable(GL_TEXTURE_2D); } */ /** Does the shader need a begin render call. * \remark Re-implement this function and return true if you need it. This method is called once per shader on each render pass. */ bool ORShaderSkyDome::ShaderNeedBeginRender() { return true; } /** Pre-rendering of shaders that is called only one time for a shader instance. * \remark ShaderBeginRender is called as many times as the number of models affected * by the instance of the shader in a given render pass. (ShaderNeedBeginRender * must return true for this function to be called). */ void ORShaderSkyDome::ShaderBeginRender( FBRenderOptions* pOptions, FBShaderModelInfo* pInfo ) { needRender = true; } void ORShaderSkyDome::ShadeModel( FBRenderOptions* pRenderOptions, FBShaderModelInfo* pShaderModelInfo, FBRenderingPass pPass ) { if (needRender == false) return; // render all skyboxe layers here FBSystem lSystem; FBScene *mScene = lSystem.Scene; int maxIndex = 0; std::vector<ORShaderSkyDome*> shaders; const int numberOfShaders = mScene->Shaders.GetCount(); for (int i=0; i<numberOfShaders; ++i) { if (FBIS( mScene->Shaders[i], ORShaderSkyDome) ) { ORShaderSkyDome *pSkyShader = (ORShaderSkyDome*) mScene->Shaders[i]; maxIndex = std::max(maxIndex, pSkyShader->LayerId.AsInt() ); shaders.push_back( (ORShaderSkyDome*) mScene->Shaders[i] ); } } // EnterRendering( pRenderOptions, pPass ); for (int i=0; i<=maxIndex; ++i) { for (auto iter=shaders.begin(); iter!=shaders.end(); ++iter) { if ( (*iter)->LayerId == i) { bool useBlend = (*iter)->Transparency != kFBAlphaSourceNoAlpha; if (useBlend) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } int count = (*iter)->GetDstCount(); for (int j=0; j<count; ++j) { FBPlug *pPlug = (*iter)->GetDst(j); if (FBIS(pPlug, FBModel) ) { (*iter)->Render(pRenderOptions, (FBModel*) pPlug, useBlend ); } } if (useBlend) { glDisable(GL_BLEND); } } } } LeaveRendering( pRenderOptions, pPass ); } void SetMaterial( FBRenderOptions* pRenderOptions, FBMaterial *pMaterial ) { pMaterial->OGLInit(); FBTexture *pTexture = pMaterial->GetTexture(); if (pTexture) { glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); pTexture->OGLInit(pRenderOptions); } } void UnSetMaterial() { glDisable(GL_TEXTURE_2D); } void ORShaderSkyDome::EnterRendering( FBRenderOptions* pRenderOptions, FBRenderingPass pPass) { glDepthMask(GL_FALSE); mCullFace = glIsEnabled(GL_CULL_FACE); glGetIntegerv( GL_CULL_FACE_MODE, &mCullFaceMode ); } void ORShaderSkyDome::LeaveRendering ( FBRenderOptions* pRenderOptions, FBRenderingPass pPass) { glDepthMask(GL_TRUE); if (mCullFace == GL_TRUE) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); glCullFace(mCullFaceMode); } void ORShaderSkyDome::Render( FBRenderOptions* pRenderOptions, FBModel *pModel, const bool useBlend ) { // DONE: render object with one diffuse texture (sky dome) FBCamera *pCamera = pRenderOptions->GetRenderingCamera(); if (pCamera && FBIS(pCamera, FBCameraSwitcher) ) pCamera = ( (FBCameraSwitcher*) pCamera)->CurrentCamera; if (pModel == nullptr || pCamera == nullptr) return; FBMatrix m; FBVector3d v; pCamera->GetCameraMatrix( m, kFBModelView ); pCamera->GetVector(v); glPushMatrix(); glLoadMatrixd(m); FBModelCullingMode cullMode = pModel->GetCullingMode(); switch(cullMode) { case kFBCullingOff: glDisable(GL_CULL_FACE); break; case kFBCullingOnCW: glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); break; case kFBCullingOnCCW: glEnable(GL_CULL_FACE); glCullFace(GL_BACK); break; } // draw model here FBModelVertexData *pData = pModel->ModelVertexData; if (pData) { pModel->GetMatrix(m); glMultMatrixd(m); pData->EnableOGLVertexData(); pData->EnableOGLUVSet(); const GLuint id = pData->GetVertexArrayVBOId(kFBGeometryArrayID_Color); if (useBlend) { if (id > 0) { glBindBuffer(GL_ARRAY_BUFFER, id); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, 0, (GLvoid*) 0); } } if (gShader) { gShader->Bind(); if (gShaderCameraLoc >= 0) GLSLShader::setUniformVector( gShaderCameraLoc, (float)v[0], (float)v[1], (float)v[2], 1.0 ); float cValue = 1.0f + 0.01f * (float) Contrast; float bValue = 1.0f + 0.01f * (float) Brightness; float sValue = 1.0f + 0.01f * (float) Saturation; float gValue = 0.01f * (float) Gamma; GLSLShader::setUniformFloat( gShaderContrastLoc, cValue ); GLSLShader::setUniformFloat( gShaderBrightnessLoc, bValue ); GLSLShader::setUniformFloat( gShaderSaturationLoc, sValue ); GLSLShader::setUniformFloat( gShaderGammaLoc, gValue ); } const int count = pData->GetSubRegionCount(); for (int i=0; i<count; ++i) { SetMaterial( pRenderOptions, pData->GetSubRegionMaterial(i) ); pData->DrawSubRegion(i); } if (gShader) { gShader->UnBind(); } pData->DisableOGLUVSet(); pData->DisableOGLVertexData(); if (id > 0) glDisableClientState(GL_COLOR_ARRAY); UnSetMaterial(); } glPopMatrix(); // needRender = false; } bool ORShaderSkyDome::FbxStore (FBFbxObject* pFbxObject) { return true; } bool ORShaderSkyDome::FbxRetrieve(FBFbxObject* pFbxObject, FBRenderer* pRenderer) { return true; } void ORShaderSkyDome::DetachDisplayContext( FBRenderOptions* pOptions, FBShaderModelInfo* pInfo ) { } FBShaderModelInfo *ORShaderSkyDome::NewShaderModelInfo(HKModelRenderInfo pModelRenderInfo, int pSubRegionIndex) { FBShaderModelInfo *lShaderModelInfo = ParentClass::NewShaderModelInfo(pModelRenderInfo, pSubRegionIndex); //FBShaderModelInfo *lShaderModelInfo = new SuperShaderModelInfo(this, pModelRenderInfo, pSubRegionIndex); return lShaderModelInfo; } void ORShaderSkyDome::UpdateModelShaderInfo( FBRenderOptions* pOptions, FBShaderModelInfo *pModelRenderInfo ) { unsigned int lVBOFormat = kFBGeometryArrayID_Point | kFBGeometryArrayID_Normal; if (pModelRenderInfo->GetOriginalTextureFlag()) { FBMaterial *lMaterial = pModelRenderInfo->GetFBMaterial(); if (lMaterial) { //HFBTexture lDiffuseTexture = pMaterial->GetTexture(kFBMaterialTextureDiffuse); FBTexture *lNormalMapTexture = lMaterial->GetTexture(kFBMaterialTextureBump); if (lNormalMapTexture == nullptr) lNormalMapTexture = lMaterial->GetTexture(kFBMaterialTextureNormalMap); if (lNormalMapTexture) lVBOFormat = lVBOFormat | kFBGeometryArrayID_Tangent | kFBGeometryArrayID_Binormal; } } // check if second uv set is needed in some texture if (Transparency != kFBAlphaSourceNoAlpha) lVBOFormat = lVBOFormat | kFBGeometryArrayID_Color; pModelRenderInfo->SetGeometryArrayIds(lVBOFormat); pModelRenderInfo->UpdateModelShaderInfo(GetShaderVersion()); }
25.258317
175
0.695592
[ "render", "object", "vector", "model" ]
5bdd4c624a2e294122493e7c229d91ae06d36010
2,151
cpp
C++
engine/commands/select_tile/source/TileSelectionKeyboardCommandMap.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
1
2020-05-24T22:44:03.000Z
2020-05-24T22:44:03.000Z
engine/commands/select_tile/source/TileSelectionKeyboardCommandMap.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
engine/commands/select_tile/source/TileSelectionKeyboardCommandMap.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
#ifdef _MSC_VER #include <curses.h> #else #include <ncurses.h> #endif #include "Conversion.hpp" #include "CommandKeys.hpp" #include "TileSelectionCommandKeys.hpp" #include "TileSelectionKeyboardCommandMap.hpp" using namespace std; TileSelectionKeyboardCommandMap::TileSelectionKeyboardCommandMap() { } TileSelectionKeyboardCommandMap::~TileSelectionKeyboardCommandMap() { } void TileSelectionKeyboardCommandMap::command_not_found(const string& keyboard_input) { if (!keyboard_input.empty()) { // Do nothing for now! } } vector<string> TileSelectionKeyboardCommandMap::get_remappable_commands() const { return { TileSelectionCommandKeys::CURSOR_MOVE_SOUTHWEST, TileSelectionCommandKeys::CURSOR_MOVE_SOUTH, TileSelectionCommandKeys::CURSOR_MOVE_SOUTHEAST, TileSelectionCommandKeys::CURSOR_MOVE_WEST, TileSelectionCommandKeys::CURSOR_MOVE_EAST, TileSelectionCommandKeys::CURSOR_MOVE_NORTHWEST, TileSelectionCommandKeys::CURSOR_MOVE_NORTH, TileSelectionCommandKeys::CURSOR_MOVE_NORTHEAST, CommandKeys::BESTIARY, TileSelectionCommandKeys::CANCEL_TILE_SELECTION }; } void TileSelectionKeyboardCommandMap::initialize_command_mapping(const Settings& settings) { command_mapping.clear(); // Non-remappable commands command_mapping = KeyboardCommandMappingMap { { std::to_string('+'), TileSelectionCommandKeys::TARGET_NEXT_CREATURE }, { std::to_string('='), TileSelectionCommandKeys::TARGET_NEXT_CREATURE }, { std::to_string('-'), TileSelectionCommandKeys::TARGET_PREV_CREATURE } }; initialize_special_key_mappings(); vector<string> remappable_commands = get_remappable_commands(); parse_keybindings(settings, remappable_commands); } KeyboardCommandMap* TileSelectionKeyboardCommandMap::clone() { return new TileSelectionKeyboardCommandMap(*this); } string TileSelectionKeyboardCommandMap::get_settings_prefix() const { return "key_til_"; } ClassIdentifier TileSelectionKeyboardCommandMap::internal_class_identifier() const { return ClassIdentifier::CLASS_ID_TILE_SELECTION_KEYBOARD_COMMAND_MAP; } #ifdef UNIT_TESTS #include "unit_tests/TileSelectionKeyboardCommandMap_test.cpp" #endif
27.935065
97
0.815435
[ "vector" ]
5bde34208f85591d059802eff6b83f2ec3a00503
1,905
cpp
C++
UVa 10311 goldbach and euler/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10311 goldbach and euler/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10311 goldbach and euler/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <algorithm> #include <iostream> #include <iomanip> #include <cstring> #include <cstdlib> #include <climits> #include <sstream> #include <fstream> #include <cstdio> #include <string> #include <vector> #include <queue> #include <cmath> #include <stack> #include <map> #include <set> using namespace std; const int INF = 0x7fffffff; typedef pair<int, int> II; typedef vector<int> IV; typedef vector<II> IIV; typedef vector<bool> BV; typedef long long i64; typedef unsigned long long u64; typedef unsigned int u32; #define For(t,v,c) for(t::const_iterator v=c.begin(); v!=c.end(); ++v) #define IsComp(n) (_c[n>>6]&(1<<((n>>1)&31))) #define SetComp(n) _c[n>>6]|=(1<<((n>>1)&31)) const int MAXP = 100000000; const int SQRP = 10000; //sqrt(MAX) int _c[(MAXP >> 6) + 1]; void prime_sieve ( ) { for ( int i = 3; i <= SQRP; i += 2 ) if ( !IsComp ( i ) ) for ( int j = i * i; j <= MAXP; j += i + i ) SetComp ( j ); } bool is_prime ( int n ) { if ( n < 2 || ( n > 2 && n % 2 == 0 ) ) return false; return !IsComp ( n ); } int Case; int main ( ) { prime_sieve ( ); while ( scanf ( "%d", &Case ) == 1 ) { if ( Case % 2 == 0 ) { int left, right; bool flag = 0; for ( int i = Case / 2; i >= 2; --i ) if ( is_prime ( i ) && is_prime ( Case - i ) && i != ( Case - i ) ) { left = i, right = Case - i, flag = 1; break; } if ( flag ) printf ( "%d is the sum of %d and %d.\n", Case, left, right ); else printf ( "%d is not the sum of two primes!\n", Case ); } else { if ( is_prime ( Case - 2 ) ) printf ( "%d is the sum of 2 and %d.\n", Case, Case - 2 ); else printf ( "%d is not the sum of two primes!\n", Case ); } } return 0; }
27.214286
99
0.503937
[ "vector" ]
5be627f962df928df7a1840926b5803f93d64c8c
6,415
hpp
C++
wasmopencv/detectorsz/include/detectorsz/detectorsz.hpp
joaolsouzajr/wasm-perf-analysis
6f80cfad558161ff488f6742b10609dd32ee0e0f
[ "MIT" ]
null
null
null
wasmopencv/detectorsz/include/detectorsz/detectorsz.hpp
joaolsouzajr/wasm-perf-analysis
6f80cfad558161ff488f6742b10609dd32ee0e0f
[ "MIT" ]
2
2020-03-24T17:10:34.000Z
2020-03-31T04:22:43.000Z
apps/detectorsz/include/detectorsz/detectorsz.hpp
lourencoccc/tccwasm
b6ce19fab81ba83a4b2db39caff11a48090c8279
[ "MIT" ]
null
null
null
/* Copyright 2019, Joao Lourenco Souza Junior, all rights reserved. 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. */ #ifndef DETECTORSZ_HHP #define DETECTORSZ_HHP #include <iostream> #include <string> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/objdetect.hpp> using namespace std; namespace detectorsz { /********* Constants ******/ const int CV_TYPE_DEFAULT = CV_8UC4; const string FACE_CASCADE_PATH = "assets/haarcascade_frontalface_alt.xml"; const string EYES_CASCADE_PATH = "assets/haarcascade_eye_tree_eyeglasses.xml"; const string FACE_DETECT_NAME = "FACE_DETECT"; const string FACE_EYES_DETECT_NAME = "FACE_EYES_DETECT"; /********* Utils ******/ struct ProcessLog { string system; string workload; string function; int frameIndex; int numberDetectedObjects; long aquisitionTime; long processTime; long posProcessTime; }; /** * @brief Information about processes executed on Face Detect functions. */ class FaceEyesDetectLog { public: FaceEyesDetectLog(); ~FaceEyesDetectLog(); string workloadName; string functionName; string systemName; int numberDetectedFaces = 0; int numberDetectedEyes = 0; int64 processTime = 0; int64 totalTime = 0; int64 preProcTime = 0; int64 tagProcTime = 0; int64 posProcTime = 0; string toString(); private: }; /** * @brief Convert any cv::Mat to type RGBA. * @param src cv::Mat * @param dest cv::Mat */ void convertAnyMatToRGBA(cv::Mat &src, cv::Mat &dest); /** * @brief Convert any cv::Mat to gray scale. * (CV_8U) * @param src cv::Mat * @param dest cv::Mat */ void convertAnyMatToRGB(cv::Mat &src, cv::Mat &dest); /** * @brief Convert any cv::Mat to gray scale. * (CV_8U) * @param src cv::Mat * @param dest cv::Mat */ void convertAnyMatToGray(cv::Mat &src, cv::Mat &dest); /** * @brief Convert any cv::Mat to represent data as an array of unsigned char * (CV_8U). * @param src cv::Mat * @param dest cv::Mat */ void convertAnyMatTo8U(cv::Mat &src, cv::Mat &dest); /** * @brief Calc the size of data cv::Mat * @param mat cv::Mat */ size_t matSize(const cv::Mat &mat); /********* Image Processs ******/ /** * @brief Image data abstraction. It is an adapter to opencv cv::Mat class. */ class MatAdapter { public: /** * cv::Mat image wrapper */ cv::Mat matImg; /** * @brief Create a default image */ MatAdapter(); /** * @brief Create a image with rows and coloumns passed by param */ MatAdapter(int rows, int cols); /** * @brief Create a image with rows and coloumns passed by param */ MatAdapter(int rows, int cols, int cvType); /** * @brief Destruct any resources used by MatAdapter instance. */ ~MatAdapter(); /** * @brief Return pointer with data from MatAdapter::matImg * @see MatAdapter::matImg * @return cv:Mat::data */ unsigned char *getData(); // void setData(unsigned char *_data); private: }; /** * @brief Class with functions to process and tranform images. */ class ImageProcess { public: /** * @brief Create a default instance of ImageProcess. */ ImageProcess(); /** * @brief Destruct any resources of ImageProcess instance. */ ~ImageProcess(); /** * @brief From original image create the new gray image with type RGBA. * @see MatAdapter * @param srcImg MatAdapter original image * @param destImg MatAdapter new gray image with type RGBA. */ void gray(MatAdapter &srcImg, MatAdapter &destImg); /** * @brief From original image create the new gray image with type RGBA. * @see MatAdapter * @param srcImg MatAdapter original image * @param destImg MatAdapter new gray image with type RGBA. */ void hsv(MatAdapter &srcImg, MatAdapter &destImg); private: }; /** * @brief Class with funcions to detect faces on frame. */ class FaceDetect { public: string dataName; /** * Log with proscess time for every workload image. */ vector<FaceEyesDetectLog> logs; /** * @brief Create a default instance of FaceDetect. */ FaceDetect(); FaceDetect(string dataName); /** * @brief Destruct any resources of FaceDetect instance. */ ~FaceDetect(); /** * @brief Detect face in image data and draw a elpse in this region * @see MatAdapter * @param src MatAdapter with image data. */ void faceDetect(MatAdapter &src); /** * @brief Detect face in image data, draw a elpse in this region and record * process time. * @see MatAdapter * @param src MatAdapter with image data. */ void faceDetectWithLog(MatAdapter &src); /** * @brief Detect face and eyes in image data and draw a elpses in those * regions. * @see MatAdapter * @param src MatAdapter with image data. */ void faceAndEyesDetect(MatAdapter &src); /** * @brief Detect face and eyes in image data, draw a elpses in those regions * and record process time. * @param src MatAdapter with image data. */ void faceAndEyesDetectWithLog(MatAdapter &src); /** * Return all logs recorded in the FaceDetecte instance. * @see FaceEyesDetectLog * @return A vector of FaceEyesDetectLog */ string logsToString(); string logsToStringAndAddCommon(string head, string columns); void updateTotalTime(int frameIndex, int time); private: cv::CascadeClassifier faceCascade; cv::CascadeClassifier eyesCascade; void loadCascadeFiles(); }; } // namespace detectorsz #endif
23.847584
80
0.70039
[ "vector" ]
5bf8ebc623c56e82c37f987138be859bb14f0dac
58,351
cpp
C++
src/engine/dinput.cpp
nikodemak/Allegiance
9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc
[ "MIT" ]
1
2017-10-28T07:39:29.000Z
2017-10-28T07:39:29.000Z
src/engine/dinput.cpp
nikodemak/Allegiance
9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc
[ "MIT" ]
null
null
null
src/engine/dinput.cpp
nikodemak/Allegiance
9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc
[ "MIT" ]
null
null
null
#include <dinput.h> #include <regkey.h> #include <zreg.h> #include "LogFile.h" #include "ddstruct.h" #include "enginep.h" #include "inputengine.h" #include "value.h" #include "window.h" #define DINPUT_BUFFERSIZE 32 #ifndef DIFEF_MODIFYIFNEEDED # define DIFEF_MODIFYIFNEEDED 0x00000010 #endif #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } ////////////////////////////////////////////////////////////////////////////// // // DDWrapers // ////////////////////////////////////////////////////////////////////////////// class DIDeviceCaps : public TZeroFillWithSize<DIDEVCAPS> { public: }; class DIDeviceInstance : public TZeroFillWithSize<DIDEVICEINSTANCE> { public: }; class DIDataFormat : public TZeroFillWithSize<DIDATAFORMAT> { public: }; class DIObjectDataFormat : public TZeroFill<DIOBJECTDATAFORMAT> { public: }; ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// const DIDATAFORMAT* g_pdfDIMouse; //Imago FFE file support (related kinda to #187) struct EFFECTS_NODE { LPDIRECTINPUTEFFECT pDIEffect; DWORD dwPlayRepeatCount; EFFECTS_NODE* pNext; }; EFFECTS_NODE g_BounceEffectsList; EFFECTS_NODE g_FireEffectsList; EFFECTS_NODE g_ExplodeEffectsList; ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// class DDInputObject : public IObject { private: ZString m_strName; DWORD m_dwType; GUID m_guidType; public: DDInputObject(const ZString& strName, DWORD dwType, const GUID& guidType) : m_strName(strName), m_dwType(dwType), m_guidType(guidType) { } const ZString& GetName() const { return m_strName; } DWORD GetDWType() const { return m_dwType; } const GUID& GetGUID() const { return m_guidType; } }; class ValueDDInputObject : public DDInputObject { private: TRef<ModifiableNumber> m_pnumber; public: ValueDDInputObject(const ZString& strName, DWORD dwID, const GUID& guidType) : DDInputObject(strName, dwID, guidType), m_pnumber(new ModifiableNumber(0)) { } ModifiableNumber* GetValue() const { return m_pnumber; } }; class ButtonDDInputObject : public DDInputObject { private: TRef<ModifiableBoolean> m_pbool; public: ButtonDDInputObject(const ZString& strName, DWORD dwID, const GUID& guidType) : DDInputObject(strName, dwID, guidType), m_pbool(new ModifiableBoolean(false)) { } ModifiableBoolean* GetValue() const { return m_pbool; } }; ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// std::string GetLastErrorAsString() { //Get the error message, if any. DWORD errorMessageID = ::GetLastError(); if (errorMessageID == 0) return std::string(); //No error message has been recorded LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); std::string message(messageBuffer, size); //Free the buffer. LocalFree(messageBuffer); return message; } class InputStreamState { public: TRef<ButtonEvent::SourceImpl> m_pbuttonEventSource; TVector<TRef<ValueDDInputObject > > m_vvalueObject; TVector<TRef<ButtonDDInputObject> > m_vbuttonObject; InputStreamState() : m_pbuttonEventSource(ButtonEvent::Source::Create()), m_vvalueObject(3), m_vbuttonObject(0) { } int GetValueCount() { return m_vvalueObject.GetCount(); } int GetButtonCount() { return m_vbuttonObject.GetCount(); } Boolean* IsDown(int id) { if (id < m_vbuttonObject.GetCount()) { return m_vbuttonObject[id]->GetValue(); } else { return NULL; } } Number* GetValue(int id) { if (id < m_vvalueObject.GetCount()) { return m_vvalueObject[id]->GetValue(); } else { return NULL; } } ButtonEvent::Source* GetEventSource() { return m_pbuttonEventSource; } }; class MouseInputStreamState : public InputStreamState { public: Rect m_rectClip; TRef<SimpleModifiableValue<Point>> m_point; float m_z; bool m_bEnabled; int m_threshold1; int m_threshold2; int m_acceleration; float m_sensitivity; MouseInputStreamState() : m_point(new SimpleModifiableValue<Point>(Point(0, 0))) { } void SetXY(float x, float y) { Point point(x, y); m_rectClip.Clip(point); m_point->SetValue(point); m_vvalueObject[0]->GetValue()->SetValue(point.X()); m_vvalueObject[1]->GetValue()->SetValue(point.Y()); } void SetRelativeXY(float x, float y) { const Point& point = m_point->GetValue(); SetXY( point.X() + x, point.Y() + y ); } void ButtonChanged(int index, bool bDown) { m_vbuttonObject[index]->GetValue()->SetValue(bDown); m_pbuttonEventSource->Trigger(ButtonEventData(index, bDown)); } void ResetWheel() { if (m_vbuttonObject[8] != NULL && m_vbuttonObject[8]->GetValue()->GetValue()) //#217 ButtonChanged(8, false); if (m_vbuttonObject[8] != NULL && m_vbuttonObject[9]->GetValue()->GetValue()) //#217 ButtonChanged(9, false); } void SetRelativeWheel(int delta) { m_z += (float)delta; if (m_vvalueObject.GetCount() >= 3 && m_vvalueObject[2] != NULL) { m_vvalueObject[2]->GetValue()->SetValue(m_z); //also treat a scroll event as a button press if (delta < 0) { ButtonChanged(8, true); } else if (delta > 0) { ButtonChanged(9, true); } else { //imago 8/13/09 use dz == 0 for button up ResetWheel(); } } } float CalculateDelta(int delta) { if (abs(delta) > m_threshold1 && m_acceleration >= 1) { if (abs(delta) > m_threshold2 && m_acceleration >= 2) { return float(delta) * 4.0f * m_sensitivity; } else { return float(delta) * 2.0f * m_sensitivity; } } return float(delta) * m_sensitivity; } }; template <typename T> class InputStreamStateWrapper : virtual public InputStream { protected: std::shared_ptr<T> m_pstate; public: InputStreamStateWrapper(const std::shared_ptr<T> pstate) : m_pstate(pstate) { } int GetValueCount() { return m_pstate->GetValueCount(); } int GetButtonCount() { return m_pstate->GetButtonCount(); } Boolean* IsDown(int id) { return m_pstate->IsDown(id); } Number* GetValue(int id) { return m_pstate->GetValue(id); } ButtonEvent::Source* GetEventSource() { return m_pstate->GetEventSource(); } }; class MouseInputStreamStateWrapper : public InputStreamStateWrapper<MouseInputStreamState>, virtual public MouseInputStream { public: MouseInputStreamStateWrapper(const std::shared_ptr<MouseInputStreamState> pstate) : InputStreamStateWrapper(pstate) {} bool IsEnabled() override { return m_pstate->m_bEnabled; } void SetEnabled(bool bEnable) override { m_pstate->m_bEnabled = bEnable; } void SetClipRect(const Rect& rect) override { m_pstate->m_rectClip = rect; Point point = m_pstate->m_point->GetValue(); m_pstate->SetXY(point.X(), point.Y()); } void SetPosition(const Point& point) override { m_pstate->SetXY(point.X(), point.Y()); } TRef<TStaticValue<Point>> GetPosition() override { return m_pstate->m_point; } float GetWheelPosition() override { return m_pstate->m_z; } void SetWheelPosition(float z) override { m_pstate->m_z = z; } void SetSensitivity(const float sens) override { m_pstate->m_sensitivity = sens; } void SetAccel(const int accel) override { m_pstate->m_acceleration = accel; } }; class RawInputPump : public TEvent<PRAWINPUT>::SourceImpl { private: public: void Pump() { MSG msg; while (::PeekMessage(&msg, NULL, WM_INPUT, WM_INPUT, PM_REMOVE)) { UINT dwSize; if (0 != GetRawInputData((HRAWINPUT)msg.lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER))) { //an error continue; } if (dwSize == 0) { //empty continue; } LPBYTE lpb = new BYTE[dwSize]; if (GetRawInputData((HRAWINPUT)msg.lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) { //incorrect length continue; } PRAWINPUT pri = (PRAWINPUT)lpb; this->Trigger(pri); delete[] lpb; } } }; class RawMouseInputStreamImpl : virtual public MouseInputStream, MouseInputStreamStateWrapper, TEvent<PRAWINPUT>::Sink { HWND m_hwnd; TRef<RawInputPump> m_ppump; TRef<TEvent<PRAWINPUT>::Sink> m_sinkDelegate; public: RawMouseInputStreamImpl(HWND hwnd, const std::shared_ptr<MouseInputStreamState> pstate, TRef<RawInputPump> ppump) : m_hwnd(hwnd), MouseInputStreamStateWrapper(pstate), m_ppump(ppump), m_sinkDelegate(nullptr) { } ~RawMouseInputStreamImpl() { SetEnabled(false); } void SetEnabled(bool bEnable) override { if (IsEnabled() == bEnable) { return; } MouseInputStreamStateWrapper::SetEnabled(bEnable); RAWINPUTDEVICE Rid[1]; Rid[0].usUsagePage = 0x01; Rid[0].usUsage = 0x02; if (IsEnabled()) { Rid[0].dwFlags = RIDEV_EXINPUTSINK | RIDEV_CAPTUREMOUSE | RIDEV_NOLEGACY; Rid[0].hwndTarget = m_hwnd; m_sinkDelegate = TEvent<PRAWINPUT>::Sink::CreateDelegate(this); m_ppump->AddSink(m_sinkDelegate); } else { Rid[0].dwFlags = RIDEV_REMOVE; Rid[0].hwndTarget = NULL; m_ppump->RemoveSink(m_sinkDelegate); m_sinkDelegate = nullptr; } if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) != TRUE) { debugf("Mouse input: Failed SetEnable (%s)", IsEnabled() ? "true" : "false"); } } void Update() override { m_pstate->ResetWheel(); } bool OnEvent(TEvent<PRAWINPUT>::Source* pevent, PRAWINPUT pri) override { if (this->IsEnabled() == false) { return true; } if (pri->header.dwType != RIM_TYPEMOUSE) { // not the mouse return true; } RAWMOUSE data = pri->data.mouse; bool bMouseAbsolute; bMouseAbsolute = data.usFlags & MOUSE_MOVE_ABSOLUTE; if (bMouseAbsolute == false) { if (data.lLastX != 0 || data.lLastY != 0) { m_pstate->SetRelativeXY( m_pstate->CalculateDelta(data.lLastX), m_pstate->CalculateDelta(-data.lLastY) ); } } else { m_pstate->SetXY(data.lLastX, data.lLastY); } if (data.usButtonFlags & RI_MOUSE_WHEEL) { m_pstate->SetRelativeWheel((short)(unsigned short)data.usButtonData); } if (data.usButtonFlags != 0) { int iButton = GetButtonIndexFromButtonFlags(data.usButtonFlags); if (iButton >= 0 && iButton < GetButtonCount()) { bool bDown = GetIsButtonDownFromButtonFlags(data.usButtonFlags); m_pstate->ButtonChanged(iButton, bDown); } } return true; } int GetButtonIndexFromButtonFlags(USHORT flag) { // the index is different from directinput to raw input, we use the directinput mapping which starts at 0 switch (flag) { case RI_MOUSE_LEFT_BUTTON_DOWN: case RI_MOUSE_LEFT_BUTTON_UP: return 0; case RI_MOUSE_RIGHT_BUTTON_DOWN: case RI_MOUSE_RIGHT_BUTTON_UP: return 1; case RI_MOUSE_BUTTON_3_DOWN: case RI_MOUSE_BUTTON_3_UP: return 2; case RI_MOUSE_BUTTON_4_DOWN: case RI_MOUSE_BUTTON_4_UP: return 3; case RI_MOUSE_BUTTON_5_DOWN: case RI_MOUSE_BUTTON_5_UP: return 4; } return -1; } bool GetIsButtonDownFromButtonFlags(USHORT flag) { switch (flag) { case RI_MOUSE_LEFT_BUTTON_DOWN: case RI_MOUSE_RIGHT_BUTTON_DOWN: case RI_MOUSE_BUTTON_3_DOWN: case RI_MOUSE_BUTTON_4_DOWN: case RI_MOUSE_BUTTON_5_DOWN: return true; case RI_MOUSE_LEFT_BUTTON_UP: case RI_MOUSE_RIGHT_BUTTON_UP: case RI_MOUSE_BUTTON_3_UP: case RI_MOUSE_BUTTON_4_UP: case RI_MOUSE_BUTTON_5_UP: return false; } return false; } }; class MouseInputStreamImpl : virtual public MouseInputStream, public MouseInputStreamStateWrapper { private: ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// BOOL EnumObjectsCallback( LPCDIDEVICEOBJECTINSTANCE pddoi ) { LPOLESTR szGUID = new WCHAR [39]; char chGUID[39]; StringFromGUID2(pddoi->guidType,szGUID,39); WideCharToMultiByte( CP_ACP, 0, szGUID, -1, chGUID, 39, 0, 0 ); m_pLogFile->OutputStringV("\t\tpddoi->guidType: %s\n",chGUID); m_pLogFile->OutputStringV("\t\tpddoi->tszName: %s\n",pddoi->tszName); m_pLogFile->OutputStringV("\t\tpddoi->dwType: %x (instance: %x)\n",DIDFT_GETTYPE(pddoi->dwType), DIDFT_GETINSTANCE(pddoi->dwType)); m_pLogFile->OutputStringV("\t\tpddoi->wUsage: %x (page: %x)\n",pddoi->wUsage,pddoi->wUsagePage); if ( pddoi->dwType & DIDFT_AXIS || pddoi->dwType & DIDFT_POV ) { int index; if (pddoi->guidType == GUID_XAxis) { index = 0; } else if (pddoi->guidType == GUID_YAxis) { index = 1; } else if (pddoi->guidType == GUID_ZAxis) { index = 2; } else { index = -1; } ValueDDInputObject* pobject = new ValueDDInputObject( pddoi->tszName, pddoi->dwType, pddoi->guidType ); if (index == -1) { m_pstate->m_vvalueObject.PushEnd(pobject); } else { m_pstate->m_vvalueObject.Set(index, pobject); } } else if (pddoi->dwType & DIDFT_PSHBUTTON) { ButtonDDInputObject* pobject = new ButtonDDInputObject( pddoi->tszName, pddoi->dwType, pddoi->guidType ); m_pstate->m_vbuttonObject.PushEnd(pobject); } return DIENUM_CONTINUE; } ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// static BOOL CALLBACK StaticEnumObjectsCallback( LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef ) { MouseInputStreamImpl* pthis = (MouseInputStreamImpl*)pvRef; pthis->m_pLogFile->OutputString("\tStaticEnumObjectsCallback:\n"); return pthis->EnumObjectsCallback(lpddoi); } ////////////////////////////////////////////////////////////////////////////// // // members // ////////////////////////////////////////////////////////////////////////////// // TRef<IDirectInputDevice2> m_pdid; TRef<IDirectInputDevice8> m_pdid; // kg: DInput8 DIDeviceCaps m_didc; DIDeviceInstance m_didi; bool m_bBuffered; HWND m_hwnd; CLogFile * m_pLogFile; //Imago 8/12/09 public: ////////////////////////////////////////////////////////////////////////////// // // Constructor // ////////////////////////////////////////////////////////////////////////////// // MouseInputStreamImpl(IDirectInputDevice2* pdid, HWND hwnd) : MouseInputStreamImpl(IDirectInputDevice8* pdid, HWND hwnd, CLogFile * pLogFile, std::shared_ptr<MouseInputStreamState> pstate) : // kg: DInput8 m_pdid(pdid), m_hwnd(hwnd), MouseInputStreamStateWrapper(pstate), m_bBuffered(true), m_pLogFile(pLogFile) { // // Are we running on NT // /*!!! OSVERSIONINFO osvi = { sizeof(osvi) }; ZVerify(GetVersionEx(&osvi)); if ((VER_PLATFORM_WIN32_NT & osvi.dwPlatformId) != 0) { m_bBuffered = false; } */ DDCall(m_pdid->GetCapabilities(&m_didc)); m_pLogFile->OutputStringV("\tInitialized mouse stream - Axes: %d, Buttons: %d, POVs: %d\n", m_didc.dwAxes,m_didc.dwButtons,m_didc.dwPOVs); // // Enumerate the buttons and values // DDCall(m_pdid->EnumObjects(StaticEnumObjectsCallback, this, DIDFT_ALL)); // // Setup the device // //Imago 8/14/09 if (m_pstate->m_vvalueObject[2] != NULL) { m_pstate->m_vbuttonObject.SetCount(10); ButtonDDInputObject* pobject = new ButtonDDInputObject("Wheel Up",0x00000301UL,GUID_ZAxis); m_pstate->m_vbuttonObject.Set(8,pobject); pobject = new ButtonDDInputObject("Wheel Down",0x00000401UL,GUID_ZAxis); m_pstate->m_vbuttonObject.Set(9,pobject); } SetupDevice(); // // We only need mouse input when we are in the foreground // DDCall(m_pdid->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)); // // Get the mouse acceleration values // int pvalue[3]; ZVerify(SystemParametersInfo(SPI_GETMOUSE, 0, pvalue, 0)); m_pstate->m_threshold1 = pvalue[0]; m_pstate->m_threshold2 = pvalue[1]; m_pstate->m_acceleration = pvalue[2]; } void SetupDevice() { // // Set the data format // DDCall(m_pdid->SetDataFormat(g_pdfDIMouse)); // // Make some buffer space // if (m_bBuffered) { DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = DINPUT_BUFFERSIZE; DDCall(m_pdid->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph)); } } ////////////////////////////////////////////////////////////////////////////// // // Methods // ////////////////////////////////////////////////////////////////////////////// void DeltaPosition(int& dx, int& dy) { if (dx != 0 || dy != 0) { m_pstate->SetRelativeXY( m_pstate->CalculateDelta(dx), m_pstate->CalculateDelta(-dy) ); dx = 0; dy = 0; } } void DeltaWheel(int dz) { m_pstate->SetRelativeWheel(dz); } void UpdateBuffered() { // // Get the data // DIDEVICEOBJECTDATA didod[DINPUT_BUFFERSIZE]; DWORD count = DINPUT_BUFFERSIZE; int dx = 0; int dy = 0; int dz = 0; HRESULT hr = m_pdid->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), didod, &count, 0); if (FAILED(hr)) { return; } if (hr == DI_BUFFEROVERFLOW) { debugf("Mouse buffer overflow, samples returned: %d", count); } for (int i = 0; i < count; ++i) { DIDEVICEOBJECTDATA& entry = didod[i]; switch (entry.dwOfs) { case DIMOFS_BUTTON0: DeltaPosition(dx, dy); m_pstate->ButtonChanged(0, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_BUTTON1: m_pstate->ButtonChanged(1, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_BUTTON2: m_pstate->ButtonChanged(2, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_BUTTON3: m_pstate->ButtonChanged(3, ((entry.dwData & 0x80) != 0)); break; // mdvalley: More buttons case DIMOFS_BUTTON4: m_pstate->ButtonChanged(4, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_BUTTON5: m_pstate->ButtonChanged(5, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_BUTTON6: m_pstate->ButtonChanged(6, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_BUTTON7: m_pstate->ButtonChanged(7, ((entry.dwData & 0x80) != 0)); break; case DIMOFS_X: dx += int(entry.dwData); break; case DIMOFS_Y: dy += int(entry.dwData); break; case DIMOFS_Z: dz += int(entry.dwData); break; } DeltaPosition(dx, dy); } DeltaWheel(dz); } void UpdatePolled() { // // Poll the device // m_pdid->Poll(); // // Get the data // // DIMOUSESTATE dims; DIMOUSESTATE2 dims; // mdvalley: Mousestate2 allows 8 buttons DDCall(m_pdid->GetDeviceState(sizeof(dims), &dims)); // // Unpack the data // int dx = int(dims.lX); int dy = int(dims.lY); int dz = int(dims.lZ); DeltaPosition(dx, dy); DeltaWheel(dz); int count = m_pstate->m_vbuttonObject.GetCount(); for (int index = 0; index < count; index++) { bool bDown = ((dims.rgbButtons[index] & 0x80) != 0); ModifiableBoolean* pbool = m_pstate->m_vbuttonObject[index]->GetValue(); if (bDown != pbool->GetValue()) { pbool->SetValue(bDown); m_pstate->ButtonChanged(index, bDown); } } } void Update() { if (m_pstate->m_bEnabled) { //ZDebugOutput("Mouse Enabled\n"); HRESULT hr = m_pdid->Acquire(); // // We have to handle the case where another app has captured the // mouse, since we may have been switched out. // if (hr != DIERR_OTHERAPPHASPRIO) { DDCall(hr); if (m_bBuffered) { UpdateBuffered(); } else { UpdatePolled(); } } } } ////////////////////////////////////////////////////////////////////////////// // // MouseInputStream // ////////////////////////////////////////////////////////////////////////////// void SetEnabled(bool bEnabled) { if (m_pstate->m_bEnabled != bEnabled) { MouseInputStreamStateWrapper::SetEnabled(bEnabled); if (IsEnabled()) { DDCall(m_pdid->SetCooperativeLevel(m_hwnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND)); } else { // DDCall(m_pdid->SetCooperativeLevel(m_hwnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND)); DDCall(m_pdid->Unacquire()); } } } }; ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// class JoystickInputStreamImpl : public JoystickInputStream { private: // TRef<IDirectInputDevice2> m_pdid; TRef<IDirectInputDevice8> m_pdid; // kg: DInput8 DIDeviceCaps m_didc; DIDeviceInstance m_didi; TVector<TRef<ValueDDInputObject > > m_vvalueObject; TVector<TRef<ButtonDDInputObject> > m_vbuttonObject; BYTE* m_pbyteData; DWORD m_sizeData; bool m_bFocus; bool m_bFFEBounceFile; //Imago 7/10 bool m_bFFEExplodeFile; //Imago 7/10 bool m_bFFEFireFile; //Imago 7/10 CLogFile * m_pLogFile; //Imago 8/12/09 ZString m_zArt; //Imago 7/10 TRef<IDirectInputEffect> m_peffectBounce; TRef<IDirectInputEffect> m_peffectFire; TRef<IDirectInputEffect> m_peffectExplode; public: ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// BOOL EnumObjectsCallback( LPCDIDEVICEOBJECTINSTANCE pddoi ) { if (!pddoi) { m_pLogFile->OutputString("\t\tLPCDIDEVICEOBJECTINSTANCE=NULL Skipping.\n"); return DIENUM_CONTINUE; } LPOLESTR szGUID = new WCHAR [39]; char chGUID[39]; StringFromGUID2(pddoi->guidType,szGUID,39); WideCharToMultiByte( CP_ACP, 0, szGUID, -1, chGUID, 39, 0, 0 ); m_pLogFile->OutputStringV("\t\tpddoi->guidType: %s\n",chGUID); m_pLogFile->OutputStringV("\t\tpddoi->tszName: %s\n",pddoi->tszName); m_pLogFile->OutputStringV("\t\tpddoi->dwType: %x (instance: %x)\n",DIDFT_GETTYPE(pddoi->dwType), DIDFT_GETINSTANCE(pddoi->dwType)); m_pLogFile->OutputStringV("\t\tpddoi->wUsage: %x (page: %x)\n",pddoi->wUsage,pddoi->wUsagePage); if ( pddoi->dwType & DIDFT_AXIS || pddoi->dwType & DIDFT_POV ) { int index; if (pddoi->guidType == GUID_XAxis ) { index = 0; } else if (pddoi->guidType == GUID_YAxis ) { index = 1; } else if ( (pddoi->guidType == GUID_Slider && pddoi->wUsage != 0x0037) //Imago 8/12/09 fixes "buged" Saitek X45 Flight Control Stick driver || pddoi->guidType == GUID_ZAxis ) { //Imago 7/10 index = 2; } else if (pddoi->guidType == GUID_RzAxis) { index = 3; } else if (pddoi->guidType == GUID_POV ) { index = 4; } else { index = -1; } ValueDDInputObject* pobject = new ValueDDInputObject( pddoi->tszName, pddoi->dwType, pddoi->guidType ); //Imago 7/10 if( ( pddoi->dwFlags & DIDOI_FFACTUATOR ) != 0 ) m_pLogFile->OutputStringV("\t\t\tHas Forcefeedback!\n",pddoi->wUsage,pddoi->wUsagePage); if (index == -1) { m_vvalueObject.PushEnd(pobject); } else { m_vvalueObject.Set(index, pobject); } } else if (pddoi->dwType & DIDFT_PSHBUTTON) { ButtonDDInputObject* pobject = new ButtonDDInputObject( pddoi->tszName, pddoi->dwType, pddoi->guidType ); m_vbuttonObject.PushEnd(pobject); } return DIENUM_CONTINUE; } ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// static BOOL CALLBACK StaticEnumObjectsCallback( LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef ) { JoystickInputStreamImpl* pthis = (JoystickInputStreamImpl*)pvRef; pthis->m_pLogFile->OutputString("\tStaticEnumObjectsCallback:\n"); return pthis->EnumObjectsCallback(lpddoi); } ////////////////////////////////////////////////////////////////////////////// // // Constructor // ////////////////////////////////////////////////////////////////////////////// // JoystickInputStreamImpl(IDirectInputDevice2* pdid, HWND hwnd) : JoystickInputStreamImpl(IDirectInputDevice8* pdid, HWND hwnd, CLogFile * pLogFile) : // kg: DInput8 Imago 8/12/09 m_pdid(pdid), m_bFocus(false), m_vvalueObject(20), //imago 12/03/09, was 5 m_pLogFile(pLogFile), m_bFFEBounceFile(false), // Imago 7/10 m_bFFEExplodeFile(false), m_bFFEFireFile(false) { m_zArt.SetEmpty(); //Imago FFE files //^ DDCall(m_pdid->GetCapabilities(&m_didc)); DDCall(m_pdid->GetDeviceInfo(&m_didi)); m_pLogFile->OutputStringV("\tInitialized joystick stream - Axes: %d, Buttons: %d, POVs: %d\n", m_didc.dwAxes,m_didc.dwButtons,m_didc.dwPOVs); // // Enumerate the buttons and values // DDCall(m_pdid->EnumObjects(StaticEnumObjectsCallback, this, DIDFT_ALL)); // // Remove any holes in the value vector // int index; int countValues = m_vvalueObject.GetCount(); index = 0; while (index < countValues) { if (m_vvalueObject[index] == NULL) { if (index != countValues - 1) { m_vvalueObject.Set(index, m_vvalueObject[countValues - 1]); } countValues--; m_vvalueObject.SetCount(countValues); } else { index++; } } //m_vvalueObject // // Build the data format // int countButtons = m_vbuttonObject.GetCount(); m_sizeData = NextMultipleOf(4, countValues * 4 + countButtons * 1); DIDataFormat didf; didf.dwObjSize = sizeof(DIOBJECTDATAFORMAT); didf.dwFlags = 0; didf.dwDataSize = m_sizeData; didf.dwNumObjs = countValues + countButtons; DIObjectDataFormat* pdiodf = new DIObjectDataFormat[didf.dwNumObjs]; didf.rgodf = pdiodf; for (index = 0; index < countValues; index++) { ValueDDInputObject* pobject = m_vvalueObject[index]; DIOBJECTDATAFORMAT& diodf = didf.rgodf[index]; diodf.pguid = (GUID*)&(pobject->GetGUID()); diodf.dwOfs = index * 4; diodf.dwType = pobject->GetDWType(); diodf.dwFlags = DIDOI_ASPECTPOSITION; } for (index = 0; index < countButtons; index++) { ButtonDDInputObject* pobject = m_vbuttonObject[index]; DIOBJECTDATAFORMAT& diodf = didf.rgodf[countValues + index]; diodf.pguid = (GUID*)&(pobject->GetGUID()); diodf.dwOfs = countValues * 4 + index; diodf.dwType = pobject->GetDWType(); diodf.dwFlags = DIDOI_ASPECTPOSITION; } DDCall(m_pdid->SetDataFormat(&didf)); delete pdiodf; // // Allocate a data receptical // m_pbyteData = new BYTE[m_sizeData]; // // We only need joystick input when we are in the foreground // DDCall(m_pdid->SetCooperativeLevel(hwnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND)); // // Set ranges // SetRanges(); } ~JoystickInputStreamImpl() { delete m_pbyteData; //Imago FFE file support if(m_bFFEBounceFile) { EmptyEffectLists(&g_BounceEffectsList); } if(m_bFFEFireFile) { EmptyEffectLists(&g_FireEffectsList); } if(m_bFFEExplodeFile) { EmptyEffectLists(&g_ExplodeEffectsList); } } ////////////////////////////////////////////////////////////////////////////// // // Implementation methods // ////////////////////////////////////////////////////////////////////////////// void SetRanges() { m_pdid->Unacquire(); int countValues = m_vvalueObject.GetCount(); for (int index = 0; index < countValues; index++) { if (m_vvalueObject[index] != NULL) { if ((m_vvalueObject[index]->GetDWType() & DIDFT_POV) == 0) { DIPROPRANGE dipr; dipr.diph.dwSize = sizeof(dipr); dipr.diph.dwHeaderSize = sizeof(dipr.diph); dipr.diph.dwHow = DIPH_BYID; dipr.diph.dwObj = m_vvalueObject[index]->GetDWType(); dipr.lMin = -100000; dipr.lMax = 100000; DDCall(m_pdid->SetProperty(DIPROP_RANGE, &dipr.diph)); } DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; DDCall(m_pdid->GetProperty(DIPROP_BUFFERSIZE, &dipdw.diph)); DIPROPDWORD dipdw5; dipdw5.diph.dwSize = sizeof(DIPROPDWORD); dipdw5.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw5.diph.dwObj = 0; dipdw5.diph.dwHow = DIPH_DEVICE; dipdw5.dwData = 0; m_pdid->SetProperty( DIPROP_AUTOCENTER, &dipdw5.diph ); //lazy DIPROPDWORD dipdw6; dipdw6.diph.dwSize = sizeof(DIPROPDWORD); dipdw6.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw6.diph.dwObj = 0; dipdw6.diph.dwHow = DIPH_DEVICE; dipdw6.dwData = 10000; m_pdid->SetProperty( DIPROP_FFGAIN, &dipdw6.diph ); // end Imago } } } void Update() { HRESULT hr = m_pdid->Acquire(); // // We have to handle the case where another app has captured the // joystick, since we may be switched out. // Or the joystick may have been unplugged. // if (SUCCEEDED(hr)) { // // Poll the device // m_pdid->Poll(); // // The MS Gamepad will return error from this funtion if the mode button is pressed // Don't assert in that case. Just don't unpack the data. // hr = m_pdid->GetDeviceState(m_sizeData, m_pbyteData); if (SUCCEEDED(hr)) { // // Unpack the data // int countValues = m_vvalueObject.GetCount(); int countButtons = m_vbuttonObject.GetCount(); for (int index = 0; index < countValues; index++) { if ((m_vvalueObject[index]->GetDWType() & DIDFT_POV) != 0) { int ivalue = ((int*)m_pbyteData)[index]; float value; if (ivalue == -1) { value = -2; } else if (ivalue > 18000) { value = float(ivalue - 36000) / 18000; } else { value = float(ivalue) / 18000; } //ZDebugOutput("RawHat: " + ZString(ivalue) + ", " + ZString(value) + "\n"); m_vvalueObject[index]->GetValue()->SetValue(value); } else { float value = float(((int*)m_pbyteData)[index]) / 100000; value = bound(value, -1.0f, 1.0f); m_vvalueObject[index]->GetValue()->SetValue(value); } } for (int index = 0; index < countButtons; index++) { m_vbuttonObject[index]->GetValue()->SetValue( m_pbyteData[countValues * 4 + index] != 0 ); } } } } void SetFocus(bool bFocus) { if (m_bFocus != bFocus) { m_bFocus = bFocus; if (m_bFocus) { // // Aquire the joystick // // !!! this doesn't work. I guess that at the time when this gets called // DInput doesn't think we are foreground yet. // DDCall(m_pdid->Acquire()); } else { // !!! this gets called automatically // DDCall(m_pdid->Unacquire()); } } } ////////////////////////////////////////////////////////////////////////////// // // Force Feedback // ////////////////////////////////////////////////////////////////////////////// static BOOL CALLBACK EnumEffectTypeProc(LPCDIEFFECTINFO pei, LPVOID pv) { GUID *pguidEffect = NULL; // report back the guid of the effect we enumerated if (pv) { pguidEffect = (GUID *)pv; *pguidEffect = pei->guid; } // BUGBUG - look at this some more.... //Imago's solution is to allow customizable effect files (from fedit.exe). return DIENUM_STOP; } //Imago FFE file suport, adapted from the old DX8.1 SDK static BOOL CALLBACK EnumAndCreateBounceEffectsCallback( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ) { JoystickInputStreamImpl* pthis = (JoystickInputStreamImpl*)pvRef; HRESULT hr; LPDIRECTINPUTEFFECT pDIEffect = NULL; if( FAILED( hr = pthis->m_pdid->CreateEffect( pDIFileEffect->GuidEffect, pDIFileEffect->lpDiEffect, &pDIEffect, NULL ) ) ) { return DIENUM_CONTINUE; } // Create a new effect node EFFECTS_NODE* pEffectNode = new EFFECTS_NODE; if( NULL == pEffectNode ) return DIENUM_STOP; ZeroMemory( pEffectNode, sizeof( EFFECTS_NODE ) ); pEffectNode->pDIEffect = pDIEffect; pEffectNode->dwPlayRepeatCount = 1; pEffectNode->pNext = g_BounceEffectsList.pNext; g_BounceEffectsList.pNext = pEffectNode; return DIENUM_CONTINUE; } static BOOL CALLBACK EnumAndCreateFireEffectsCallback( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ) { JoystickInputStreamImpl* pthis = (JoystickInputStreamImpl*)pvRef; HRESULT hr; LPDIRECTINPUTEFFECT pDIEffect = NULL; if( FAILED( hr = pthis->m_pdid->CreateEffect( pDIFileEffect->GuidEffect, pDIFileEffect->lpDiEffect, &pDIEffect, NULL ) ) ) { return DIENUM_CONTINUE; } // Create a new effect node EFFECTS_NODE* pEffectNode = new EFFECTS_NODE; if( NULL == pEffectNode ) return DIENUM_STOP; ZeroMemory( pEffectNode, sizeof( EFFECTS_NODE ) ); pEffectNode->pDIEffect = pDIEffect; pEffectNode->dwPlayRepeatCount = 1; pEffectNode->pNext = g_FireEffectsList.pNext; g_FireEffectsList.pNext = pEffectNode; return DIENUM_CONTINUE; } static BOOL CALLBACK EnumAndCreateExplodeEffectsCallback( LPCDIFILEEFFECT pDIFileEffect, VOID* pvRef ) { JoystickInputStreamImpl* pthis = (JoystickInputStreamImpl*)pvRef; HRESULT hr; LPDIRECTINPUTEFFECT pDIEffect = NULL; if( FAILED( hr = pthis->m_pdid->CreateEffect( pDIFileEffect->GuidEffect, pDIFileEffect->lpDiEffect, &pDIEffect, NULL ) ) ) { return DIENUM_CONTINUE; } // Create a new effect node EFFECTS_NODE* pEffectNode = new EFFECTS_NODE; if( NULL == pEffectNode ) return DIENUM_STOP; ZeroMemory( pEffectNode, sizeof( EFFECTS_NODE ) ); pEffectNode->pDIEffect = pDIEffect; pEffectNode->dwPlayRepeatCount = 1; pEffectNode->pNext = g_ExplodeEffectsList.pNext; g_ExplodeEffectsList.pNext = pEffectNode; return DIENUM_CONTINUE; } HRESULT PlayFFEFromFile(EFFECTS_NODE * pEffectsList) { EFFECTS_NODE* pEffectNode = pEffectsList->pNext; LPDIRECTINPUTEFFECT pDIEffect = NULL; HRESULT hr; while ( pEffectNode && pEffectNode != pEffectsList ) { pDIEffect = pEffectNode->pDIEffect; if( NULL != pDIEffect ) { if( FAILED( hr = pDIEffect->Start( pEffectNode->dwPlayRepeatCount, 0 ) ) ) return hr; } pEffectNode = pEffectNode->pNext; } return S_OK; } VOID EmptyEffectLists(EFFECTS_NODE * pEffectsList) { EFFECTS_NODE* pEffectNode = pEffectsList->pNext; EFFECTS_NODE* pEffectDelete; while ( pEffectNode != pEffectsList && pEffectNode != NULL) { pEffectDelete = pEffectNode; pEffectNode = pEffectNode->pNext; SAFE_RELEASE( pEffectDelete->pDIEffect ); SAFE_DELETE( pEffectDelete ); } pEffectsList->pNext = pEffectsList; } //^ Imago 7/10 void CreateEffects() { GUID guidEffect; DIEFFECT diEffect; DIENVELOPE diEnvelope; DWORD rgdwAxes[2]; LONG rglDirections[2]; DICONSTANTFORCE dicf; DIPERIODIC dipf; // // initialize DIEFFECT and DIENVELOPE structures // ZeroMemory(&diEffect, sizeof(DIEFFECT)); ZeroMemory(&diEnvelope, sizeof(DIENVELOPE)); // // these fields are the same for all effects we will be creating // diEffect.dwSize = sizeof(DIEFFECT); diEffect.dwSamplePeriod = 0; // use default sample period diEffect.dwTriggerButton = DIEB_NOTRIGGER; diEffect.dwTriggerRepeatInterval = 0; diEffect.rgdwAxes = rgdwAxes; diEffect.rglDirection = rglDirections; diEffect.dwGain = 7500; // todo: gain selected by user // // both the "bounce" and "fire" effects will be based on the first // constant force effect enumerated // // // don't check for errors. DInput sometimes return error, but then works anyway. // //DDCall( m_pdid->EnumEffects( #ifndef __GNUC__ (LPDIENUMEFFECTSCALLBACK) #endif &EnumEffectTypeProc, &guidEffect, DIEFT_CONSTANTFORCE //) ); // // Create the bounce effect // dicf.lMagnitude = 10000; rgdwAxes[0] = DIJOFS_X; rgdwAxes[1] = DIJOFS_Y; rglDirections[0] = 0; rglDirections[1] = 0; diEffect.dwFlags = DIEFF_OBJECTOFFSETS | DIEFF_POLAR; diEffect.dwDuration = 200000; diEffect.cAxes = 2; diEffect.lpEnvelope = NULL; diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE); diEffect.lpvTypeSpecificParams = &dicf; //Imago 7/10 if (!FAILED(m_pdid->EnumEffectsInFile(m_zArt+"/bounce.ffe", EnumAndCreateBounceEffectsCallback, this, DIFEF_MODIFYIFNEEDED ))) { m_bFFEBounceFile = true; } else { //DDCall( m_pdid->CreateEffect( guidEffect, &diEffect, &m_peffectBounce, NULL //) ); } // // Create the fire effect // dicf.lMagnitude = 10000; rgdwAxes[0] = DIJOFS_Y; rglDirections[0] = 1; diEffect.dwFlags = DIEFF_OBJECTOFFSETS | DIEFF_CARTESIAN; diEffect.dwDuration = 20000; diEffect.cAxes = 1; diEffect.lpEnvelope = NULL; diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE); diEffect.lpvTypeSpecificParams = &dicf; //Imago 7/10 if (!FAILED(m_pdid->EnumEffectsInFile(m_zArt+"/fire.ffe", EnumAndCreateFireEffectsCallback, this, DIFEF_MODIFYIFNEEDED ))) { m_bFFEFireFile = true; } else { //DDCall( m_pdid->CreateEffect( guidEffect, &diEffect, &m_peffectFire, NULL //) ); } // // the "explode" effect will be based on the first // periodic effect enumerated // //Imago 7/10 if (!FAILED(m_pdid->EnumEffectsInFile(m_zArt+"/explode.ffe", EnumAndCreateExplodeEffectsCallback, this, DIFEF_MODIFYIFNEEDED ))) { m_bFFEExplodeFile = true; } else { //DDCall( m_pdid->EnumEffects( #ifndef __GNUC__ (LPDIENUMEFFECTSCALLBACK) #endif &EnumEffectTypeProc, &guidEffect, DIEFT_PERIODIC //) ); } // // Create the explode effect. // We want to shape the explode effect so that it starts // at it's peak and then fades out // diEnvelope.dwSize = sizeof(DIENVELOPE); diEnvelope.dwAttackLevel = 0; diEnvelope.dwAttackTime = 0; diEnvelope.dwFadeLevel = 0; diEnvelope.dwFadeTime = 1000000; dipf.dwMagnitude = 10000; dipf.lOffset = 0; dipf.dwPhase = 0; dipf.dwPeriod = 100000; rgdwAxes[0] = DIJOFS_X; rglDirections[0] = 0; diEffect.dwFlags = DIEFF_OBJECTOFFSETS | DIEFF_CARTESIAN; diEffect.dwDuration = 1000000; diEffect.cAxes = 1; diEffect.lpEnvelope = &diEnvelope; diEffect.cbTypeSpecificParams = sizeof(DIPERIODIC); diEffect.lpvTypeSpecificParams = &dipf; //DDCall( m_pdid->CreateEffect( guidEffect, &diEffect, &m_peffectExplode, NULL //) ); } void PlayFFEffect(short effectID, LONG lDirection) { // // !!! Don't check for errors here. Sometimes these functions will return error // switch (effectID) { case 0: //Imago 7/10 if (m_bFFEFireFile) { PlayFFEFromFile(&g_FireEffectsList); } else { if (m_peffectFire) { m_peffectFire->Start(1, 0); } } break; case 1: //Imago 7/10 if (m_bFFEBounceFile) { PlayFFEFromFile(&g_BounceEffectsList); //Imago - TODO - Add Left/Right/Front/Back bounce effect seperation now that we can easily load presets } else { if (m_peffectBounce) { DIEFFECT diEffect; LONG rglDirections[2] = { 0, 0 }; ZeroMemory(&diEffect, sizeof(DIEFFECT)); diEffect.dwSize = sizeof(DIEFFECT); rglDirections[0] = lDirection * 100; diEffect.dwFlags = DIEFF_OBJECTOFFSETS | DIEFF_POLAR; diEffect.cAxes = 2; diEffect.rglDirection = rglDirections; m_peffectBounce->SetParameters(&diEffect, DIEP_DIRECTION); m_peffectBounce->Start(1, 0); } } case 2: //Imago 7/10 if (m_bFFEExplodeFile) { PlayFFEFromFile(&g_ExplodeEffectsList); //Imago } else { if (m_peffectExplode) { m_peffectExplode->Start(1, 0); } } break; } } ////////////////////////////////////////////////////////////////////////////// // // JoystickInputStream methods // ////////////////////////////////////////////////////////////////////////////// bool HasForceFeedback() { return (m_didc.dwFlags & DIDC_FORCEFEEDBACK) != 0; } ZString GetShortDescription(int index) { return "Joy " + ZString(index); } ZString GetDescription() { return m_didi.tszInstanceName; } ZString GetValueDescription(int id) { return m_vvalueObject[id]->GetName(); } ////////////////////////////////////////////////////////////////////////////// // // InputStream methods // ////////////////////////////////////////////////////////////////////////////// int GetValueCount() { return m_vvalueObject.GetCount(); } int GetButtonCount() { return m_vbuttonObject.GetCount(); } Boolean* IsDown(int id) { if (id < m_vbuttonObject.GetCount()) { return m_vbuttonObject[id]->GetValue(); } else { return NULL; } } Number* GetValue(int id) { // BT - 10/17 - Guarding against a -1 appearing in the input map which then causes a crash. if (id >= 0 && id < m_vvalueObject.GetCount()) { return m_vvalueObject[id]->GetValue(); } else { return NULL; } } ButtonEvent::Source* GetEventSource() { ZUnimplemented(); return NULL; } }; ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// class InputEngineImpl : public InputEngine { private: ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// bool EnumDeviceCallback(LPDIDEVICEINSTANCE pdidi) { if (!pdidi) { m_joylog.OutputString("\tLPDIDEVICEINSTANCE=NULL Skipping.\n"); return DIENUM_CONTINUE; } // Imago 8/18/09 ZString strName = pdidi->tszProductName; if (strName.ReverseFind("Keyboard") != -1) { m_joylog.OutputString("\tSkipping keyboard as input.\n"); return DIENUM_CONTINUE; } TRef<IDirectInputDevice> pdid; // TRef<IDirectInputDevice2> pdid2; TRef<IDirectInputDevice8> pdid2; // mdvalley: DInput7 DDCall(m_pdi->CreateDevice( pdidi->guidInstance, &pdid, NULL)); // DDCall(pdid->QueryInterface(IID_IDirectInputDevice2, (void**)&pdid2)); DDCall(pdid->QueryInterface(IID_IDirectInputDevice8, (void**)&pdid2)); m_joylog.OutputStringV("\tpdidi->dwDevType: %x (subtype: %x)\n",GET_DIDEVICE_TYPE(pdidi->dwDevType),GET_DIDEVICE_SUBTYPE(pdidi->dwDevType)); m_joylog.OutputStringV("\tpdidi->tszProductName: %s\n",pdidi->tszProductName); switch (pdidi->dwDevType & 0xff) { case DI8DEVTYPE_MOUSE: // kg Di8 DIDEVTYPE_MOUSE: { if (m_pmouseInputStreamDirectInput == NULL) { m_pmouseInputStreamDirectInput = new MouseInputStreamImpl(pdid2, m_hwnd, &m_joylog, m_pMouseState); } } break; case DI8DEVTYPE_JOYSTICK: // kg Di8 DIDEVTYPE_JOYSTICK: case DI8DEVTYPE_GAMEPAD: //Imago 7/23/09 case DI8DEVTYPE_FLIGHT: // --^ case DI8DEVTYPE_1STPERSON: // Imago 11/09 { TRef<JoystickInputStreamImpl> pjoystickInputStream = new JoystickInputStreamImpl(pdid2, m_hwnd, &m_joylog); m_vjoystickInputStream.PushEnd(pjoystickInputStream); } break; } return DIENUM_CONTINUE; } ////////////////////////////////////////////////////////////////////////////// // // // ////////////////////////////////////////////////////////////////////////////// static BOOL CALLBACK StaticEnumDeviceCallback(LPDIDEVICEINSTANCE pdidi, LPVOID pv) { InputEngineImpl* pthis = (InputEngineImpl*)pv; pthis->m_joylog.OutputString("StaticEnumDeviceCallback:\n"); return pthis->EnumDeviceCallback(pdidi); } ////////////////////////////////////////////////////////////////////////////// // // data members // ////////////////////////////////////////////////////////////////////////////// HWND m_hwnd; bool m_bFocus; TRef<IDirectInput> m_pdi; TVector<TRef<JoystickInputStreamImpl> > m_vjoystickInputStream; TRef<MouseInputStream> m_pmouseInputStream; TRef<MouseInputStreamImpl> m_pmouseInputStreamDirectInput; HINSTANCE m_hdinput; CLogFile m_joylog; //Imago 8/12/09 std::shared_ptr<MouseInputStreamState> m_pMouseState; TRef<RawInputPump> m_pRawInputPump; TRef<Boolean> m_pUseMethodRaw; TRef<Value> m_pConfigurationUpdater; public: ////////////////////////////////////////////////////////////////////////////// // // Constructor // ////////////////////////////////////////////////////////////////////////////// typedef HRESULT (WINAPI *PFNDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter); InputEngineImpl(HWND hwnd, TRef<Boolean> pUseMethodRaw) : m_hwnd(hwnd), m_bFocus(false), m_joylog("DirectInput.log"), m_pUseMethodRaw(pUseMethodRaw), m_pMouseState(std::make_shared<MouseInputStreamState>()), m_pRawInputPump(new RawInputPump()) { // // Create the direct input object // #ifdef Dynamic_DInput m_hdinput = ::LoadLibrary("dinput.dll"); ZAssert(m_hdinput != NULL); PFNDirectInputCreate pfn = (PFNDirectInputCreate)::GetProcAddress(m_hdinput, "DirectInputCreateA"); ZAssert(pfn != NULL); DDCall(pfn( GetModuleHandle(NULL), DIRECTINPUT_VERSION, &m_pdi, NULL )); // // grab the address of a few dinput globals // // g_pdfDIMouse = (DIDATAFORMAT*)::GetProcAddress(m_hdinput, "c_dfDIMouse"); g_pdfDIMouse = (DIDATAFORMAT*)::GetProcAddress(m_hdinput, "c_dfDIMouse2"); // mdvalley: Mouse2 for more buttons ZAssert(g_pdfDIMouse != NULL); #else DDCall(DirectInput8Create( // KG - Di8 update GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&m_pdi, NULL )); // g_pdfDIMouse = &c_dfDIMouse; g_pdfDIMouse = &c_dfDIMouse2; // mdvalley: Mouse2 for more buttons #endif // // If we failed then exit the app // if (m_pdi == NULL) { ::MessageBox(NULL, "Error initializing DirectInput. Check your installation", "Error", MB_OK); _exit(0); } // // Enumerate the devices // m_joylog.OutputString("Initialized DirectInput\n"); EnumerateJoysticks(); m_joylog.CloseLogFile(); m_pConfigurationUpdater = new CallbackWhenChanged<bool>([this](bool bUseRaw) { bool bCurrentlyEnabled = false; if (m_pmouseInputStream != nullptr) { bCurrentlyEnabled = m_pmouseInputStream->IsEnabled(); m_pmouseInputStream->SetEnabled(false); } if (bUseRaw) { m_pmouseInputStream = new RawMouseInputStreamImpl(m_hwnd, m_pMouseState, m_pRawInputPump); } else { m_pmouseInputStream = m_pmouseInputStreamDirectInput; } m_pmouseInputStream->SetEnabled(bCurrentlyEnabled); }, m_pUseMethodRaw); m_pConfigurationUpdater->Update(); } ////////////////////////////////////////////////////////////////////////////// // // InputEngine methods // ////////////////////////////////////////////////////////////////////////////// void EnumerateJoysticks() { // // Free up the old devices // m_vjoystickInputStream.SetEmpty(); // // Enumerate all of the devices // DDCall(m_pdi->EnumDevices( 0,//DIDEVTYPE_JOYSTICK, (LPDIENUMDEVICESCALLBACK)StaticEnumDeviceCallback, this, DIEDFL_ATTACHEDONLY )); } int GetJoystickCount() { return m_vjoystickInputStream.GetCount(); } JoystickInputStream* GetJoystick(int index) { if ( index >= 0 && index < m_vjoystickInputStream.GetCount() ) { return m_vjoystickInputStream[index]; } else { return NULL; } } MouseInputStream* GetMouse() { return m_pmouseInputStream; } void Update() { if (m_bFocus) { m_pConfigurationUpdater->Update(); m_pmouseInputStream->Update(); m_pRawInputPump->Pump(); int count = m_vjoystickInputStream.GetCount(); for(int index = 0; index < count; index++) { m_vjoystickInputStream[index]->Update(); } } } void SetFocus(bool bFocus) { if (m_bFocus != bFocus) { m_bFocus = bFocus; int count = m_vjoystickInputStream.GetCount(); for(int index = 0; index < count; index++) { m_vjoystickInputStream[index]->SetFocus(m_bFocus); } } } }; TRef<InputEngine> CreateInputEngine(HWND hwnd, TRef<Boolean> pUseMethodRaw) { return new InputEngineImpl(hwnd, pUseMethodRaw); }
28.972691
153
0.516444
[ "object", "shape", "vector" ]
5bfc84664d0964fe836927e50cdcb0e6c44bcc92
1,285
cpp
C++
books/exploring_cpp_11/list0101.cpp
argodev/learn
d815beb9c1f8fa3dd8cd917640ebcca5822205c3
[ "MIT" ]
null
null
null
books/exploring_cpp_11/list0101.cpp
argodev/learn
d815beb9c1f8fa3dd8cd917640ebcca5822205c3
[ "MIT" ]
15
2020-01-28T22:25:10.000Z
2022-03-11T23:21:02.000Z
books/exploring_cpp_11/list0101.cpp
argodev/learn
d815beb9c1f8fa3dd8cd917640ebcca5822205c3
[ "MIT" ]
null
null
null
/// sort the standard input alphabetically /// Read lines of text, sort them, and print the results to the standard output. /// If the command line names a file, read from that file. Otherwise, read from /// the standard input. The entire input is stored in memory, so don't try /// this with input files that exceed available RAM #include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> void read(std::istream& in, std::vector<std::string>& text) { std::string line; while (std::getline(in, line)) { text.push_back(line); } } int main(int argc, char* argv[]) { // Part 1. Read the entire input into text. If the command line names a file, // read that file. Otherwise, read the standard input. std::vector<std::string> text; /// Store the lines of text here if (argc < 2) { read(std::cin, text); } else { std::ifstream in(argv[1]); if (not in) { std::perror(argv[1]); return EXIT_FAILURE; } read(in, text); } // part 2. sort the text std::sort(text.begin(), text.end()); // part 3. print the sorted text std::copy(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout, "\n")); }
31.341463
93
0.626459
[ "vector" ]
75003a2b6664b5fef5cc5f041d3bd9f52d8fc812
23,945
cpp
C++
modules/viz/src/interactor_style.cpp
webpolis/opencv
d99ef8bc421219c84d3ee55e478b158d3c675963
[ "BSD-3-Clause" ]
1
2019-04-19T22:56:53.000Z
2019-04-19T22:56:53.000Z
modules/viz/src/interactor_style.cpp
cangunel/opencv
42f9ee3f3e580a2c8495b4b56669f06708de53b1
[ "BSD-3-Clause" ]
null
null
null
modules/viz/src/interactor_style.cpp
cangunel/opencv
42f9ee3f3e580a2c8495b4b56669f06708de53b1
[ "BSD-3-Clause" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // // Authors: // * Ozan Tonkal, ozantonkal@gmail.com // * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com // // OpenCV Viz module is complete rewrite of // PCL visualization module (www.pointclouds.org) // //M*/ #include "precomp.hpp" namespace cv { namespace viz { vtkStandardNewMacro(InteractorStyle) }} ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::Initialize() { // Set windows size (width, height) to unknown (-1) win_size_ = Vec2i(-1, -1); win_pos_ = Vec2i(0, 0); max_win_size_ = Vec2i(-1, -1); init_ = true; stereo_anaglyph_mask_default_ = true; // Initialize the keyboard event callback as none keyboardCallback_ = 0; keyboard_callback_cookie_ = 0; // Initialize the mouse event callback as none mouseCallback_ = 0; mouse_callback_cookie_ = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::saveScreenshot(const String &file) { FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]); vtkSmartPointer<vtkWindowToImageFilter> wif = vtkSmartPointer<vtkWindowToImageFilter>::New(); wif->SetInput(Interactor->GetRenderWindow()); vtkSmartPointer<vtkPNGWriter> snapshot_writer = vtkSmartPointer<vtkPNGWriter>::New(); snapshot_writer->SetInputConnection(wif->GetOutputPort()); snapshot_writer->SetFileName(file.c_str()); snapshot_writer->Write(); cout << "Screenshot successfully captured (" << file.c_str() << ")" << endl; } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::exportScene(const String &file) { vtkSmartPointer<vtkExporter> exporter; if (file.size() > 5 && file.substr(file.size() - 5) == ".vrml") { exporter = vtkSmartPointer<vtkVRMLExporter>::New(); vtkVRMLExporter::SafeDownCast(exporter)->SetFileName(file.c_str()); } else { exporter = vtkSmartPointer<vtkOBJExporter>::New(); vtkOBJExporter::SafeDownCast(exporter)->SetFilePrefix(file.c_str()); } exporter->SetInput(Interactor->GetRenderWindow()); exporter->Write(); cout << "Scene successfully exported (" << file.c_str() << ")" << endl; } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::zoomIn() { FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]); // Zoom in StartDolly(); double factor = 10.0 * 0.2 * .5; Dolly(std::pow(1.1, factor)); EndDolly(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::zoomOut() { FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]); // Zoom out StartDolly(); double factor = 10.0 * -0.2 * .5; Dolly(std::pow(1.1, factor)); EndDolly(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnChar() { // Make sure we ignore the same events we handle in OnKeyDown to avoid calling things twice FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]); if (Interactor->GetKeyCode() >= '0' && Interactor->GetKeyCode() <= '9') return; String key(Interactor->GetKeySym()); if (key.find("XF86ZoomIn") != String::npos) zoomIn(); else if (key.find("XF86ZoomOut") != String::npos) zoomOut(); int keymod = Interactor->GetAltKey(); switch (Interactor->GetKeyCode()) { // All of the options below simply exit case 'h': case 'H': case 'l': case 'L': case 'p': case 'P': case 'j': case 'J': case 'c': case 'C': case 43: // KEY_PLUS case 45: // KEY_MINUS case 'f': case 'F': case 'g': case 'G': case 'o': case 'O': case 'u': case 'U': case 'q': case 'Q': { break; } // S and R have a special !ALT case case 'r': case 'R': case 's': case 'S': { if (!keymod) Superclass::OnChar(); break; } default: { Superclass::OnChar(); break; } } } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::registerMouseCallback(void (*callback)(const MouseEvent&, void*), void* cookie) { // Register the callback function and store the user data mouseCallback_ = callback; mouse_callback_cookie_ = cookie; } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::registerKeyboardCallback(void (*callback)(const KeyboardEvent&, void*), void *cookie) { // Register the callback function and store the user data keyboardCallback_ = callback; keyboard_callback_cookie_ = cookie; } ////////////////////////////////////////////////////////////////////////////////////////////// int cv::viz::InteractorStyle::getModifiers() { int modifiers = KeyboardEvent::NONE; if (Interactor->GetAltKey()) modifiers |= KeyboardEvent::ALT; if (Interactor->GetControlKey()) modifiers |= KeyboardEvent::CTRL; if (Interactor->GetShiftKey()) modifiers |= KeyboardEvent::SHIFT; return modifiers; } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnKeyDown() { CV_Assert("Interactor style not initialized. Please call Initialize() before continuing" && init_); FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]); // Save the initial windows width/height if (win_size_[0] == -1 || win_size_[1] == -1) win_size_ = Vec2i(Interactor->GetRenderWindow()->GetSize()); bool alt = Interactor->GetAltKey() != 0; std::string key(Interactor->GetKeySym()); if (key.find("XF86ZoomIn") != std::string::npos) zoomIn(); else if (key.find("XF86ZoomOut") != std::string::npos) zoomOut(); switch (Interactor->GetKeyCode()) { case 'h': case 'H': { std::cout << "| Help:\n" "-------\n" " p, P : switch to a point-based representation\n" " w, W : switch to a wireframe-based representation (where available)\n" " s, S : switch to a surface-based representation (where available)\n" "\n" " j, J : take a .PNG snapshot of the current window view\n" " k, K : export scene to Wavefront .obj format\n" " ALT + k, K : export scene to VRML format\n" " c, C : display current camera/window parameters\n" " f, F : fly to point mode, hold the key and move mouse where to fly\n" "\n" " e, E : exit the interactor\n" " q, Q : stop and call VTK's TerminateApp\n" "\n" " +/- : increment/decrement overall point size\n" " +/- [+ ALT] : zoom in/out \n" "\n" " r, R [+ ALT] : reset camera [to viewpoint = {0, 0, 0} -> center_{x, y, z}]\n" "\n" " ALT + s, S : turn stereo mode on/off\n" " ALT + f, F : switch between maximized window mode and original size\n" "\n" << std::endl; break; } // Switch representation to points case 'p': case 'P': { vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors(); vtkCollectionSimpleIterator ait; for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); ) for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); ) { vtkActor* apart = vtkActor::SafeDownCast(path->GetLastNode()->GetViewProp()); apart->GetProperty()->SetRepresentationToPoints(); } break; } // Save a PNG snapshot case 'j': case 'J': saveScreenshot(cv::format("screenshot-%d.png", (unsigned int)time(0))); break; // Export scene as in obj or vrml format case 'k': case 'K': { String format = alt ? "scene-%d.vrml" : "scene-%d"; exportScene(cv::format(format.c_str(), (unsigned int)time(0))); break; } // display current camera settings/parameters case 'c': case 'C': { vtkSmartPointer<vtkCamera> cam = Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); Vec2d clip(cam->GetClippingRange()); Vec3d focal(cam->GetFocalPoint()), pos(cam->GetPosition()), view(cam->GetViewUp()); Vec2i win_pos(Interactor->GetRenderWindow()->GetPosition()); Vec2i win_size(Interactor->GetRenderWindow()->GetSize()); double angle = cam->GetViewAngle () / 180.0 * CV_PI; String data = cv::format("clip(%f,%f) focal(%f,%f,%f) pos(%f,%f,%f) view(%f,%f,%f) angle(%f) winsz(%d,%d) winpos(%d,%d)", clip[0], clip[1], focal[0], focal[1], focal[2], pos[0], pos[1], pos[2], view[0], view[1], view[2], angle, win_size[0], win_size[1], win_pos[0], win_pos[1]); std::cout << data.c_str() << std::endl; break; } case '=': { zoomIn(); break; } case 43: // KEY_PLUS { if (alt) zoomIn(); else { vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors(); vtkCollectionSimpleIterator ait; for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); ) for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); ) { vtkActor* apart = vtkActor::SafeDownCast(path->GetLastNode()->GetViewProp()); float psize = apart->GetProperty()->GetPointSize(); if (psize < 63.0f) apart->GetProperty()->SetPointSize(psize + 1.0f); } } break; } case 45: // KEY_MINUS { if (alt) zoomOut(); else { vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors(); vtkCollectionSimpleIterator ait; for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); ) for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); ) { vtkActor* apart = vtkActor::SafeDownCast(path->GetLastNode()->GetViewProp()); float psize = apart->GetProperty()->GetPointSize(); if (psize > 1.0f) apart->GetProperty()->SetPointSize(psize - 1.0f); } } break; } // Switch between maximize and original window size case 'f': case 'F': { if (alt) { Vec2i screen_size(Interactor->GetRenderWindow()->GetScreenSize()); Vec2i win_size(Interactor->GetRenderWindow()->GetSize()); // Is window size = max? if (win_size == max_win_size_) { Interactor->GetRenderWindow()->SetSize(win_size_.val); Interactor->GetRenderWindow()->SetPosition(win_pos_.val); Interactor->GetRenderWindow()->Render(); Interactor->Render(); } // Set to max else { win_pos_ = Vec2i(Interactor->GetRenderWindow()->GetPosition()); win_size_ = win_size; Interactor->GetRenderWindow()->SetSize(screen_size.val); Interactor->GetRenderWindow()->Render(); Interactor->Render(); max_win_size_ = Vec2i(Interactor->GetRenderWindow()->GetSize()); } } else { AnimState = VTKIS_ANIM_ON; Interactor->GetPicker()->Pick(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1], 0.0, CurrentRenderer); vtkSmartPointer<vtkAbstractPropPicker> picker = vtkAbstractPropPicker::SafeDownCast(Interactor->GetPicker()); if (picker) if (picker->GetPath()) Interactor->FlyTo(CurrentRenderer, picker->GetPickPosition()); AnimState = VTKIS_ANIM_OFF; } break; } // 's'/'S' w/out ALT case 's': case 'S': { if (alt) { vtkSmartPointer<vtkRenderWindow> window = Interactor->GetRenderWindow(); if (!window->GetStereoRender()) { static Vec2i red_blue(4, 3), magenta_green(2, 5); window->SetAnaglyphColorMask (stereo_anaglyph_mask_default_ ? red_blue.val : magenta_green.val); stereo_anaglyph_mask_default_ = !stereo_anaglyph_mask_default_; } window->SetStereoRender(!window->GetStereoRender()); Interactor->Render(); } else Superclass::OnKeyDown(); break; } case 'o': case 'O': { vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera(); cam->SetParallelProjection(!cam->GetParallelProjection()); CurrentRenderer->Render(); break; } // Overwrite the camera reset case 'r': case 'R': { if (!alt) { Superclass::OnKeyDown(); break; } WidgetActorMap::iterator it = widget_actor_map_->begin(); // it might be that some actors don't have a valid transformation set -> we skip them to avoid a seg fault. for (; it != widget_actor_map_->end(); ++it) { vtkProp3D * actor = vtkProp3D::SafeDownCast(it->second); if (actor && actor->GetUserMatrix()) break; } vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera(); // if a valid transformation was found, use it otherwise fall back to default view point. if (it != widget_actor_map_->end()) { vtkMatrix4x4* m = vtkProp3D::SafeDownCast(it->second)->GetUserMatrix(); cam->SetFocalPoint(m->GetElement(0, 3) - m->GetElement(0, 2), m->GetElement(1, 3) - m->GetElement(1, 2), m->GetElement(2, 3) - m->GetElement(2, 2)); cam->SetViewUp (m->GetElement(0, 1), m->GetElement(1, 1), m->GetElement(2, 1)); cam->SetPosition(m->GetElement(0, 3), m->GetElement(1, 3), m->GetElement(2, 3)); } else { cam->SetPosition(0, 0, 0); cam->SetFocalPoint(0, 0, 1); cam->SetViewUp(0, -1, 0); } // go to the next actor for the next key-press event. if (it != widget_actor_map_->end()) ++it; else it = widget_actor_map_->begin(); CurrentRenderer->SetActiveCamera(cam); CurrentRenderer->ResetCameraClippingRange(); CurrentRenderer->Render(); break; } case 'q': case 'Q': { Interactor->ExitCallback(); return; } default: { Superclass::OnKeyDown(); break; } } KeyboardEvent event(KeyboardEvent::KEY_DOWN, Interactor->GetKeySym(), Interactor->GetKeyCode(), getModifiers()); if (keyboardCallback_) keyboardCallback_(event, keyboard_callback_cookie_); Interactor->Render(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnKeyUp() { KeyboardEvent event(KeyboardEvent::KEY_UP, Interactor->GetKeySym(), Interactor->GetKeyCode(), getModifiers()); if (keyboardCallback_) keyboardCallback_(event, keyboard_callback_cookie_); Superclass::OnKeyUp(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnMouseMove() { Vec2i p(Interactor->GetEventPosition()); MouseEvent event(MouseEvent::MouseMove, MouseEvent::NoButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnMouseMove(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnLeftButtonDown() { Vec2i p(Interactor->GetEventPosition()); MouseEvent::Type type = (Interactor->GetRepeatCount() == 0) ? MouseEvent::MouseButtonPress : MouseEvent::MouseDblClick; MouseEvent event(type, MouseEvent::LeftButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnLeftButtonDown(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnLeftButtonUp() { Vec2i p(Interactor->GetEventPosition()); MouseEvent event(MouseEvent::MouseButtonRelease, MouseEvent::LeftButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnLeftButtonUp(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnMiddleButtonDown() { Vec2i p(Interactor->GetEventPosition()); MouseEvent::Type type = (Interactor->GetRepeatCount() == 0) ? MouseEvent::MouseButtonPress : MouseEvent::MouseDblClick; MouseEvent event(type, MouseEvent::MiddleButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnMiddleButtonDown(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnMiddleButtonUp() { Vec2i p(Interactor->GetEventPosition()); MouseEvent event(MouseEvent::MouseButtonRelease, MouseEvent::MiddleButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnMiddleButtonUp(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnRightButtonDown() { Vec2i p(Interactor->GetEventPosition()); MouseEvent::Type type = (Interactor->GetRepeatCount() == 0) ? MouseEvent::MouseButtonPress : MouseEvent::MouseDblClick; MouseEvent event(type, MouseEvent::RightButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnRightButtonDown(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnRightButtonUp() { Vec2i p(Interactor->GetEventPosition()); MouseEvent event(MouseEvent::MouseButtonRelease, MouseEvent::RightButton, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); Superclass::OnRightButtonUp(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnMouseWheelForward() { Vec2i p(Interactor->GetEventPosition()); MouseEvent event(MouseEvent::MouseScrollUp, MouseEvent::VScroll, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); if (Interactor->GetRepeatCount() && mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); if (Interactor->GetAltKey()) { // zoom vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera(); double opening_angle = cam->GetViewAngle(); if (opening_angle > 15.0) opening_angle -= 1.0; cam->SetViewAngle(opening_angle); cam->Modified(); CurrentRenderer->ResetCameraClippingRange(); CurrentRenderer->Modified(); CurrentRenderer->Render(); Interactor->Render(); } else Superclass::OnMouseWheelForward(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnMouseWheelBackward() { Vec2i p(Interactor->GetEventPosition()); MouseEvent event(MouseEvent::MouseScrollDown, MouseEvent::VScroll, p, getModifiers()); if (mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); if (Interactor->GetRepeatCount() && mouseCallback_) mouseCallback_(event, mouse_callback_cookie_); if (Interactor->GetAltKey()) { // zoom vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera(); double opening_angle = cam->GetViewAngle(); if (opening_angle < 170.0) opening_angle += 1.0; cam->SetViewAngle(opening_angle); cam->Modified(); CurrentRenderer->ResetCameraClippingRange(); CurrentRenderer->Modified(); CurrentRenderer->Render(); Interactor->Render(); } else Superclass::OnMouseWheelBackward(); } ////////////////////////////////////////////////////////////////////////////////////////////// void cv::viz::InteractorStyle::OnTimer() { CV_Assert("Interactor style not initialized." && init_); Interactor->Render(); }
37.414063
134
0.553602
[ "render" ]
75016376395bf8852b248ae4df6d41750b531af5
2,920
cpp
C++
src/ae_dense.cpp
wichtounet/word_spotting
7e25513acc684d79f5c6b622d1d2e55fc40d3192
[ "MIT" ]
4
2017-11-07T02:36:30.000Z
2022-01-20T17:46:06.000Z
src/ae_dense.cpp
wichtounet/word_spotting
7e25513acc684d79f5c6b622d1d2e55fc40d3192
[ "MIT" ]
null
null
null
src/ae_dense.cpp
wichtounet/word_spotting
7e25513acc684d79f5c6b622d1d2e55fc40d3192
[ "MIT" ]
1
2019-12-11T11:03:25.000Z
2019-12-11T11:03:25.000Z
//======================================================================= // Copyright Baptiste Wicht 2015-2017. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef SPOTTER_NO_AE #include "dll/neural/dense_layer.hpp" #include "dll/dbn.hpp" #include "dll/trainer/stochastic_gradient_descent.hpp" #include "ae_config.hpp" // Must be first #include "ae_dense.hpp" #include "ae_evaluation.hpp" namespace { template<size_t N> void dense_evaluate(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches, float learning_rate, size_t epochs) { using network_t = typename dll::dbn_desc< dll::dbn_layers< dll::dense_layer<patch_height * patch_width, N>, dll::dense_layer<N, patch_height * patch_width> >, dll::updater<dll::updater_type::MOMENTUM>, dll::weight_decay<dll::decay_type::L2>, dll::trainer<dll::sgd_trainer>, dll::batch_size<batch_size>, dll::shuffle >::dbn_t; auto net = std::make_unique<network_t>(); net->display(); // Configure the network net->learning_rate = learning_rate; net->initial_momentum = 0.9; net->momentum = 0.9; // Train as autoencoder net->fine_tune_ae(training_patches, epochs); auto folder = spot::evaluate_patches_ae<0, image_t>(dataset, set, conf, *net, train_word_names, test_image_names, false, params); std::cout << "AE-Result: Dense(" << N << "):" << folder << std::endl; } } // end of anonymous namespace void dense_evaluate_all(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches){ if (conf.dense && !conf.deep) { dense_evaluate<10>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-3, epochs); dense_evaluate<50>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-3, epochs); dense_evaluate<100>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs); dense_evaluate<200>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs); dense_evaluate<300>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs); dense_evaluate<400>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs); dense_evaluate<500>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs); } } #endif // SPOTTER_NO_AE
43.58209
242
0.67774
[ "vector" ]
7506f78e6c22d90ab473777e749fcc36641f4f21
5,505
cpp
C++
testing/coders.cpp
spcl/GMS
bd8f384ca2f02c52909f4ab77cbb86edba89c7b6
[ "MIT" ]
10
2021-06-22T12:38:38.000Z
2022-02-17T19:27:54.000Z
testing/coders.cpp
spcl/GMS
bd8f384ca2f02c52909f4ab77cbb86edba89c7b6
[ "MIT" ]
1
2021-07-29T06:37:18.000Z
2021-07-29T06:37:18.000Z
testing/coders.cpp
spcl/GMS
bd8f384ca2f02c52909f4ab77cbb86edba89c7b6
[ "MIT" ]
4
2021-05-17T09:32:19.000Z
2021-12-25T06:27:07.000Z
#include "test_helper.h" #include <gms/representations/graphs/coders/coders-utils/varint_utils.h> using testing::UnorderedElementsAre; TEST(CodersUtils, ToVarint) { std::vector<uint64_t> input{2, 4, 10, 100000, 300}; unsigned char *out = new unsigned char[8]; ASSERT_EQ(toVarint(input[0], out), 1); ASSERT_EQ(toVarint(input[1], out), 1); ASSERT_EQ(toVarint(input[2], out), 1); ASSERT_EQ(toVarint(input[3], out), 3); ASSERT_EQ(toVarint(input[4], out), 2); delete[] out; } TEST(CodersUtils, ToVarintRoundTrip) { std::vector<uint64_t> input{2, 4, 10, 100000, 300}; unsigned char *out = new unsigned char[8]; int size = 0; size += toVarint(input[0], out + size); size += toVarint(input[1], out + size); size += toVarint(input[2], out + size); size += toVarint(input[3], out + size); size += toVarint(input[4], out + size); int offset = 0; uint64_t *decoded = new uint64_t[5]; offset += fromVarint(out + offset, decoded); ASSERT_EQ(decoded[0], 2); offset += fromVarint(out + offset, &decoded[1]); ASSERT_EQ(decoded[1], 4); offset += fromVarint(out + offset, &decoded[2]); ASSERT_EQ(decoded[2], 10); offset += fromVarint(out + offset, &decoded[3]); ASSERT_EQ(decoded[3], 100000); offset += fromVarint(out + offset, &decoded[4]); ASSERT_EQ(decoded[4], 300); delete[] out; delete[] decoded; } TEST(CodersUtils, ToVarint64Bit) { int64_t num; unsigned char out[10]; uint64_t decoded[2]; num = 42; toVarint(num, &out[0]); fromVarint(&out[0], &decoded[0]); ASSERT_EQ(decoded[0], 42); // 2^42 num = 4398046511104; toVarint(num, &out[0]); fromVarint(&out[0], &decoded[0]); ASSERT_EQ(decoded[0], 4398046511104); } TEST(CodersNeighborhoods, VarintNeighborhoodFromCSR) { using namespace GMS::CLI; Args args; args.symmetrize = true; Builder builder((GapbsCompat(args))); pvector<EdgePair<NodeId, NodeId>> el; el.push_back(EdgePair(0, 10)); el.push_back(EdgePair(0, 500)); el.push_back(EdgePair(0, 3000)); auto check_neigh = [](auto &g) { std::vector<NodeId> neigh_vec; for (NodeId v : g.out_neigh(0)) { neigh_vec.push_back(v); } ASSERT_THAT(neigh_vec, UnorderedElementsAre(10, 500, 3000)); }; auto csrgraph = builder.MakeGraphFromEL(el); check_neigh(csrgraph); auto bytegraph = builder.csrToCGraphGeneric<VarintByteBasedGraph>(csrgraph); check_neigh(bytegraph); auto wordgraph = builder.csrToCGraphGeneric<VarintWordBasedGraph>(csrgraph); check_neigh(wordgraph); } TEST(CodersNeighborhoods, VarintNeighborhoodFromCSRLastNeigh) { using namespace GMS::CLI; Args args; args.symmetrize = true; Builder builder((GapbsCompat(args))); pvector<EdgePair<NodeId, NodeId>> el; el.push_back(EdgePair(3, 0)); el.push_back(EdgePair(3, 1)); el.push_back(EdgePair(3, 2)); auto check_neigh = [](auto &g) { std::vector<NodeId> neigh_vec; for (NodeId v : g.out_neigh(3)) { neigh_vec.push_back(v); } ASSERT_THAT(neigh_vec, UnorderedElementsAre(0, 1, 2)); }; auto csrgraph = builder.MakeGraphFromEL(el); check_neigh(csrgraph); auto bytegraph = builder.csrToCGraphGeneric<VarintByteBasedGraph>(csrgraph); check_neigh(bytegraph); auto wordgraph = builder.csrToCGraphGeneric<VarintWordBasedGraph>(csrgraph); check_neigh(wordgraph); } /* TEST(CodersNeighborhoods, ByteBasedNeighborhood) { // TODO(doc): // VarintByteBasedGraph packs neighborhood of node i as concatenation of the following bytes // [ENC(deg[i]), pack_first(i, N(i, 0)), ENC(diff(i, 1)), ..., ENC(diff(i, deg[i] - 1))] // where // pack_first(i, n) = i < n : [0x00, ENC(i - n)] : [0x01, ENC(n - i)] // ENC(uint64_t x) = toVarint variable-length encoding of x // diff(i, n) = N(i, n) - N(i, n - 1) NodeId n = 0; uint64_t offsets[1]; unsigned char *adj_data = new unsigned char[200]; int size = 0; // deg = 3 size += toVarint(3 - 0, adj_data + size); // 10 > node 0 adj_data[size++] = NEXT_VAL_GREATER; offsets[0] = size; // 10 - node 0 size += toVarint(10 - 0, adj_data + size); size += toVarint(500 - 10, adj_data + size); size += toVarint(3000 - 500, adj_data + size); VarintByteBasedGraph::CompressedNeighbourhood neighborhood(n, adj_data, offsets); std::vector<NodeId> neigh_vec; for (NodeId v : neighborhood) { neigh_vec.push_back(v); } ASSERT_THAT(neigh_vec, UnorderedElementsAre(10, 500, 3000)); delete[] adj_data; } */ /* TEST(CodersNeighbors, WordBasedNeighborhood) { // TODO the code could become more modular and unit testable by extracting these encoder operations (for buffers) NodeId n = 0; uint64_t offsets[1] = {0}; unsigned char *adj_data = new unsigned char[50]; int size = 0; size += toVarint(3, adj_data + size); adj_data[size++] = NEXT_VAL_GREATER; size += toVarint(10 - 3, adj_data + size); size += toVarint(500 - 10, adj_data + size); size += toVarint(3000 - 500, adj_data + size); VarintWordBasedGraph::CompressedNeighbourhood neighborhood(n, adj_data, offsets); std::vector<NodeId> neigh_vec; for (NodeId v : neighborhood) { neigh_vec.push_back(v); } ASSERT_THAT(neigh_vec, UnorderedElementsAre(10, 500, 3000)); delete[] adj_data; }*/
30.583333
117
0.639782
[ "vector" ]
750876259a57452a500619b13c609be21d16f000
1,410
cpp
C++
Algorithms/0336.Palindrome_Pairs.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/0336.Palindrome_Pairs.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/0336.Palindrome_Pairs.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
typedef long long LL; class Solution { public: const LL base = 31; const LL mod = (int) 1e9+7; const static int maxl = 301; const static int maxn = 5000; LL pref[maxn]; LL suff[maxn]; LL powr[maxl]; int char2int(char c) { return c-'a'+1; } void add(vector<vector<int>>& ans , int i , int j) { vector<int> v; v.push_back(i); v.push_back(j); ans.push_back(v); } vector<vector<int>> palindromePairs(vector<string>& ar) { int n = ar.size(); powr[0] = 1; for( int i = 1 ; i < maxl ; i++ ) powr[i] = (powr[i-1] * base) % mod; for( int i = 0 ; i < n ; i++ ) { int len = ar[i].length(); for( int j = 0 ; j < len ; j++ ) { pref[i] = (base*pref[i]+char2int(ar[i][j]))%mod; suff[i] = (base*suff[i]+char2int(ar[i][len-1-j]))%mod; } } vector<vector<int>> ans; for( int i = 0 ; i < n ; i++ ) for( int j = 0 ; j < n ; j++ ) if(i != j) { int l1 = ar[i].length(); int l2 = ar[j].length(); LL val1 = (powr[l2]*pref[i]+pref[j])%mod; LL val2 = (powr[l1]*suff[j]+suff[i])%mod; if(val1 == val2) add(ans,i,j); } return ans; } };
30.652174
70
0.414184
[ "vector" ]
75112fad48cf9ee58a0aed32a0d0a8b3f5488e74
29,741
cpp
C++
src/dae.cpp
1mingfei/mapp4py
b72a90b4ab8984cf40d90944df60505e1a3f6a49
[ "MIT" ]
null
null
null
src/dae.cpp
1mingfei/mapp4py
b72a90b4ab8984cf40d90944df60505e1a3f6a49
[ "MIT" ]
null
null
null
src/dae.cpp
1mingfei/mapp4py
b72a90b4ab8984cf40d90944df60505e1a3f6a49
[ "MIT" ]
null
null
null
#include "dae.h" #include "MAPP.h" #include "atoms_dmd.h" #include "dynamic_dmd.h" #include "ff_dmd.h" #include "memory.h" #ifdef MINCG_W_NEWTON #include "min_cg_dmd.h" #endif using namespace MAPP_NS; /*-------------------------------------------- --------------------------------------------*/ DAE::DAE(): max_nsteps(1000), a_tol(sqrt(std::numeric_limits<type0>::epsilon())), min_dt(std::numeric_limits<type0>::epsilon()), c(NULL), c_d(NULL), xprt(NULL), ncs(0), ntally(1000), nreset(0), chng_box(false), S_dof{DESIG2(__dim__,__dim__,false)}, S{DESIG2(__dim__,__dim__,NAN)}, max_nnewton_iters(5), max_ngmres_iters(5) { } /*-------------------------------------------- --------------------------------------------*/ DAE::~DAE() { } /*-------------------------------------------- --------------------------------------------*/ void DAE::pre_run_chk(AtomsDMD* __atoms, ForceFieldDMD* __ff) { //check if configuration is loaded if(!__atoms) throw std::string("cannot start dae run without initial conditions"); //check if force field is loaded if(!__ff) throw std::string("cannot start dae run without governing equations (force field)"); if(std::isnan(__atoms->kB)) throw std::string("boltzmann constant should be set prior to dae run"); if(std::isnan(__atoms->hP)) throw std::string("planck constant should be set prior to dae run"); //check to see if the H_dof components are consistent with stoms->dof if(chng_box && !__atoms->x_dof->is_empty()) { bool* dof=__atoms->x_dof->begin(); int __dof_lcl[__dim__]{DESIG(__dim__,0)}; for(int i=0;i<__atoms->natms_lcl;i++,dof+=__dim__) Algebra::Do<__dim__>::func([&dof,&__dof_lcl](int i){ if(!dof[i]) __dof_lcl[i]=1;}); int __dof[__dim__]{DESIG(__dim__,0)}; MPI_Allreduce(__dof_lcl,__dof,__dim__,MPI_INT,MPI_MAX,__atoms->world); std::string err_msg=std::string(); for(int i=0;i<__dim__;i++) for(int j=i;j<__dim__;j++) if(S_dof[i][j] && __dof[i]) { /* if(!err_msg.empty()) err_msg+="\n"; err_msg+="cannot impose stress component ["+Print::to_string(i)+"]["+Print::to_string(j) +"] while any of the atoms do not have degree freedom in "+Print::to_string(i) +" direction"; */ err_msg+="\nyou have atoms that do not have degree freedom in "+Print::to_string(i) +" direction they will be deformed affinely due to defined degrees of freedom H_dof["+Print::to_string(i)+"]["+Print::to_string(j)+"]"; } //if(!err_msg.empty()) throw err_msg; if(!err_msg.empty() && ntally) { err_msg="Warning:"+err_msg+"\n"; fprintf(MAPP::mapp_out,"%s",err_msg.c_str()); } } } /*-------------------------------------------- --------------------------------------------*/ void DAE::init_static() { //static related ncs=atoms->natms_lcl*c_dim; //a_tol_sqrt_nc_dofs=a_tol*sqrt(static_cast<type0>(calc_ndofs(atoms))); c=atoms->c->begin(); c_d=ff->c_d->begin(); } /*-------------------------------------------- --------------------------------------------*/ void DAE::fin_static() { //static related c=c_d=NULL; } /*-------------------------------------------- --------------------------------------------*/ void DAE::init() { nerr_mins=0; c_dim=atoms->c_dim; ff->c_d->fill(); #ifdef MINCG_W_NEWTON ls=new LineSearchBrent(); bool __H_dof[__dim__][__dim__]; for(int i=0;i<__dim__;i++) for(int j=0;j<__dim__;j++) __H_dof[i][j]=false; min= new MinCGDMD(1.0e-9,__H_dof,false,1.0,0.1,ls); min->atoms=atoms; min->ff=ff; min->init(); min->ntally=0; dynamic=min->dynamic; #else dynamic=new DynamicDMD(atoms,ff,chng_box,{atoms->c_dof},{atoms->x_dof,atoms->alpha_dof},{}); dynamic->init(); #endif ff->calc_ndof(); a_tol_sqrt_nc_dof=a_tol*sqrt(static_cast<type0>(ff->nc_dof)); int n=ff->nx_dof+ff->nalpha_dof; Algebra::DoLT<__dim__>::func([this,&n](int i,int j) {if(!std::isnan(S[i][j])) ++n;}); sqrt_nx_nalpha_nS_dof=sqrt(static_cast<type0>(n)); a_tol_sqrt_nx_nalpha_nS_dof=a_tol*sqrt_nx_nalpha_nS_dof; } /*-------------------------------------------- --------------------------------------------*/ void DAE::fin() { #ifdef MINCG_W_NEWTON min->fin(); min->ff=NULL; min->atoms=NULL; delete min; min=NULL; delete ls; ls=NULL; #else dynamic->fin(); delete dynamic; #endif dynamic=NULL; } /*-------------------------------------------- --------------------------------------------*/ type0 DAE::calc_err() { if(!chng_box) return ff->err/sqrt_nx_nalpha_nS_dof; type0 err_sq=0.0; type0 (&S_fe)[__dim__][__dim__]=atoms->S_fe; Algebra::DoLT<__dim__>::func([&S_fe,&err_sq,this](int i,int j) {if(!std::isnan(S[i][j])) err_sq+=(S[i][j]-S_fe[i][j])*(S[i][j]-S_fe[i][j]);}); err_sq*=(atoms->vol)*(atoms->vol); err_sq+=(ff->err)*(ff->err); return sqrt(err_sq)/sqrt_nx_nalpha_nS_dof; } /*-------------------------------------------- --------------------------------------------*/ void DAE::min_error_true() { #ifdef MINCG_W_NEWTON int __step=atoms->step; min->run(10000); atoms->step=__step; #endif VecTens<type0,2> x(atoms,true,atoms->H,atoms->x,atoms->alpha); VecTens<type0,2> f(atoms,true,ff->F_H,ff->f,ff->f_alpha); VecTens<type0,2> h(atoms,true,__dim__,c_dim); #ifndef NEW_UPDTAE vec* uvecs[2]; uvecs[0]=atoms->x; uvecs[1]=atoms->alpha; #endif type0 norm,res,res_sq; __GMRES__<VecTens<type0,2>> gmres(max_ngmres_iters,atoms,true,__dim__,c_dim); /* auto J=[this](VecTens<type0,2>& dx,VecTens<type0,2>& Jdx)->void { #ifdef OLD_UPDATE dynamic->update(dx.vecs[0],dx.A); dynamic->update(dx.vecs[1]); #else dynamic->update(dx.A,dx.vecs[0],dx.vecs[1]); #endif type0* __vec=ff->J(dx.vecs[0],dx.vecs[1],Jdx.vecs[0],Jdx.vecs[1]); Algebra::DyadicV_2_MLT(__vec,Jdx.A); type0 dlog_vol=0.0; type0 (&H)[__dim__][__dim__]=atoms->H; Algebra::Do<__dim__>::func([&H,&dx,&dlog_vol](int i) { dlog_vol+=dx.A[i][i]/H[i][i]; }); type0 tmp=dlog_vol*atoms->vol; Algebra::DoLT<__dim__>::func([&Jdx,&tmp,this](int i,int j) { if(!S_dof[i][j]) Jdx.A[i][j]=0.0; else Jdx.A[i][j]-=S[i][j]*tmp; }); }; */ auto J=[this](VecTens<type0,2>& dx,VecTens<type0,2>& Jdx)->void { #ifdef OLD_UPDATE dynamic->update(dx.vecs[0]); dynamic->update(dx.vecs[1]); #else dynamic->update(dx.vecs[0],dx.vecs[1]); #endif const int n=atoms->natms_lcl+atoms->natms_ph; type0* __dx=dx.vecs[0]->begin(); type0* __x=atoms->x->begin(); for(int i=0;i<n;i++,__dx+=__dim__,__x+=__dim__) Algebra::V_mul_MLT_add_in(__x,dx.A,__dx); type0* __vec=ff->J(dx.vecs[0],dx.vecs[1],Jdx.vecs[0],Jdx.vecs[1]); Algebra::DyadicV_2_MLT(__vec,Jdx.A); type0 dlog_vol=0.0; type0 (&H)[__dim__][__dim__]=atoms->H; Algebra::Do<__dim__>::func([&H,&dx,&dlog_vol](int i) { dlog_vol+=dx.A[i][i]; }); type0 tmp=dlog_vol*atoms->vol; Algebra::DoLT<__dim__>::func([&Jdx,&tmp,this](int i,int j) { if(!S_dof[i][j]) Jdx.A[i][j]=0.0; else Jdx.A[i][j]-=S[i][j]*tmp; }); }; res_sq=ff->prepJ_n_res(f.vecs[0],f.vecs[1]); type0 vol_neg=-atoms->vol; Algebra::DoLT<__dim__>::func([&res_sq,&f,this,&vol_neg](int i,int j) { if(!std::isnan(S[i][j])) { f.A[i][j]=ff->F_H[i][j]-S[i][j]*vol_neg; res_sq+=f.A[i][j]*f.A[i][j]; } else f.A[i][j]=0.0; }); res=sqrt(res_sq); type0 r; int istep=0; for(;istep<max_nnewton_iters && res/a_tol_sqrt_nx_nalpha_nS_dof>1.0;istep++) { gmres.solve(J,f,0.005*a_tol_sqrt_nx_nalpha_nS_dof,norm,h); const int n0=atoms->natms_lcl; type0* __x=atoms->x->begin(); type0* __dx=h.vecs[0]->begin(); for(int i=0;i<n0;i++,__dx+=__dim__,__x+=__dim__) Algebra::V_mul_MLT_add_in(__x,h.A,__dx); Algebra::MLT_mul_MLT(atoms->H,h.A,h.A); const int n=atoms->natms_lcl*c_dim; type0* alpha_vec=atoms->alpha->begin(); type0* halpha_vec=h.vecs[1]->begin(); type0 r_lcl=1.0,tmp; for(int i=0;i<n;i++) { tmp=alpha_vec[i]+r_lcl*halpha_vec[i]; if(tmp<0.0) { r_lcl=-alpha_vec[i]/halpha_vec[i]; while(alpha_vec[i]+r_lcl*halpha_vec[i]<=0.0) r_lcl=nextafter(r_lcl,0.0); } } MPI_Allreduce(&r_lcl,&r,1,Vec<type0>::MPI_T,MPI_MIN,atoms->world); if(r==1.0) x+=h; else { r*=0.5; x+=r*h; } type0 max_alpha_lcl=0.0; type0* c_vec=atoms->c->begin(); for(int i=0;i<n;i++) if(c_vec[i]>=0.0) max_alpha_lcl=MAX(max_alpha_lcl,alpha_vec[i]); MPI_Allreduce(&max_alpha_lcl,&atoms->max_alpha,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world); atoms->update_H(); #ifdef OLD_UPDATE dynamic->update(uvecs,2); #else dynamic->update<true,true>(); #endif res_sq=ff->prepJ_n_res(f.vecs[0],f.vecs[1]); type0 vol_neg=-atoms->vol; Algebra::DoLT<__dim__>::func([&res_sq,&f,this,&vol_neg](int i,int j) { if(!std::isnan(S[i][j])) { f.A[i][j]=ff->F_H[i][j]-S[i][j]*vol_neg; res_sq+=f.A[i][j]*f.A[i][j]; } else f.A[i][j]=0.0; }); res=sqrt(res_sq); } if(istep) nerr_mins++; } /*-------------------------------------------- --------------------------------------------*/ void DAE::min_error_false() { #ifdef MINCG_W_NEWTON int __step=atoms->step; min->run(10000); atoms->step=__step; #endif VecTens<type0,2> x(atoms,false,atoms->H,atoms->x,atoms->alpha); VecTens<type0,2> f(atoms,false,ff->F_H,ff->f,ff->f_alpha); VecTens<type0,2> h(atoms,false,__dim__,c_dim); #ifndef NEW_UPDTAE vec* uvecs[2]; uvecs[0]=atoms->x; uvecs[1]=atoms->alpha; #endif type0 norm,res,res_sq; __GMRES__<VecTens<type0,2>> gmres(max_ngmres_iters,atoms,false,__dim__,c_dim); auto J=[this](VecTens<type0,2>& x,VecTens<type0,2>& Jx)->void { #ifdef OLD_UPDATE dynamic->update(x.vecs[0]); dynamic->update(x.vecs[1]); #else dynamic->update(x.vecs[0],x.vecs[1]); #endif ff->J(x.vecs[0],x.vecs[1],Jx.vecs[0],Jx.vecs[1]); }; res_sq=ff->prepJ_n_res(f.vecs[0],f.vecs[1]); res=sqrt(res_sq); type0 r; int istep=0; for(;istep<max_nnewton_iters && res/a_tol_sqrt_nx_nalpha_nS_dof>1.0;istep++) { gmres.solve(J,f,0.005*a_tol_sqrt_nx_nalpha_nS_dof,norm,h); const int n=atoms->natms_lcl*c_dim; type0* alpha_vec=atoms->alpha->begin(); type0* halpha_vec=h.vecs[1]->begin(); type0 r_lcl=1.0,tmp; for(int i=0;i<n;i++) { tmp=alpha_vec[i]+r_lcl*halpha_vec[i]; if(tmp<0.0) { r_lcl=-alpha_vec[i]/halpha_vec[i]; while(alpha_vec[i]+r_lcl*halpha_vec[i]<=0.0) r_lcl=nextafter(r_lcl,0.0); } } MPI_Allreduce(&r_lcl,&r,1,Vec<type0>::MPI_T,MPI_MIN,atoms->world); if(r==1.0) x+=h; else { r*=0.5; x+=r*h; } type0 max_alpha_lcl=0.0; type0* c_vec=atoms->c->begin(); for(int i=0;i<n;i++) if(c_vec[i]>=0.0) max_alpha_lcl=MAX(max_alpha_lcl,alpha_vec[i]); MPI_Allreduce(&max_alpha_lcl,&atoms->max_alpha,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world); #ifdef OLD_UPDATE dynamic->update(uvecs,2); #else dynamic->update<true,true>(); #endif res_sq=ff->prepJ_n_res(f.vecs[0],f.vecs[1]); res=sqrt(res_sq); } if(istep) nerr_mins++; } /*------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------------*/ PyObject* DAE::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds) { Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0)); PyObject* self=reinterpret_cast<PyObject*>(__self); return self; } /*-------------------------------------------- --------------------------------------------*/ int DAE::__init__(PyObject* self,PyObject* args,PyObject* kwds) { FuncAPI<> f("__init__"); if(f(args,kwds)==-1) return -1; Object* __self=reinterpret_cast<Object*>(self); __self->dae=new DAE(); __self->xprt=NULL; return 0; } /*-------------------------------------------- --------------------------------------------*/ PyObject* DAE::__alloc__(PyTypeObject* type,Py_ssize_t) { Object* __self=new Object; Py_TYPE(__self)=type; Py_REFCNT(__self)=1; __self->dae=NULL; __self->xprt=NULL; return reinterpret_cast<PyObject*>(__self); } /*-------------------------------------------- --------------------------------------------*/ void DAE::__dealloc__(PyObject* self) { Object* __self=reinterpret_cast<Object*>(self); delete __self->dae; __self->dae=NULL; if(__self->xprt) Py_DECREF(__self->xprt); __self->xprt=NULL; delete __self; } /*--------------------------------------------*/ PyTypeObject DAE::TypeObject={PyObject_HEAD_INIT(NULL)}; /*--------------------------------------------*/ int DAE::setup_tp() { TypeObject.tp_name="mapp.dmd.dae"; TypeObject.tp_doc="chemical integration"; TypeObject.tp_flags=Py_TPFLAGS_DEFAULT; TypeObject.tp_basicsize=sizeof(Object); TypeObject.tp_new=__new__; TypeObject.tp_init=__init__; TypeObject.tp_alloc=__alloc__; TypeObject.tp_dealloc=__dealloc__; setup_tp_methods(); TypeObject.tp_methods=methods; setup_tp_getset(); TypeObject.tp_getset=getset; int ichk=PyType_Ready(&TypeObject); if(ichk<0) return ichk; Py_INCREF(&TypeObject); return ichk; } /*--------------------------------------------*/ PyGetSetDef DAE::getset[]=EmptyPyGetSetDef(8); /*--------------------------------------------*/ void DAE::setup_tp_getset() { getset_a_tol(getset[0]); getset_max_nsteps(getset[1]); getset_min_dt(getset[2]); getset_nreset(getset[3]); getset_ntally(getset[4]); getset_S(getset[5]); getset_export(getset[6]); } /*--------------------------------------------*/ PyMethodDef DAE::methods[]=EmptyPyMethodDef(1); /*--------------------------------------------*/ void DAE::setup_tp_methods() { } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_a_tol(PyGetSetDef& getset) { getset.name=(char*)"a_tol"; getset.doc=(char*)R"---( (double) LTE tolerance Absolute error tolerence in local trucation error )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<type0>::build(reinterpret_cast<Object*>(self)->dae->a_tol); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<type0> a_tol("a_tol"); a_tol.logics[0]=VLogics("gt",0.0)*VLogics("lt",1.0); int ichk=a_tol.set(op); if(ichk==-1) return -1; reinterpret_cast<Object*>(self)->dae->a_tol=a_tol.val; return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_max_nsteps(PyGetSetDef& getset) { getset.name=(char*)"max_nsteps"; getset.doc=(char*)R"---( (int) maximum number of steps Maximum number of steps to achieve energy minimization )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<int>::build(reinterpret_cast<Object*>(self)->dae->max_nsteps); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<int> max_nsteps("max_nsteps"); max_nsteps.logics[0]=VLogics("ge",0); int ichk=max_nsteps.set(op); if(ichk==-1) return -1; reinterpret_cast<Object*>(self)->dae->max_nsteps=max_nsteps.val; return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_min_dt(PyGetSetDef& getset) { getset.name=(char*)"min_dt"; getset.doc=(char*)R"---( (double) minimum time step Minimum time step )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<type0>::build(reinterpret_cast<Object*>(self)->dae->min_dt); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<type0> min_dt("min_dt"); min_dt.logics[0]=VLogics("gt",0.0); int ichk=min_dt.set(op); if(ichk==-1) return -1; reinterpret_cast<Object*>(self)->dae->min_dt=min_dt.val; return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_nreset(PyGetSetDef& getset) { getset.name=(char*)"nreset"; getset.doc=(char*)R"---( (int) configuration reset period Number of steps to reset and readjust. If set to 0 no readjustment will occur )---"; getset.get=[](PyObject* self,void*)->PyObject* { int niters=reinterpret_cast<Object*>(self)->dae->nreset; return var<int>::build(niters,NULL); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<int> nreset("nreset"); nreset.logics[0]=VLogics("ge",0); int ichk=nreset.set(op); if(ichk==-1) return -1; reinterpret_cast<Object*>(self)->dae->nreset=nreset.val; return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_ntally(PyGetSetDef& getset) { getset.name=(char*)"ntally"; getset.doc=(char*)R"---( (int) thermodynamic tallying period Number of steps to be taken from one thermodynamics output to the next. )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<int>::build(reinterpret_cast<Object*>(self)->dae->ntally); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<int> ntally("ntally"); ntally.logics[0]=VLogics("ge",0); int ichk=ntally.set(op); if(ichk==-1) return -1; reinterpret_cast<Object*>(self)->dae->ntally=ntally.val; return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_S(PyGetSetDef& getset) { getset.name=(char*)"S"; getset.doc=(char*)R"---( (symm<double[dim][dim]>) external stress tensor External stress imposed on system, here dim is the dimension of simulation )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<symm<type0[__dim__][__dim__]>>::build(reinterpret_cast<Object*>(self)->dae->S); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<symm<type0[__dim__][__dim__]>> S("S"); int ichk=S.set(op); if(ichk==-1) return -1; bool (&__S_dof)[__dim__][__dim__]=reinterpret_cast<Object*>(self)->dae->S_dof; type0 (&__S)[__dim__][__dim__]=reinterpret_cast<Object*>(self)->dae->S; bool& __chng_box=reinterpret_cast<Object*>(self)->dae->chng_box; __chng_box=false; Algebra::DoLT<__dim__>::func([&__S_dof,&__S,&__chng_box,&S](int i,int j) { if(std::isnan(S.val[i][j])) { __S[i][j]=__S[j][i]=NAN; __S_dof[i][j]=__S_dof[j][i]=false; } else { __S[i][j]=__S[j][i]=S.val[i][j]; __S_dof[i][j]=__S_dof[j][i]=true; __chng_box=true; } }); return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::getset_export(PyGetSetDef& getset) { getset.name=(char*)"export"; getset.doc=(char*)R"---( (mapp.dmd.export) export object Export object to record the snapshots of the system while minimizing )---"; getset.get=[](PyObject* self,void*)->PyObject* { ExportDMD::Object* xprt=reinterpret_cast<Object*>(self)->xprt; if(!xprt) Py_RETURN_NONE; Py_INCREF(xprt); return reinterpret_cast<PyObject*>(xprt); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<OP<ExportDMD>> xprt("export"); int ichk=xprt.set(op); if(ichk==-1) return -1; if(reinterpret_cast<Object*>(self)->xprt) Py_DECREF(reinterpret_cast<Object*>(self)->xprt); Py_INCREF(xprt.val.ob); reinterpret_cast<Object*>(self)->xprt=reinterpret_cast<ExportDMD::Object*>(xprt.val.ob); return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void DAE::ml_run(PyMethodDef& tp_methods) { tp_methods.ml_flags=METH_VARARGS | METH_KEYWORDS; tp_methods.ml_name="run"; tp_methods.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { Object* __self=reinterpret_cast<Object*>(self); FuncAPI<OP<AtomsDMD>,type0> f("run",{"atoms","t"}); f.logics<1>()[0]=VLogics("ge",0.0); if(f(args,kwds)) return NULL; AtomsDMD* __atoms=reinterpret_cast<AtomsDMD::Object*>(f.val<0>().ob)->atoms; ForceFieldDMD* __ff=reinterpret_cast<AtomsDMD::Object*>(f.val<0>().ob)->ff; ExportDMD* __xprt=__self->xprt==NULL ? NULL:__self->xprt->xprt; try { __self->dae->pre_run_chk(__atoms,__ff); } catch(std::string& err_msg) { PyErr_SetString(PyExc_TypeError,err_msg.c_str()); return NULL; } __self->dae->atoms=__atoms; __self->dae->ff=__ff; __self->dae->xprt=__xprt; try { __self->dae->init(); } catch(std::string& err_msg) { __self->dae->xprt=NULL; __self->dae->ff=NULL; __self->dae->atoms=NULL; PyErr_SetString(PyExc_TypeError,err_msg.c_str()); return NULL; } __self->dae->run(f.val<1>()); __self->dae->fin(); __self->dae->xprt=NULL; __self->dae->ff=NULL; __self->dae->atoms=NULL; Py_RETURN_NONE; }); tp_methods.ml_doc=(char*)R"---( run(atoms,t) Execute DEA This method starts differential-algebraic equations for a given atoms object and number of time. Parameters ---------- atoms : mapp.dmd.atoms System of interest t : double Desired time Returns ------- None )---"; } /*-------------------------------------------- --------------------------------------------*/ #include <iostream> #include "random.h" #include "ff_eam_dmd.h" /*-------------------------------------------- natms = 250; No = 100; SetDirectory[NotebookDirectory[]]; A = Import["data.txt", "Data"]; Manipulate[ ListLinePlot[ { Table[{A[[i*No + j, 1]], A[[i*No + j, 2]]}, {j, 1, No}], Table[{A[[i*No + j, 1]], A[[i*No + j, 3]]}, {j, 1, No}] }, PlotRange -> All, Epilog -> Inset[Graphics[Text[Style[ToString[i], Large]]]] ] , {i, 0, natms - 1, 1}] --------------------------------------------*/ /* void DAE::ml_Jtest(PyMethodDef& tp_methods) { tp_methods.ml_flags=METH_VARARGS | METH_KEYWORDS; tp_methods.ml_name="Jtest"; tp_methods.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { FuncAPI<OP<AtomsDMD>> fff("Jtest",{"atoms"}); if(fff(args,kwds)) return NULL; AtomsDMD* atoms=reinterpret_cast<AtomsDMD::Object*>(fff.val<0>().ob)->atoms; ForceFieldDMD* ff=reinterpret_cast<AtomsDMD::Object*>(fff.val<0>().ob)->ff; bool chng_box=false; int c_dim=atoms->c_dim; auto J=[&ff](VecTens<type0,2>& x,VecTens<type0,2>& Jx)->void { ff->J_timer(x,Jx); }; Random rand(3541684); constexpr int nvecs=100; type0 delta=1.0e-9; VecTens<type0,2> x(atoms,chng_box,atoms->H,atoms->x,atoms->alpha); VecTens<type0,2> f0(atoms,chng_box,__dim__,c_dim); VecTens<type0,2> f(atoms,chng_box,__dim__,c_dim); VecTens<type0,2> h(atoms,chng_box,__dim__,c_dim); VecTens<type0,2> Jh(atoms,chng_box,__dim__,c_dim); VecTens<type0,2> x0(atoms,chng_box,__dim__,c_dim); VecTens<type0,2>* dFs=new VecTens<type0,2>[nvecs]; for(int i=0;i<nvecs;i++) { dFs[i].~VecTens(); new (dFs+i) VecTens<type0,2>(atoms,chng_box,__dim__,c_dim); } DynamicDMD* dynamic=new DynamicDMD(atoms,ff,chng_box,{h.vecs[0],h.vecs[1]}, {x0.vecs[0],x0.vecs[1],f0.vecs[0],f0.vecs[1],Jh.vecs[0],Jh.vecs[1]},{}); for(int i=0;i<nvecs;i++) { dynamic->add_xchng(dFs[i].vecs[0]); dynamic->add_xchng(dFs[i].vecs[1]); } dynamic->init(); x0=x; vec* uvecs[2]; uvecs[0]=atoms->x; uvecs[1]=atoms->alpha; int natms_lcl=atoms->natms_lcl; type0* __h=h.vecs[0]->begin(); for(int i=0;i<natms_lcl*__dim__;i++) { if(rand.uniform()>0.5) __h[i]=rand.uniform()*0.01/(delta*nvecs); else __h[i]=-rand.uniform()*0.01/(delta*nvecs); } __h=h.vecs[1]->begin(); for(int i=0;i<natms_lcl*c_dim;i++) { __h[i]=0.0; if(rand.uniform()>0.5) __h[i]=rand.uniform()*0.01/(delta*nvecs); else __h[i]=-rand.uniform()*0.01/(delta*nvecs); } ff->prep_timer(f0); J(h,Jh); for(int ivec=0;ivec<nvecs;ivec++) { type0 __delta=delta*ivec; x=x0+__delta*h; type0 max_alpha_lcl=0.0; const int n=atoms->natms_lcl*atoms->alpha->dim; type0* alpha_vec=atoms->alpha->begin(); type0* c_vec=atoms->c->begin(); for(int i=0;i<n;i++) if(c_vec[i]>=0.0) max_alpha_lcl=MAX(max_alpha_lcl,alpha_vec[i]); MPI_Allreduce(&max_alpha_lcl,&atoms->max_alpha,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world); if(chng_box) atoms->update_H(); dynamic->update(uvecs,2); printf("%d\n",ivec); ff->prep_timer(f.vecs[0],f.vecs[0]); dFs[ivec]=f-f0; } x=x0; type0 max_alpha_lcl=0.0; const int n=atoms->natms_lcl*atoms->alpha->dim; type0* alpha_vec=atoms->alpha->begin(); type0* c_vec=atoms->c->begin(); for(int i=0;i<n;i++) if(c_vec[i]>=0.0) max_alpha_lcl=MAX(max_alpha_lcl,alpha_vec[i]); MPI_Allreduce(&max_alpha_lcl,&atoms->max_alpha,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world); if(chng_box) atoms->update_H(); dynamic->update(uvecs,2); natms_lcl=atoms->natms_lcl; FILE* fp; fp=fopen("/Users/sina/Desktop/data_x.txt","w"); for(int i=0;i<natms_lcl*__dim__;i++) for(int ivec=0;ivec<nvecs;ivec++) fprintf(fp,"%e\t%e\t%e\n",ivec*delta,dFs[ivec].vecs[0]->begin()[i],-Jh.vecs[0]->begin()[i]*ivec*delta); fclose(fp); fp=fopen("/Users/sina/Desktop/data_alpha.txt","w"); for(int i=0;i<natms_lcl*c_dim;i++) for(int ivec=0;ivec<nvecs;ivec++) fprintf(fp,"%e\t%e\t%e\n",ivec*delta,dFs[ivec].vecs[1]->begin()[i],-Jh.vecs[1]->begin()[i]*ivec*delta); fclose(fp); dynamic->fin(); delete dynamic; Py_RETURN_NONE; }); tp_methods.ml_doc=(char*)R"---( )---"; } */
28.846751
155
0.496554
[ "object" ]
7519ef3ee83ec91b6f84328463bb44c587e679e6
48,629
cpp
C++
src/engine/GltfImporter.cpp
Kuranes/KickstartRT_demo
6de7453ca42e46db180f8bead7ba23f9e8936b69
[ "MIT" ]
83
2021-07-19T13:55:33.000Z
2022-03-29T16:00:57.000Z
src/engine/GltfImporter.cpp
CompileException/donut
bc400a8c2c9db9c3c5ed16190dc108e75722b503
[ "MIT" ]
2
2021-11-04T06:41:28.000Z
2021-11-30T08:25:28.000Z
src/engine/GltfImporter.cpp
CompileException/donut
bc400a8c2c9db9c3c5ed16190dc108e75722b503
[ "MIT" ]
10
2021-07-19T15:03:58.000Z
2022-01-10T07:15:35.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * 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. */ #define CGLTF_IMPLEMENTATION #include <cgltf.h> #include <donut/engine/GltfImporter.h> #include <donut/engine/TextureCache.h> #include <donut/engine/SceneGraph.h> #include <donut/core/vfs/VFS.h> #include <donut/core/log.h> #include "nvrhi/common/misc.h" using namespace donut::math; using namespace donut::vfs; using namespace donut::engine; class BufferRegionBlob : public IBlob { private: std::shared_ptr<IBlob> m_parent; const void* m_data; size_t m_size; public: BufferRegionBlob(const std::shared_ptr<IBlob>& parent, size_t offset, size_t size) : m_parent(parent) , m_data(static_cast<const uint8_t*>(parent->data()) + offset) , m_size(size) { } [[nodiscard]] const void* data() const override { return m_data; } [[nodiscard]] size_t size() const override { return m_size; } }; GltfImporter::GltfImporter(std::shared_ptr<vfs::IFileSystem> fs, std::shared_ptr<SceneTypeFactory> sceneTypeFactory) : m_fs(std::move(fs)) , m_SceneTypeFactory(std::move(sceneTypeFactory)) { } struct cgltf_vfs_context { std::shared_ptr<donut::vfs::IFileSystem> fs; std::vector<std::shared_ptr<IBlob>> blobs; }; static cgltf_result cgltf_read_file_vfs(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options,const char* path, cgltf_size* size, void** data) { cgltf_vfs_context* context = (cgltf_vfs_context*)file_options->user_data; auto blob = context->fs->readFile(path); if (!blob) return cgltf_result_file_not_found; context->blobs.push_back(blob); if (size) *size = blob->size(); if (data) *data = (void*)blob->data(); // NOLINT(clang-diagnostic-cast-qual) return cgltf_result_success; } void cgltf_release_file_vfs(const struct cgltf_memory_options*, const struct cgltf_file_options*, void*) { // do nothing } // glTF only support DDS images through the MSFT_texture_dds extension. // Since cgltf does not support this extension, we parse the custom extension string as json here. // See https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds static const cgltf_image* ParseDdsImage(const cgltf_texture* texture, const cgltf_data* objects) { for (size_t i = 0; i < texture->extensions_count; i++) { const cgltf_extension& ext = texture->extensions[i]; if (!ext.name || !ext.data) continue; if (strcmp(ext.name, "MSFT_texture_dds") != 0) continue; size_t extensionLength = strlen(ext.data); if (extensionLength > 1024) return nullptr; // safeguard against weird inputs jsmn_parser parser; jsmn_init(&parser); // count the tokens, normally there are 3 int numTokens = jsmn_parse(&parser, ext.data, extensionLength, nullptr, 0); // allocate the tokens on the stack jsmntok_t* tokens = (jsmntok_t*)alloca(numTokens * sizeof(jsmntok_t)); // reset the parser and prse jsmn_init(&parser); int numParsed = jsmn_parse(&parser, ext.data, extensionLength, tokens, numTokens); if (numParsed != numTokens) goto fail; if (tokens[0].type != JSMN_OBJECT) goto fail; // expecting that the extension is an object for (int k = 1; k < numTokens; k++) { if (tokens[k].type != JSMN_STRING) goto fail; // expecting a string key if (cgltf_json_strcmp(tokens + k, (const uint8_t*)ext.data, "source") == 0) { ++k; int index = cgltf_json_to_int(tokens + k, (const uint8_t*)ext.data); if (index < 0) goto fail; // expecting a non-negative integer; non-value results in CGLTF_ERROR_JSON which is negative if (size_t(index) >= objects->images_count) { donut::log::warning("Invalid image index %d specified in glTF texture definition", index); return nullptr; } return objects->images + index; } // this was something else - skip it k = cgltf_skip_json(tokens, k); } fail: donut::log::warning("Failed to parse the DDS glTF extension: %s", ext.data); return nullptr; } return nullptr; } static const char* cgltf_error_to_string(cgltf_result res) { switch(res) { case cgltf_result_success: return "Success"; case cgltf_result_data_too_short: return "Data is too short"; case cgltf_result_unknown_format: return "Unknown format"; case cgltf_result_invalid_json: return "Invalid JSON"; case cgltf_result_invalid_gltf: return "Invalid glTF"; case cgltf_result_invalid_options: return "Invalid options"; case cgltf_result_file_not_found: return "File not found"; case cgltf_result_io_error: return "I/O error"; case cgltf_result_out_of_memory: return "Out of memory"; case cgltf_result_legacy_gltf: return "Legacy glTF"; default: return "Unknown error"; } } static std::pair<const uint8_t*, size_t> cgltf_buffer_iterator(const cgltf_accessor* accessor, size_t defaultStride) { // TODO: sparse accessor support const cgltf_buffer_view* view = accessor->buffer_view; const uint8_t* data = (uint8_t*)view->buffer->data + view->offset + accessor->offset; const size_t stride = view->stride ? view->stride : defaultStride; return std::make_pair(data, stride); } bool GltfImporter::Load( const std::filesystem::path& fileName, TextureCache& textureCache, SceneLoadingStats& stats, tf::Executor* executor, SceneImportResult& result) const { // Set this to 'true' if you need to fix broken tangents in a model. // Patched buffers will be saved alongside the gltf file, named like "<scene-name>.buffer<N>.bin" constexpr bool c_ForceRebuildTangents = false; result.rootNode.reset(); cgltf_vfs_context vfsContext; vfsContext.fs = m_fs; cgltf_options options{}; options.file.read = &cgltf_read_file_vfs; options.file.release = &cgltf_release_file_vfs; options.file.user_data = &vfsContext; std::string normalizedFileName = fileName.lexically_normal().generic_string(); cgltf_data* objects = nullptr; cgltf_result res = cgltf_parse_file(&options, normalizedFileName.c_str(), &objects); if (res != cgltf_result_success) { log::error("Couldn't load glTF file '%s': %s", normalizedFileName.c_str(), cgltf_error_to_string(res)); return false; } res = cgltf_load_buffers(&options, objects, normalizedFileName.c_str()); if (res != cgltf_result_success) { log::error("Failed to load buffers for glTF file '%s': ", normalizedFileName.c_str(), cgltf_error_to_string(res)); return false; } std::unordered_map<const cgltf_image*, std::shared_ptr<LoadedTexture>> textures; auto load_texture = [&textures, &textureCache, executor, &fileName, objects, &vfsContext](const cgltf_texture* texture, bool sRGB) { if (!texture) return std::shared_ptr<LoadedTexture>(nullptr); // See if the extensions include a DDS image const cgltf_image* ddsImage = ParseDdsImage(texture, objects); if ((!texture->image || (!texture->image->uri && !texture->image->buffer_view)) && (!ddsImage || (!ddsImage->uri && !ddsImage->buffer_view))) return std::shared_ptr<LoadedTexture>(nullptr); // Pick either DDS or standard image, prefer DDS const cgltf_image* activeImage = (ddsImage && (ddsImage->uri || ddsImage->buffer_view)) ? ddsImage : texture->image; auto it = textures.find(activeImage); if (it != textures.end()) return it->second; std::shared_ptr<LoadedTexture> loadedTexture; if (activeImage->buffer_view) { // If the image has inline data, like coming from a GLB container, use that. const uint8_t* dataPtr = static_cast<const uint8_t*>(activeImage->buffer_view->buffer->data) + activeImage->buffer_view->offset; const size_t dataSize = activeImage->buffer_view->size; // We need to have a managed pointer to the texture data for async decoding. std::shared_ptr<IBlob> textureData; // Try to find an existing file blob that includes our data. for (const auto& blob : vfsContext.blobs) { const uint8_t* blobData = static_cast<const uint8_t*>(blob->data()); const size_t blobSize = blob->size(); if (blobData < dataPtr && blobData + blobSize > dataPtr) { // Found the file blob - create a range blob out of it and keep a strong reference. assert(dataPtr + dataSize <= blobData + blobSize); textureData = std::make_shared<BufferRegionBlob>(blob, dataPtr - blobData, dataSize); break; } } // Didn't find a file blob - copy the data into a new container. if (!textureData) { void* dataCopy = malloc(dataSize); assert(dataCopy); memcpy(dataCopy, dataPtr, dataSize); textureData = std::make_shared<vfs::Blob>(dataCopy, dataSize); } uint64_t imageIndex = activeImage - objects->images; std::string name = activeImage->name ? activeImage->name : fileName.filename().generic_string() + "[" + std::to_string(imageIndex) + "]"; std::string mimeType = activeImage->mime_type ? activeImage->mime_type : ""; #ifdef DONUT_WITH_TASKFLOW if (executor) loadedTexture = textureCache.LoadTextureFromMemoryAsync(textureData, name, mimeType, sRGB, *executor); else #endif loadedTexture = textureCache.LoadTextureFromMemoryDeferred(textureData, name, mimeType, sRGB); } else { // No inline data - read a file. #ifdef DONUT_WITH_TASKFLOW if (executor) loadedTexture = textureCache.LoadTextureFromFileAsync(fileName.parent_path() / activeImage->uri, sRGB, *executor); else #endif loadedTexture = textureCache.LoadTextureFromFileDeferred(fileName.parent_path() / activeImage->uri, sRGB); } textures[activeImage] = loadedTexture; return loadedTexture; }; std::unordered_map<const cgltf_material*, std::shared_ptr<Material>> materials; for (size_t mat_idx = 0; mat_idx < objects->materials_count; mat_idx++) { const cgltf_material& material = objects->materials[mat_idx]; std::shared_ptr<Material> matinfo = m_SceneTypeFactory->CreateMaterial(); if (material.name) matinfo->name = material.name; bool useTransmission = false; if (material.has_pbr_specular_glossiness) { matinfo->useSpecularGlossModel = true; matinfo->baseOrDiffuseTexture = load_texture(material.pbr_specular_glossiness.diffuse_texture.texture, true); matinfo->metalRoughOrSpecularTexture = load_texture(material.pbr_specular_glossiness.specular_glossiness_texture.texture, true); matinfo->baseOrDiffuseColor = material.pbr_specular_glossiness.diffuse_factor; matinfo->specularColor = material.pbr_specular_glossiness.specular_factor; matinfo->roughness = 1.f - material.pbr_specular_glossiness.glossiness_factor; matinfo->opacity = material.pbr_specular_glossiness.diffuse_factor[3]; if (material.has_transmission) { } } else if (material.has_pbr_metallic_roughness) { matinfo->useSpecularGlossModel = false; matinfo->baseOrDiffuseTexture = load_texture(material.pbr_metallic_roughness.base_color_texture.texture, true); matinfo->metalRoughOrSpecularTexture = load_texture(material.pbr_metallic_roughness.metallic_roughness_texture.texture, false); matinfo->baseOrDiffuseColor = material.pbr_metallic_roughness.base_color_factor; matinfo->metalness = material.pbr_metallic_roughness.metallic_factor; matinfo->roughness = material.pbr_metallic_roughness.roughness_factor; matinfo->opacity = material.pbr_metallic_roughness.base_color_factor[3]; } if (material.has_transmission) { if (material.has_pbr_specular_glossiness) { log::warning("Material '%s' uses the KHR_materials_transmission extension, which is undefined on materials using the " "KHR_materials_pbrSpecularGlossiness extension model.", material.name ? material.name : "<Unnamed>"); } matinfo->transmissionTexture = load_texture(material.transmission.transmission_texture.texture, false); matinfo->transmissionFactor = material.transmission.transmission_factor; useTransmission = true; } matinfo->emissiveTexture = load_texture(material.emissive_texture.texture, true); matinfo->emissiveColor = material.emissive_factor; matinfo->emissiveIntensity = dm::maxComponent(matinfo->emissiveColor); if (matinfo->emissiveIntensity > 0.f) matinfo->emissiveColor /= matinfo->emissiveIntensity; else matinfo->emissiveIntensity = 1.f; matinfo->normalTexture = load_texture(material.normal_texture.texture, false); matinfo->normalTextureScale = material.normal_texture.scale; matinfo->occlusionTexture = load_texture(material.occlusion_texture.texture, false); matinfo->occlusionStrength = material.occlusion_texture.scale; matinfo->alphaCutoff = material.alpha_cutoff; matinfo->doubleSided = material.double_sided; switch (material.alpha_mode) { case cgltf_alpha_mode_opaque: matinfo->domain = useTransmission ? MaterialDomain::Transmissive : MaterialDomain::Opaque; break; case cgltf_alpha_mode_mask: matinfo->domain = useTransmission ? MaterialDomain::TransmissiveAlphaTested : MaterialDomain::AlphaTested; break; case cgltf_alpha_mode_blend: matinfo->domain = useTransmission ? MaterialDomain::TransmissiveAlphaBlended : MaterialDomain::AlphaBlended; break; } materials[&material] = matinfo; } size_t totalIndices = 0; size_t totalVertices = 0; bool hasJoints = false; for (size_t mesh_idx = 0; mesh_idx < objects->meshes_count; mesh_idx++) { const cgltf_mesh& mesh = objects->meshes[mesh_idx]; for (size_t prim_idx = 0; prim_idx < mesh.primitives_count; prim_idx++) { const cgltf_primitive& prim = mesh.primitives[prim_idx]; if (prim.type != cgltf_primitive_type_triangles || prim.attributes_count == 0) continue; if (prim.indices) totalIndices += prim.indices->count; else totalIndices += prim.attributes->data->count; totalVertices += prim.attributes->data->count; if (!hasJoints) { // Detect if the primitive has joints or weights attributes. for (size_t attr_idx = 0; attr_idx < prim.attributes_count; attr_idx++) { const cgltf_attribute& attr = prim.attributes[attr_idx]; if (attr.type == cgltf_attribute_type_joints || attr.type == cgltf_attribute_type_weights) { hasJoints = true; break; } } } } } auto buffers = std::make_shared<BufferGroup>(); buffers->indexData.resize(totalIndices); buffers->positionData.resize(totalVertices); buffers->normalData.resize(totalVertices); buffers->tangentData.resize(totalVertices); buffers->texcoord1Data.resize(totalVertices); if (hasJoints) { // Allocate joint/weight arrays for all the vertices in the model. // This is wasteful in case the model has both skinned and non-skinned meshes; TODO: improve. buffers->jointData.resize(totalVertices); buffers->weightData.resize(totalVertices); } totalIndices = 0; totalVertices = 0; std::unordered_map<const cgltf_mesh*, std::shared_ptr<MeshInfo>> meshMap; std::vector<float3> computedTangents; std::vector<float3> computedBitangents; std::vector<std::shared_ptr<MeshInfo>> meshes; for (size_t mesh_idx = 0; mesh_idx < objects->meshes_count; mesh_idx++) { const cgltf_mesh& mesh = objects->meshes[mesh_idx]; std::shared_ptr<MeshInfo> minfo = m_SceneTypeFactory->CreateMesh(); if (mesh.name) minfo->name = mesh.name; minfo->buffers = buffers; minfo->indexOffset = (uint32_t)totalIndices; minfo->vertexOffset = (uint32_t)totalVertices; meshes.push_back(minfo); meshMap[&mesh] = minfo; for (size_t prim_idx = 0; prim_idx < mesh.primitives_count; prim_idx++) { const cgltf_primitive& prim = mesh.primitives[prim_idx]; if (prim.type != cgltf_primitive_type_triangles || prim.attributes_count == 0) continue; if (prim.indices) { assert(prim.indices->component_type == cgltf_component_type_r_32u || prim.indices->component_type == cgltf_component_type_r_16u || prim.indices->component_type == cgltf_component_type_r_8u); assert(prim.indices->type == cgltf_type_scalar); } const cgltf_accessor* positions = nullptr; const cgltf_accessor* normals = nullptr; const cgltf_accessor* tangents = nullptr; const cgltf_accessor* texcoords = nullptr; const cgltf_accessor* joint_weights = nullptr; const cgltf_accessor* joint_indices = nullptr; for (size_t attr_idx = 0; attr_idx < prim.attributes_count; attr_idx++) { const cgltf_attribute& attr = prim.attributes[attr_idx]; // ReSharper disable once CppIncompleteSwitchStatement // ReSharper disable once CppDefaultCaseNotHandledInSwitchStatement switch(attr.type) // NOLINT(clang-diagnostic-switch) { case cgltf_attribute_type_position: assert(attr.data->type == cgltf_type_vec3); assert(attr.data->component_type == cgltf_component_type_r_32f); positions = attr.data; break; case cgltf_attribute_type_normal: assert(attr.data->type == cgltf_type_vec3); assert(attr.data->component_type == cgltf_component_type_r_32f); normals = attr.data; break; case cgltf_attribute_type_tangent: assert(attr.data->type == cgltf_type_vec4); assert(attr.data->component_type == cgltf_component_type_r_32f); tangents = attr.data; break; case cgltf_attribute_type_texcoord: assert(attr.data->type == cgltf_type_vec2); assert(attr.data->component_type == cgltf_component_type_r_32f); if (attr.index == 0) texcoords = attr.data; break; case cgltf_attribute_type_joints: assert(attr.data->type == cgltf_type_vec4); assert(attr.data->component_type == cgltf_component_type_r_8u || attr.data->component_type == cgltf_component_type_r_16u); joint_indices = attr.data; break; case cgltf_attribute_type_weights: assert(attr.data->type == cgltf_type_vec4); assert(attr.data->component_type == cgltf_component_type_r_8u || attr.data->component_type == cgltf_component_type_r_16u || attr.data->component_type == cgltf_component_type_r_32f); joint_weights = attr.data; break; } } assert(positions); size_t indexCount = 0; if (prim.indices) { indexCount = prim.indices->count; // copy the indices auto [indexSrc, indexStride] = cgltf_buffer_iterator(prim.indices, 0); uint32_t* indexDst = buffers->indexData.data() + totalIndices; switch(prim.indices->component_type) { case cgltf_component_type_r_8u: if (!indexStride) indexStride = sizeof(uint8_t); for (size_t i_idx = 0; i_idx < indexCount; i_idx++) { *indexDst = *(const uint8_t*)indexSrc; indexSrc += indexStride; indexDst++; } break; case cgltf_component_type_r_16u: if (!indexStride) indexStride = sizeof(uint16_t); for (size_t i_idx = 0; i_idx < indexCount; i_idx++) { *indexDst = *(const uint16_t*)indexSrc; indexSrc += indexStride; indexDst++; } break; case cgltf_component_type_r_32u: if (!indexStride) indexStride = sizeof(uint32_t); for (size_t i_idx = 0; i_idx < indexCount; i_idx++) { *indexDst = *(const uint32_t*)indexSrc; indexSrc += indexStride; indexDst++; } break; default: assert(false); } } else { indexCount = positions->count; // generate the indices uint32_t* indexDst = buffers->indexData.data() + totalIndices; for (size_t i_idx = 0; i_idx < indexCount; i_idx++) { *indexDst = (uint32_t)i_idx; indexDst++; } } dm::box3 bounds = dm::box3::empty(); if (positions) { auto [positionSrc, positionStride] = cgltf_buffer_iterator(positions, sizeof(float) * 3); float3* positionDst = buffers->positionData.data() + totalVertices; for (size_t v_idx = 0; v_idx < positions->count; v_idx++) { *positionDst = (const float*)positionSrc; bounds |= *positionDst; positionSrc += positionStride; ++positionDst; } } if (normals) { assert(normals->count == positions->count); auto [normalSrc, normalStride] = cgltf_buffer_iterator(normals, sizeof(float) * 3); uint32_t* normalDst = buffers->normalData.data() + totalVertices; for (size_t v_idx = 0; v_idx < normals->count; v_idx++) { float3 normal = (const float*)normalSrc; *normalDst = vectorToSnorm8(normal); normalSrc += normalStride; ++normalDst; } } if (tangents) { assert(tangents->count == positions->count); auto [tangentSrc, tangentStride] = cgltf_buffer_iterator(tangents, sizeof(float) * 4); uint32_t* tangentDst = buffers->tangentData.data() + totalVertices; for (size_t v_idx = 0; v_idx < tangents->count; v_idx++) { float4 tangent = (const float*)tangentSrc; *tangentDst = vectorToSnorm8(tangent); tangentSrc += tangentStride; ++tangentDst; } } if (texcoords) { assert(texcoords->count == positions->count); auto [texcoordSrc, texcoordStride] = cgltf_buffer_iterator(texcoords, sizeof(float) * 2); float2* texcoordDst = buffers->texcoord1Data.data() + totalVertices; for (size_t v_idx = 0; v_idx < texcoords->count; v_idx++) { *texcoordDst = (const float*)texcoordSrc; texcoordSrc += texcoordStride; ++texcoordDst; } } else { float2* texcoordDst = buffers->texcoord1Data.data() + totalVertices; for (size_t v_idx = 0; v_idx < positions->count; v_idx++) { *texcoordDst = float2(0.f); ++texcoordDst; } } if (normals && texcoords && (!tangents || c_ForceRebuildTangents)) { auto [positionSrc, positionStride] = cgltf_buffer_iterator(positions, sizeof(float) * 3); auto [texcoordSrc, texcoordStride] = cgltf_buffer_iterator(texcoords, sizeof(float) * 2); auto [normalSrc, normalStride] = cgltf_buffer_iterator(normals, sizeof(float) * 3); const uint32_t* indexSrc = buffers->indexData.data() + totalIndices; computedTangents.resize(positions->count); std::fill(computedTangents.begin(), computedTangents.end(), float3(0.f)); computedBitangents.resize(positions->count); std::fill(computedBitangents.begin(), computedBitangents.end(), float3(0.f)); for (size_t t_idx = 0; t_idx < indexCount / 3; t_idx++) { uint3 tri = indexSrc; indexSrc += 3; float3 p0 = (const float*)(positionSrc + positionStride * tri.x); float3 p1 = (const float*)(positionSrc + positionStride * tri.y); float3 p2 = (const float*)(positionSrc + positionStride * tri.z); float2 t0 = (const float*)(texcoordSrc + texcoordStride * tri.x); float2 t1 = (const float*)(texcoordSrc + texcoordStride * tri.y); float2 t2 = (const float*)(texcoordSrc + texcoordStride * tri.z); float3 dPds = p1 - p0; float3 dPdt = p2 - p0; float2 dTds = t1 - t0; float2 dTdt = t2 - t0; float r = 1.0f / (dTds.x * dTdt.y - dTds.y * dTdt.x); float3 tangent = r * (dPds * dTdt.y - dPdt * dTds.y); float3 bitangent = r * (dPdt * dTds.x - dPds * dTdt.x); float tangentLength = length(tangent); float bitangentLength = length(bitangent); if (tangentLength > 0 && bitangentLength > 0) { tangent /= tangentLength; bitangent /= bitangentLength; computedTangents[tri.x] += tangent; computedTangents[tri.y] += tangent; computedTangents[tri.z] += tangent; computedBitangents[tri.x] += bitangent; computedBitangents[tri.y] += bitangent; computedBitangents[tri.z] += bitangent; } } uint8_t* tangentSrc = nullptr; size_t tangentStride = 0; if (tangents) { auto pair = cgltf_buffer_iterator(tangents, sizeof(float) * 4); tangentSrc = const_cast<uint8_t*>(pair.first); tangentStride = pair.second; } uint32_t* tangentDst = buffers->tangentData.data() + totalVertices; for (size_t v_idx = 0; v_idx < positions->count; v_idx++) { float3 normal = (const float*)normalSrc; float3 tangent = computedTangents[v_idx]; float3 bitangent = computedBitangents[v_idx]; float sign = 0; float tangentLength = length(tangent); float bitangentLength = length(bitangent); if (tangentLength > 0 && bitangentLength > 0) { tangent /= tangentLength; bitangent /= bitangentLength; float3 cross_b = cross(normal, tangent); sign = (dot(cross_b, bitangent) > 0) ? -1.f : 1.f; } *tangentDst = vectorToSnorm8(float4(tangent, sign)); if (c_ForceRebuildTangents && tangents) { *(float4*)tangentSrc = float4(tangent, sign); tangentSrc += tangentStride; } normalSrc += normalStride; ++tangentDst; } } if (joint_indices) { assert(joint_indices->count == positions->count); auto [jointSrc, jointStride] = cgltf_buffer_iterator(joint_indices, 0); vector<uint16_t, 4>* jointDst = buffers->jointData.data() + totalVertices; if (joint_indices->component_type == cgltf_component_type_r_8u) { for (size_t v_idx = 0; v_idx < joint_indices->count; v_idx++) { *jointDst = dm::vector<uint16_t, 4>(jointSrc[0], jointSrc[1], jointSrc[2], jointSrc[3]); jointSrc += jointStride; ++jointDst; } } else { assert(joint_indices->component_type == cgltf_component_type_r_16u); for (size_t v_idx = 0; v_idx < joint_indices->count; v_idx++) { const uint16_t* jointSrcUshort = (const uint16_t*)jointSrc; *jointDst = dm::vector<uint16_t, 4>(jointSrcUshort[0], jointSrcUshort[1], jointSrcUshort[2], jointSrcUshort[3]); jointSrc += jointStride; ++jointDst; } } } if (joint_weights) { assert(joint_weights->count == positions->count); auto [weightSrc, weightStride] = cgltf_buffer_iterator(joint_weights, 0); float4* weightDst = buffers->weightData.data() + totalVertices; if (joint_weights->component_type == cgltf_component_type_r_8u) { for (size_t v_idx = 0; v_idx < joint_indices->count; v_idx++) { *weightDst = dm::float4( float(weightSrc[0]) / 255.f, float(weightSrc[1]) / 255.f, float(weightSrc[2]) / 255.f, float(weightSrc[3]) / 255.f); weightSrc += weightStride; ++weightDst; } } else if (joint_weights->component_type == cgltf_component_type_r_16u) { for (size_t v_idx = 0; v_idx < joint_indices->count; v_idx++) { const uint16_t* weightSrcUshort = (const uint16_t*)weightSrc; *weightDst = dm::float4( float(weightSrcUshort[0]) / 65535.f, float(weightSrcUshort[1]) / 65535.f, float(weightSrcUshort[2]) / 65535.f, float(weightSrcUshort[3]) / 65535.f); weightSrc += weightStride; ++weightDst; } } else { assert(joint_weights->component_type == cgltf_component_type_r_32f); for (size_t v_idx = 0; v_idx < joint_indices->count; v_idx++) { *weightDst = (const float*)weightSrc; weightSrc += weightStride; ++weightDst; } } } auto geometry = m_SceneTypeFactory->CreateMeshGeometry(); geometry->material = materials[prim.material]; geometry->indexOffsetInMesh = minfo->totalIndices; geometry->vertexOffsetInMesh = minfo->totalVertices; geometry->numIndices = (uint32_t)indexCount; geometry->numVertices = (uint32_t)positions->count; geometry->objectSpaceBounds = bounds; minfo->objectSpaceBounds |= bounds; minfo->totalIndices += geometry->numIndices; minfo->totalVertices += geometry->numVertices; minfo->geometries.push_back(geometry); totalIndices += geometry->numIndices; totalVertices += geometry->numVertices; } } std::unordered_map<const cgltf_camera*, std::shared_ptr<SceneCamera>> cameraMap; for (size_t camera_idx = 0; camera_idx < objects->cameras_count; camera_idx++) { const cgltf_camera* src = &objects->cameras[camera_idx]; std::shared_ptr<SceneCamera> dst; if (src->type == cgltf_camera_type_perspective) { std::shared_ptr<PerspectiveCamera> perspectiveCamera = std::make_shared<PerspectiveCamera>(); perspectiveCamera->zNear = src->data.perspective.znear; if (src->data.perspective.has_zfar) perspectiveCamera->zFar = src->data.perspective.zfar; perspectiveCamera->verticalFov = src->data.perspective.yfov; if (src->data.perspective.has_aspect_ratio) perspectiveCamera->aspectRatio = src->data.perspective.aspect_ratio; dst = perspectiveCamera; } else { std::shared_ptr<OrthographicCamera> orthographicCamera = std::make_shared<OrthographicCamera>(); orthographicCamera->zNear = src->data.orthographic.znear; orthographicCamera->zFar = src->data.orthographic.zfar; orthographicCamera->xMag = src->data.orthographic.xmag; orthographicCamera->yMag = src->data.orthographic.ymag; dst = orthographicCamera; } cameraMap[src] = dst; } std::unordered_map<const cgltf_light*, std::shared_ptr<Light>> lightMap; for (size_t light_idx = 0; light_idx < objects->lights_count; light_idx++) { const cgltf_light* src = &objects->lights[light_idx]; std::shared_ptr<Light> dst; switch(src->type) // NOLINT(clang-diagnostic-switch-enum) { case cgltf_light_type_directional: { auto directional = std::make_shared<DirectionalLight>(); directional->irradiance = src->intensity; directional->color = src->color; dst = directional; break; } case cgltf_light_type_point: { auto point = std::make_shared<PointLight>(); point->intensity = src->intensity; point->color = src->color; point->range = src->range; dst = point; break; } case cgltf_light_type_spot: { auto spot = std::make_shared<SpotLight>(); spot->intensity = src->intensity; spot->color = src->color; spot->range = src->range; spot->innerAngle = dm::degrees(src->spot_inner_cone_angle); spot->outerAngle = dm::degrees(src->spot_outer_cone_angle); dst = spot; break; } default: break; } if (dst) { lightMap[src] = dst; } } // build the scene graph std::shared_ptr<SceneGraph> graph = std::make_shared<SceneGraph>(); std::shared_ptr<SceneGraphNode> root = std::make_shared<SceneGraphNode>(); std::unordered_map<cgltf_node*, std::shared_ptr<SceneGraphNode>> nodeMap; std::vector<cgltf_node*> skinnedNodes; struct StackItem { std::shared_ptr<SceneGraphNode> dstParent; cgltf_node** srcNodes = nullptr; size_t srcCount = 0; }; std::vector<StackItem> stack; root->SetName(fileName.filename().generic_string()); int unnamedCameraCounter = 1; StackItem context; context.dstParent = root; context.srcNodes = objects->scene->nodes; context.srcCount = objects->scene->nodes_count; while (context.srcCount > 0) { cgltf_node* src = *context.srcNodes; ++context.srcNodes; --context.srcCount; auto dst = std::make_shared<SceneGraphNode>(); nodeMap[src] = dst; if (src->has_matrix) { // decompose the matrix into TRS affine3 aff = affine3(&src->matrix[0], &src->matrix[4], &src->matrix[8], &src->matrix[12]); double3 translation; double3 scaling; dquat rotation; decomposeAffine(dm::daffine3(aff), &translation, &rotation, &scaling); dst->SetTransform(&translation, &rotation, &scaling); } else { if (src->has_scale) dst->SetScaling(dm::double3(dm::float3(src->scale))); if (src->has_rotation) dst->SetRotation(dm::dquat(dm::quat::fromXYZW(src->rotation))); if (src->has_translation) dst->SetTranslation(dm::double3(dm::float3(src->translation))); } if (src->name) dst->SetName(src->name); graph->Attach(context.dstParent, dst); if (src->skin) { // process the skinned nodes later, when the graph is constructed skinnedNodes.push_back(src); } else if (src->mesh) { auto found = meshMap.find(src->mesh); if (found != meshMap.end()) { auto leaf = m_SceneTypeFactory->CreateMeshInstance(found->second); dst->SetLeaf(leaf); } } if (src->camera) { auto found = cameraMap.find(src->camera); if (found != cameraMap.end()) { auto camera = found->second; if (dst->GetLeaf()) { auto node = std::make_shared<SceneGraphNode>(); node->SetLeaf(camera); graph->Attach(dst, node); } else { dst->SetLeaf(camera); } if (src->camera->name) { camera->SetName(src->camera->name); } else if (camera->GetName().empty()) { camera->SetName("Camera" + std::to_string(unnamedCameraCounter)); ++unnamedCameraCounter; } } } if (src->light) { auto found = lightMap.find(src->light); if (found != lightMap.end()) { auto light = found->second; if (dst->GetLeaf()) { auto node = std::make_shared<SceneGraphNode>(); node->SetLeaf(light); graph->Attach(dst, node); } else { dst->SetLeaf(light); } } } if (src->children_count) { stack.push_back(context); context.dstParent = dst; context.srcNodes = src->children; context.srcCount = src->children_count; } else { // go up the stack until we find a node where some nodes are left while (context.srcCount == 0 && !stack.empty()) { context.dstParent->ReverseChildren(); context = stack.back(); stack.pop_back(); } } } for (auto* src : skinnedNodes) { assert(src->skin); assert(src->mesh); std::shared_ptr<MeshInfo> prorotypeMesh; auto found = meshMap.find(src->mesh); if (found != meshMap.end()) { prorotypeMesh = found->second; auto skinnedInstance = std::make_shared<SkinnedMeshInstance>(m_SceneTypeFactory, prorotypeMesh); skinnedInstance->joints.resize(src->skin->joints_count); for (size_t joint_idx = 0; joint_idx < src->skin->joints_count; joint_idx++) { SkinnedMeshJoint& joint = skinnedInstance->joints[joint_idx]; cgltf_accessor_read_float(src->skin->inverse_bind_matrices, joint_idx, joint.inverseBindMatrix.m_data, 16); joint.node = nodeMap[src->skin->joints[joint_idx]]; if (!joint.node->GetLeaf()) { joint.node->SetLeaf(std::make_shared<SkinnedMeshReference>(skinnedInstance)); } } auto dst = nodeMap[src]; dst->SetLeaf(skinnedInstance); } } result.rootNode = root; auto animationContainer = root; if (objects->animations_count > 1) { animationContainer = std::make_shared<SceneGraphNode>(); animationContainer->SetName("Animations"); graph->Attach(root, animationContainer); } std::unordered_map<const cgltf_animation_sampler*, std::shared_ptr<animation::Sampler>> animationSamplers; for (size_t a_idx = 0; a_idx < objects->animations_count; a_idx++) { const cgltf_animation* srcAnim = &objects->animations[a_idx]; auto dstAnim = std::make_shared<SceneGraphAnimation>(); animationSamplers.clear(); for (size_t s_idx = 0; s_idx < srcAnim->samplers_count; s_idx++) { const cgltf_animation_sampler* srcSampler = &srcAnim->samplers[s_idx]; auto dstSampler = std::make_shared<animation::Sampler>(); switch (srcSampler->interpolation) { case cgltf_interpolation_type_linear: dstSampler->SetInterpolationMode(animation::InterpolationMode::Linear); break; case cgltf_interpolation_type_step: dstSampler->SetInterpolationMode(animation::InterpolationMode::Step); break; case cgltf_interpolation_type_cubic_spline: dstSampler->SetInterpolationMode(animation::InterpolationMode::HermiteSpline); break; } const cgltf_accessor* times = srcSampler->input; const cgltf_accessor* values = srcSampler->output; assert(times->type == cgltf_type_scalar); for (size_t sample_idx = 0; sample_idx < times->count; sample_idx++) { animation::Keyframe keyframe; bool timeRead = cgltf_accessor_read_float(times, sample_idx, &keyframe.time, 1); bool valueRead; if (srcSampler->interpolation == cgltf_interpolation_type_cubic_spline) { valueRead = cgltf_accessor_read_float(values, sample_idx * 3 + 0, &keyframe.inTangent.x, 4); valueRead = cgltf_accessor_read_float(values, sample_idx * 3 + 1, &keyframe.value.x, 4); valueRead = cgltf_accessor_read_float(values, sample_idx * 3 + 2, &keyframe.outTangent.x, 4); } else { valueRead = cgltf_accessor_read_float(values, sample_idx, &keyframe.value.x, 4); } if (timeRead && valueRead) dstSampler->AddKeyframe(keyframe); } if (!dstSampler->GetKeyframes().empty()) animationSamplers[srcSampler] = dstSampler; else log::warning("Animation channel imported with no keyframes, ignoring."); } for (size_t channel_idx = 0; channel_idx < srcAnim->channels_count; channel_idx++) { const cgltf_animation_channel* srcChannel = &srcAnim->channels[channel_idx]; auto dstNode = nodeMap[srcChannel->target_node]; if (!dstNode) continue; AnimationAttribute attribute; switch (srcChannel->target_path) { case cgltf_animation_path_type_translation: attribute = AnimationAttribute::Translation; break; case cgltf_animation_path_type_rotation: attribute = AnimationAttribute::Rotation; break; case cgltf_animation_path_type_scale: attribute = AnimationAttribute::Scaling; break; case cgltf_animation_path_type_weights: case cgltf_animation_path_type_invalid: default: log::warning("Unsupported glTF animation taregt: %d", srcChannel->target_path); continue; } auto dstSampler = animationSamplers[srcChannel->sampler]; if (!dstSampler) continue; auto dstTrack = std::make_shared<SceneGraphAnimationChannel>(dstSampler, dstNode, attribute); dstAnim->AddChannel(dstTrack); } if (dstAnim->IsVald()) { auto animationNode = std::make_shared<SceneGraphNode>(); animationNode->SetName(dstAnim->GetName()); graph->Attach(animationContainer, animationNode); animationNode->SetLeaf(dstAnim); if (srcAnim->name) animationNode->SetName(srcAnim->name); } } animationContainer->ReverseChildren(); if (c_ForceRebuildTangents) { for (size_t buffer_idx = 0; buffer_idx < objects->buffers_count; buffer_idx++) { std::filesystem::path outputFileName = fileName.parent_path() / fileName.stem(); outputFileName += ".buffer" + std::to_string(buffer_idx) + ".bin"; m_fs->writeFile(outputFileName, objects->buffers[buffer_idx].data, objects->buffers[buffer_idx].size); } } cgltf_free(objects); return true; }
38.411532
201
0.565383
[ "mesh", "geometry", "object", "vector", "model" ]
751f3985498c38f019d85be02e30ee19ba61f9ac
7,668
cpp
C++
src/percept/mesh/mod/smoother/SGridJacobianUtil.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
3
2017-08-08T21:06:02.000Z
2020-01-08T13:23:36.000Z
src/percept/mesh/mod/smoother/SGridJacobianUtil.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2016-12-17T00:18:56.000Z
2019-08-09T15:29:25.000Z
src/percept/mesh/mod/smoother/SGridJacobianUtil.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2017-11-30T07:02:41.000Z
2019-08-05T17:07:04.000Z
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering // Solutions of Sandia, LLC (NTESS). Under the terms of Contract // DE-NA0003525 with NTESS, the U.S. Government retains certain rights // in this software. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <percept/Percept.hpp> #if !defined(NO_GEOM_SUPPORT) #include "SGridJacobianUtil.hpp" #include <percept/structured/BlockStructuredGrid.hpp> namespace percept { template<size_t N> std::ostream& operator<<(std::ostream& os, const std::array<double, N>& arr) { for (unsigned i=0; i < N; ++i) os << arr[i] << (i == N-1 ? "" : " "); return os; } /** * Structured grid nodes numbering * * 6 7 * o------------------o * /| /| * / | / | * / | / | * / | / | * / | / | * / | / | * 4 / | 5 / | * o------------------o | * | | | | * | 2 o----------|-------o 3 * | / | / * | / | / * | / | / * | / | / * | / | / * | / | / * |/ |/ * o------------------o * 0 1 * */ static const int locs_hex[8][4] = {{0, 1, 2, 4}, {1, 3, 0, 5}, {2, 0, 3, 6}, {3, 2, 1, 7}, {4, 6, 5, 0}, {5, 4, 7, 1}, {6, 7, 4, 2}, {7, 5, 6, 3}}; /// modeled after code from Mesquite::IdealWeightMeanRatio::evaluate() bool JacobianUtilImpl<StructuredGrid>:: operator()(double& averageJ, PerceptMesh& eMesh, typename StructuredGrid::MTElement cell_ijkb, typename StructuredGrid::MTField *coord_field, const typename StructuredGrid::MTCellTopology * topology_data_in ) { EXCEPTWATCH; DenseMatrix<3,3> J; int i=0; bool metric_invalid = false; using Array4D = typename StructuredGrid::MTField::Array4D; std::shared_ptr<BlockStructuredGrid> bgrid = eMesh.get_block_structured_grid(); unsigned iblock = cell_ijkb[3]; VERIFY_OP_ON(iblock, <, bgrid->m_sblocks.size(), "bad iblock"); std::shared_ptr<StructuredBlock> sgrid = bgrid->m_sblocks[iblock]; Array4D& a4d = (*coord_field->m_block_fields[iblock]); const int A0 = sgrid->m_access_ordering[0], A1 = sgrid->m_access_ordering[1], A2 = sgrid->m_access_ordering[2]; m_num_nodes = 8; //v_i.size(); std::vector<std::array<double,3> > v_i(8); std::array<unsigned,3> indx{{0,0,0}}, II{{0,0,0}}; unsigned cnt = 0; for ( indx[2]=0; indx[2] < 2; ++indx[2]) { II[2] = indx[2] + cell_ijkb[2]; for ( indx[1]=0; indx[1] < 2; ++indx[1]) { II[1] = indx[1] + cell_ijkb[1]; for ( indx[0]=0; indx[0] < 2; ++indx[0]) { II[0] = indx[0] + cell_ijkb[0]; for (unsigned ic=0; ic < 3; ++ic) { v_i[cnt][ic] = a4d(II[A0], II[A1], II[A2], ic); } ++cnt; } } } #define VERTEX(vi) (vi.data()) for (i = 0; i < 8; ++i) { bool mi = jacobian_matrix_3D(m_detJ[i], m_J[i], VERTEX(v_i[locs_hex[i][0]]), VERTEX(v_i[locs_hex[i][1]]), VERTEX(v_i[locs_hex[i][2]]), VERTEX(v_i[locs_hex[i][3]])); metric_invalid = metric_invalid || mi; } averageJ = average_metrics(m_detJ, 8); return metric_invalid; } /// modeled after code from Mesquite::IdealWeightMeanRatio::evaluate(), and TargetMetricUtil /// fills the mGrad member variable given the array of (member variable) m_dMetric_dA terms bool JacobianUtilImpl<StructuredGrid>::grad_metric_util( PerceptMesh& eMesh, typename StructuredGrid::MTElement element, typename StructuredGrid::MTField *coord_field, const typename StructuredGrid::MTCellTopology * topology_data ) { int i=0; bool metric_valid = true; for (i = 0; i < 8; ++i) { const int *indices_hex = locs_hex[i]; grad_util(m_dMetric_dA[i], m_grad[i], 8, 3, indices_hex, 4); } return metric_valid; } /// calculates dMetric_dA (@param dMdA) times dA/dx_n_i to get the gradient of the metric dMetric_dx_n_i, where /// x_n_i is the i'th coordinate of the n'th node in the element. /// @param indices are the 4 indices associated with this corner of the element, passed in from the grad_metric function /// Note: this is the dMetric_dx_n_i term associated with a particular corner, so there are up to nnode of these passed /// in from the grad_metric function /// @see jacobian_matrix_3D void JacobianUtilImpl<StructuredGrid>::grad_util(const DenseMatrix<3,3>& dMdA, double grad[NNODES_MAX][3], const int nnode, const int spd, const int *indices, const int nind) { for (int i=0; i < nnode; i++) for (int j=0; j < 3; j++) grad[i][j]=0.0; grad[indices[1]][0] += dMdA(0,0)*(+1); grad[indices[0]][0] += dMdA(0,0)*(-1); grad[indices[2]][0] += dMdA(0,1)*(+1); grad[indices[0]][0] += dMdA(0,1)*(-1); grad[indices[3]][0] += dMdA(0,2)*(+1); grad[indices[0]][0] += dMdA(0,2)*(-1); grad[indices[1]][1] += dMdA(1,0)*(+1); grad[indices[0]][1] += dMdA(1,0)*(-1); grad[indices[2]][1] += dMdA(1,1)*(+1); grad[indices[0]][1] += dMdA(1,1)*(-1); grad[indices[3]][1] += dMdA(1,2)*(+1); grad[indices[0]][1] += dMdA(1,2)*(-1); grad[indices[1]][2] += dMdA(2,0)*(+1); grad[indices[0]][2] += dMdA(2,0)*(-1); grad[indices[2]][2] += dMdA(2,1)*(+1); grad[indices[0]][2] += dMdA(2,1)*(-1); grad[indices[3]][2] += dMdA(2,2)*(+1); grad[indices[0]][2] += dMdA(2,2)*(-1); } bool SGridJacobianUtil(double& averageJ, double detJ[8], typename StructuredGrid::MTField::Array4D coords, typename StructuredGrid::MTElement cell_ijkb) { DenseMatrix<3,3> J; bool metric_invalid = false; //const int A0 = sgrid->m_access_ordering[0], A1 = sgrid->m_access_ordering[1], A2 = sgrid->m_access_ordering[2]; const int A0 = 0, A1 = 1, A2 = 2; std::vector<std::array<double,3> > v_i(8); std::array<unsigned,3> indx{{0,0,0}}, II{{0,0,0}}; unsigned cnt = 0; for ( indx[2]=0; indx[2] < 2; ++indx[2]) { II[2] = indx[2] + cell_ijkb[2]; for ( indx[1]=0; indx[1] < 2; ++indx[1]) { II[1] = indx[1] + cell_ijkb[1]; for ( indx[0]=0; indx[0] < 2; ++indx[0]) { II[0] = indx[0] + cell_ijkb[0]; for (unsigned ic=0; ic < 3; ++ic) { v_i[cnt][ic] = coords(II[A0], II[A1], II[A2], ic); } ++cnt; } } } #define VERTEX(vi) (vi.data()) //double x0[3], x1[3], x2[3], x3[3]; for (int i = 0; i < 8; ++i) { bool mi = jacobian_matrix_3D(detJ[i], J, VERTEX(v_i[locs_hex[i][0]]), VERTEX(v_i[locs_hex[i][1]]), VERTEX(v_i[locs_hex[i][2]]), VERTEX(v_i[locs_hex[i][3]])); metric_invalid = metric_invalid || mi; } //averageJ = average_metrics(m_detJ, 8); //double average_metrics(const double detJ[NNODES_MAX], const unsigned n) { averageJ=0.0; for (unsigned i=0; i < 8; i++) averageJ += detJ[i]; averageJ/=double(8); } return metric_invalid; } } // namespace percept #endif
33.929204
176
0.518258
[ "vector" ]
75230d12f8d9fcafe705b40743eab3924a351d04
4,616
cpp
C++
aws-cpp-sdk-connect/source/model/ContactFlowType.cpp
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-connect/source/model/ContactFlowType.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-connect/source/model/ContactFlowType.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/connect/model/ContactFlowType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace Connect { namespace Model { namespace ContactFlowTypeMapper { static const int CONTACT_FLOW_HASH = HashingUtils::HashString("CONTACT_FLOW"); static const int CUSTOMER_QUEUE_HASH = HashingUtils::HashString("CUSTOMER_QUEUE"); static const int CUSTOMER_HOLD_HASH = HashingUtils::HashString("CUSTOMER_HOLD"); static const int CUSTOMER_WHISPER_HASH = HashingUtils::HashString("CUSTOMER_WHISPER"); static const int AGENT_HOLD_HASH = HashingUtils::HashString("AGENT_HOLD"); static const int AGENT_WHISPER_HASH = HashingUtils::HashString("AGENT_WHISPER"); static const int OUTBOUND_WHISPER_HASH = HashingUtils::HashString("OUTBOUND_WHISPER"); static const int AGENT_TRANSFER_HASH = HashingUtils::HashString("AGENT_TRANSFER"); static const int QUEUE_TRANSFER_HASH = HashingUtils::HashString("QUEUE_TRANSFER"); ContactFlowType GetContactFlowTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == CONTACT_FLOW_HASH) { return ContactFlowType::CONTACT_FLOW; } else if (hashCode == CUSTOMER_QUEUE_HASH) { return ContactFlowType::CUSTOMER_QUEUE; } else if (hashCode == CUSTOMER_HOLD_HASH) { return ContactFlowType::CUSTOMER_HOLD; } else if (hashCode == CUSTOMER_WHISPER_HASH) { return ContactFlowType::CUSTOMER_WHISPER; } else if (hashCode == AGENT_HOLD_HASH) { return ContactFlowType::AGENT_HOLD; } else if (hashCode == AGENT_WHISPER_HASH) { return ContactFlowType::AGENT_WHISPER; } else if (hashCode == OUTBOUND_WHISPER_HASH) { return ContactFlowType::OUTBOUND_WHISPER; } else if (hashCode == AGENT_TRANSFER_HASH) { return ContactFlowType::AGENT_TRANSFER; } else if (hashCode == QUEUE_TRANSFER_HASH) { return ContactFlowType::QUEUE_TRANSFER; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ContactFlowType>(hashCode); } return ContactFlowType::NOT_SET; } Aws::String GetNameForContactFlowType(ContactFlowType enumValue) { switch(enumValue) { case ContactFlowType::CONTACT_FLOW: return "CONTACT_FLOW"; case ContactFlowType::CUSTOMER_QUEUE: return "CUSTOMER_QUEUE"; case ContactFlowType::CUSTOMER_HOLD: return "CUSTOMER_HOLD"; case ContactFlowType::CUSTOMER_WHISPER: return "CUSTOMER_WHISPER"; case ContactFlowType::AGENT_HOLD: return "AGENT_HOLD"; case ContactFlowType::AGENT_WHISPER: return "AGENT_WHISPER"; case ContactFlowType::OUTBOUND_WHISPER: return "OUTBOUND_WHISPER"; case ContactFlowType::AGENT_TRANSFER: return "AGENT_TRANSFER"; case ContactFlowType::QUEUE_TRANSFER: return "QUEUE_TRANSFER"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ContactFlowTypeMapper } // namespace Model } // namespace Connect } // namespace Aws
35.507692
94
0.639298
[ "model" ]
970d7472d2442f4268844bac7800025155322b65
33,145
cc
C++
wrappers/7.0.0/vtkXMLWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkXMLWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkXMLWriterWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkAlgorithmWrap.h" #include "vtkXMLWriterWrap.h" #include "vtkObjectWrap.h" #include "vtkDataCompressorWrap.h" #include "vtkDataObjectWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkXMLWriterWrap::ptpl; VtkXMLWriterWrap::VtkXMLWriterWrap() { } VtkXMLWriterWrap::VtkXMLWriterWrap(vtkSmartPointer<vtkXMLWriter> _native) { native = _native; } VtkXMLWriterWrap::~VtkXMLWriterWrap() { } void VtkXMLWriterWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkXMLWriter").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("XMLWriter").ToLocalChecked(), ConstructorGetter); } void VtkXMLWriterWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkXMLWriterWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkXMLWriterWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "EncodeAppendedDataOff", EncodeAppendedDataOff); Nan::SetPrototypeMethod(tpl, "encodeAppendedDataOff", EncodeAppendedDataOff); Nan::SetPrototypeMethod(tpl, "EncodeAppendedDataOn", EncodeAppendedDataOn); Nan::SetPrototypeMethod(tpl, "encodeAppendedDataOn", EncodeAppendedDataOn); Nan::SetPrototypeMethod(tpl, "GetByteOrder", GetByteOrder); Nan::SetPrototypeMethod(tpl, "getByteOrder", GetByteOrder); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetCompressor", GetCompressor); Nan::SetPrototypeMethod(tpl, "getCompressor", GetCompressor); Nan::SetPrototypeMethod(tpl, "GetDataMode", GetDataMode); Nan::SetPrototypeMethod(tpl, "getDataMode", GetDataMode); Nan::SetPrototypeMethod(tpl, "GetEncodeAppendedData", GetEncodeAppendedData); Nan::SetPrototypeMethod(tpl, "getEncodeAppendedData", GetEncodeAppendedData); Nan::SetPrototypeMethod(tpl, "GetFileName", GetFileName); Nan::SetPrototypeMethod(tpl, "getFileName", GetFileName); Nan::SetPrototypeMethod(tpl, "GetHeaderType", GetHeaderType); Nan::SetPrototypeMethod(tpl, "getHeaderType", GetHeaderType); Nan::SetPrototypeMethod(tpl, "GetIdType", GetIdType); Nan::SetPrototypeMethod(tpl, "getIdType", GetIdType); Nan::SetPrototypeMethod(tpl, "GetInput", GetInput); Nan::SetPrototypeMethod(tpl, "getInput", GetInput); Nan::SetPrototypeMethod(tpl, "GetNumberOfTimeSteps", GetNumberOfTimeSteps); Nan::SetPrototypeMethod(tpl, "getNumberOfTimeSteps", GetNumberOfTimeSteps); Nan::SetPrototypeMethod(tpl, "GetTimeStep", GetTimeStep); Nan::SetPrototypeMethod(tpl, "getTimeStep", GetTimeStep); Nan::SetPrototypeMethod(tpl, "GetTimeStepRange", GetTimeStepRange); Nan::SetPrototypeMethod(tpl, "getTimeStepRange", GetTimeStepRange); Nan::SetPrototypeMethod(tpl, "GetWriteToOutputString", GetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "getWriteToOutputString", GetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetByteOrder", SetByteOrder); Nan::SetPrototypeMethod(tpl, "setByteOrder", SetByteOrder); Nan::SetPrototypeMethod(tpl, "SetByteOrderToBigEndian", SetByteOrderToBigEndian); Nan::SetPrototypeMethod(tpl, "setByteOrderToBigEndian", SetByteOrderToBigEndian); Nan::SetPrototypeMethod(tpl, "SetByteOrderToLittleEndian", SetByteOrderToLittleEndian); Nan::SetPrototypeMethod(tpl, "setByteOrderToLittleEndian", SetByteOrderToLittleEndian); Nan::SetPrototypeMethod(tpl, "SetCompressor", SetCompressor); Nan::SetPrototypeMethod(tpl, "setCompressor", SetCompressor); Nan::SetPrototypeMethod(tpl, "SetCompressorType", SetCompressorType); Nan::SetPrototypeMethod(tpl, "setCompressorType", SetCompressorType); Nan::SetPrototypeMethod(tpl, "SetCompressorTypeToNone", SetCompressorTypeToNone); Nan::SetPrototypeMethod(tpl, "setCompressorTypeToNone", SetCompressorTypeToNone); Nan::SetPrototypeMethod(tpl, "SetCompressorTypeToZLib", SetCompressorTypeToZLib); Nan::SetPrototypeMethod(tpl, "setCompressorTypeToZLib", SetCompressorTypeToZLib); Nan::SetPrototypeMethod(tpl, "SetDataMode", SetDataMode); Nan::SetPrototypeMethod(tpl, "setDataMode", SetDataMode); Nan::SetPrototypeMethod(tpl, "SetDataModeToAppended", SetDataModeToAppended); Nan::SetPrototypeMethod(tpl, "setDataModeToAppended", SetDataModeToAppended); Nan::SetPrototypeMethod(tpl, "SetDataModeToAscii", SetDataModeToAscii); Nan::SetPrototypeMethod(tpl, "setDataModeToAscii", SetDataModeToAscii); Nan::SetPrototypeMethod(tpl, "SetDataModeToBinary", SetDataModeToBinary); Nan::SetPrototypeMethod(tpl, "setDataModeToBinary", SetDataModeToBinary); Nan::SetPrototypeMethod(tpl, "SetEncodeAppendedData", SetEncodeAppendedData); Nan::SetPrototypeMethod(tpl, "setEncodeAppendedData", SetEncodeAppendedData); Nan::SetPrototypeMethod(tpl, "SetFileName", SetFileName); Nan::SetPrototypeMethod(tpl, "setFileName", SetFileName); Nan::SetPrototypeMethod(tpl, "SetHeaderType", SetHeaderType); Nan::SetPrototypeMethod(tpl, "setHeaderType", SetHeaderType); Nan::SetPrototypeMethod(tpl, "SetHeaderTypeToUInt32", SetHeaderTypeToUInt32); Nan::SetPrototypeMethod(tpl, "setHeaderTypeToUInt32", SetHeaderTypeToUInt32); Nan::SetPrototypeMethod(tpl, "SetHeaderTypeToUInt64", SetHeaderTypeToUInt64); Nan::SetPrototypeMethod(tpl, "setHeaderTypeToUInt64", SetHeaderTypeToUInt64); Nan::SetPrototypeMethod(tpl, "SetIdType", SetIdType); Nan::SetPrototypeMethod(tpl, "setIdType", SetIdType); Nan::SetPrototypeMethod(tpl, "SetIdTypeToInt32", SetIdTypeToInt32); Nan::SetPrototypeMethod(tpl, "setIdTypeToInt32", SetIdTypeToInt32); Nan::SetPrototypeMethod(tpl, "SetIdTypeToInt64", SetIdTypeToInt64); Nan::SetPrototypeMethod(tpl, "setIdTypeToInt64", SetIdTypeToInt64); Nan::SetPrototypeMethod(tpl, "SetInputData", SetInputData); Nan::SetPrototypeMethod(tpl, "setInputData", SetInputData); Nan::SetPrototypeMethod(tpl, "SetNumberOfTimeSteps", SetNumberOfTimeSteps); Nan::SetPrototypeMethod(tpl, "setNumberOfTimeSteps", SetNumberOfTimeSteps); Nan::SetPrototypeMethod(tpl, "SetTimeStep", SetTimeStep); Nan::SetPrototypeMethod(tpl, "setTimeStep", SetTimeStep); Nan::SetPrototypeMethod(tpl, "SetTimeStepRange", SetTimeStepRange); Nan::SetPrototypeMethod(tpl, "setTimeStepRange", SetTimeStepRange); Nan::SetPrototypeMethod(tpl, "SetWriteToOutputString", SetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "setWriteToOutputString", SetWriteToOutputString); Nan::SetPrototypeMethod(tpl, "Start", Start); Nan::SetPrototypeMethod(tpl, "start", Start); Nan::SetPrototypeMethod(tpl, "Stop", Stop); Nan::SetPrototypeMethod(tpl, "stop", Stop); Nan::SetPrototypeMethod(tpl, "Write", Write); Nan::SetPrototypeMethod(tpl, "write", Write); Nan::SetPrototypeMethod(tpl, "WriteNextTime", WriteNextTime); Nan::SetPrototypeMethod(tpl, "writeNextTime", WriteNextTime); Nan::SetPrototypeMethod(tpl, "WriteToOutputStringOff", WriteToOutputStringOff); Nan::SetPrototypeMethod(tpl, "writeToOutputStringOff", WriteToOutputStringOff); Nan::SetPrototypeMethod(tpl, "WriteToOutputStringOn", WriteToOutputStringOn); Nan::SetPrototypeMethod(tpl, "writeToOutputStringOn", WriteToOutputStringOn); #ifdef VTK_NODE_PLUS_VTKXMLWRITERWRAP_INITPTPL VTK_NODE_PLUS_VTKXMLWRITERWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkXMLWriterWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { Nan::ThrowError("Cannot create instance of abstract class."); return; } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkXMLWriterWrap::EncodeAppendedDataOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->EncodeAppendedDataOff(); } void VtkXMLWriterWrap::EncodeAppendedDataOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->EncodeAppendedDataOn(); } void VtkXMLWriterWrap::GetByteOrder(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetByteOrder(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkXMLWriterWrap::GetCompressor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); vtkDataCompressor * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCompressor(); VtkDataCompressorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataCompressorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataCompressorWrap *w = new VtkDataCompressorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkXMLWriterWrap::GetDataMode(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDataMode(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetEncodeAppendedData(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetEncodeAppendedData(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetFileName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkXMLWriterWrap::GetHeaderType(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetHeaderType(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetIdType(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetIdType(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetInput(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { vtkDataObject * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetInput( info[0]->Int32Value() ); VtkDataObjectWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataObjectWrap *w = new VtkDataObjectWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } vtkDataObject * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetInput(); VtkDataObjectWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkDataObjectWrap *w = new VtkDataObjectWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkXMLWriterWrap::GetNumberOfTimeSteps(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfTimeSteps(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetTimeStep(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTimeStep(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::GetTimeStepRange(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTimeStepRange(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 2 * sizeof(int)); Local<v8::Int32Array> at = v8::Int32Array::New(ab, 0, 2); memcpy(ab->GetContents().Data(), r, 2 * sizeof(int)); info.GetReturnValue().Set(at); } void VtkXMLWriterWrap::GetWriteToOutputString(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetWriteToOutputString(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); vtkXMLWriter * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkXMLWriterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkXMLWriterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkXMLWriterWrap *w = new VtkXMLWriterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkXMLWriterWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkXMLWriter * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkXMLWriterWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkXMLWriterWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkXMLWriterWrap *w = new VtkXMLWriterWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetByteOrder(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetByteOrder( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetByteOrderToBigEndian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetByteOrderToBigEndian(); } void VtkXMLWriterWrap::SetByteOrderToLittleEndian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetByteOrderToLittleEndian(); } void VtkXMLWriterWrap::SetCompressor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkDataCompressorWrap::ptpl))->HasInstance(info[0])) { VtkDataCompressorWrap *a0 = ObjectWrap::Unwrap<VtkDataCompressorWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCompressor( (vtkDataCompressor *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetCompressorType(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCompressorType( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetCompressorTypeToNone(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetCompressorTypeToNone(); } void VtkXMLWriterWrap::SetCompressorTypeToZLib(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetCompressorTypeToZLib(); } void VtkXMLWriterWrap::SetDataMode(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetDataMode( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetDataModeToAppended(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetDataModeToAppended(); } void VtkXMLWriterWrap::SetDataModeToAscii(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetDataModeToAscii(); } void VtkXMLWriterWrap::SetDataModeToBinary(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetDataModeToBinary(); } void VtkXMLWriterWrap::SetEncodeAppendedData(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetEncodeAppendedData( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetFileName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetFileName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetHeaderType(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetHeaderType( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetHeaderTypeToUInt32(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetHeaderTypeToUInt32(); } void VtkXMLWriterWrap::SetHeaderTypeToUInt64(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetHeaderTypeToUInt64(); } void VtkXMLWriterWrap::SetIdType(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetIdType( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetIdTypeToInt32(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetIdTypeToInt32(); } void VtkXMLWriterWrap::SetIdTypeToInt64(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->SetIdTypeToInt64(); } void VtkXMLWriterWrap::SetInputData(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[0])) { VtkDataObjectWrap *a0 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetInputData( (vtkDataObject *) a0->native.GetPointer() ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[1])) { VtkDataObjectWrap *a1 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[1]->ToObject()); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetInputData( info[0]->Int32Value(), (vtkDataObject *) a1->native.GetPointer() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetNumberOfTimeSteps(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetNumberOfTimeSteps( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetTimeStep(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTimeStep( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetTimeStepRange(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsInt32Array()) { v8::Local<v8::Int32Array>a0(v8::Local<v8::Int32Array>::Cast(info[0]->ToObject())); if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTimeStepRange( (int *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); int b0[2]; if( a0->Length() < 2 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 2; i++ ) { if( !a0->Get(i)->IsInt32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Int32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTimeStepRange( b0 ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsInt32()) { if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetTimeStepRange( info[0]->Int32Value(), info[1]->Int32Value() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::SetWriteToOutputString(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetWriteToOutputString( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::Start(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->Start(); } void VtkXMLWriterWrap::Stop(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->Stop(); } void VtkXMLWriterWrap::Write(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->Write(); info.GetReturnValue().Set(Nan::New(r)); } void VtkXMLWriterWrap::WriteNextTime(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->WriteNextTime( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkXMLWriterWrap::WriteToOutputStringOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->WriteToOutputStringOff(); } void VtkXMLWriterWrap::WriteToOutputStringOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkXMLWriterWrap *wrapper = ObjectWrap::Unwrap<VtkXMLWriterWrap>(info.Holder()); vtkXMLWriter *native = (vtkXMLWriter *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->WriteToOutputStringOn(); }
30.520258
110
0.720591
[ "object" ]
971125b1ccfc9c843534d3600307ea142a8edae6
14,214
cpp
C++
Source/WebKit/NetworkProcess/IndexedDB/WebIDBServer.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebKit/NetworkProcess/IndexedDB/WebIDBServer.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebKit/NetworkProcess/IndexedDB/WebIDBServer.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2019 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebIDBServer.h" #include "WebIDBConnectionToClient.h" #include "WebIDBServerMessages.h" #include <WebCore/SQLiteDatabaseTracker.h> #include <WebCore/StorageQuotaManager.h> #include <wtf/threads/BinarySemaphore.h> #if ENABLE(INDEXED_DATABASE) namespace WebKit { Ref<WebIDBServer> WebIDBServer::create(PAL::SessionID sessionID, const String& directory, WebCore::IDBServer::IDBServer::StorageQuotaManagerSpaceRequester&& spaceRequester) { return adoptRef(*new WebIDBServer(sessionID, directory, WTFMove(spaceRequester))); } WebIDBServer::WebIDBServer(PAL::SessionID sessionID, const String& directory, WebCore::IDBServer::IDBServer::StorageQuotaManagerSpaceRequester&& spaceRequester) : CrossThreadTaskHandler("com.apple.WebKit.IndexedDBServer", WTF::CrossThreadTaskHandler::AutodrainedPoolForRunLoop::Use) { ASSERT(RunLoop::isMain()); BinarySemaphore semaphore; postTask([this, protectedThis = makeRef(*this), &semaphore, sessionID, directory = directory.isolatedCopy(), spaceRequester = WTFMove(spaceRequester)] () mutable { m_server = makeUnique<WebCore::IDBServer::IDBServer>(sessionID, directory, WTFMove(spaceRequester)); semaphore.signal(); }); semaphore.wait(); } WebIDBServer::~WebIDBServer() { ASSERT(RunLoop::isMain()); } void WebIDBServer::closeAndDeleteDatabasesModifiedSince(WallTime modificationTime, CompletionHandler<void()>&& callback) { ASSERT(RunLoop::isMain()); postTask([this, protectedThis = makeRef(*this), modificationTime, callback = WTFMove(callback)]() mutable { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->closeAndDeleteDatabasesModifiedSince(modificationTime); postTaskReply(CrossThreadTask([callback = WTFMove(callback)]() mutable { callback(); })); }); } void WebIDBServer::closeAndDeleteDatabasesForOrigins(const Vector<WebCore::SecurityOriginData>& originDatas, CompletionHandler<void()>&& callback) { ASSERT(RunLoop::isMain()); postTask([this, protectedThis = makeRef(*this), originDatas = originDatas.isolatedCopy(), callback = WTFMove(callback)] () mutable { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->closeAndDeleteDatabasesForOrigins(originDatas); postTaskReply(CrossThreadTask([callback = WTFMove(callback)]() mutable { callback(); })); }); } void WebIDBServer::renameOrigin(const WebCore::SecurityOriginData& oldOrigin, const WebCore::SecurityOriginData& newOrigin, CompletionHandler<void()>&& callback) { ASSERT(RunLoop::isMain()); postTask([this, protectedThis = makeRef(*this), oldOrigin = oldOrigin.isolatedCopy(), newOrigin = newOrigin.isolatedCopy(), callback = WTFMove(callback)] () mutable { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->renameOrigin(oldOrigin, newOrigin); postTaskReply(CrossThreadTask(WTFMove(callback))); }); } void WebIDBServer::suspend() { ASSERT(RunLoop::isMain()); if (m_isSuspended) return; m_isSuspended = true; m_server->lock().lock(); m_server->stopDatabaseActivitiesOnMainThread(); } void WebIDBServer::resume() { ASSERT(RunLoop::isMain()); if (!m_isSuspended) return; m_isSuspended = false; m_server->lock().unlock(); } void WebIDBServer::openDatabase(const WebCore::IDBRequestData& requestData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->openDatabase(requestData); } void WebIDBServer::deleteDatabase(const WebCore::IDBRequestData& requestData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->deleteDatabase(requestData); } void WebIDBServer::abortTransaction(const WebCore::IDBResourceIdentifier& transactionIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->abortTransaction(transactionIdentifier); } void WebIDBServer::commitTransaction(const WebCore::IDBResourceIdentifier& transactionIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->commitTransaction(transactionIdentifier); } void WebIDBServer::didFinishHandlingVersionChangeTransaction(uint64_t databaseConnectionIdentifier, const WebCore::IDBResourceIdentifier& transactionIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->didFinishHandlingVersionChangeTransaction(databaseConnectionIdentifier, transactionIdentifier); } void WebIDBServer::createObjectStore(const WebCore::IDBRequestData& requestData, const WebCore::IDBObjectStoreInfo& objectStoreInfo) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->createObjectStore(requestData, objectStoreInfo); } void WebIDBServer::deleteObjectStore(const WebCore::IDBRequestData& requestData, const String& objectStoreName) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->deleteObjectStore(requestData, objectStoreName); } void WebIDBServer::renameObjectStore(const WebCore::IDBRequestData& requestData, uint64_t objectStoreIdentifier, const String& newName) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->renameObjectStore(requestData, objectStoreIdentifier, newName); } void WebIDBServer::clearObjectStore(const WebCore::IDBRequestData& requestData, uint64_t objectStoreIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->clearObjectStore(requestData, objectStoreIdentifier); } void WebIDBServer::createIndex(const WebCore::IDBRequestData& requestData, const WebCore::IDBIndexInfo& indexInfo) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->createIndex(requestData, indexInfo); } void WebIDBServer::deleteIndex(const WebCore::IDBRequestData& requestData, uint64_t objectStoreIdentifier, const String& indexName) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->deleteIndex(requestData, objectStoreIdentifier, indexName); } void WebIDBServer::renameIndex(const WebCore::IDBRequestData& requestData, uint64_t objectStoreIdentifier, uint64_t indexIdentifier, const String& newName) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->renameIndex(requestData, objectStoreIdentifier, indexIdentifier, newName); } void WebIDBServer::putOrAdd(const WebCore::IDBRequestData& requestData, const WebCore::IDBKeyData& keyData, const WebCore::IDBValue& value, WebCore::IndexedDB::ObjectStoreOverwriteMode overWriteMode) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->putOrAdd(requestData, keyData, value, overWriteMode); } void WebIDBServer::getRecord(const WebCore::IDBRequestData& requestData, const WebCore::IDBGetRecordData& getRecordData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->getRecord(requestData, getRecordData); } void WebIDBServer::getAllRecords(const WebCore::IDBRequestData& requestData, const WebCore::IDBGetAllRecordsData& getAllRecordsData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->getAllRecords(requestData, getAllRecordsData); } void WebIDBServer::getCount(const WebCore::IDBRequestData& requestData, const WebCore::IDBKeyRangeData& keyRangeData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->getCount(requestData, keyRangeData); } void WebIDBServer::deleteRecord(const WebCore::IDBRequestData& requestData, const WebCore::IDBKeyRangeData& keyRangeData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->deleteRecord(requestData, keyRangeData); } void WebIDBServer::openCursor(const WebCore::IDBRequestData& requestData, const WebCore::IDBCursorInfo& cursorInfo) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->openCursor(requestData, cursorInfo); } void WebIDBServer::iterateCursor(const WebCore::IDBRequestData& requestData, const WebCore::IDBIterateCursorData& iterateCursorData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->iterateCursor(requestData, iterateCursorData); } void WebIDBServer::establishTransaction(uint64_t databaseConnectionIdentifier, const WebCore::IDBTransactionInfo& transactionInfo) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->establishTransaction(databaseConnectionIdentifier, transactionInfo); } void WebIDBServer::databaseConnectionPendingClose(uint64_t databaseConnectionIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->databaseConnectionPendingClose(databaseConnectionIdentifier); } void WebIDBServer::databaseConnectionClosed(uint64_t databaseConnectionIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->databaseConnectionClosed(databaseConnectionIdentifier); } void WebIDBServer::abortOpenAndUpgradeNeeded(uint64_t databaseConnectionIdentifier, const WebCore::IDBResourceIdentifier& transactionIdentifier) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->abortOpenAndUpgradeNeeded(databaseConnectionIdentifier, transactionIdentifier); } void WebIDBServer::didFireVersionChangeEvent(uint64_t databaseConnectionIdentifier, const WebCore::IDBResourceIdentifier& requestIdentifier, WebCore::IndexedDB::ConnectionClosedOnBehalfOfServer connectionClosed) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->didFireVersionChangeEvent(databaseConnectionIdentifier, requestIdentifier, connectionClosed); } void WebIDBServer::openDBRequestCancelled(const WebCore::IDBRequestData& requestData) { ASSERT(!RunLoop::isMain()); LockHolder locker(m_server->lock()); m_server->openDBRequestCancelled(requestData); } void WebIDBServer::getAllDatabaseNamesAndVersions(IPC::Connection& connection, const WebCore::IDBResourceIdentifier& requestIdentifier, const WebCore::ClientOrigin& origin) { ASSERT(!RunLoop::isMain()); auto* webIDBConnection = m_connectionMap.get(connection.uniqueID()); ASSERT(webIDBConnection); LockHolder locker(m_server->lock()); m_server->getAllDatabaseNamesAndVersions(webIDBConnection->identifier(), requestIdentifier, origin); } void WebIDBServer::addConnection(IPC::Connection& connection, WebCore::ProcessIdentifier processIdentifier) { ASSERT(RunLoop::isMain()); postTask([this, protectedThis = makeRef(*this), protectedConnection = makeRefPtr(connection), processIdentifier] { auto[iter, isNewEntry] = m_connectionMap.ensure(protectedConnection->uniqueID(), [&] { return makeUnique<WebIDBConnectionToClient>(*protectedConnection, processIdentifier); }); ASSERT_UNUSED(isNewEntry, isNewEntry); LockHolder locker(m_server->lock()); m_server->registerConnection(iter->value->connectionToClient()); }); m_connections.add(&connection); connection.addThreadMessageReceiver(Messages::WebIDBServer::messageReceiverName(), this); } void WebIDBServer::removeConnection(IPC::Connection& connection) { ASSERT(RunLoop::isMain()); m_connections.remove(&connection); connection.removeThreadMessageReceiver(Messages::WebIDBServer::messageReceiverName()); postTask([this, protectedThis = makeRef(*this), connectionID = connection.uniqueID()] { auto connection = m_connectionMap.take(connectionID); ASSERT(connection); LockHolder locker(m_server->lock()); m_server->unregisterConnection(connection->connectionToClient()); }); } void WebIDBServer::postTask(Function<void()>&& task) { ASSERT(RunLoop::isMain()); CrossThreadTaskHandler::postTask(CrossThreadTask(WTFMove(task))); } void WebIDBServer::dispatchToThread(Function<void()>&& task) { CrossThreadTaskHandler::postTask(CrossThreadTask(WTFMove(task))); } void WebIDBServer::close() { ASSERT(RunLoop::isMain()); // Remove the references held by IPC::Connection. for (auto* connection : m_connections) connection->removeThreadMessageReceiver(Messages::WebIDBServer::messageReceiverName()); CrossThreadTaskHandler::setCompletionCallback([protectedThis = makeRef(*this)]() mutable { ASSERT(!RunLoop::isMain()); callOnMainRunLoop([protectedThis = WTFMove(protectedThis)]() mutable { }); }); postTask([this]() mutable { m_connectionMap.clear(); m_server = nullptr; CrossThreadTaskHandler::kill(); }); } } // namespace WebKit #endif
34.838235
211
0.750809
[ "vector" ]
9712568e30b23b5423fb567e91dc428664fe23a3
33,264
cpp
C++
third_party/WebKit/Source/modules/payments/PaymentRequest.cpp
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
third_party/WebKit/Source/modules/payments/PaymentRequest.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/payments/PaymentRequest.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 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 "modules/payments/PaymentRequest.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/ScriptState.h" #include "bindings/core/v8/V8StringResource.h" #include "bindings/modules/v8/V8AndroidPayMethodData.h" #include "bindings/modules/v8/V8PaymentDetails.h" #include "core/EventTypeNames.h" #include "core/dom/DOMException.h" #include "core/dom/ExceptionCode.h" #include "core/events/Event.h" #include "core/events/EventQueue.h" #include "core/frame/FrameOwner.h" #include "core/html/HTMLIFrameElement.h" #include "modules/EventTargetModulesNames.h" #include "modules/payments/AndroidPayMethodData.h" #include "modules/payments/AndroidPayTokenization.h" #include "modules/payments/HTMLIFrameElementPayments.h" #include "modules/payments/PaymentAddress.h" #include "modules/payments/PaymentItem.h" #include "modules/payments/PaymentRequestUpdateEvent.h" #include "modules/payments/PaymentResponse.h" #include "modules/payments/PaymentShippingOption.h" #include "modules/payments/PaymentsValidators.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/wtf_array.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/mojo/MojoHelper.h" #include "public/platform/InterfaceProvider.h" #include "public/platform/Platform.h" #include "public/platform/WebTraceLocation.h" #include "wtf/HashSet.h" #include <utility> using payments::mojom::blink::CanMakePaymentQueryResult; using payments::mojom::blink::PaymentAddressPtr; using payments::mojom::blink::PaymentCurrencyAmount; using payments::mojom::blink::PaymentCurrencyAmountPtr; using payments::mojom::blink::PaymentDetails; using payments::mojom::blink::PaymentDetailsModifier; using payments::mojom::blink::PaymentDetailsModifierPtr; using payments::mojom::blink::PaymentDetailsPtr; using payments::mojom::blink::PaymentDetailsPtr; using payments::mojom::blink::PaymentErrorReason; using payments::mojom::blink::PaymentItem; using payments::mojom::blink::PaymentItemPtr; using payments::mojom::blink::PaymentMethodData; using payments::mojom::blink::PaymentMethodDataPtr; using payments::mojom::blink::PaymentOptions; using payments::mojom::blink::PaymentOptionsPtr; using payments::mojom::blink::PaymentResponsePtr; using payments::mojom::blink::PaymentShippingOption; using payments::mojom::blink::PaymentShippingOptionPtr; using payments::mojom::blink::PaymentShippingType; namespace mojo { template <> struct TypeConverter<PaymentCurrencyAmountPtr, blink::PaymentCurrencyAmount> { static PaymentCurrencyAmountPtr Convert( const blink::PaymentCurrencyAmount& input) { PaymentCurrencyAmountPtr output = PaymentCurrencyAmount::New(); output->currency = input.currency(); output->value = input.value(); if (input.hasCurrencySystem()) output->currencySystem = input.currencySystem(); return output; } }; template <> struct TypeConverter<PaymentItemPtr, blink::PaymentItem> { static PaymentItemPtr Convert(const blink::PaymentItem& input) { PaymentItemPtr output = PaymentItem::New(); output->label = input.label(); output->amount = PaymentCurrencyAmount::From(input.amount()); output->pending = input.pending(); return output; } }; template <> struct TypeConverter<PaymentShippingOptionPtr, blink::PaymentShippingOption> { static PaymentShippingOptionPtr Convert( const blink::PaymentShippingOption& input) { PaymentShippingOptionPtr output = PaymentShippingOption::New(); output->id = input.id(); output->label = input.label(); output->amount = PaymentCurrencyAmount::From(input.amount()); output->selected = input.hasSelected() && input.selected(); return output; } }; template <> struct TypeConverter<PaymentDetailsModifierPtr, blink::PaymentDetailsModifier> { static PaymentDetailsModifierPtr Convert( const blink::PaymentDetailsModifier& input) { PaymentDetailsModifierPtr output = PaymentDetailsModifier::New(); output->supported_methods = input.supportedMethods(); if (input.hasTotal()) output->total = PaymentItem::From(input.total()); if (input.hasAdditionalDisplayItems()) { for (size_t i = 0; i < input.additionalDisplayItems().size(); ++i) { output->additional_display_items.append( PaymentItem::From(input.additionalDisplayItems()[i])); } } return output; } }; template <> struct TypeConverter<PaymentDetailsPtr, blink::PaymentDetails> { static PaymentDetailsPtr Convert(const blink::PaymentDetails& input) { PaymentDetailsPtr output = PaymentDetails::New(); output->total = PaymentItem::From(input.total()); if (input.hasDisplayItems()) { for (size_t i = 0; i < input.displayItems().size(); ++i) { output->display_items.append( PaymentItem::From(input.displayItems()[i])); } } if (input.hasShippingOptions()) { for (size_t i = 0; i < input.shippingOptions().size(); ++i) { output->shipping_options.append( PaymentShippingOption::From(input.shippingOptions()[i])); } } if (input.hasModifiers()) { for (size_t i = 0; i < input.modifiers().size(); ++i) { output->modifiers.append( PaymentDetailsModifier::From(input.modifiers()[i])); } } if (input.hasError()) output->error = input.error(); else output->error = emptyString(); return output; } }; template <> struct TypeConverter<PaymentOptionsPtr, blink::PaymentOptions> { static PaymentOptionsPtr Convert(const blink::PaymentOptions& input) { PaymentOptionsPtr output = PaymentOptions::New(); output->request_payer_name = input.requestPayerName(); output->request_payer_email = input.requestPayerEmail(); output->request_payer_phone = input.requestPayerPhone(); output->request_shipping = input.requestShipping(); if (input.shippingType() == "delivery") output->shipping_type = PaymentShippingType::DELIVERY; else if (input.shippingType() == "pickup") output->shipping_type = PaymentShippingType::PICKUP; else output->shipping_type = PaymentShippingType::SHIPPING; return output; } }; } // namespace mojo namespace blink { namespace { using payments::mojom::blink::AndroidPayCardNetwork; using payments::mojom::blink::AndroidPayTokenization; // If the website does not call complete() 60 seconds after show() has been // resolved, then behave as if the website called complete("fail"). static const int completeTimeoutSeconds = 60; const struct { const AndroidPayCardNetwork code; const char* name; } kAndroidPayNetwork[] = {{AndroidPayCardNetwork::AMEX, "AMEX"}, {AndroidPayCardNetwork::DISCOVER, "DISCOVER"}, {AndroidPayCardNetwork::MASTERCARD, "MASTERCARD"}, {AndroidPayCardNetwork::VISA, "VISA"}}; const struct { const AndroidPayTokenization code; const char* name; } kAndroidPayTokenization[] = { {AndroidPayTokenization::GATEWAY_TOKEN, "GATEWAY_TOKEN"}, {AndroidPayTokenization::NETWORK_TOKEN, "NETWORK_TOKEN"}}; // Validates ShippingOption or PaymentItem, which happen to have identical // fields, except for "id", which is present only in ShippingOption. template <typename T> void validateShippingOptionOrPaymentItem(const T& item, ExceptionState& exceptionState) { if (!item.hasLabel() || item.label().isEmpty()) { exceptionState.throwTypeError("Item label required"); return; } if (!item.hasAmount()) { exceptionState.throwTypeError("Currency amount required"); return; } if (!item.amount().hasCurrency()) { exceptionState.throwTypeError("Currency code required"); return; } if (!item.amount().hasValue()) { exceptionState.throwTypeError("Currency value required"); return; } String errorMessage; if (!PaymentsValidators::isValidCurrencyCodeFormat( item.amount().currency(), item.amount().currencySystem(), &errorMessage)) { exceptionState.throwTypeError(errorMessage); return; } if (!PaymentsValidators::isValidAmountFormat(item.amount().value(), &errorMessage)) { exceptionState.throwTypeError(errorMessage); return; } } void validateDisplayItems(const HeapVector<PaymentItem>& items, ExceptionState& exceptionState) { for (const auto& item : items) { validateShippingOptionOrPaymentItem(item, exceptionState); if (exceptionState.hadException()) return; } } // Returns false if |options| should be ignored, even if an exception was not // thrown. TODO(rouslan): Clear shipping options instead of ignoring them when // http://crbug.com/601193 is fixed. bool validateShippingOptions(const HeapVector<PaymentShippingOption>& options, ExceptionState& exceptionState) { HashSet<String> uniqueIds; for (const auto& option : options) { if (!option.hasId() || option.id().isEmpty()) { exceptionState.throwTypeError("ShippingOption id required"); return false; } if (uniqueIds.contains(option.id())) return false; uniqueIds.add(option.id()); validateShippingOptionOrPaymentItem(option, exceptionState); if (exceptionState.hadException()) return false; } return true; } void validatePaymentDetailsModifiers( const HeapVector<PaymentDetailsModifier>& modifiers, ExceptionState& exceptionState) { if (modifiers.isEmpty()) { exceptionState.throwTypeError( "Must specify at least one payment details modifier"); return; } for (const auto& modifier : modifiers) { if (modifier.supportedMethods().isEmpty()) { exceptionState.throwTypeError( "Must specify at least one payment method identifier"); return; } if (modifier.hasTotal()) { validateShippingOptionOrPaymentItem(modifier.total(), exceptionState); if (exceptionState.hadException()) return; if (modifier.total().amount().value()[0] == '-') { exceptionState.throwTypeError( "Total amount value should be non-negative"); return; } } if (modifier.hasAdditionalDisplayItems()) { validateDisplayItems(modifier.additionalDisplayItems(), exceptionState); if (exceptionState.hadException()) return; } } } // Returns false if the shipping options should be ignored without throwing an // exception. bool validatePaymentDetails(const PaymentDetails& details, ExceptionState& exceptionState) { bool keepShippingOptions = true; if (!details.hasTotal()) { exceptionState.throwTypeError("Must specify total"); return keepShippingOptions; } validateShippingOptionOrPaymentItem(details.total(), exceptionState); if (exceptionState.hadException()) return keepShippingOptions; if (details.total().amount().value()[0] == '-') { exceptionState.throwTypeError("Total amount value should be non-negative"); return keepShippingOptions; } if (details.hasDisplayItems()) { validateDisplayItems(details.displayItems(), exceptionState); if (exceptionState.hadException()) return keepShippingOptions; } if (details.hasShippingOptions()) { keepShippingOptions = validateShippingOptions(details.shippingOptions(), exceptionState); if (exceptionState.hadException()) return keepShippingOptions; } if (details.hasModifiers()) { validatePaymentDetailsModifiers(details.modifiers(), exceptionState); if (exceptionState.hadException()) return keepShippingOptions; } String errorMessage; if (!PaymentsValidators::isValidErrorMsgFormat(details.error(), &errorMessage)) { exceptionState.throwTypeError(errorMessage); } return keepShippingOptions; } void maybeSetAndroidPayMethodata( const ScriptValue& input, payments::mojom::blink::PaymentMethodDataPtr& output) { AndroidPayMethodData androidPay; TrackExceptionState exceptionState; V8AndroidPayMethodData::toImpl(input.isolate(), input.v8Value(), androidPay, exceptionState); if (exceptionState.hadException()) return; if (androidPay.hasEnvironment() && androidPay.environment() == "TEST") output->environment = payments::mojom::blink::AndroidPayEnvironment::TEST; output->merchant_name = androidPay.merchantName(); output->merchant_id = androidPay.merchantId(); if (androidPay.hasAllowedCardNetworks()) { output->allowed_card_networks.resize( androidPay.allowedCardNetworks().size()); size_t numberOfNetworks = 0; for (size_t i = 0; i < androidPay.allowedCardNetworks().size(); ++i) { for (size_t j = 0; j < arraysize(kAndroidPayNetwork); ++j) { if (androidPay.allowedCardNetworks()[i] == kAndroidPayNetwork[j].name) { output->allowed_card_networks[numberOfNetworks++] = kAndroidPayNetwork[j].code; break; } } } output->allowed_card_networks.resize(numberOfNetworks); } if (androidPay.hasPaymentMethodTokenizationParameters()) { const blink::AndroidPayTokenization& tokenization = androidPay.paymentMethodTokenizationParameters(); output->tokenization_type = payments::mojom::blink::AndroidPayTokenization::UNSPECIFIED; if (tokenization.hasTokenizationType()) { for (size_t j = 0; j < arraysize(kAndroidPayTokenization); ++j) { if (tokenization.tokenizationType() == kAndroidPayTokenization[j].name) { output->tokenization_type = kAndroidPayTokenization[j].code; break; } } } if (tokenization.hasParameters()) { Vector<String> keys; tokenization.parameters().getPropertyNames(keys); output->parameters.resize(keys.size()); size_t numberOfParameters = 0; String value; for (size_t i = 0; i < keys.size(); ++i) { if (!DictionaryHelper::get(tokenization.parameters(), keys[i], value)) continue; output->parameters[numberOfParameters] = payments::mojom::blink::AndroidPayTokenizationParameter::New(); output->parameters[numberOfParameters]->key = keys[i]; output->parameters[numberOfParameters]->value = value; ++numberOfParameters; } output->parameters.resize(numberOfParameters); } } } void validateAndConvertPaymentMethodData( const HeapVector<PaymentMethodData>& input, Vector<payments::mojom::blink::PaymentMethodDataPtr>& output, ExceptionState& exceptionState) { if (input.isEmpty()) { exceptionState.throwTypeError( "Must specify at least one payment method identifier"); return; } output.resize(input.size()); for (size_t i = 0; i < input.size(); ++i) { const auto& paymentMethodData = input[i]; if (paymentMethodData.supportedMethods().isEmpty()) { exceptionState.throwTypeError( "Must specify at least one payment method identifier"); return; } String stringifiedData = ""; if (paymentMethodData.hasData() && !paymentMethodData.data().isEmpty()) { if (!paymentMethodData.data().v8Value()->IsObject() || paymentMethodData.data().v8Value()->IsArray()) { exceptionState.throwTypeError( "Data should be a JSON-serializable object"); return; } v8::Local<v8::String> value; if (!v8::JSON::Stringify( paymentMethodData.data().context(), paymentMethodData.data().v8Value().As<v8::Object>()) .ToLocal(&value)) { exceptionState.throwTypeError( "Unable to parse payment method specific data"); return; } stringifiedData = v8StringToWebCoreString<String>(value, DoNotExternalize); } output[i] = payments::mojom::blink::PaymentMethodData::New(); output[i]->supported_methods = paymentMethodData.supportedMethods(); output[i]->stringified_data = stringifiedData; maybeSetAndroidPayMethodata(paymentMethodData.data(), output[i]); } } String getSelectedShippingOption(const PaymentDetails& details) { String result; if (!details.hasShippingOptions()) return result; for (int i = details.shippingOptions().size() - 1; i >= 0; --i) { if (details.shippingOptions()[i].hasSelected() && details.shippingOptions()[i].selected()) { return details.shippingOptions()[i].id(); } } return result; } String getValidShippingType(const String& shippingType) { static const char* const validValues[] = { "shipping", "delivery", "pickup", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(validValues); i++) { if (shippingType == validValues[i]) return shippingType; } return validValues[0]; } PaymentDetailsPtr maybeKeepShippingOptions(PaymentDetailsPtr details, bool keep) { if (!keep) details->shipping_options.resize(0); return details; } bool allowedToUsePaymentRequest(const Frame* frame) { // To determine whether a Document object |document| is allowed to use the // feature indicated by attribute name |allowpaymentrequest|, run these steps: // 1. If |document| has no browsing context, then return false. if (!frame) return false; // 2. If |document|'s browsing context is a top-level browsing context, then // return true. if (frame->isMainFrame()) return true; // 3. If |document|'s browsing context has a browsing context container that // is an iframe element with an |allowpaymentrequest| attribute specified, and // whose node document is allowed to use the feature indicated by // |allowpaymentrequest|, then return true. if (RuntimeEnabledFeatures::paymentRequestIFrameEnabled() && frame->owner() && frame->owner()->allowPaymentRequest()) { return allowedToUsePaymentRequest(frame->tree().parent()); } // 4. Return false. return false; } } // namespace PaymentRequest* PaymentRequest::create( ScriptState* scriptState, const HeapVector<PaymentMethodData>& methodData, const PaymentDetails& details, ExceptionState& exceptionState) { return new PaymentRequest(scriptState, methodData, details, PaymentOptions(), exceptionState); } PaymentRequest* PaymentRequest::create( ScriptState* scriptState, const HeapVector<PaymentMethodData>& methodData, const PaymentDetails& details, const PaymentOptions& options, ExceptionState& exceptionState) { return new PaymentRequest(scriptState, methodData, details, options, exceptionState); } PaymentRequest::~PaymentRequest() {} ScriptPromise PaymentRequest::show(ScriptState* scriptState) { if (!m_paymentProvider.is_bound() || m_showResolver) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Already called show() once")); if (!scriptState->domWindow() || !scriptState->domWindow()->frame()) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Cannot show the payment request")); m_paymentProvider->Show(); m_showResolver = ScriptPromiseResolver::create(scriptState); return m_showResolver->promise(); } ScriptPromise PaymentRequest::abort(ScriptState* scriptState) { if (m_abortResolver) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Cannot abort() again until the previous abort() " "has resolved or rejected")); if (!m_showResolver) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Never called show(), so nothing to abort")); m_abortResolver = ScriptPromiseResolver::create(scriptState); m_paymentProvider->Abort(); return m_abortResolver->promise(); } ScriptPromise PaymentRequest::canMakePayment(ScriptState* scriptState) { if (!m_paymentProvider.is_bound() || m_canMakePaymentResolver || !scriptState->contextIsValid()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Cannot query payment request")); } m_paymentProvider->CanMakePayment(); m_canMakePaymentResolver = ScriptPromiseResolver::create(scriptState); return m_canMakePaymentResolver->promise(); } bool PaymentRequest::hasPendingActivity() const { return m_showResolver || m_completeResolver; } const AtomicString& PaymentRequest::interfaceName() const { return EventTargetNames::PaymentRequest; } ExecutionContext* PaymentRequest::getExecutionContext() const { return ContextLifecycleObserver::getExecutionContext(); } ScriptPromise PaymentRequest::complete(ScriptState* scriptState, PaymentComplete result) { if (m_completeResolver) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Already called complete() once")); if (!m_completeTimer.isActive()) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create( InvalidStateError, "Timed out after 60 seconds, complete() called too late")); // User has cancelled the transaction while the website was processing it. if (!m_paymentProvider) return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "Request cancelled")); m_completeTimer.stop(); // The payment provider should respond in PaymentRequest::OnComplete(). m_paymentProvider->Complete(payments::mojom::blink::PaymentComplete(result)); m_completeResolver = ScriptPromiseResolver::create(scriptState); return m_completeResolver->promise(); } void PaymentRequest::onUpdatePaymentDetails( const ScriptValue& detailsScriptValue) { if (!m_showResolver || !m_paymentProvider) return; PaymentDetails details; TrackExceptionState exceptionState; V8PaymentDetails::toImpl(detailsScriptValue.isolate(), detailsScriptValue.v8Value(), details, exceptionState); if (exceptionState.hadException()) { m_showResolver->reject( DOMException::create(SyntaxError, exceptionState.message())); clearResolversAndCloseMojoConnection(); return; } bool keepShippingOptions = validatePaymentDetails(details, exceptionState); if (exceptionState.hadException()) { m_showResolver->reject( DOMException::create(SyntaxError, exceptionState.message())); clearResolversAndCloseMojoConnection(); return; } if (m_options.requestShipping()) { if (keepShippingOptions) m_shippingOption = getSelectedShippingOption(details); else m_shippingOption = String(); } m_paymentProvider->UpdateWith(maybeKeepShippingOptions( payments::mojom::blink::PaymentDetails::From(details), keepShippingOptions)); } void PaymentRequest::onUpdatePaymentDetailsFailure(const String& error) { if (m_showResolver) m_showResolver->reject(DOMException::create(AbortError, error)); if (m_completeResolver) m_completeResolver->reject(DOMException::create(AbortError, error)); clearResolversAndCloseMojoConnection(); } DEFINE_TRACE(PaymentRequest) { visitor->trace(m_options); visitor->trace(m_shippingAddress); visitor->trace(m_showResolver); visitor->trace(m_completeResolver); visitor->trace(m_abortResolver); visitor->trace(m_canMakePaymentResolver); EventTargetWithInlineData::trace(visitor); ContextLifecycleObserver::trace(visitor); } void PaymentRequest::onCompleteTimeoutForTesting() { m_completeTimer.stop(); onCompleteTimeout(0); } PaymentRequest::PaymentRequest(ScriptState* scriptState, const HeapVector<PaymentMethodData>& methodData, const PaymentDetails& details, const PaymentOptions& options, ExceptionState& exceptionState) : ContextLifecycleObserver(scriptState->getExecutionContext()), ActiveScriptWrappable(this), m_options(options), m_clientBinding(this), m_completeTimer(this, &PaymentRequest::onCompleteTimeout) { Vector<payments::mojom::blink::PaymentMethodDataPtr> validatedMethodData; validateAndConvertPaymentMethodData(methodData, validatedMethodData, exceptionState); if (exceptionState.hadException()) return; if (!scriptState->getExecutionContext()->isSecureContext()) { exceptionState.throwSecurityError("Must be in a secure context"); return; } if (!allowedToUsePaymentRequest(scriptState->domWindow()->frame())) { exceptionState.throwSecurityError( RuntimeEnabledFeatures::paymentRequestIFrameEnabled() ? "Must be in a top-level browsing context or an iframe needs to " "specify 'allowpaymentrequest' explicitly" : "Must be in a top-level browsing context"); return; } bool keepShippingOptions = validatePaymentDetails(details, exceptionState); if (exceptionState.hadException()) return; if (details.hasError() && !details.error().isEmpty()) { exceptionState.throwTypeError("Error value should be empty"); return; } if (m_options.requestShipping()) { if (keepShippingOptions) m_shippingOption = getSelectedShippingOption(details); m_shippingType = getValidShippingType(m_options.shippingType()); } scriptState->domWindow()->frame()->interfaceProvider()->getInterface( mojo::GetProxy(&m_paymentProvider)); m_paymentProvider.set_connection_error_handler(convertToBaseCallback( WTF::bind(&PaymentRequest::OnError, wrapWeakPersistent(this), PaymentErrorReason::UNKNOWN))); m_paymentProvider->Init( m_clientBinding.CreateInterfacePtrAndBind(), std::move(validatedMethodData), maybeKeepShippingOptions( payments::mojom::blink::PaymentDetails::From(details), keepShippingOptions && m_options.requestShipping()), payments::mojom::blink::PaymentOptions::From(m_options)); } void PaymentRequest::contextDestroyed() { clearResolversAndCloseMojoConnection(); } void PaymentRequest::OnShippingAddressChange(PaymentAddressPtr address) { DCHECK(m_showResolver); DCHECK(!m_completeResolver); String errorMessage; if (!PaymentsValidators::isValidShippingAddress(address, &errorMessage)) { m_showResolver->reject(DOMException::create(SyntaxError, errorMessage)); clearResolversAndCloseMojoConnection(); return; } m_shippingAddress = new PaymentAddress(std::move(address)); PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::create(EventTypeNames::shippingaddresschange); event->setTarget(this); event->setPaymentDetailsUpdater(this); bool success = getExecutionContext()->getEventQueue()->enqueueEvent(event); DCHECK(success); ALLOW_UNUSED_LOCAL(success); } void PaymentRequest::OnShippingOptionChange(const String& shippingOptionId) { DCHECK(m_showResolver); DCHECK(!m_completeResolver); m_shippingOption = shippingOptionId; PaymentRequestUpdateEvent* event = PaymentRequestUpdateEvent::create(EventTypeNames::shippingoptionchange); event->setTarget(this); event->setPaymentDetailsUpdater(this); bool success = getExecutionContext()->getEventQueue()->enqueueEvent(event); DCHECK(success); ALLOW_UNUSED_LOCAL(success); } void PaymentRequest::OnPaymentResponse( payments::mojom::blink::PaymentResponsePtr response) { DCHECK(m_showResolver); DCHECK(!m_completeResolver); DCHECK(!m_completeTimer.isActive()); if (m_options.requestShipping()) { if (!response->shipping_address || response->shipping_option.isEmpty()) { m_showResolver->reject(DOMException::create(SyntaxError)); clearResolversAndCloseMojoConnection(); return; } String errorMessage; if (!PaymentsValidators::isValidShippingAddress(response->shipping_address, &errorMessage)) { m_showResolver->reject(DOMException::create(SyntaxError, errorMessage)); clearResolversAndCloseMojoConnection(); return; } m_shippingAddress = new PaymentAddress(response->shipping_address.Clone()); m_shippingOption = response->shipping_option; } else { if (response->shipping_address || !response->shipping_option.isNull()) { m_showResolver->reject(DOMException::create(SyntaxError)); clearResolversAndCloseMojoConnection(); return; } } if ((m_options.requestPayerName() && response->payer_name.isEmpty()) || (m_options.requestPayerEmail() && response->payer_email.isEmpty()) || (m_options.requestPayerPhone() && response->payer_phone.isEmpty()) || (!m_options.requestPayerName() && !response->payer_name.isNull()) || (!m_options.requestPayerEmail() && !response->payer_email.isNull()) || (!m_options.requestPayerPhone() && !response->payer_phone.isNull())) { m_showResolver->reject(DOMException::create(SyntaxError)); clearResolversAndCloseMojoConnection(); return; } m_completeTimer.startOneShot(completeTimeoutSeconds, BLINK_FROM_HERE); m_showResolver->resolve(new PaymentResponse(std::move(response), this)); // Do not close the mojo connection here. The merchant website should call // PaymentResponse::complete(String), which will be forwarded over the mojo // connection to display a success or failure message to the user. m_showResolver.clear(); } void PaymentRequest::OnError(PaymentErrorReason error) { if (!Platform::current()) { // TODO(rockot): Clean this up once renderer shutdown sequence is fixed. return; } bool isError = false; ExceptionCode ec = UnknownError; String message; switch (error) { case PaymentErrorReason::USER_CANCEL: message = "Request cancelled"; break; case PaymentErrorReason::NOT_SUPPORTED: isError = true; ec = NotSupportedError; message = "The payment method is not supported"; break; case PaymentErrorReason::UNKNOWN: isError = true; ec = UnknownError; message = "Request failed"; break; } DCHECK(!message.isEmpty()); if (isError) { if (m_completeResolver) m_completeResolver->reject(DOMException::create(ec, message)); if (m_showResolver) m_showResolver->reject(DOMException::create(ec, message)); if (m_abortResolver) m_abortResolver->reject(DOMException::create(ec, message)); if (m_canMakePaymentResolver) m_canMakePaymentResolver->reject(DOMException::create(ec, message)); } else { if (m_completeResolver) m_completeResolver->reject(message); if (m_showResolver) m_showResolver->reject(message); if (m_abortResolver) m_abortResolver->reject(message); if (m_canMakePaymentResolver) m_canMakePaymentResolver->reject(message); } clearResolversAndCloseMojoConnection(); } void PaymentRequest::OnComplete() { DCHECK(m_completeResolver); m_completeResolver->resolve(); clearResolversAndCloseMojoConnection(); } void PaymentRequest::OnAbort(bool abortedSuccessfully) { DCHECK(m_abortResolver); DCHECK(m_showResolver); if (!abortedSuccessfully) { m_abortResolver->reject(DOMException::create(InvalidStateError)); m_abortResolver.clear(); return; } m_showResolver->reject(DOMException::create(AbortError)); m_abortResolver->resolve(); clearResolversAndCloseMojoConnection(); } void PaymentRequest::OnCanMakePayment(CanMakePaymentQueryResult result) { DCHECK(m_canMakePaymentResolver); switch (result) { case CanMakePaymentQueryResult::CAN_MAKE_PAYMENT: m_canMakePaymentResolver->resolve(true); break; case CanMakePaymentQueryResult::CANNOT_MAKE_PAYMENT: m_canMakePaymentResolver->resolve(false); break; case CanMakePaymentQueryResult::QUERY_QUOTA_EXCEEDED: m_canMakePaymentResolver->reject( DOMException::create(QuotaExceededError, "Query quota exceeded")); break; } m_canMakePaymentResolver.clear(); } void PaymentRequest::onCompleteTimeout(TimerBase*) { m_paymentProvider->Complete(payments::mojom::blink::PaymentComplete(Fail)); clearResolversAndCloseMojoConnection(); } void PaymentRequest::clearResolversAndCloseMojoConnection() { m_completeTimer.stop(); m_completeResolver.clear(); m_showResolver.clear(); m_abortResolver.clear(); m_canMakePaymentResolver.clear(); if (m_clientBinding.is_bound()) m_clientBinding.Close(); m_paymentProvider.reset(); } } // namespace blink
34.151951
80
0.705808
[ "object", "vector" ]
97129e9215d5dd9a97697db91c01ba5b1877ce42
1,825
cpp
C++
Chapter20/CounterSelector/CounterSelector.cpp
fengjixuchui/Win10SysProgBookSamples
360aff30a19da2ea4c9be6f41c481aa8bf39a2b0
[ "MIT" ]
249
2019-07-09T17:14:43.000Z
2022-03-28T01:54:26.000Z
Chapter20/CounterSelector/CounterSelector.cpp
fengjixuchui/Win10SysProgBookSamples
360aff30a19da2ea4c9be6f41c481aa8bf39a2b0
[ "MIT" ]
8
2019-07-12T21:08:29.000Z
2022-01-04T12:32:00.000Z
Chapter20/CounterSelector/CounterSelector.cpp
isabella232/Win10SysProgBookSamples
97e479a9a4923ecf94866bae516a76bde02ef71e
[ "MIT" ]
70
2019-07-10T02:14:55.000Z
2022-03-08T00:53:07.000Z
// CounterSelector.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <Windows.h> #include <Pdh.h> #include <pdhmsg.h> #include <stdio.h> #include <vector> #include <memory> #include <string> #pragma comment(lib, "pdh") PDH_STATUS CALLBACK SelectorCallback(DWORD_PTR context); std::vector<std::wstring> counters; int main() { PDH_BROWSE_DLG_CONFIG config = { 0 }; auto size = 16 << 10; // 16 KB auto buffer = std::make_unique<WCHAR[]>(size); WCHAR title[] = L"Select Counters"; config.bDisableMachineSelection = FALSE; config.bLocalCountersOnly = TRUE; config.bSingleCounterPerDialog = TRUE; // BUG: setting to TRUE does not cause a crash with <All Instances> but nothing is reported as selected config.bSingleCounterPerAdd = FALSE; config.bIncludeInstanceIndex = TRUE; //config.bWildCardInstances = TRUE; config.bHideDetailBox = TRUE; config.szReturnPathBuffer = buffer.get(); config.cchReturnPathLength = size; config.pCallBack = SelectorCallback; config.dwCallBackArg = reinterpret_cast<DWORD_PTR>(&config); config.szDialogBoxCaption = title; config.szDataSource = nullptr; config.dwDefaultDetailLevel = PERF_DETAIL_EXPERT; auto error = ::PdhBrowseCounters(&config); if (ERROR_SUCCESS != error && PDH_DIALOG_CANCELLED != error) { printf("Error invoking dialog (%u)\n", error); return 1; } printf("Counters selected:\n"); for (auto& counter : counters) printf("%ws\n", counter.c_str()); return 0; } PDH_STATUS CALLBACK SelectorCallback(DWORD_PTR context) { auto config = reinterpret_cast<PDH_BROWSE_DLG_CONFIG*>(context); if (config->CallBackStatus == ERROR_SUCCESS) { auto buffer = config->szReturnPathBuffer; for (auto p = buffer; *p; p += wcslen(p) + 1) { counters.push_back(p); } } return config->CallBackStatus; }
28.515625
105
0.734795
[ "vector" ]
9715bebea8fc63c2b8f10cba0b27ec135aacca49
2,043
cpp
C++
example.cpp
dabbertorres/ThreadPool
120ea06e724a392d59d58ddd9464c5fbadbaf7f3
[ "MIT" ]
30
2015-11-08T20:00:12.000Z
2022-01-27T04:22:53.000Z
example.cpp
dabbertorres/ThreadPool
120ea06e724a392d59d58ddd9464c5fbadbaf7f3
[ "MIT" ]
2
2017-01-10T16:55:43.000Z
2017-05-09T01:21:38.000Z
example.cpp
dabbertorres/ThreadPool
120ea06e724a392d59d58ddd9464c5fbadbaf7f3
[ "MIT" ]
9
2017-03-17T13:33:33.000Z
2020-06-12T04:32:45.000Z
#include <iostream> #include <sstream> #include <random> #include "ThreadPool.hpp" void hello() { std::cout << "hello from thread #" << std::this_thread::get_id() << "!\n"; } void hola() { std::cout << "hola from thread #" << std::this_thread::get_id() << "!\n"; } int add(int x, int y) { return x + y; } int main(int argc, char** argv) { using namespace dbr; cc::ThreadPool pool; // queue up 200 jobs, then run them pool.pause(true); for (int i = 0; i < 200; ++i) pool.add(i % 2 == 1 ? hello : hola); pool.pause(false); // wait for all jobs to finish pool.wait(); std::cout << std::endl; std::random_device rd; std::default_random_engine rand(rd()); std::uniform_int_distribution<int> dist(1, 100); // get ids of threads being used for (auto& id : pool.ids()) std::cout << "Thread ID: " << id << std::endl; std::cout << std::endl; std::vector<std::tuple<int, int, std::future<int>>> results; // add 100 more jobs of a different function type, using the same pool // these will start executing immediately for (int i = 0; i < 100; ++i) { auto one = dist(rand); auto two = dist(rand); results.emplace_back(one, two, pool.add(add, one, two)); } // wait until those are all done pool.wait(); for (auto& res : results) std::cout << std::get<0>(res) << " + " << std::get<1>(res) << " = " << std::get<2>(res).get() << std::endl; std::cout << std::endl; results.clear(); // now add some more, using a lambda for (int i = 0; i < 100; ++i) { auto one = dist(rand); auto two = dist(rand); results.emplace_back(one, two, pool.add([](auto x, auto y) { return x - y; }, one, two)); } // wait until those are all done pool.wait(); for (auto& res : results) std::cout << std::get<0>(res) << " - " << std::get<1>(res) << " = " << std::get<2>(res).get() << std::endl; std::cout << std::endl; return 0; }
23.215909
115
0.543808
[ "vector" ]
971b0af906b025ef673cbdc3d36c4b007c1b74de
652
cpp
C++
ros_pkg/map_image/src/drawers/ImageDrawer.cpp
introlab/securbot
0652ddf3e2dbcf0bb6ffcf76898749b67e443327
[ "Apache-2.0" ]
20
2019-03-13T13:37:51.000Z
2022-01-25T16:56:35.000Z
ros_pkg/map_image/src/drawers/ImageDrawer.cpp
introlab/securbot
0652ddf3e2dbcf0bb6ffcf76898749b67e443327
[ "Apache-2.0" ]
15
2019-02-27T20:29:34.000Z
2020-08-24T19:44:20.000Z
ros_pkg/map_image/src/drawers/ImageDrawer.cpp
introlab/securbot
0652ddf3e2dbcf0bb6ffcf76898749b67e443327
[ "Apache-2.0" ]
13
2019-07-31T00:47:49.000Z
2021-04-15T01:33:02.000Z
#include "map_image_generator/drawers/ImageDrawer.h" using namespace map_image_generator; ImageDrawer::ImageDrawer(const Parameters& parameters, ros::NodeHandle& nodeHandle, tf::TransformListener& tfListener) : m_parameters(parameters), m_nodeHandle(nodeHandle), m_tfListener(tfListener) { } ImageDrawer::~ImageDrawer() { } void ImageDrawer::convertTransformToMapCoordinates(const tf::Transform& transform, int& x, int& y) { x = static_cast<int>(transform.getOrigin().getX() * m_parameters.resolution() + m_parameters.xOrigin()); y = static_cast<int>(transform.getOrigin().getY() * m_parameters.resolution() + m_parameters.yOrigin()); }
36.222222
120
0.768405
[ "transform" ]
971dade09c92fb37aba0f15a35de654066fac39d
17,298
cc
C++
Digit_Example/opt_two_step/gen/opt/step_width_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Digit_Example/opt_two_step/gen/opt/step_width_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Digit_Example/opt_two_step/gen/opt/step_width_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Fri 5 Nov 2021 16:18:40 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1) { double t443; double t1731; double t1653; double t1371; double t1868; double t2108; double t1679; double t1940; double t1998; double t1139; double t2205; double t2335; double t2346; double t2450; double t2075; double t2351; double t2354; double t969; double t2468; double t2475; double t2476; double t2495; double t2449; double t2477; double t2486; double t834; double t2499; double t2504; double t2509; double t2591; double t2488; double t2545; double t2559; double t570; double t2614; double t2636; double t2645; double t2652; double t2575; double t2648; double t2650; double t568; double t2653; double t2654; double t2659; double t2670; double t2651; double t2663; double t2664; double t567; double t2743; double t2750; double t2755; double t2763; double t447; double t2837; double t2859; double t2862; double t2863; double t2866; double t2857; double t2867; double t2868; double t2872; double t2873; double t2874; double t2869; double t2897; double t2902; double t2923; double t2948; double t2952; double t2917; double t2953; double t2965; double t2979; double t2982; double t2983; double t2977; double t2999; double t3000; double t3050; double t3059; double t3060; double t3014; double t3073; double t3100; double t3112; double t3120; double t3123; double t511; double t3110; double t3124; double t3131; double t3133; double t3135; double t3136; double t3231; double t3232; double t3233; double t3227; double t3234; double t3243; double t3250; double t3251; double t3261; double t3247; double t3262; double t3275; double t3308; double t3327; double t3333; double t3297; double t3337; double t3340; double t3353; double t3354; double t3357; double t3349; double t3358; double t3359; double t3361; double t3362; double t3365; double t3360; double t3371; double t3372; double t3390; double t3395; double t3404; double t3389; double t3424; double t3433; double t3452; double t3458; double t3460; double t3444; double t3461; double t3462; double t3465; double t3466; double t3467; double t3132; double t3138; double t3139; double t3144; double t3145; double t3146; double t2668; double t2756; double t2760; double t2761; double t2764; double t2767; double t2768; double t2771; double t2785; double t3141; double t3148; double t3175; double t3188; double t3219; double t3224; double t3464; double t3468; double t3469; double t3536; double t3543; double t3544; double t3545; double t3546; double t3547; double t3549; double t3552; double t3555; double t3638; double t3639; double t3640; double t3548; double t3559; double t3565; double t3225; double t3471; double t3474; double t3645; double t3647; double t3650; double t3478; double t3570; double t3593; double t3617; double t3627; double t3636; double t3661; double t3674; double t3675; double t3704; double t3708; double t3709; double t3716; double t3718; double t3719; double t3687; double t3688; double t3689; double t3691; double t3710; double t3720; double t3721; double t3724; double t3739; double t3742; double t3743; double t3744; double t3750; double t3751; double t501; double t3798; double t3805; double t3797; double t3809; double t3812; double t3819; double t3803; double t3806; double t3807; double t3839; double t3795; double t3871; double t3873; double t3874; double t3808; double t3851; double t3861; double t3876; double t3887; double t3869; double t3877; double t3879; double t3791; double t3888; double t3889; double t3892; double t3902; double t3882; double t3893; double t3894; double t3787; double t3903; double t3908; double t3912; double t3961; double t3898; double t3951; double t3959; double t3763; double t3962; double t3964; double t3965; double t3978; double t3960; double t3967; double t3973; double t3760; double t3979; double t3981; double t3982; double t3756; double t4150; double t4162; double t4163; double t4073; double t4091; double t4112; double t4177; double t4181; double t4182; double t4149; double t4165; double t4173; double t4176; double t4183; double t4211; double t4216; double t4218; double t4219; double t4215; double t4221; double t4222; double t4225; double t4228; double t4229; double t4224; double t4240; double t4245; double t4248; double t4251; double t4252; double t4029; double t4246; double t4253; double t4255; double t4267; double t4268; double t4269; double t4328; double t4350; double t4364; double t4319; double t4320; double t4321; double t4377; double t4378; double t4379; double t4323; double t4371; double t4372; double t4376; double t4384; double t4385; double t4388; double t4389; double t4402; double t4386; double t4426; double t4443; double t4452; double t4455; double t4456; double t4450; double t4457; double t4464; double t4469; double t4470; double t4471; double t4468; double t4473; double t4475; double t4477; double t4481; double t4482; t443 = Cos(var1[4]); t1731 = Cos(var1[21]); t1653 = Sin(var1[4]); t1371 = Sin(var1[21]); t1868 = Sin(var1[5]); t2108 = Cos(var1[22]); t1679 = t1371*t1653; t1940 = t1731*t443*t1868; t1998 = t1679 + t1940; t1139 = Sin(var1[22]); t2205 = -1.*t1731*t1653; t2335 = t443*t1371*t1868; t2346 = t2205 + t2335; t2450 = Cos(var1[23]); t2075 = t1139*t1998; t2351 = t2108*t2346; t2354 = t2075 + t2351; t969 = Sin(var1[23]); t2468 = t2108*t1998; t2475 = -1.*t1139*t2346; t2476 = t2468 + t2475; t2495 = Cos(var1[24]); t2449 = t969*t2354; t2477 = t2450*t2476; t2486 = t2449 + t2477; t834 = Sin(var1[24]); t2499 = t2450*t2354; t2504 = -1.*t969*t2476; t2509 = t2499 + t2504; t2591 = Cos(var1[25]); t2488 = t834*t2486; t2545 = t2495*t2509; t2559 = t2488 + t2545; t570 = Sin(var1[25]); t2614 = t2495*t2486; t2636 = -1.*t834*t2509; t2645 = t2614 + t2636; t2652 = Cos(var1[26]); t2575 = -1.*t570*t2559; t2648 = t2591*t2645; t2650 = t2575 + t2648; t568 = Sin(var1[26]); t2653 = t2591*t2559; t2654 = t570*t2645; t2659 = t2653 + t2654; t2670 = Cos(var1[30]); t2651 = t568*t2650; t2663 = t2652*t2659; t2664 = t2651 + t2663; t567 = Sin(var1[30]); t2743 = t2652*t2650; t2750 = -1.*t568*t2659; t2755 = t2743 + t2750; t2763 = Sin(var1[31]); t447 = Cos(var1[5]); t2837 = Sin(var1[3]); t2859 = Cos(var1[3]); t2862 = t2859*t447; t2863 = t2837*t1653*t1868; t2866 = t2862 + t2863; t2857 = -1.*t443*t1371*t2837; t2867 = t1731*t2866; t2868 = t2857 + t2867; t2872 = t1731*t443*t2837; t2873 = t1371*t2866; t2874 = t2872 + t2873; t2869 = t1139*t2868; t2897 = t2108*t2874; t2902 = t2869 + t2897; t2923 = t2108*t2868; t2948 = -1.*t1139*t2874; t2952 = t2923 + t2948; t2917 = t969*t2902; t2953 = t2450*t2952; t2965 = t2917 + t2953; t2979 = t2450*t2902; t2982 = -1.*t969*t2952; t2983 = t2979 + t2982; t2977 = t834*t2965; t2999 = t2495*t2983; t3000 = t2977 + t2999; t3050 = t2495*t2965; t3059 = -1.*t834*t2983; t3060 = t3050 + t3059; t3014 = -1.*t570*t3000; t3073 = t2591*t3060; t3100 = t3014 + t3073; t3112 = t2591*t3000; t3120 = t570*t3060; t3123 = t3112 + t3120; t511 = Cos(var1[31]); t3110 = t568*t3100; t3124 = t2652*t3123; t3131 = t3110 + t3124; t3133 = t2652*t3100; t3135 = -1.*t568*t3123; t3136 = t3133 + t3135; t3231 = -1.*t447*t2837; t3232 = t2859*t1653*t1868; t3233 = t3231 + t3232; t3227 = -1.*t2859*t443*t1371; t3234 = t1731*t3233; t3243 = t3227 + t3234; t3250 = t1731*t2859*t443; t3251 = t1371*t3233; t3261 = t3250 + t3251; t3247 = t1139*t3243; t3262 = t2108*t3261; t3275 = t3247 + t3262; t3308 = t2108*t3243; t3327 = -1.*t1139*t3261; t3333 = t3308 + t3327; t3297 = t969*t3275; t3337 = t2450*t3333; t3340 = t3297 + t3337; t3353 = t2450*t3275; t3354 = -1.*t969*t3333; t3357 = t3353 + t3354; t3349 = t834*t3340; t3358 = t2495*t3357; t3359 = t3349 + t3358; t3361 = t2495*t3340; t3362 = -1.*t834*t3357; t3365 = t3361 + t3362; t3360 = -1.*t570*t3359; t3371 = t2591*t3365; t3372 = t3360 + t3371; t3390 = t2591*t3359; t3395 = t570*t3365; t3404 = t3390 + t3395; t3389 = t568*t3372; t3424 = t2652*t3404; t3433 = t3389 + t3424; t3452 = t2652*t3372; t3458 = -1.*t568*t3404; t3460 = t3452 + t3458; t3444 = -1.*t567*t3433; t3461 = t2670*t3460; t3462 = t3444 + t3461; t3465 = t2670*t3433; t3466 = t567*t3460; t3467 = t3465 + t3466; t3132 = -1.*t567*t3131; t3138 = t2670*t3136; t3139 = t3132 + t3138; t3144 = t2670*t3131; t3145 = t567*t3136; t3146 = t3144 + t3145; t2668 = -1.*t567*t2664; t2756 = t2670*t2755; t2760 = t2668 + t2756; t2761 = t511*t2760; t2764 = t2670*t2664; t2767 = t567*t2755; t2768 = t2764 + t2767; t2771 = -1.*t2763*t2768; t2785 = t2761 + t2771; t3141 = -1.*t2763*t3139; t3148 = -1.*t511*t3146; t3175 = t3141 + t3148; t3188 = t2859*t447*t1653; t3219 = t2837*t1868; t3224 = t3188 + t3219; t3464 = t511*t3462; t3468 = -1.*t2763*t3467; t3469 = t3464 + t3468; t3536 = -1.*t2763*t3462; t3543 = -1.*t511*t3467; t3544 = t3536 + t3543; t3545 = t447*t2837*t1653; t3546 = -1.*t2859*t1868; t3547 = t3545 + t3546; t3549 = t511*t3139; t3552 = -1.*t2763*t3146; t3555 = t3549 + t3552; t3638 = -0.0315*t3224; t3639 = 0.05456*t3469; t3640 = var1[0] + t3638 + t3639; t3548 = 0.5*t3547; t3559 = -0.866025*t3555; t3565 = t3548 + t3559; t3225 = 0.5*t3224; t3471 = -0.866025*t3469; t3474 = t3225 + t3471; t3645 = -0.0315*t3547; t3647 = 0.05456*t3555; t3650 = var1[1] + t3645 + t3647; t3478 = -1.*t3175*t3474; t3570 = t3544*t3565; t3593 = t3478 + t3570; t3617 = 0.5*t443*t447; t3627 = -0.866025*t2785; t3636 = t3617 + t3627; t3661 = -1.*t2763*t2760; t3674 = -1.*t511*t2768; t3675 = t3661 + t3674; t3704 = 0.866025*t3224; t3708 = 0.5*t3469; t3709 = t3704 + t3708; t3716 = 0.866025*t3547; t3718 = 0.5*t3555; t3719 = t3716 + t3718; t3687 = 0.866025*t443*t447; t3688 = 0.5*t2785; t3689 = t3687 + t3688; t3691 = t3689*t3593; t3710 = t3175*t3709; t3720 = -1.*t3544*t3719; t3721 = t3710 + t3720; t3724 = t3636*t3721; t3739 = t3709*t3565; t3742 = -1.*t3474*t3719; t3743 = t3739 + t3742; t3744 = -1.*t3675*t3743; t3750 = 0. + t3691 + t3724 + t3744; t3751 = 1/t3750; t501 = -0.0315*t443*t447; t3798 = Cos(var1[6]); t3805 = Sin(var1[6]); t3797 = Cos(var1[7]); t3809 = -1.*t3798*t1653; t3812 = t443*t1868*t3805; t3819 = t3809 + t3812; t3803 = t443*t3798*t1868; t3806 = t1653*t3805; t3807 = t3803 + t3806; t3839 = Sin(var1[7]); t3795 = Cos(var1[8]); t3871 = t3797*t3819; t3873 = t3807*t3839; t3874 = t3871 + t3873; t3808 = t3797*t3807; t3851 = -1.*t3819*t3839; t3861 = t3808 + t3851; t3876 = Sin(var1[8]); t3887 = Cos(var1[9]); t3869 = t3795*t3861; t3877 = t3874*t3876; t3879 = t3869 + t3877; t3791 = Sin(var1[9]); t3888 = t3795*t3874; t3889 = -1.*t3861*t3876; t3892 = t3888 + t3889; t3902 = Cos(var1[10]); t3882 = t3791*t3879; t3893 = t3887*t3892; t3894 = t3882 + t3893; t3787 = Sin(var1[10]); t3903 = t3887*t3879; t3908 = -1.*t3791*t3892; t3912 = t3903 + t3908; t3961 = Cos(var1[11]); t3898 = -1.*t3787*t3894; t3951 = t3902*t3912; t3959 = t3898 + t3951; t3763 = Sin(var1[11]); t3962 = t3902*t3894; t3964 = t3787*t3912; t3965 = t3962 + t3964; t3978 = Cos(var1[15]); t3960 = t3763*t3959; t3967 = t3961*t3965; t3973 = t3960 + t3967; t3760 = Sin(var1[15]); t3979 = t3961*t3959; t3981 = -1.*t3763*t3965; t3982 = t3979 + t3981; t3756 = Cos(var1[16]); t4150 = t2859*t443*t3798; t4162 = t3233*t3805; t4163 = t4150 + t4162; t4073 = t3798*t3233; t4091 = -1.*t2859*t443*t3805; t4112 = t4073 + t4091; t4177 = t3797*t4163; t4181 = t4112*t3839; t4182 = t4177 + t4181; t4149 = t3797*t4112; t4165 = -1.*t4163*t3839; t4173 = t4149 + t4165; t4176 = t3795*t4173; t4183 = t4182*t3876; t4211 = t4176 + t4183; t4216 = t3795*t4182; t4218 = -1.*t4173*t3876; t4219 = t4216 + t4218; t4215 = t3791*t4211; t4221 = t3887*t4219; t4222 = t4215 + t4221; t4225 = t3887*t4211; t4228 = -1.*t3791*t4219; t4229 = t4225 + t4228; t4224 = -1.*t3787*t4222; t4240 = t3902*t4229; t4245 = t4224 + t4240; t4248 = t3902*t4222; t4251 = t3787*t4229; t4252 = t4248 + t4251; t4029 = Sin(var1[16]); t4246 = t3763*t4245; t4253 = t3961*t4252; t4255 = t4246 + t4253; t4267 = t3961*t4245; t4268 = -1.*t3763*t4252; t4269 = t4267 + t4268; t4328 = t443*t3798*t2837; t4350 = t2866*t3805; t4364 = t4328 + t4350; t4319 = t3798*t2866; t4320 = -1.*t443*t2837*t3805; t4321 = t4319 + t4320; t4377 = t3797*t4364; t4378 = t4321*t3839; t4379 = t4377 + t4378; t4323 = t3797*t4321; t4371 = -1.*t4364*t3839; t4372 = t4323 + t4371; t4376 = t3795*t4372; t4384 = t4379*t3876; t4385 = t4376 + t4384; t4388 = t3795*t4379; t4389 = -1.*t4372*t3876; t4402 = t4388 + t4389; t4386 = t3791*t4385; t4426 = t3887*t4402; t4443 = t4386 + t4426; t4452 = t3887*t4385; t4455 = -1.*t3791*t4402; t4456 = t4452 + t4455; t4450 = -1.*t3787*t4443; t4457 = t3902*t4456; t4464 = t4450 + t4457; t4469 = t3902*t4443; t4470 = t3787*t4456; t4471 = t4469 + t4470; t4468 = t3763*t4464; t4473 = t3961*t4471; t4475 = t4468 + t4473; t4477 = t3961*t4464; t4481 = -1.*t3763*t4471; t4482 = t4477 + t4481; p_output1[0]=(0. + t3175*t3636 - 1.*t3565*t3675)*t3751*(t3638 - 0.05456*(-1.*t4029*(t3978*t4255 + t3760*t4269) + t3756*(-1.*t3760*t4255 + t3978*t4269)) + var1[0]) + (0. - 1.*t3544*t3636 + t3474*t3675)*t3751*(t3645 - 0.05456*(-1.*t4029*(t3978*t4475 + t3760*t4482) + t3756*(-1.*t3760*t4475 + t3978*t4482)) + var1[1]) + (0. + t3478 + t3570)*t3751*(-0.05456*(t3756*(-1.*t3760*t3973 + t3978*t3982) - 1.*(t3973*t3978 + t3760*t3982)*t4029) + t501 + var1[2]) + t3751*(t3636*(-1.*t3175*t3640 + t3544*t3650) - 1.*(-1.*t3565*t3640 + t3474*t3650)*t3675 - 1.*t3593*(0.05456*t2785 + t501 + var1[2])); } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 36 && ncols == 1) && !(mrows == 1 && ncols == 36))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 1, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1); } #else // MATLAB_MEX_FILE #include "step_width_RightStance.hh" namespace RightStance { void step_width_RightStance_raw(double *p_output1, const double *var1) { // Call Subroutines output1(p_output1, var1); } } #endif // MATLAB_MEX_FILE
21.461538
588
0.645393
[ "vector" ]
9724010b408afce5ac3575e25deb83e56d6d7e97
2,271
cpp
C++
ParallelPcap/PythonExtensions/ParallelPcapExt.cpp
Isdriai/packet2vec
44c0b6719652bb412980fedcb885e6e0b51746ae
[ "BSD-2-Clause" ]
1
2021-05-21T11:29:32.000Z
2021-05-21T11:29:32.000Z
ParallelPcap/PythonExtensions/ParallelPcapExt.cpp
Isdriai/packet2vec
44c0b6719652bb412980fedcb885e6e0b51746ae
[ "BSD-2-Clause" ]
6
2020-11-13T19:04:49.000Z
2022-02-10T02:05:50.000Z
ParallelPcap/PythonExtensions/ParallelPcapExt.cpp
Isdriai/packet2vec
44c0b6719652bb412980fedcb885e6e0b51746ae
[ "BSD-2-Clause" ]
2
2021-04-01T15:41:09.000Z
2021-05-21T11:29:01.000Z
#include <boost/python.hpp> #include <boost/python/numpy.hpp> #include <ParallelPcap/Pcap.hpp> #include <ParallelPcap/Util.hpp> #include <ParallelPcap/CountDictionary.hpp> #include <ParallelPcap/Packet.hpp> #include <ParallelPcap/Packet2Vec.hpp> #include <ParallelPcap/PacketInfo.hpp> #include <ParallelPcap/DARPA2009.hpp> #include <ParallelPcap/ReadPcap.hpp> #include <ParallelPcap/TestPcap.hpp> #include <vector> BOOST_PYTHON_MODULE(parallelpcap) { using namespace parallel_pcap; using namespace boost::python; // Initialization Py_Initialize(); boost::python::numpy::initialize(); class_<Pcap>("Pcap", init<std::string>()) .def("getNumPackets", &Pcap::getNumPackets) .def("applyNgramOperator", &Pcap::applyNgramOperator) ; class_<std::vector<std::vector<std::string>>>("TwoDStringVector"); def("flatten", flatten<std::string>); def("setParallelPcapThreads", setGlobalNumThreads); class_<PacketHeader>("PacketHeader", init<uint32_t, uint32_t, uint32_t, uint32_t>()) .def("getTimestampSeconds", &PacketHeader::getTimestampSeconds) .def("getTimestampUseconds", &PacketHeader::getTimestampUseconds) .def("getIncludedLength", &PacketHeader::getIncludedLength) .def("getOriginalLength", &PacketHeader::getOriginalLength) ; /** * Adds the Packet2Vec class to our parallelpcap module * "return_value_policy" tells boost that our methods are returning pointers */ class_<Packet2Vec>("Packet2Vec", init<numpy::ndarray&, std::string, bool>()) .def(init<std::string, bool>()) .def("generateX", &Packet2Vec::generateX) .def("generateY", &Packet2Vec::generateY) .def("generateXTokens", &Packet2Vec::generateXTokens) .def("attacks", &Packet2Vec::attacks) ; class_<ReadPcap>("ReadPcap", init<std::string, list&, size_t, std::string, bool>()) .def(init<std::string, list&, size_t, std::string, std::string, std::string, bool>() ) ; class_<TestPcap>("TestPcap", init<std::string, numpy::ndarray&, list&, std::string, bool>()) .def("featureVector", &TestPcap::featureVector) .def("labelVector", &TestPcap::labelVector) ; }
30.28
78
0.671951
[ "vector" ]
97241209d1a875ea505badd028145a5e70a27599
3,006
cpp
C++
srtp/crypto/openssl/hmac.cpp
stelabouras/ZRTPCPP
6b3cd8e6783642292bad0c21e3e5e5ce45ff3e03
[ "Apache-2.0" ]
67
2015-01-02T18:22:18.000Z
2022-02-26T21:31:06.000Z
srtp/crypto/openssl/hmac.cpp
stelabouras/ZRTPCPP
6b3cd8e6783642292bad0c21e3e5e5ce45ff3e03
[ "Apache-2.0" ]
27
2015-01-11T10:33:36.000Z
2020-05-28T10:52:21.000Z
srtp/crypto/openssl/hmac.cpp
stelabouras/ZRTPCPP
6b3cd8e6783642292bad0c21e3e5e5ce45ff3e03
[ "Apache-2.0" ]
44
2015-02-27T07:21:53.000Z
2022-01-04T03:05:08.000Z
/* * Copyright 2006 - 2018, Werner Dittmann * * 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. */ /* * Authors: Werner Dittmann */ #include <cstdint> #include <openssl/hmac.h> #include <srtp/crypto/hmac.h> #include <vector> void hmac_sha1(const uint8_t* key, int64_t keyLength, const uint8_t* data, uint64_t dataLength, uint8_t* mac, int32_t* macLength) { HMAC(EVP_sha1(), key, static_cast<int>(keyLength), data, dataLength, mac, reinterpret_cast<uint32_t*>(macLength)); } void hmac_sha1(const uint8_t* key, uint64_t keyLength, const std::vector<const uint8_t*>& data, const std::vector<uint64_t>& dataLength, uint8_t* mac, int32_t* macLength) { HMAC_CTX ctx = {}; HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, key, static_cast<int>(keyLength), EVP_sha1(), NULL); for (size_t i = 0, size = data.size(); i < size; i++) { HMAC_Update(&ctx, data[i], dataLength[i]); } HMAC_Final(&ctx, mac, reinterpret_cast<uint32_t*>(macLength)); HMAC_CTX_cleanup(&ctx); } void* createSha1HmacContext(const uint8_t* key, uint64_t keyLength) { auto* ctx = (HMAC_CTX*)malloc(sizeof(HMAC_CTX)); HMAC_CTX_init(ctx); HMAC_Init_ex(ctx, key, static_cast<int>(keyLength), EVP_sha1(), nullptr); return ctx; } void* initializeSha1HmacContext(void* ctx, uint8_t* key, uint64_t keyLength) { auto *pctx = (HMAC_CTX*)ctx; HMAC_CTX_init(pctx); HMAC_Init_ex(pctx, key, static_cast<int>(keyLength), EVP_sha1(), nullptr); return pctx; } void hmacSha1Ctx(void* ctx, const uint8_t* data, uint64_t data_length, uint8_t* mac, int32_t* mac_length) { auto* pctx = (HMAC_CTX*)ctx; HMAC_Init_ex(pctx, nullptr, 0, nullptr, nullptr); HMAC_Update(pctx, data, data_length ); HMAC_Final(pctx, mac, reinterpret_cast<uint32_t*>(mac_length) ); } void hmacSha1Ctx(void* ctx, const std::vector<const uint8_t*>& data, const std::vector<uint64_t>& dataLength, uint8_t* mac, uint32_t* macLength) { auto* pctx = (HMAC_CTX*)ctx; HMAC_Init_ex(pctx, nullptr, 0, nullptr, nullptr); for (size_t i = 0, size = data.size(); i < size; i++) { HMAC_Update(pctx, data[i], dataLength[i]); } HMAC_Final(pctx, mac, reinterpret_cast<uint32_t*>(macLength) ); } void freeSha1HmacContext(void* ctx) { if (ctx) { HMAC_CTX_cleanup((HMAC_CTX*)ctx); free(ctx); } }
30.989691
78
0.657352
[ "vector" ]
9725f42952c7b141f7a8f3d59021a322ae8550fb
2,429
cpp
C++
boboleetcode/Play-Leetcode-master/0220-Contains-Duplicate-III/cpp-0220/main2.cpp
yaominzh/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2021-03-25T05:26:55.000Z
2021-04-20T03:33:24.000Z
boboleetcode/Play-Leetcode-master/0220-Contains-Duplicate-III/cpp-0220/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0220-Contains-Duplicate-III/cpp-0220/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/contains-duplicate-iii/description/ /// Author : liuyubobobo /// Time : 2017-11-15 #include <iostream> #include <vector> #include <unordered_map> using namespace std; // Based on Buckets // each time, all we need to check is the bucket that x belongs to and its two adjacent buckets // // One thing worth mentioning is the difference from bucket sort – // Each of our buckets contains at most one element at any time, // because two elements in a bucket means "almost duplicate" and we can return early from the function. // Therefore, a HashMap with an element associated with a bucket label is enough for our purpose. // // Time Complexity: O(n) // Space Complexity: O(k) class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if(t < 0) return false; unordered_map<long long, long long> buckets; long long w = (long long)t + (long long)1; for(int i = 0 ; i < nums.size() ; i ++){ long long num = (long long)nums[i]; long long id = getID(num, w); // check if bucket id is empty, each bucket may contain at most one element if(buckets.find(id) != buckets.end()) return true; // check the neighbor buckets for almost duplicate if(buckets.find(id - 1) != buckets.end() && buckets[id - 1] >= num - (long long)t) return true; if(buckets.find(id + 1) != buckets.end() && buckets[id + 1] <= num + (long long)t) return true; // now bucket id is empty and no almost duplicate in neighbor buckets buckets[id] = num; if(buckets.size() == k + 1) buckets.erase(getID((long long)nums[i-k], w)); } return false; } private: // Get the ID of the bucket from element value x and bucket width w // Since `-3 / 5 = 0` and but we need `-3 / 5 = -1`. long long getID(long long x, long long w){ return x < 0 ? (x + 1) / w - 1 : x / w; } }; void printBool(bool b){ cout << (b ? "True" : "False") << endl; } int main() { int nums[] = {-2147483648, -2147483647}; vector<int> vec(nums, nums + sizeof(nums)/sizeof(int)); int k = 3; int t = 3; printBool(Solution().containsNearbyAlmostDuplicate(vec, k, t)); return 0; }
29.987654
103
0.586249
[ "vector" ]
9726b1b455a0fcef17b4249c6595ff2cf1583e5b
855
cpp
C++
CodeChef/Practice Solutions/Beginner/Forgotten Language/Sol_by_Pandz18.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
8
2021-02-14T13:13:27.000Z
2022-01-08T23:58:32.000Z
CodeChef/Practice Solutions/Beginner/Forgotten Language/Sol_by_Pandz18.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
CodeChef/Practice Solutions/Beginner/Forgotten Language/Sol_by_Pandz18.cpp
shouryagupta21/Fork_CPP
8f5baed045ef430cca19d871c8854abc3b6ad44f
[ "MIT" ]
15
2021-03-01T03:54:29.000Z
2021-10-19T18:29:00.000Z
#include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef long int l; #define loop(n1) for(ll i=0;i<n1;i++) #define pb push_back #define ppb pop_back #define pb push_back #define mp make_pair #define debug(n) cout<<n<<endl #define mod 1000000007 #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) int main() { int t; cin>>t; while(t--) { int n,k,i,x; cin>>n>>k; string s; vector<string> flang,mlang; loop(n) { cin>>s; flang.push_back(s); } loop(k) { cin>>x; loop(x) { cin>>s; mlang.push_back(s); } } sort(mlang.begin(),mlang.end()); for(auto word:flang) { int flag=0; for(auto mw:mlang) { if(word==mw) {cout<<"YES"<<" ";flag=1;break;} } if(flag==0) cout<<"NO"<<" "; } cout<<endl; } return 0; }
13.571429
62
0.563743
[ "vector" ]
9730209fd8ef50b24016e44c9e38c94c4e22e5a6
5,910
cc
C++
include/parquet/column/column-io-benchmark.cc
djc80s/c-cpp_study
3ea8289c358a2b732524ab391aa87c4a8fc0b6a7
[ "BSD-2-Clause" ]
null
null
null
include/parquet/column/column-io-benchmark.cc
djc80s/c-cpp_study
3ea8289c358a2b732524ab391aa87c4a8fc0b6a7
[ "BSD-2-Clause" ]
null
null
null
include/parquet/column/column-io-benchmark.cc
djc80s/c-cpp_study
3ea8289c358a2b732524ab391aa87c4a8fc0b6a7
[ "BSD-2-Clause" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "benchmark/benchmark.h" #include "parquet/column/reader.h" #include "parquet/column/writer.h" #include "parquet/file/reader-internal.h" #include "parquet/file/writer-internal.h" #include "parquet/util/memory.h" namespace parquet { using schema::PrimitiveNode; namespace benchmark { std::unique_ptr<Int64Writer> BuildWriter(int64_t output_size, OutputStream* dst, ColumnChunkMetaDataBuilder* metadata, ColumnDescriptor* schema, const WriterProperties* properties) { std::unique_ptr<SerializedPageWriter> pager( new SerializedPageWriter(dst, Compression::UNCOMPRESSED, metadata)); return std::unique_ptr<Int64Writer>(new Int64Writer( metadata, std::move(pager), output_size, Encoding::PLAIN, properties)); } std::shared_ptr<ColumnDescriptor> Int64Schema(Repetition::type repetition) { auto node = PrimitiveNode::Make("int64", repetition, Type::INT64); return std::make_shared<ColumnDescriptor>( node, repetition != Repetition::REQUIRED, repetition == Repetition::REPEATED); } void SetBytesProcessed(::benchmark::State& state, Repetition::type repetition) { int64_t bytes_processed = state.iterations() * state.range_x() * sizeof(int64_t); if (repetition != Repetition::REQUIRED) { bytes_processed += state.iterations() * state.range_x() * sizeof(int16_t); } if (repetition == Repetition::REPEATED) { bytes_processed += state.iterations() * state.range_x() * sizeof(int16_t); } state.SetBytesProcessed(state.iterations() * state.range_x() * sizeof(int16_t)); } template <Repetition::type repetition> static void BM_WriteInt64Column(::benchmark::State& state) { format::ColumnChunk thrift_metadata; std::vector<int64_t> values(state.range_x(), 128); std::vector<int16_t> definition_levels(state.range_x(), 1); std::vector<int16_t> repetition_levels(state.range_x(), 0); std::shared_ptr<ColumnDescriptor> schema = Int64Schema(repetition); std::shared_ptr<WriterProperties> properties = default_writer_properties(); auto metadata = ColumnChunkMetaDataBuilder::Make( properties, schema.get(), reinterpret_cast<uint8_t*>(&thrift_metadata)); while (state.KeepRunning()) { InMemoryOutputStream stream; std::unique_ptr<Int64Writer> writer = BuildWriter( state.range_x(), &stream, metadata.get(), schema.get(), properties.get()); writer->WriteBatch( values.size(), definition_levels.data(), repetition_levels.data(), values.data()); writer->Close(); } SetBytesProcessed(state, repetition); } BENCHMARK_TEMPLATE(BM_WriteInt64Column, Repetition::REQUIRED)->Range(1024, 65536); BENCHMARK_TEMPLATE(BM_WriteInt64Column, Repetition::OPTIONAL)->Range(1024, 65536); BENCHMARK_TEMPLATE(BM_WriteInt64Column, Repetition::REPEATED)->Range(1024, 65536); std::unique_ptr<Int64Reader> BuildReader( std::shared_ptr<Buffer>& buffer, int64_t num_values, ColumnDescriptor* schema) { std::unique_ptr<InMemoryInputStream> source(new InMemoryInputStream(buffer)); std::unique_ptr<SerializedPageReader> page_reader( new SerializedPageReader(std::move(source), num_values, Compression::UNCOMPRESSED)); return std::unique_ptr<Int64Reader>(new Int64Reader(schema, std::move(page_reader))); } template <Repetition::type repetition> static void BM_ReadInt64Column(::benchmark::State& state) { format::ColumnChunk thrift_metadata; std::vector<int64_t> values(state.range_x(), 128); std::vector<int16_t> definition_levels(state.range_x(), 1); std::vector<int16_t> repetition_levels(state.range_x(), 0); std::shared_ptr<ColumnDescriptor> schema = Int64Schema(repetition); std::shared_ptr<WriterProperties> properties = default_writer_properties(); auto metadata = ColumnChunkMetaDataBuilder::Make( properties, schema.get(), reinterpret_cast<uint8_t*>(&thrift_metadata)); InMemoryOutputStream stream; std::unique_ptr<Int64Writer> writer = BuildWriter( state.range_x(), &stream, metadata.get(), schema.get(), properties.get()); writer->WriteBatch( values.size(), definition_levels.data(), repetition_levels.data(), values.data()); writer->Close(); std::shared_ptr<Buffer> src = stream.GetBuffer(); std::vector<int64_t> values_out(state.range_y()); std::vector<int16_t> definition_levels_out(state.range_y()); std::vector<int16_t> repetition_levels_out(state.range_y()); while (state.KeepRunning()) { std::unique_ptr<Int64Reader> reader = BuildReader(src, state.range_y(), schema.get()); int64_t values_read = 0; for (size_t i = 0; i < values.size(); i += values_read) { reader->ReadBatch(values_out.size(), definition_levels_out.data(), repetition_levels_out.data(), values_out.data(), &values_read); } } SetBytesProcessed(state, repetition); } BENCHMARK_TEMPLATE(BM_ReadInt64Column, Repetition::REQUIRED) ->RangePair(1024, 65536, 1, 1024); BENCHMARK_TEMPLATE(BM_ReadInt64Column, Repetition::OPTIONAL) ->RangePair(1024, 65536, 1, 1024); BENCHMARK_TEMPLATE(BM_ReadInt64Column, Repetition::REPEATED) ->RangePair(1024, 65536, 1, 1024); } // namespace benchmark } // namespace parquet
39.66443
90
0.745008
[ "vector" ]
97374120e2f749d27b59c6ec9123495f96765a49
13,273
cpp
C++
2021/algorithm-design-assignment/assignment-2/base.cpp
KivalEvan/CPU-Scheduling-Simulation
f80d080aab94db053a70a1115ebd4cd97c41d65b
[ "MIT" ]
null
null
null
2021/algorithm-design-assignment/assignment-2/base.cpp
KivalEvan/CPU-Scheduling-Simulation
f80d080aab94db053a70a1115ebd4cd97c41d65b
[ "MIT" ]
null
null
null
2021/algorithm-design-assignment/assignment-2/base.cpp
KivalEvan/CPU-Scheduling-Simulation
f80d080aab94db053a70a1115ebd4cd97c41d65b
[ "MIT" ]
null
null
null
#include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <vector> using namespace std; class Planet { public: string p_name; int x, y, z; int weight, profit; Planet() { this->p_name = ""; this->x = 0; this->y = 0; this->z = 0; this->weight = 0; this->profit = 0; } Planet(const Planet& p) { this->p_name = p.p_name; this->x = p.x; this->y = p.y; this->z = p.z; this->weight = p.weight; this->profit = p.profit; } double calcValue() const { return this->weight > 0 ? static_cast<double>(this->profit) / static_cast<double>(this->weight) : 0; } }; class Edge { public: string point_a, point_b; double distance; }; double calcDistancePlanet(const Planet a, const Planet b) { return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2) + pow(a.z - b.z, 2)); } // for now it go bidirectional void connectVertex(double** am, vector<pair<int, double>> al[], Planet* p, const int x, const int y) { double dist = calcDistancePlanet(p[x], p[y]); al[x].push_back(make_pair(y, dist)); al[y].push_back(make_pair(x, dist)); am[x][y] = dist; am[y][x] = dist; } int countEdge(vector<pair<int, double>> al[], const int V) { int total = 0; for (int i = 0; i < V; i++) { total += al[i].size(); } return total / 2; } void getEdgeList(const Planet* p, double** const am, Edge* ed, const int V, const int E) { int count = 0; for (int i = 0; i < V; i++) { for (int j = i; j < V; j++) { if (am[i][j] != 0 && count < E) { ed[count].point_a = p[i].p_name; ed[count].point_b = p[j].p_name; ed[count].distance = am[i][j]; count++; } } } } template <typename T> void swap(T* a, T* b) { T t = *a; *a = *b; *b = t; } // template <typename T> // int partition(T* arr, int low, int high) { // T pivot = arr[high]; // pivot // int i = (low - 1); // Index of smaller element // for (int j = low; j <= high - 1; j++) { // // If current element is smaller than or // // equal to pivot // if (arr[j] <= pivot) { // i++; // increment index of smaller element // swap(&arr[i], &arr[j]); // } // } // swap(&arr[i + 1], &arr[high]); // return (i + 1); // } // template <typename T> // void quickSort(T* arr, int low, int high) { // if (low < high) { // // pi is partitioning index, arr[p] is now // // at right place // int pi = partition(arr, low, high); // // Separately sort elements before // // partition and after partition // quickSort(arr, low, pi - 1); // quickSort(arr, pi + 1, high); // } // } int partitionEdge(Edge* ed, const int low, const int high) { double pivot = ed[high].distance; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (ed[j].distance <= pivot) { i++; swap(&ed[i], &ed[j]); } } swap(&ed[i + 1], &ed[high]); return (i + 1); } void quickSortEdge(Edge* ed, const int low, const int high) { if (low < high) { int pi = partitionEdge(ed, low, high); quickSortEdge(ed, low, pi - 1); quickSortEdge(ed, pi + 1, high); } } int partitionPlanet(Planet* p, const int low, const int high) { double pivot = p[high].calcValue(); int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (p[j].calcValue() <= pivot) { i++; swap(&p[i], &p[j]); } } swap(&p[i + 1], &p[high]); return (i + 1); } void quickSortPlanet(Planet* p, const int low, const int high) { if (low < high) { int pi = partitionPlanet(p, low, high); quickSortPlanet(p, low, pi - 1); quickSortPlanet(p, pi + 1, high); } } // since array is sorted, we can just reverse them to get either descending or ascending order template <typename T> void reverseArray(T* arr, int start, int end) { while (start < end) { T temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } int** OIKnapsackAlgorithm(const Planet* p, const int V, const int W) { // new set + empty set of planet Planet* p_set = new Planet[V + 1]; for (int i = 0; i < V; i++) { p_set[i + 1] = p[i]; } // matrix[item + 1][weight + 1] int** matrix; matrix = new int*[V + 1]; for (int i = 0; i < V + 1; i++) { matrix[i] = new int[W + 1]; for (int w = 0; w < W + 1; w++) { matrix[i][w] = 0; } } // do algo and fill matrix for (int i = 0; i < V + 1; i++) { for (int w = 0; w < W + 1; w++) { if (p_set[i].weight <= w) { matrix[i][w] = i - 1 >= 0 ? max(p_set[i].profit + matrix[i - 1][w - p_set[i].weight], matrix[i - 1][w]) : 0; } else { matrix[i][w] = i - 1 >= 0 ? matrix[i - 1][w] : 0; } } } return matrix; } int* OIKnapsackGetSet(const Planet* p, int** const matrix, const int V, const int W) { int* set = new int[V]; int i = V; int j = W; while (i > 0 && j > 0) { if (matrix[i][j] == (i - 1 > 0 ? matrix[i - 1][j] : 0)) { set[i - 1] = 0; i--; } else { set[i - 1] = 1; i--; j = j - p[i].weight; } } return set; } void OIKnapsackResult(const Planet* p, const int* set, const int V) { string order = ""; int profit = 0; int weight = 0; cout << "0/1 Knapsack Result: " << endl; for (int i = 0; i < V; i++) { if (set[i] == 1) { if (order != "") { order += " -> "; } cout << p[i].p_name << endl; cout << "Profit: " << p[i].profit << '$' << endl; cout << "Weight: " << p[i].weight << " ton(s)" << endl; cout << "Value: " << p[i].calcValue() << endl; cout << endl; order += p[i].p_name; profit += p[i].profit; weight += p[i].weight; } } cout << "Planet to visit: " << order << endl; cout << "Total Profit: " << profit << endl; cout << "Total Weight: " << weight << endl; } void printList(const Planet* p, vector<pair<int, double>> al[], const int V) { int v; double w; for (int i = 0; i < V; i++) { cout << p[i].p_name; for (auto it = al[i].begin(); it != al[i].end(); it++) { v = it->first; w = it->second; cout << " -> " << p[v].p_name << " | " << static_cast<int>(w); } cout << endl; } } template <typename T> void printMatrix(const Planet* p, T** const am, const int V) { cout << " "; for (int i = 0; i < V; i++) { cout << setw(10) << p[i].p_name; } cout << endl; for (int i = 0; i < V; i++) { cout << p[i].p_name; for (int j = 0; j < V; j++) { cout << setw(10) << static_cast<int>(am[i][j]); } cout << endl; } } template <typename T> void printOIKnapsackMatrix(const Planet* p, T** const am, const int V, const int W) { cout << "0/1 Knapsack Table:" << endl; cout << " "; for (int i = 0; i < V; i++) { cout << setw(10) << p[i].p_name; } cout << endl << " "; for (int i = 0; i < V + 1; i++) { cout << setw(10) << i; } cout << endl; for (int i = 0; i < W + 1; i++) { cout << setw(2) << i; for (int j = 0; j < V + 1; j++) { cout << setw(10) << static_cast<int>(am[j][i]); } cout << endl; } } void printGraph(const Planet* p, vector<pair<int, double>> al[], double** const am, const int V) { cout << "Adjacency List:" << endl; printList(p, al, V); cout << endl; cout << "Adjacency Matrix:" << endl; printMatrix(p, am, V); } template <typename T> void printArray(const T* arr, int count) { for (int i = 0; i < count; i++) { cout << arr[i] << ' '; } cout << endl; } void printPlanetEdge(const Edge* ed, const int E) { for (int i = 0; i < E; i++) { cout << ed[i].point_a << " -- " << ed[i].point_b << " distance: " << static_cast<int>(ed[i].distance) << endl; } } void printPlanetValue(const Planet* p, const int V) { for (int i = 0; i < V; i++) { cout << p[i].p_name << " value: " << p[i].calcValue() << endl; } } void printKnapsackTable(const Planet* p, const int V) { cout << "Knapsack Table:"; cout << endl << setw(10) << "Planet"; for (int i = 0; i < V; i++) { cout << setw(10) << p[i].p_name; } cout << endl << setw(10) << "Profit"; for (int i = 0; i < V; i++) { cout << setw(10) << p[i].profit; } cout << endl << setw(10) << "Weigth"; for (int i = 0; i < V; i++) { cout << setw(10) << p[i].weight; } cout << endl << setw(10) << "Value"; for (int i = 0; i < V; i++) { cout << setw(10) << p[i].calcValue(); } cout << endl; } int main() { const int P_COUNT = 10; Planet* p = new Planet[P_COUNT]; /* Planet Reference 0 - A 1 - B 2 - C 3 - D 4 - E 5 - F 6 - G 7 - H 8 - I 9 - J */ ifstream file_planet("A2planets.txt"); if (file_planet.is_open()) { for (int i = 0; i < P_COUNT; i++) { file_planet >> p[i].p_name >> p[i].x >> p[i].y >> p[i].z >> p[i].weight >> p[i].profit; } } file_planet.close(); // ADJACENCY LIST // pair<planet_id, distance> vector<pair<int, double>> adj_list[P_COUNT]; // ADJACENCY MATRIX // ah yes, pointer to pointer double** adj_matrix; adj_matrix = new double*[P_COUNT]; for (int i = 0; i < P_COUNT; i++) { adj_matrix[i] = new double[P_COUNT]; for (int j = 0; j < P_COUNT; j++) { adj_matrix[i][j] = 0; } } // connect the planet the game // for now it connects both way connectVertex(adj_matrix, adj_list, p, 0, 3); connectVertex(adj_matrix, adj_list, p, 0, 5); connectVertex(adj_matrix, adj_list, p, 0, 7); connectVertex(adj_matrix, adj_list, p, 0, 9); connectVertex(adj_matrix, adj_list, p, 1, 3); connectVertex(adj_matrix, adj_list, p, 1, 4); connectVertex(adj_matrix, adj_list, p, 1, 6); connectVertex(adj_matrix, adj_list, p, 2, 4); connectVertex(adj_matrix, adj_list, p, 2, 5); connectVertex(adj_matrix, adj_list, p, 2, 8); connectVertex(adj_matrix, adj_list, p, 3, 9); connectVertex(adj_matrix, adj_list, p, 4, 6); connectVertex(adj_matrix, adj_list, p, 4, 8); connectVertex(adj_matrix, adj_list, p, 5, 7); connectVertex(adj_matrix, adj_list, p, 6, 8); connectVertex(adj_matrix, adj_list, p, 6, 9); connectVertex(adj_matrix, adj_list, p, 7, 8); connectVertex(adj_matrix, adj_list, p, 7, 9); // PRINT BOTH ADJACENCY MATRIX AND ADJANCENCY LIST // print some info for verification printGraph(p, adj_list, adj_matrix, P_COUNT); // SORT EDGE DISTANCE BY ASCENDING ORDER // get edge list const int E_COUNT = countEdge(adj_list, P_COUNT); Edge* planet_edge = new Edge[E_COUNT]; getEdgeList(p, adj_matrix, planet_edge, P_COUNT, E_COUNT); // cout << endl // << "Original Edge:" << endl; // printPlanetEdge(planet_edge, E_COUNT); quickSortEdge(planet_edge, 0, E_COUNT - 1); cout << endl << "Sorted edge distance in ascending order:" << endl; printPlanetEdge(planet_edge, E_COUNT); // SORT PLANET VALUE BY DESCENDING ORDER // copy planet to sort for value Planet* planet_value = new Planet[P_COUNT]; for (int i = 0; i < P_COUNT; i++) { planet_value[i] = p[i]; } // cout << endl // << "Original Value:" << endl; // printPlanetValue(planet_value, P_COUNT); quickSortPlanet(planet_value, 0, P_COUNT - 1); // cout << endl // << "Sorted Value:" << endl; // printPlanetValue(planet_value, P_COUNT); reverseArray(planet_value, 0, P_COUNT - 1); cout << endl << "Sorted planet Value in descending order:" << endl; printPlanetValue(planet_value, P_COUNT); // PROGRAM 4 - DYNAMIC PROGRAMMING // 1/0 Knapsack Algorithm // use either 'p' or 'planet_value' // 'planet_value' as it is sorted by value // would use shortest path to find planet visting order but i dont have them at the time of writing this code const int MAX_WEIGHT = 80; cout << endl; printKnapsackTable(p, P_COUNT); int** knapsackMatrix = OIKnapsackAlgorithm(p, P_COUNT, MAX_WEIGHT); int* knapsackSet = OIKnapsackGetSet(p, knapsackMatrix, P_COUNT, MAX_WEIGHT); cout << endl; printOIKnapsackMatrix(p, knapsackMatrix, P_COUNT, MAX_WEIGHT); cout << endl; // printArray(knapsackSet, P_COUNT); OIKnapsackResult(p, knapsackSet, P_COUNT); cout << endl << "Enter anything to exit..."; cin.get(); return 0; }
28.917211
124
0.508174
[ "vector" ]
973d224143b20f668401b12f9d00552b8c946e62
704
cpp
C++
src/test/test_math.cpp
TheBeardedOn3/useful_functions
3b67db22859f4162f27d2720237f1e5c91f80669
[ "BSD-3-Clause" ]
null
null
null
src/test/test_math.cpp
TheBeardedOn3/useful_functions
3b67db22859f4162f27d2720237f1e5c91f80669
[ "BSD-3-Clause" ]
null
null
null
src/test/test_math.cpp
TheBeardedOn3/useful_functions
3b67db22859f4162f27d2720237f1e5c91f80669
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> #include "include/UsefulTemplates.hpp" // template <typename T> // bool Useful::contains_element(const std::vector<T>& _vec, T _element) // { // return std::find(_vec.begin(), _vec.end(), _element) != _vec.end(); // } int main(int argc, char** argv) { // Wrap ATAN ----------------------------------------- { std::cout << "Contains Element" << std::endl; std::vector<int> nums{1,2,3}; std::cout << UsefulTemplates::contains_element<int>(nums, 1) << std::endl; std::cout << UsefulTemplates::contains_element<int>(nums, 4) << std::endl; std::cout << std::endl; } // Recast Vector ----------------------------------------- }
28.16
78
0.546875
[ "vector" ]
974290392e2cc70d04b38ba5538ed64b2eba366b
334
cpp
C++
Libs/Globals.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
Libs/Globals.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
Libs/Globals.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
#include "Globals.h" vector<nTMap> maps; nTMap usrMap; Mechanics *world=new Mechanics(); Player *player; nTColor clearColor; vector<vector<string> >playerAnim; vector<vector<int> >playerAnimSize; vector<vector<string> >enemyAnim; vector<vector<int> >enemyAnimSize; AL *al; Tutorials *zero=new Tutorials("",0); int languageIdx=0;
17.578947
36
0.757485
[ "vector" ]
97454f21ed1d7e47e6abe605e5aa55dcc842db5d
1,163
hh
C++
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommLaserTrackingDataData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
null
null
null
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommLaserTrackingDataData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommLaserTrackingDataData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef COMMTRACKINGOBJECTS_COMMLASERTRACKINGDATA_DATA_H_ #define COMMTRACKINGOBJECTS_COMMLASERTRACKINGDATA_DATA_H_ #include "CommTrackingObjects/CommLaserTrackedObjectData.hh" #include "CommBasicObjects/CommMobileLaserScanData.hh" #include <vector> namespace CommTrackingObjectsIDL { typedef std::vector<CommTrackingObjectsIDL::CommLaserTrackedObject> CommLaserTrackingData_objects_type; struct CommLaserTrackingData { CommBasicObjectsIDL::CommMobileLaserScan scan; CommLaserTrackingData_objects_type objects; }; }; #endif /* COMMTRACKINGOBJECTS_COMMLASERTRACKINGDATA_DATA_H_ */
33.228571
104
0.708512
[ "vector" ]
97469ac4cf816b37cb593ced3cc8ac781071c343
2,694
hpp
C++
gdfast/src/vector.hpp
maartenbreddels/mab
112dcfbc4a74b07aff13d489b3776bca58fe9bdf
[ "MIT" ]
1
2018-12-01T04:10:34.000Z
2018-12-01T04:10:34.000Z
gdfast/src/vector.hpp
maartenbreddels/mab
112dcfbc4a74b07aff13d489b3776bca58fe9bdf
[ "MIT" ]
null
null
null
gdfast/src/vector.hpp
maartenbreddels/mab
112dcfbc4a74b07aff13d489b3776bca58fe9bdf
[ "MIT" ]
null
null
null
#include "cpptools.hpp" #include <cmath> #include <stdio.h> #include <tuple> double mysum() { return 0; } template<typename Head, typename ...Tail> double mysum(Head head, Tail... tail) { return head + mysum(tail...); } template<int N> struct lagrange_basis { //typedef monomial<N-1> subtype; typedef typename genseq<N-1>::type seq; enum { size = N }; template<typename... Tail> //double operator()(double x, double a, Tail... tail) { double operator()(double x, Tail... tail) { //int N = sizeof...(Tail); //return a * lj<sizeof...(Tail), N>(x) + this->operator()(x, tail...); //dot(a, tail..., std::tuple<Tail...> t(tail...); return test(x, t, typename genseq<N-1>::type()); //return 0; } template<int I> double unit_vector(double x) { //int N = sizeof...(Tail); //return a * lj<sizeof...(Tail), N>(x) + this->operator()(x, tail...); //dot(a, tail..., //std::tuple<Tail...> t(tail...); return I; //return lj<I, N>(x); //return 0; } template<typename T, int ...S> double test(double x, T t, ::seq<S...>) { return mysum(std::get<S>(t) * lj<S, N>(x)...); return 0; } double operator()(double x) { return 0; } template<int J, int K> double lj(double x) { printf("x = %.2f J=%d K=%d\n", x, J, K); typename genseq<K-1>::type s; return ljm<J, K>(x, s); } template<int J, int K, int M, int ...S> double ljm(double x, ::seq<M, S...> s) { //typename genseq<M-1>::type snext; double xm = (1.*M)/(K-1.); double xj = (1.*J)/(K-1.); ::seq<S...> snext; if(J == M) { return ljm<J,K>(x, snext); } else { double y = (x-xm) / (xj-xm); //int j = J; //int k = K; //int m = M; printf("x = %.2f J=%d K=%d M=%d xm=%.2f xj=%.2f y=%.2f\n", x, J, K, M, xm, xj, y); return y * ljm<J,K>(x, snext); } } template<int J, int K> double ljm(double x, ::seq<> s) { return 1; } }; template<int N> struct monomial_basis { //typedef monomial<N-1> subtype; typedef typename genseq<N-1>::type seq; enum { size = N }; template<typename... Tail> double operator()(double x, double a, Tail... tail) { int N = sizeof...(Tail); return a * pow(x, N) + this->operator()(x, tail...); } double operator()(double x) { return 0; } }; template<typename B> struct vector { typedef B basis; double a[B::size]; template<typename... Args> vector(Args... args) : a{args...} { } double operator()(double x) { typename basis::seq s; return call(x, s); } template<int ...S> double call(double x, seq<S...>) { basis b; //double t = b.template unit_vector<1>(0.3); //return b(x, this->x[S]...); return mysum((a[S] * (b.template unit_vector<S>(x)))...); //return mysum(a[S]...); } void print() { } };
22.830508
85
0.567929
[ "vector" ]
974d855bc84842fffbcb9357d64ea311fff02953
221,378
cpp
C++
Satellite/libraries/ADXL345/ADXL345.cpp
AldaCL/CanSat
abe4004afdee61b4d3f7e0ac3b7618ecc042d772
[ "MIT" ]
4
2020-01-23T17:30:35.000Z
2022-03-03T23:14:40.000Z
Satellite/libraries/ADXL345/ADXL345.cpp
AldaCL/CanSat
abe4004afdee61b4d3f7e0ac3b7618ecc042d772
[ "MIT" ]
1
2020-06-14T20:47:19.000Z
2020-06-15T16:03:40.000Z
Satellite/libraries/ADXL345/ADXL345.cpp
AldaCL/CanSat
abe4004afdee61b4d3f7e0ac3b7618ecc042d772
[ "MIT" ]
2
2020-01-23T17:30:41.000Z
2020-06-14T19:57:16.000Z
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars2.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars3.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link crossorigin="anonymous" media="all" integrity="sha512-dxFVfmRlzgntw9xnKsYVxQUyV8JZifjI76hlssNAlbCn/gOmgfo4skfRATXTzQ8qG+NNgIh6fvkeQttpFQRpQQ==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-7711557e6465ce09edc3dc672ac615c5.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-Xmr5ClGKswOccXdyL0RCm5oWrxTpJKvZtsPy+7nl5MR/F81Hr5msZN5tygUK1lzL60fJZlXxsuD9/T6rsaphPg==" rel="stylesheet" href="https://github.githubassets.com/assets/github-5e6af90a518ab3039c7177722f44429b.css" /> <meta name="viewport" content="width=device-width"> <title>Arduino-ADXL345/ADXL345.cpp at master · jarzebski/Arduino-ADXL345</title> <meta name="description" content="ADXL345 Triple Axis Accelerometer Arduino Library. - jarzebski/Arduino-ADXL345"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="twitter:image:src" content="https://avatars3.githubusercontent.com/u/3647?s=400&amp;v=4" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary" /><meta name="twitter:title" content="jarzebski/Arduino-ADXL345" /><meta name="twitter:description" content="ADXL345 Triple Axis Accelerometer Arduino Library. - jarzebski/Arduino-ADXL345" /> <meta property="og:image" content="https://avatars3.githubusercontent.com/u/3647?s=400&amp;v=4" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="jarzebski/Arduino-ADXL345" /><meta property="og:url" content="https://github.com/jarzebski/Arduino-ADXL345" /><meta property="og:description" content="ADXL345 Triple Axis Accelerometer Arduino Library. - jarzebski/Arduino-ADXL345" /> <link rel="assets" href="https://github.githubassets.com/"> <link rel="web-socket" href="wss://live.github.com/_sockets/VjI6NDkwNjc0MTI4OjQxOWVjOTE3MDQxMjg3OTE4ZjQwN2JhMzk2YzY3NDQ5Zjk0NDFhMjhjM2M2ZDczNDI3YWFiNDEyYTk1MDJmYzE=--5fec34997dda0fb0f32941ef40816a8ccfad3a9d"> <link rel="sudo-modal" href="/sessions/sudo_modal"> <meta name="request-id" content="A674:320C:1102D80:1D0BC75:5E29D5F2" data-pjax-transient> <meta name="selected-link" value="repo_source" data-pjax-transient> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="octolytics-host" content="collector.githubapp.com" /><meta name="octolytics-app-id" content="github" /><meta name="octolytics-event-url" content="https://collector.githubapp.com/github-external/browser_event" /><meta name="octolytics-dimension-request_id" content="A674:320C:1102D80:1D0BC75:5E29D5F2" /><meta name="octolytics-dimension-region_edge" content="iad" /><meta name="octolytics-dimension-region_render" content="iad" /><meta name="octolytics-dimension-ga_id" content="" class="js-octo-ga-id" /><meta name="octolytics-dimension-visitor_id" content="5284668684745599487" /><meta name="octolytics-actor-id" content="22565959" /><meta name="octolytics-actor-login" content="uma-dev" /><meta name="octolytics-actor-hash" content="c2f8c3e413692146ba56f8e7b044035103c7cacedbd1904e5ba13975c5d47667" /> <meta name="analytics-location" content="/&lt;user-name&gt;/&lt;repo-name&gt;/blob/show" data-pjax-transient="true" /> <meta name="google-analytics" content="UA-3769691-2"> <meta class="js-ga-set" name="userId" content="278ed74d90b3840b68c66ff3a3da7f0f"> <meta class="js-ga-set" name="dimension1" content="Logged In"> <meta name="hostname" content="github.com"> <meta name="user-login" content="uma-dev"> <meta name="expected-hostname" content="github.com"> <meta name="js-proxy-site-detection-payload" content="MmJlODA4MDQyZGRiODc2MzQwNDY0MThlNmU1YWI3NjZjNDhmODEyNGU1NWEwMzRmYjg0YzhiNTdiMTFkYjVjYnx7InJlbW90ZV9hZGRyZXNzIjoiMTMyLjI0OC4xNTYuMjUzIiwicmVxdWVzdF9pZCI6IkE2NzQ6MzIwQzoxMTAyRDgwOjFEMEJDNzU6NUUyOUQ1RjIiLCJ0aW1lc3RhbXAiOjE1Nzk4MDAwNjMsImhvc3QiOiJnaXRodWIuY29tIn0="> <meta name="enabled-features" content="MARKETPLACE_FEATURED_BLOG_POSTS,MARKETPLACE_INVOICED_BILLING,MARKETPLACE_SOCIAL_PROOF_CUSTOMERS,MARKETPLACE_TRENDING_SOCIAL_PROOF,MARKETPLACE_RECOMMENDATIONS,MARKETPLACE_PENDING_INSTALLATIONS,NOTIFY_ON_BLOCK,RELATED_ISSUES,GHE_CLOUD_TRIAL"> <meta name="html-safe-nonce" content="bedae82b94782ccf1cea78b70b766ee4260f310f"> <meta http-equiv="x-pjax-version" content="6347b41dd92fb4aa59d47f2e455e520a"> <link href="https://github.com/jarzebski/Arduino-ADXL345/commits/master.atom" rel="alternate" title="Recent Commits to Arduino-ADXL345:master" type="application/atom+xml"> <meta name="go-import" content="github.com/jarzebski/Arduino-ADXL345 git https://github.com/jarzebski/Arduino-ADXL345.git"> <meta name="octolytics-dimension-user_id" content="3647" /><meta name="octolytics-dimension-user_login" content="jarzebski" /><meta name="octolytics-dimension-repository_id" content="16022877" /><meta name="octolytics-dimension-repository_nwo" content="jarzebski/Arduino-ADXL345" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="16022877" /><meta name="octolytics-dimension-repository_network_root_nwo" content="jarzebski/Arduino-ADXL345" /><meta name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" content="false" /> <link rel="canonical" href="https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp" data-pjax-transient> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="icon" type="image/x-icon" class="js-site-favicon" href="https://github.githubassets.com/favicon.ico"> <meta name="theme-color" content="#1e2327"> <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials"> </head> <body class="logged-in env-production page-responsive page-blob"> <div class="position-relative js-header-wrapper "> <a href="#start-of-content" tabindex="1" class="p-3 bg-blue text-white show-on-focus js-skip-to-content">Skip to content</a> <span class="Progress progress-pjax-loader position-fixed width-full js-pjax-loader-bar"> <span class="progress-pjax-loader-bar top-0 left-0" style="width: 0%;"></span> </span> <header class="Header js-details-container Details flex-wrap flex-lg-nowrap p-responsive" role="banner"> <div class="Header-item d-none d-lg-flex"> <a class="Header-link" href="https://github.com/" data-hotkey="g d" aria-label="Homepage" data-ga-click="Header, go to dashboard, icon:logo"> <svg class="octicon octicon-mark-github v-align-middle" height="32" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg> </a> </div> <div class="Header-item d-lg-none"> <button class="Header-link btn-link js-details-target" type="button" aria-label="Toggle navigation" aria-expanded="false"> <svg height="24" class="octicon octicon-three-bars" viewBox="0 0 12 16" version="1.1" width="18" aria-hidden="true"><path fill-rule="evenodd" d="M11.41 9H.59C0 9 0 8.59 0 8c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zm0-4H.59C0 5 0 4.59 0 4c0-.59 0-1 .59-1H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1h.01zM.59 11H11.4c.59 0 .59.41.59 1 0 .59 0 1-.59 1H.59C0 13 0 12.59 0 12c0-.59 0-1 .59-1z"/></svg> </button> </div> <div class="Header-item Header-item--full flex-column flex-lg-row width-full flex-order-2 flex-lg-order-none mr-0 mr-lg-3 mt-3 mt-lg-0 Details-content--hidden"> <div class="header-search flex-self-stretch flex-lg-self-auto mr-0 mr-lg-3 mb-3 mb-lg-0 scoped-search site-scoped-search js-site-search position-relative js-jump-to" role="combobox" aria-owns="jump-to-results" aria-label="Search or jump to" aria-haspopup="listbox" aria-expanded="false" > <div class="position-relative"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="16022877" data-scoped-search-url="/jarzebski/Arduino-ADXL345/search" data-unscoped-search-url="/search" action="/jarzebski/Arduino-ADXL345/search" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="&#x2713;" /> <label class="form-control input-sm header-search-wrapper p-0 header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center js-chromeless-input-container"> <input type="text" class="form-control input-sm header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable" data-hotkey="s,/" name="q" value="" placeholder="Search or jump to…" data-unscoped-placeholder="Search or jump to…" data-scoped-placeholder="Search or jump to…" autocapitalize="off" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search or jump to…" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input class="js-data-jump-to-suggestions-path-csrf" type="hidden" value="P7QT3dBIytD6WtLbnLi9b0p+SzMtFrjZaNriMMmP5IQFEdYhcMXbExwLAfidCF9Jm3s2F5/KIiWdUjJDAj9egA=="> <input type="hidden" class="js-site-search-type-field" name="type" > <img src="https://github.githubassets.com/images/search-key-slash.svg" alt="" class="mr-2 header-search-key-slash"> <div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container"> <ul class="d-none js-jump-to-suggestions-template-container"> <li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item js-jump-to-suggestion" role="option"> <a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open p-2" href=""> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"/></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg> </div> <img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar d-none" alt="" aria-label="Team" src="" width="28" height="28"> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository"> In this repository </span> <span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub"> All GitHub </span> <span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span class="d-inline-block ml-1 v-align-middle">↵</span> </div> </a> </li> </ul> <ul class="d-none js-jump-to-no-results-template-container"> <li class="d-flex flex-justify-center flex-items-center f5 d-none js-jump-to-suggestion p-2"> <span class="text-gray">No suggested jump to results</span> </li> </ul> <ul id="jump-to-results" role="listbox" class="p-0 m-0 js-navigation-container jump-to-suggestions-results-container js-jump-to-suggestions-results-container"> <li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item js-jump-to-scoped-search d-none" role="option"> <a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open p-2" href=""> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"/></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg> </div> <img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar d-none" alt="" aria-label="Team" src="" width="28" height="28"> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository"> In this repository </span> <span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub"> All GitHub </span> <span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span class="d-inline-block ml-1 v-align-middle">↵</span> </div> </a> </li> <li class="d-flex flex-justify-start flex-items-center p-0 f5 navigation-item js-navigation-item js-jump-to-global-search d-none" role="option"> <a tabindex="-1" class="no-underline d-flex flex-auto flex-items-center jump-to-suggestions-path js-jump-to-suggestion-path js-navigation-open p-2" href=""> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg height="16" width="16" class="octicon octicon-repo flex-shrink-0 js-jump-to-octicon-repo d-none" title="Repository" aria-label="Repository" viewBox="0 0 12 16" version="1.1" role="img"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <svg height="16" width="16" class="octicon octicon-project flex-shrink-0 js-jump-to-octicon-project d-none" title="Project" aria-label="Project" viewBox="0 0 15 16" version="1.1" role="img"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"/></svg> <svg height="16" width="16" class="octicon octicon-search flex-shrink-0 js-jump-to-octicon-search d-none" title="Search" aria-label="Search" viewBox="0 0 16 16" version="1.1" role="img"><path fill-rule="evenodd" d="M15.7 13.3l-3.81-3.83A5.93 5.93 0 0013 6c0-3.31-2.69-6-6-6S1 2.69 1 6s2.69 6 6 6c1.3 0 2.48-.41 3.47-1.11l3.83 3.81c.19.2.45.3.7.3.25 0 .52-.09.7-.3a.996.996 0 000-1.41v.01zM7 10.7c-2.59 0-4.7-2.11-4.7-4.7 0-2.59 2.11-4.7 4.7-4.7 2.59 0 4.7 2.11 4.7 4.7 0 2.59-2.11 4.7-4.7 4.7z"/></svg> </div> <img class="avatar mr-2 flex-shrink-0 js-jump-to-suggestion-avatar d-none" alt="" aria-label="Team" src="" width="28" height="28"> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none js-jump-to-badge-search"> <span class="js-jump-to-badge-search-text-default d-none" aria-label="in this repository"> In this repository </span> <span class="js-jump-to-badge-search-text-global d-none" aria-label="in all of GitHub"> All GitHub </span> <span aria-hidden="true" class="d-inline-block ml-1 v-align-middle">↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 bg-gray px-1 text-gray-light ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span class="d-inline-block ml-1 v-align-middle">↵</span> </div> </a> </li> <li class="d-flex flex-justify-center flex-items-center p-0 f5 js-jump-to-suggestion"> <img src="https://github.githubassets.com/images/spinners/octocat-spinner-128.gif" alt="Octocat Spinner Icon" class="m-2" width="28"> </li> </ul> </div> </label> </form> </div> </div> <nav class="d-flex flex-column flex-lg-row flex-self-stretch flex-lg-self-auto" aria-label="Global"> <a class="Header-link d-block d-lg-none py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15" data-ga-click="Header, click, Nav menu - item:dashboard:user" aria-label="Dashboard" href="/dashboard"> Dashboard </a> <a class="js-selected-navigation-item Header-link mr-0 mr-lg-3 py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15" data-hotkey="g p" data-ga-click="Header, click, Nav menu - item:pulls context:user" aria-label="Pull requests you created" data-selected-links="/pulls /pulls/assigned /pulls/mentioned /pulls" href="/pulls"> Pull requests </a> <a class="js-selected-navigation-item Header-link mr-0 mr-lg-3 py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15" data-hotkey="g i" data-ga-click="Header, click, Nav menu - item:issues context:user" aria-label="Issues you created" data-selected-links="/issues /issues/assigned /issues/mentioned /issues" href="/issues"> Issues </a> <div class="mr-0 mr-lg-3 py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15"> <a class="js-selected-navigation-item Header-link" data-ga-click="Header, click, Nav menu - item:marketplace context:user" data-octo-click="marketplace_click" data-octo-dimensions="location:nav_bar" data-selected-links=" /marketplace" href="/marketplace"> Marketplace </a> </div> <a class="js-selected-navigation-item Header-link mr-0 mr-lg-3 py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15" data-ga-click="Header, click, Nav menu - item:explore" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship showcases showcases_search showcases_landing /explore" href="/explore"> Explore </a> <a class="Header-link d-block d-lg-none mr-0 mr-lg-3 py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15" href="https://github.com/uma-dev"> <img class="avatar" height="20" width="20" alt="@uma-dev" src="https://avatars1.githubusercontent.com/u/22565959?s=60&amp;v=4" /> uma-dev </a> <!-- '"` --><!-- </textarea></xmp> --></option></form><form action="/logout" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="XG0/aWQO7VXU+qbSIOJsJhSBMrxK+xGG6J/HZqwMZfyGJgpnHlKT62dGk9ZzdEj1OzyafcILrQH76EqsmMs7Lg==" /> <button type="submit" class="Header-link mr-0 mr-lg-3 py-2 py-lg-0 border-top border-lg-top-0 border-white-fade-15 d-lg-none btn-link d-block width-full text-left" data-ga-click="Header, sign out, icon:logout" style="padding-left: 2px;"> <svg class="octicon octicon-sign-out v-align-middle" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 9V7H8V5h4V3l4 3-4 3zm-2 3H6V3L2 1h8v3h1V1c0-.55-.45-1-1-1H1C.45 0 0 .45 0 1v11.38c0 .39.22.73.55.91L6 16.01V13h4c.55 0 1-.45 1-1V8h-1v4z"/></svg> Sign out </button> </form></nav> </div> <div class="Header-item Header-item--full flex-justify-center d-lg-none position-relative"> <div class="css-truncate css-truncate-target width-fit position-absolute left-0 right-0 text-center"> <svg class="octicon octicon-repo" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <a class="Header-link" href="/jarzebski">jarzebski</a> / <a class="Header-link" href="/jarzebski/Arduino-ADXL345">Arduino-ADXL345</a> </div> </div> <div class="Header-item mr-0 mr-lg-3 flex-order-1 flex-lg-order-none"> <a aria-label="You have no unread notifications" class="Header-link notification-indicator position-relative tooltipped tooltipped-sw js-socket-channel js-notification-indicator" data-hotkey="g n" data-ga-click="Header, go to notifications, icon:read" data-channel="notification-changed:22565959" href="/notifications"> <span class="js-indicator-modifier mail-status "></span> <svg class="octicon octicon-bell" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 12v1H0v-1l.73-.58c.77-.77.81-2.55 1.19-4.42C2.69 3.23 6 2 6 2c0-.55.45-1 1-1s1 .45 1 1c0 0 3.39 1.23 4.16 5 .38 1.88.42 3.66 1.19 4.42l.66.58H14zm-7 4c1.11 0 2-.89 2-2H5c0 1.11.89 2 2 2z"/></svg> </a> </div> <div class="Header-item position-relative d-none d-lg-flex"> <details class="details-overlay details-reset"> <summary class="Header-link" aria-label="Create new…" data-ga-click="Header, create new, icon:add"> <svg class="octicon octicon-plus" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 9H7v5H5V9H0V7h5V2h2v5h5v2z"/></svg> <span class="dropdown-caret"></span> </summary> <details-menu class="dropdown-menu dropdown-menu-sw"> <a role="menuitem" class="dropdown-item" href="/new" data-ga-click="Header, create new repository"> New repository </a> <a role="menuitem" class="dropdown-item" href="/new/import" data-ga-click="Header, import a repository"> Import repository </a> <a role="menuitem" class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, create new gist"> New gist </a> <a role="menuitem" class="dropdown-item" href="/organizations/new" data-ga-click="Header, create new organization"> New organization </a> <div role="none" class="dropdown-divider"></div> <div class="dropdown-header"> <span title="jarzebski/Arduino-ADXL345">This repository</span> </div> <a role="menuitem" class="dropdown-item" href="/jarzebski/Arduino-ADXL345/issues/new" data-ga-click="Header, create new issue" data-skip-pjax> New issue </a> </details-menu> </details> </div> <div class="Header-item position-relative mr-0 d-none d-lg-flex"> <details class="details-overlay details-reset js-feature-preview-indicator-container" data-feature-preview-indicator-src="/users/uma-dev/feature_preview/indicator_check.json"> <summary class="Header-link" aria-label="View profile and more" data-ga-click="Header, show menu, icon:avatar"> <img alt="@uma-dev" class="avatar" src="https://avatars2.githubusercontent.com/u/22565959?s=40&amp;v=4" height="20" width="20"> <span class="feature-preview-indicator js-feature-preview-indicator" hidden></span> <span class="dropdown-caret"></span> </summary> <details-menu class="dropdown-menu dropdown-menu-sw mt-2" style="width: 180px"> <div class="header-nav-current-user css-truncate"><a role="menuitem" class="no-underline user-profile-link px-3 pt-2 pb-2 mb-n2 mt-n1 d-block" href="/uma-dev" data-ga-click="Header, go to profile, text:Signed in as">Signed in as <strong class="css-truncate-target">uma-dev</strong></a></div> <div role="none" class="dropdown-divider"></div> <div class="pl-3 pr-3 f6 user-status-container js-user-status-context pb-1" data-url="/users/status?compact=1&amp;link_mentions=0&amp;truncate=1"> <div class="js-user-status-container user-status-compact rounded-1 px-2 py-1 mt-2 border " data-team-hovercards-enabled> <details class="js-user-status-details details-reset details-overlay details-overlay-dark"> <summary class="btn-link btn-block link-gray no-underline js-toggle-user-status-edit toggle-user-status-edit " role="menuitem" data-hydro-click="{&quot;event_type&quot;:&quot;user_profile.click&quot;,&quot;payload&quot;:{&quot;profile_user_id&quot;:3647,&quot;target&quot;:&quot;EDIT_USER_STATUS&quot;,&quot;user_id&quot;:22565959,&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;}}" data-hydro-click-hmac="bc743ae3f2a26c0778ad0d977c2e11c4d800a0731a13623f2bad65501a12545f"> <div class="d-flex"> <div class="f6 lh-condensed user-status-header d-inline-block v-align-middle user-status-emoji-only-header circle pr-2 " style="max-width: 29px" > <div class="user-status-emoji-container flex-shrink-0 mr-1 mt-1 lh-condensed-ultra v-align-bottom" style=""> <svg class="octicon octicon-smiley" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm4.81 12.81a6.72 6.72 0 01-2.17 1.45c-.83.36-1.72.53-2.64.53-.92 0-1.81-.17-2.64-.53-.81-.34-1.55-.83-2.17-1.45a6.773 6.773 0 01-1.45-2.17A6.59 6.59 0 011.21 8c0-.92.17-1.81.53-2.64.34-.81.83-1.55 1.45-2.17.62-.62 1.36-1.11 2.17-1.45A6.59 6.59 0 018 1.21c.92 0 1.81.17 2.64.53.81.34 1.55.83 2.17 1.45.62.62 1.11 1.36 1.45 2.17.36.83.53 1.72.53 2.64 0 .92-.17 1.81-.53 2.64-.34.81-.83 1.55-1.45 2.17zM4 6.8v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2H5.2C4.53 8 4 7.47 4 6.8zm5 0v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2h-.59C9.53 8 9 7.47 9 6.8zm4 3.2c-.72 1.88-2.91 3-5 3s-4.28-1.13-5-3c-.14-.39.23-1 .66-1h8.59c.41 0 .89.61.75 1z"/></svg> </div> </div> <div class=" d-inline-block v-align-middle css-truncate css-truncate-target user-status-message-wrapper f6" style="line-height: 20px;" > <div class="d-inline-block text-gray-dark v-align-text-top text-left"> <span class="text-gray ml-2">Set status</span> </div> </div> </div> </summary> <details-dialog class="details-dialog rounded-1 anim-fade-in fast Box Box--overlay" role="dialog" tabindex="-1"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="position-relative flex-auto js-user-status-form" action="/users/status?compact=1&amp;link_mentions=0&amp;truncate=1" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="_method" value="put" /><input type="hidden" name="authenticity_token" value="Ribqm/ydFhArppFSiNIwQUv20m//9UKHvgoBa/uh936DtLHyOg1NYE777Zow1mljTusvZ1d0PaArM0vWd9Wm3g==" /> <div class="Box-header bg-gray border-bottom p-3"> <button class="Box-btn-octicon js-toggle-user-status-edit btn-octicon float-right" type="reset" aria-label="Close dialog" data-close-dialog> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> </button> <h3 class="Box-title f5 text-bold text-gray-dark">Edit status</h3> </div> <input type="hidden" name="emoji" class="js-user-status-emoji-field" value=""> <input type="hidden" name="organization_id" class="js-user-status-org-id-field" value=""> <div class="px-3 py-2 text-gray-dark"> <div class="js-characters-remaining-container position-relative mt-2"> <div class="input-group d-table form-group my-0 js-user-status-form-group"> <span class="input-group-button d-table-cell v-align-middle" style="width: 1%"> <button type="button" aria-label="Choose an emoji" class="btn-outline btn js-toggle-user-status-emoji-picker btn-open-emoji-picker p-0"> <span class="js-user-status-original-emoji" hidden></span> <span class="js-user-status-custom-emoji"></span> <span class="js-user-status-no-emoji-icon" > <svg class="octicon octicon-smiley" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm4.81 12.81a6.72 6.72 0 01-2.17 1.45c-.83.36-1.72.53-2.64.53-.92 0-1.81-.17-2.64-.53-.81-.34-1.55-.83-2.17-1.45a6.773 6.773 0 01-1.45-2.17A6.59 6.59 0 011.21 8c0-.92.17-1.81.53-2.64.34-.81.83-1.55 1.45-2.17.62-.62 1.36-1.11 2.17-1.45A6.59 6.59 0 018 1.21c.92 0 1.81.17 2.64.53.81.34 1.55.83 2.17 1.45.62.62 1.11 1.36 1.45 2.17.36.83.53 1.72.53 2.64 0 .92-.17 1.81-.53 2.64-.34.81-.83 1.55-1.45 2.17zM4 6.8v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2H5.2C4.53 8 4 7.47 4 6.8zm5 0v-.59c0-.66.53-1.19 1.2-1.19h.59c.66 0 1.19.53 1.19 1.19v.59c0 .67-.53 1.2-1.19 1.2h-.59C9.53 8 9 7.47 9 6.8zm4 3.2c-.72 1.88-2.91 3-5 3s-4.28-1.13-5-3c-.14-.39.23-1 .66-1h8.59c.41 0 .89.61.75 1z"/></svg> </span> </button> </span> <text-expander keys=": @" data-mention-url="/autocomplete/user-suggestions" data-emoji-url="/autocomplete/emoji"> <input type="text" autocomplete="off" data-no-org-url="/autocomplete/user-suggestions" data-org-url="/suggestions?mention_suggester=1" data-maxlength="80" class="d-table-cell width-full form-control js-user-status-message-field js-characters-remaining-field" placeholder="What's happening?" name="message" value="" aria-label="What is your current status?"> </text-expander> <div class="error">Could not update your status, please try again.</div> </div> <div style="margin-left: 53px" class="my-1 text-small label-characters-remaining js-characters-remaining" data-suffix="remaining" hidden> 80 remaining </div> </div> <include-fragment class="js-user-status-emoji-picker" data-url="/users/status/emoji"></include-fragment> <div class="overflow-auto ml-n3 mr-n3 px-3 border-bottom" style="max-height: 33vh"> <div class="user-status-suggestions js-user-status-suggestions collapsed overflow-hidden"> <h4 class="f6 text-normal my-3">Suggestions:</h4> <div class="mx-3 mt-2 clearfix"> <div class="float-left col-6"> <button type="button" value=":palm_tree:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1"> <div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji"> <g-emoji alias="palm_tree" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f334.png">🌴</g-emoji> </div> <div class="d-flex flex-items-center no-underline js-predefined-user-status-message ws-normal text-left" style="border-left: 1px solid transparent"> On vacation </div> </button> <button type="button" value=":face_with_thermometer:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1"> <div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji"> <g-emoji alias="face_with_thermometer" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f912.png">🤒</g-emoji> </div> <div class="d-flex flex-items-center no-underline js-predefined-user-status-message ws-normal text-left" style="border-left: 1px solid transparent"> Out sick </div> </button> </div> <div class="float-left col-6"> <button type="button" value=":house:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1"> <div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji"> <g-emoji alias="house" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f3e0.png">🏠</g-emoji> </div> <div class="d-flex flex-items-center no-underline js-predefined-user-status-message ws-normal text-left" style="border-left: 1px solid transparent"> Working from home </div> </button> <button type="button" value=":dart:" class="d-flex flex-items-baseline flex-items-stretch lh-condensed f6 btn-link link-gray no-underline js-predefined-user-status mb-1"> <div class="emoji-status-width mr-2 v-align-middle js-predefined-user-status-emoji"> <g-emoji alias="dart" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f3af.png">🎯</g-emoji> </div> <div class="d-flex flex-items-center no-underline js-predefined-user-status-message ws-normal text-left" style="border-left: 1px solid transparent"> Focusing </div> </button> </div> </div> </div> <div class="user-status-limited-availability-container"> <div class="form-checkbox my-0"> <input type="checkbox" name="limited_availability" value="1" class="js-user-status-limited-availability-checkbox" data-default-message="I may be slow to respond." aria-describedby="limited-availability-help-text-truncate-true-compact-true" id="limited-availability-truncate-true-compact-true"> <label class="d-block f5 text-gray-dark mb-1" for="limited-availability-truncate-true-compact-true"> Busy </label> <p class="note" id="limited-availability-help-text-truncate-true-compact-true"> When others mention you, assign you, or request your review, GitHub will let them know that you have limited availability. </p> </div> </div> </div> <div class="d-inline-block f5 mr-2 pt-3 pb-2" > <div class="d-inline-block mr-1"> Clear status </div> <details class="js-user-status-expire-drop-down f6 dropdown details-reset details-overlay d-inline-block mr-2"> <summary class="f5 btn-link link-gray-dark border px-2 py-1 rounded-1" aria-haspopup="true"> <div class="js-user-status-expiration-interval-selected d-inline-block v-align-baseline"> Never </div> <div class="dropdown-caret"></div> </summary> <ul class="dropdown-menu dropdown-menu-se pl-0 overflow-auto" style="width: 220px; max-height: 15.5em"> <li> <button type="button" class="btn-link dropdown-item js-user-status-expire-button ws-normal" title="Never"> <span class="d-inline-block text-bold mb-1">Never</span> <div class="f6 lh-condensed">Keep this status until you clear your status or edit your status.</div> </button> </li> <li class="dropdown-divider" role="none"></li> <li> <button type="button" class="btn-link dropdown-item ws-normal js-user-status-expire-button" title="in 30 minutes" value="2020-01-23T11:51:03-06:00"> in 30 minutes </button> </li> <li> <button type="button" class="btn-link dropdown-item ws-normal js-user-status-expire-button" title="in 1 hour" value="2020-01-23T12:21:03-06:00"> in 1 hour </button> </li> <li> <button type="button" class="btn-link dropdown-item ws-normal js-user-status-expire-button" title="in 4 hours" value="2020-01-23T15:21:03-06:00"> in 4 hours </button> </li> <li> <button type="button" class="btn-link dropdown-item ws-normal js-user-status-expire-button" title="today" value="2020-01-23T23:59:59-06:00"> today </button> </li> <li> <button type="button" class="btn-link dropdown-item ws-normal js-user-status-expire-button" title="this week" value="2020-01-26T23:59:59-06:00"> this week </button> </li> </ul> </details> <input class="js-user-status-expiration-date-input" type="hidden" name="expires_at" value=""> </div> <include-fragment class="js-user-status-org-picker" data-url="/users/status/organizations"></include-fragment> </div> <div class="d-flex flex-items-center flex-justify-between p-3 border-top"> <button type="submit" disabled class="width-full btn btn-primary mr-2 js-user-status-submit"> Set status </button> <button type="button" disabled class="width-full js-clear-user-status-button btn ml-2 "> Clear status </button> </div> </form> </details-dialog> </details> </div> </div> <div role="none" class="dropdown-divider"></div> <a role="menuitem" class="dropdown-item" href="/uma-dev" data-ga-click="Header, go to profile, text:your profile">Your profile</a> <a role="menuitem" class="dropdown-item" href="/uma-dev?tab=repositories" data-ga-click="Header, go to repositories, text:your repositories">Your repositories</a> <a role="menuitem" class="dropdown-item" href="/uma-dev?tab=projects" data-ga-click="Header, go to projects, text:your projects">Your projects</a> <a role="menuitem" class="dropdown-item" href="/uma-dev?tab=stars" data-ga-click="Header, go to starred repos, text:your stars">Your stars</a> <a role="menuitem" class="dropdown-item" href="https://gist.github.com/mine" data-ga-click="Header, your gists, text:your gists">Your gists</a> <div role="none" class="dropdown-divider"></div> <div id="feature-enrollment-toggle" class="hide-sm hide-md feature-preview-details position-relative"> <button type="button" class="dropdown-item btn-link" role="menuitem" data-feature-preview-trigger-url="/users/uma-dev/feature_previews" data-feature-preview-close-details="{&quot;event_type&quot;:&quot;feature_preview.clicks.close_modal&quot;,&quot;payload&quot;:{&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;,&quot;user_id&quot;:22565959}}" data-feature-preview-close-hmac="0d7d5c5e870a2e1dcc7b81f6e361c0183b394d1ccba45a8043d255c2af74b26d" data-hydro-click="{&quot;event_type&quot;:&quot;feature_preview.clicks.open_modal&quot;,&quot;payload&quot;:{&quot;link_location&quot;:&quot;user_dropdown&quot;,&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;,&quot;user_id&quot;:22565959}}" data-hydro-click-hmac="5cab44cee326e13eb9436e21be3602fa9e7f75301240ede9e9c5ab5f243d8694" > Feature preview </button> <span class="feature-preview-indicator js-feature-preview-indicator" hidden></span> </div> <a role="menuitem" class="dropdown-item" href="https://help.github.com" data-ga-click="Header, go to help, text:help">Help</a> <a role="menuitem" class="dropdown-item" href="/settings/profile" data-ga-click="Header, go to settings, icon:settings">Settings</a> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="logout-form" action="/logout" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="oiaeRazD8QMOwoa+UqyiO/z62AoBjfYErJ9+gYwQxQ94batL1p+Pvb1+s7oBOobo00dwy4l9SoO/6PNLuNeb3Q==" /> <button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout" role="menuitem"> Sign out </button> <input type="text" name="required_field_2fe9" hidden="hidden" class="form-control" /> <input type="hidden" name="timestamp" value="1579800063071" class="form-control" /> <input type="hidden" name="timestamp_secret" value="5c2c1007b3dda2f1dc497714ad41a1cddc928a23498d4ef8640c27d930ca7bcd" class="form-control" /> </form> </details-menu> </details> </div> </header> </div> <div id="start-of-content" class="show-on-focus"></div> <div id="js-flash-container"> </div> <div class="application-main " data-commit-hovercards-enabled> <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main > <div class=" pagehead repohead readability-menu experiment-repo-nav pt-0 pt-lg-4 "> <div class="container-lg mb-4 p-responsive d-none d-lg-flex"> <div class="flex-auto min-width-0 width-fit mr-3"> <h1 class="public d-flex flex-wrap flex-items-center break-word float-none"> <svg class="octicon octicon-repo mr-1" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg> <span class="author" itemprop="author"> <a class="url fn" rel="author" data-hovercard-type="user" data-hovercard-url="/users/jarzebski/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/jarzebski">jarzebski</a> </span> <span class="path-divider">/</span> <strong itemprop="name" class="mr-2"> <a data-pjax="#js-repo-pjax-container" href="/jarzebski/Arduino-ADXL345">Arduino-ADXL345</a> </strong> </h1> </div> <ul class="pagehead-actions flex-shrink-0"> <li> <!-- '"` --><!-- </textarea></xmp> --></option></form><form data-remote="true" class="clearfix js-social-form js-social-container" action="/notifications/subscribe" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="ZSFRo++tTcpgxdIV9V82t9zOW8dbinCSRQynbfNafoiRITPHZRfYoIpQ36/sqkbC8yqBfoDMJlDJWoz21fcgtQ==" /> <input type="hidden" name="repository_id" value="16022877"> <details class="details-reset details-overlay select-menu float-left"> <summary class="select-menu-button float-left btn btn-sm btn-with-count" data-hydro-click="{&quot;event_type&quot;:&quot;repository.click&quot;,&quot;payload&quot;:{&quot;target&quot;:&quot;WATCH_BUTTON&quot;,&quot;repository_id&quot;:16022877,&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;,&quot;user_id&quot;:22565959}}" data-hydro-click-hmac="a9032951b921b1895d2499570bd77aff8179cb4c790d28d1c4fedd4403d760ea" data-ga-click="Repository, click Watch settings, action:blob#show"> <span data-menu-button> <svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg> Watch </span> </summary> <details-menu class="select-menu-modal position-absolute mt-5" style="z-index: 99;"> <div class="select-menu-header"> <span class="select-menu-title">Notifications</span> </div> <div class="select-menu-list"> <button type="submit" name="do" value="included" class="select-menu-item width-full" aria-checked="true" role="menuitemradio"> <svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg> <div class="select-menu-item-text"> <span class="select-menu-item-heading">Not watching</span> <span class="description">Be notified only when participating or @mentioned.</span> <span class="hidden-select-button-text" data-menu-button-contents> <svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg> Watch </span> </div> </button> <button type="submit" name="do" value="release_only" class="select-menu-item width-full" aria-checked="false" role="menuitemradio"> <svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg> <div class="select-menu-item-text"> <span class="select-menu-item-heading">Releases only</span> <span class="description">Be notified of new releases, and when participating or @mentioned.</span> <span class="hidden-select-button-text" data-menu-button-contents> <svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg> Unwatch releases </span> </div> </button> <button type="submit" name="do" value="subscribed" class="select-menu-item width-full" aria-checked="false" role="menuitemradio"> <svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg> <div class="select-menu-item-text"> <span class="select-menu-item-heading">Watching</span> <span class="description">Be notified of all conversations.</span> <span class="hidden-select-button-text" data-menu-button-contents> <svg class="octicon octicon-eye v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg> Unwatch </span> </div> </button> <button type="submit" name="do" value="ignore" class="select-menu-item width-full" aria-checked="false" role="menuitemradio"> <svg class="octicon octicon-check select-menu-item-icon" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5L12 5z"/></svg> <div class="select-menu-item-text"> <span class="select-menu-item-heading">Ignoring</span> <span class="description">Never be notified.</span> <span class="hidden-select-button-text" data-menu-button-contents> <svg class="octicon octicon-mute v-align-text-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 2.81v10.38c0 .67-.81 1-1.28.53L3 10H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h2l3.72-3.72C7.19 1.81 8 2.14 8 2.81zm7.53 3.22l-1.06-1.06-1.97 1.97-1.97-1.97-1.06 1.06L11.44 8 9.47 9.97l1.06 1.06 1.97-1.97 1.97 1.97 1.06-1.06L13.56 8l1.97-1.97z"/></svg> Stop ignoring </span> </div> </button> </div> </details-menu> </details> <a class="social-count js-social-count" href="/jarzebski/Arduino-ADXL345/watchers" aria-label="5 users are watching this repository"> 5 </a> </form> </li> <li> <div class="js-toggler-container js-social-container starring-container "> <form class="starred js-social-form" action="/jarzebski/Arduino-ADXL345/unstar" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="zgkyxKkNwtfJhVti0SR6rSKr31MyzHRZ1EIxHflRd7tZdH9cqOMXXfMXlUr/J4fiSiOSqiUnjoizan3ueZ+4Rw==" /> <input type="hidden" name="context" value="repository"></input> <button type="submit" class="btn btn-sm btn-with-count js-toggler-target" aria-label="Unstar this repository" title="Unstar jarzebski/Arduino-ADXL345" data-hydro-click="{&quot;event_type&quot;:&quot;repository.click&quot;,&quot;payload&quot;:{&quot;target&quot;:&quot;UNSTAR_BUTTON&quot;,&quot;repository_id&quot;:16022877,&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;,&quot;user_id&quot;:22565959}}" data-hydro-click-hmac="92c872d6feee53dcba05414fb002597be165f1c506fd11c9ad40af1990f5c028" data-ga-click="Repository, click unstar button, action:blob#show; text:Unstar"> <svg aria-label="star" height="16" class="octicon octicon-star v-align-text-bottom" viewBox="0 0 14 16" version="1.1" width="14" role="img"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"/></svg> Unstar </button> <a class="social-count js-social-count" href="/jarzebski/Arduino-ADXL345/stargazers" aria-label="40 users starred this repository"> 40 </a> </form> <form class="unstarred js-social-form" action="/jarzebski/Arduino-ADXL345/star" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="njx6+WsmJd2LyZvAc2aDmPADkovUP22zrEwXyfF7oUZ1liK0siLMPkzPv7vzrWWr6bTB6N79YZEzGL+UcxKRDw==" /> <input type="hidden" name="context" value="repository"></input> <button type="submit" class="btn btn-sm btn-with-count js-toggler-target" aria-label="Unstar this repository" title="Star jarzebski/Arduino-ADXL345" data-hydro-click="{&quot;event_type&quot;:&quot;repository.click&quot;,&quot;payload&quot;:{&quot;target&quot;:&quot;STAR_BUTTON&quot;,&quot;repository_id&quot;:16022877,&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;,&quot;user_id&quot;:22565959}}" data-hydro-click-hmac="473e4f5d6a7d4d7ea25cb0d5e880937a28208c372867e284dafb76c6efcadb2d" data-ga-click="Repository, click star button, action:blob#show; text:Star"> <svg aria-label="star" height="16" class="octicon octicon-star v-align-text-bottom" viewBox="0 0 14 16" version="1.1" width="14" role="img"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74L14 6z"/></svg> Star </button> <a class="social-count js-social-count" href="/jarzebski/Arduino-ADXL345/stargazers" aria-label="40 users starred this repository"> 40 </a> </form> </div> </li> <li> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="btn-with-count" action="/jarzebski/Arduino-ADXL345/fork" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="xl7TG21N17QQASVN8IWLFLLJ0A5BRD24MFLt1k1E/pgtRXJnZGobDbNOYOwuid6kPcotOBJJ7mmWMw9r0xOLYA==" /> <button class="btn btn-sm btn-with-count" data-hydro-click="{&quot;event_type&quot;:&quot;repository.click&quot;,&quot;payload&quot;:{&quot;target&quot;:&quot;FORK_BUTTON&quot;,&quot;repository_id&quot;:16022877,&quot;client_id&quot;:&quot;1230432811.1575250431&quot;,&quot;originating_request_id&quot;:&quot;A674:320C:1102D80:1D0BC75:5E29D5F2&quot;,&quot;originating_url&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345.cpp&quot;,&quot;referrer&quot;:&quot;https://github.com/jarzebski/Arduino-ADXL345&quot;,&quot;user_id&quot;:22565959}}" data-hydro-click-hmac="62b4382840e7fb2ef74d76d04529e0100b07cb968d9de71ec418fbc44ba3c67e" data-ga-click="Repository, show fork modal, action:blob#show; text:Fork" type="submit" title="Fork your own copy of jarzebski/Arduino-ADXL345 to your account" aria-label="Fork your own copy of jarzebski/Arduino-ADXL345 to your account"> <svg class="octicon octicon-repo-forked v-align-text-bottom" viewBox="0 0 10 16" version="1.1" width="10" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 00-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 002 1a1.993 1.993 0 00-1 3.72V6.5l3 3v1.78A1.993 1.993 0 005 15a1.993 1.993 0 001-3.72V9.5l3-3V4.72A1.993 1.993 0 008 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg> Fork </button></form> <a href="/jarzebski/Arduino-ADXL345/network/members" class="social-count" aria-label="36 users forked this repository"> 36 </a> </li> </ul> </div> <nav class="hx_reponav reponav js-repo-nav js-sidenav-container-pjax clearfix container-lg p-responsive d-none d-lg-block" itemscope itemtype="http://schema.org/BreadcrumbList" aria-label="Repository" data-pjax="#js-repo-pjax-container"> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a class="js-selected-navigation-item selected reponav-item" itemprop="url" data-hotkey="g c" aria-current="page" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages /jarzebski/Arduino-ADXL345" href="/jarzebski/Arduino-ADXL345"> <div class="d-inline"><svg class="octicon octicon-code" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg></div> <span itemprop="name">Code</span> <meta itemprop="position" content="1"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" data-hotkey="g i" class="js-selected-navigation-item reponav-item" data-selected-links="repo_issues repo_labels repo_milestones /jarzebski/Arduino-ADXL345/issues" href="/jarzebski/Arduino-ADXL345/issues"> <div class="d-inline"><svg class="octicon octicon-issue-opened" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 011.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg></div> <span itemprop="name">Issues</span> <span class="Counter">2</span> <meta itemprop="position" content="2"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a data-hotkey="g p" data-skip-pjax="true" itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_pulls checks /jarzebski/Arduino-ADXL345/pulls" href="/jarzebski/Arduino-ADXL345/pulls"> <div class="d-inline"><svg class="octicon octicon-git-pull-request" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0010 15a1.993 1.993 0 001-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 00-1 3.72v6.56A1.993 1.993 0 002 15a1.993 1.993 0 001-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg></div> <span itemprop="name">Pull requests</span> <span class="Counter">2</span> <meta itemprop="position" content="4"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement" class="position-relative float-left"> <a data-hotkey="g w" data-skip-pjax="true" class="js-selected-navigation-item reponav-item" data-selected-links="repo_actions /jarzebski/Arduino-ADXL345/actions" href="/jarzebski/Arduino-ADXL345/actions"> <div class="d-inline"><svg class="octicon octicon-play" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14 8A7 7 0 110 8a7 7 0 0114 0zm-8.223 3.482l4.599-3.066a.5.5 0 000-.832L5.777 4.518A.5.5 0 005 4.934v6.132a.5.5 0 00.777.416z"/></svg></div> Actions </a> </span> <a data-hotkey="g b" class="js-selected-navigation-item reponav-item" data-selected-links="repo_projects new_repo_project repo_project /jarzebski/Arduino-ADXL345/projects" href="/jarzebski/Arduino-ADXL345/projects"> <div class="d-inline"><svg class="octicon octicon-project" viewBox="0 0 15 16" version="1.1" width="15" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 00-1 1v14a1 1 0 001 1h13a1 1 0 001-1V1a1 1 0 00-1-1z"/></svg></div> Projects <span class="Counter" >0</span> </a> <a class="js-selected-navigation-item reponav-item" data-hotkey="g w" data-selected-links="repo_wiki /jarzebski/Arduino-ADXL345/wiki" href="/jarzebski/Arduino-ADXL345/wiki"> <div class="d-inline"><svg class="octicon octicon-book" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M3 5h4v1H3V5zm0 3h4V7H3v1zm0 2h4V9H3v1zm11-5h-4v1h4V5zm0 2h-4v1h4V7zm0 2h-4v1h4V9zm2-6v9c0 .55-.45 1-1 1H9.5l-1 1-1-1H2c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1h5.5l1 1 1-1H15c.55 0 1 .45 1 1zm-8 .5L7.5 3H2v9h6V3.5zm7-.5H9.5l-.5.5V12h6V3z"/></svg></div> Wiki </a> <a data-skip-pjax="true" class="js-selected-navigation-item reponav-item" data-selected-links="security alerts policy token_scanning code_scanning /jarzebski/Arduino-ADXL345/security/advisories" href="/jarzebski/Arduino-ADXL345/security/advisories"> <div class="d-inline"><svg class="octicon octicon-shield" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 2l7-2 7 2v6.02C14 12.69 8.69 16 7 16c-1.69 0-7-3.31-7-7.98V2zm1 .75L7 1l6 1.75v5.268C13 12.104 8.449 15 7 15c-1.449 0-6-2.896-6-6.982V2.75zm1 .75L7 2v12c-1.207 0-5-2.482-5-5.985V3.5z"/></svg></div> Security </a> <a class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors dependency_graph pulse people /jarzebski/Arduino-ADXL345/pulse" href="/jarzebski/Arduino-ADXL345/pulse"> <div class="d-inline"><svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg></div> Insights </a> </nav> <div class="reponav-wrapper reponav-small d-lg-none"> <nav class="reponav js-reponav text-center no-wrap" itemscope itemtype="http://schema.org/BreadcrumbList"> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a class="js-selected-navigation-item selected reponav-item" itemprop="url" aria-current="page" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages /jarzebski/Arduino-ADXL345" href="/jarzebski/Arduino-ADXL345"> <span itemprop="name">Code</span> <meta itemprop="position" content="1"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_issues repo_labels repo_milestones /jarzebski/Arduino-ADXL345/issues" href="/jarzebski/Arduino-ADXL345/issues"> <span itemprop="name">Issues</span> <span class="Counter">2</span> <meta itemprop="position" content="2"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_pulls checks /jarzebski/Arduino-ADXL345/pulls" href="/jarzebski/Arduino-ADXL345/pulls"> <span itemprop="name">Pull requests</span> <span class="Counter">2</span> <meta itemprop="position" content="4"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_projects new_repo_project repo_project /jarzebski/Arduino-ADXL345/projects" href="/jarzebski/Arduino-ADXL345/projects"> <span itemprop="name">Projects</span> <span class="Counter">0</span> <meta itemprop="position" content="5"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_actions /jarzebski/Arduino-ADXL345/actions" href="/jarzebski/Arduino-ADXL345/actions"> <span itemprop="name">Actions</span> <meta itemprop="position" content="6"> </a> </span> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="repo_wiki /jarzebski/Arduino-ADXL345/wiki" href="/jarzebski/Arduino-ADXL345/wiki"> <span itemprop="name">Wiki</span> <meta itemprop="position" content="7"> </a> </span> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="security alerts policy token_scanning code_scanning /jarzebski/Arduino-ADXL345/security/advisories" href="/jarzebski/Arduino-ADXL345/security/advisories"> <span itemprop="name">Security</span> <meta itemprop="position" content="8"> </a> <a class="js-selected-navigation-item reponav-item" data-selected-links="pulse /jarzebski/Arduino-ADXL345/pulse" href="/jarzebski/Arduino-ADXL345/pulse"> Pulse </a> <span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement"> <a itemprop="url" class="js-selected-navigation-item reponav-item" data-selected-links="community /jarzebski/Arduino-ADXL345/community" href="/jarzebski/Arduino-ADXL345/community"> Community </a> </span> </nav> </div> </div> <div class="container-lg clearfix new-discussion-timeline experiment-repo-nav p-responsive"> <div class="repository-content "> <a class="d-none js-permalink-shortcut" data-hotkey="y" href="/jarzebski/Arduino-ADXL345/blob/37c67cdcf648d92ef608d4a4001edbdbc03c4ac4/ADXL345.cpp">Permalink</a> <!-- blob contrib key: blob_contributors:v21:b7a6e01a820fc523f3afd0de55754d1a --> <div class="d-flex flex-items-start flex-shrink-0 pb-3 flex-column flex-md-row"> <span class="d-flex flex-justify-between width-full width-md-auto"> <details class="details-reset details-overlay branch-select-menu " id="branch-select-menu"> <summary class="btn btn-sm css-truncate" data-hotkey="w" title="Switch branches or tags"> <i>Branch:</i> <span class="css-truncate-target" data-menu-button>master</span> <span class="dropdown-caret"></span> </summary> <details-menu class="SelectMenu SelectMenu--hasFilter" src="/jarzebski/Arduino-ADXL345/refs/master/ADXL345.cpp?source_action=show&amp;source_controller=blob" preload> <div class="SelectMenu-modal"> <include-fragment class="SelectMenu-loading" aria-label="Menu is loading"> <svg class="octicon octicon-octoface anim-pulse" height="32" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M14.7 5.34c.13-.32.55-1.59-.13-3.31 0 0-1.05-.33-3.44 1.3-1-.28-2.07-.32-3.13-.32s-2.13.04-3.13.32c-2.39-1.64-3.44-1.3-3.44-1.3-.68 1.72-.26 2.99-.13 3.31C.49 6.21 0 7.33 0 8.69 0 13.84 3.33 15 7.98 15S16 13.84 16 8.69c0-1.36-.49-2.48-1.3-3.35zM8 14.02c-3.3 0-5.98-.15-5.98-3.35 0-.76.38-1.48 1.02-2.07 1.07-.98 2.9-.46 4.96-.46 2.07 0 3.88-.52 4.96.46.65.59 1.02 1.3 1.02 2.07 0 3.19-2.68 3.35-5.98 3.35zM5.49 9.01c-.66 0-1.2.8-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.54-1.78-1.2-1.78zm5.02 0c-.66 0-1.2.79-1.2 1.78s.54 1.79 1.2 1.79c.66 0 1.2-.8 1.2-1.79s-.53-1.78-1.2-1.78z"/></svg> </include-fragment> </div> </details-menu> </details> <div class="BtnGroup flex-shrink-0 d-md-none"> <a href="/jarzebski/Arduino-ADXL345/find/master" class="js-pjax-capture-input btn btn-sm BtnGroup-item" data-pjax data-hotkey="t"> Find file </a> <clipboard-copy value="ADXL345.cpp" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> </span> <h2 id="blob-path" class="breadcrumb flex-auto min-width-0 text-normal flex-md-self-center ml-md-2 mr-md-3 my-2 my-md-0"> <span class="js-repo-root text-bold"><span class="js-path-segment"><a data-pjax="true" href="/jarzebski/Arduino-ADXL345"><span>Arduino-ADXL345</span></a></span></span><span class="separator">/</span><strong class="final-path">ADXL345.cpp</strong> </h2> <div class="BtnGroup flex-shrink-0 d-none d-md-inline-block"> <a href="/jarzebski/Arduino-ADXL345/find/master" class="js-pjax-capture-input btn btn-sm BtnGroup-item" data-pjax data-hotkey="t"> Find file </a> <clipboard-copy value="ADXL345.cpp" class="btn btn-sm BtnGroup-item"> Copy path </clipboard-copy> </div> </div> <div class="Box Box--condensed d-flex flex-column flex-shrink-0"> <div class="Box-body d-flex flex-justify-between bg-blue-light flex-column flex-md-row flex-items-start flex-md-items-center"> <span class="pr-md-4 f6"> <a rel="author" data-skip-pjax="true" data-hovercard-type="user" data-hovercard-url="/users/jarzebski/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/jarzebski"><img class="avatar" src="https://avatars1.githubusercontent.com/u/3647?s=40&amp;v=4" width="20" height="20" alt="@jarzebski" /></a> <a class="text-bold link-gray-dark lh-default v-align-middle" rel="author" data-hovercard-type="user" data-hovercard-url="/users/jarzebski/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/jarzebski">jarzebski</a> <span class="lh-default v-align-middle"> <a data-pjax="true" title="Added read scaled values in g" class="link-gray" href="/jarzebski/Arduino-ADXL345/commit/7b2b200ec55baad9591419d38c847bd9241c3d93">Added read scaled values in g</a> </span> </span> <span class="d-inline-block flex-shrink-0 v-align-bottom f6 mt-2 mt-md-0"> <a class="pr-2 text-mono link-gray" href="/jarzebski/Arduino-ADXL345/commit/7b2b200ec55baad9591419d38c847bd9241c3d93" data-pjax>7b2b200</a> <relative-time datetime="2014-10-20T22:40:09Z" class="no-wrap">Oct 21, 2014</relative-time> </span> </div> <div class="Box-body d-flex flex-items-center flex-auto f6 border-bottom-0 flex-wrap" > <details class="details-reset details-overlay details-overlay-dark lh-default text-gray-dark float-left mr-2" id="blob_contributors_box"> <summary class="btn-link"> <span><strong>1</strong> contributor</span> </summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast" aria-label="Users who have contributed to this file" src="/jarzebski/Arduino-ADXL345/contributors-list/master/ADXL345.cpp" preload> <div class="Box-header"> <button class="Box-btn-octicon btn-octicon float-right" type="button" aria-label="Close dialog" data-close-dialog> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> </button> <h3 class="Box-title"> Users who have contributed to this file </h3> </div> <include-fragment class="octocat-spinner my-3" aria-label="Loading..."></include-fragment> </details-dialog> </details> </div> </div> <div class="Box mt-3 position-relative"> <div class="Box-header py-2 d-flex flex-column flex-shrink-0 flex-md-row flex-md-items-center"> <div class="text-mono f6 flex-auto pr-3 flex-order-2 flex-md-order-1 mt-2 mt-md-0"> 567 lines (463 sloc) <span class="file-info-divider"></span> 12.6 KB </div> <div class="d-flex py-1 py-md-0 flex-auto flex-order-1 flex-md-order-2 flex-sm-grow-0 flex-justify-between"> <div class="BtnGroup"> <a id="raw-url" class="btn btn-sm BtnGroup-item" href="/jarzebski/Arduino-ADXL345/raw/master/ADXL345.cpp">Raw</a> <a class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b" href="/jarzebski/Arduino-ADXL345/blame/master/ADXL345.cpp">Blame</a> <a rel="nofollow" class="btn btn-sm BtnGroup-item" href="/jarzebski/Arduino-ADXL345/commits/master/ADXL345.cpp">History</a> </div> <div> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="inline-form js-update-url-with-hash" action="/jarzebski/Arduino-ADXL345/edit/master/ADXL345.cpp" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="jajFxVTYxoViFg/fYKYvysP5uR/4dYN/oQmPSKl/OhEQgp71wLvPQ6GXwI8JbX92CnzAEHmHiyVjTLMS6+n/Ow==" /> <button class="btn-octicon tooltipped tooltipped-nw" type="submit" aria-label="Fork this project and edit the file" data-hotkey="e" data-disable-with> <svg class="octicon octicon-pencil" viewBox="0 0 14 16" version="1.1" width="14" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 011.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"/></svg> </button> </form> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="inline-form" action="/jarzebski/Arduino-ADXL345/delete/master/ADXL345.cpp" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="GC1wL1Q4TwQG4kGRhG957SoXnwULQDU+V+iLueSNzoP6JZkHnm3tZeeespJbiDW1HD2fUCcZRhi/pu+dMsCAAg==" /> <button class="btn-octicon btn-octicon-danger tooltipped tooltipped-nw" type="submit" aria-label="Fork this project and delete the file" data-disable-with> <svg class="octicon octicon-trashcan" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"/></svg> </button> </form> </div> </div> </div> <div itemprop="text" class="Box-body p-0 blob-wrapper data type-c "> <table class="highlight tab-size js-file-line-container" data-tab-size="8"> <tr> <td id="L1" class="blob-num js-line-number" data-line-number="1"></td> <td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">/*</span></span></td> </tr> <tr> <td id="L2" class="blob-num js-line-number" data-line-number="2"></td> <td id="LC2" class="blob-code blob-code-inner js-file-line"><span class="pl-c">ADXL345.cpp - Class file for the ADXL345 Triple Axis Accelerometer Arduino Library.</span></td> </tr> <tr> <td id="L3" class="blob-num js-line-number" data-line-number="3"></td> <td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L4" class="blob-num js-line-number" data-line-number="4"></td> <td id="LC4" class="blob-code blob-code-inner js-file-line"><span class="pl-c">Version: 1.1.0</span></td> </tr> <tr> <td id="L5" class="blob-num js-line-number" data-line-number="5"></td> <td id="LC5" class="blob-code blob-code-inner js-file-line"><span class="pl-c">(c) 2014 Korneliusz Jarzebski</span></td> </tr> <tr> <td id="L6" class="blob-num js-line-number" data-line-number="6"></td> <td id="LC6" class="blob-code blob-code-inner js-file-line"><span class="pl-c">www.jarzebski.pl</span></td> </tr> <tr> <td id="L7" class="blob-num js-line-number" data-line-number="7"></td> <td id="LC7" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L8" class="blob-num js-line-number" data-line-number="8"></td> <td id="LC8" class="blob-code blob-code-inner js-file-line"><span class="pl-c">This program is free software: you can redistribute it and/or modify</span></td> </tr> <tr> <td id="L9" class="blob-num js-line-number" data-line-number="9"></td> <td id="LC9" class="blob-code blob-code-inner js-file-line"><span class="pl-c">it under the terms of the version 3 GNU General Public License as</span></td> </tr> <tr> <td id="L10" class="blob-num js-line-number" data-line-number="10"></td> <td id="LC10" class="blob-code blob-code-inner js-file-line"><span class="pl-c">published by the Free Software Foundation.</span></td> </tr> <tr> <td id="L11" class="blob-num js-line-number" data-line-number="11"></td> <td id="LC11" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L12" class="blob-num js-line-number" data-line-number="12"></td> <td id="LC12" class="blob-code blob-code-inner js-file-line"><span class="pl-c">This program is distributed in the hope that it will be useful,</span></td> </tr> <tr> <td id="L13" class="blob-num js-line-number" data-line-number="13"></td> <td id="LC13" class="blob-code blob-code-inner js-file-line"><span class="pl-c">but WITHOUT ANY WARRANTY; without even the implied warranty of</span></td> </tr> <tr> <td id="L14" class="blob-num js-line-number" data-line-number="14"></td> <td id="LC14" class="blob-code blob-code-inner js-file-line"><span class="pl-c">MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span></td> </tr> <tr> <td id="L15" class="blob-num js-line-number" data-line-number="15"></td> <td id="LC15" class="blob-code blob-code-inner js-file-line"><span class="pl-c">GNU General Public License for more details.</span></td> </tr> <tr> <td id="L16" class="blob-num js-line-number" data-line-number="16"></td> <td id="LC16" class="blob-code blob-code-inner js-file-line"><span class="pl-c"></span></td> </tr> <tr> <td id="L17" class="blob-num js-line-number" data-line-number="17"></td> <td id="LC17" class="blob-code blob-code-inner js-file-line"><span class="pl-c">You should have received a copy of the GNU General Public License</span></td> </tr> <tr> <td id="L18" class="blob-num js-line-number" data-line-number="18"></td> <td id="LC18" class="blob-code blob-code-inner js-file-line"><span class="pl-c">along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;.</span></td> </tr> <tr> <td id="L19" class="blob-num js-line-number" data-line-number="19"></td> <td id="LC19" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">*/</span></span></td> </tr> <tr> <td id="L20" class="blob-num js-line-number" data-line-number="20"></td> <td id="LC20" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L21" class="blob-num js-line-number" data-line-number="21"></td> <td id="LC21" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L22" class="blob-num js-line-number" data-line-number="22"></td> <td id="LC22" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">include</span> <span class="pl-s"><span class="pl-pds">&quot;</span>Arduino.h<span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L23" class="blob-num js-line-number" data-line-number="23"></td> <td id="LC23" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">else</span></td> </tr> <tr> <td id="L24" class="blob-num js-line-number" data-line-number="24"></td> <td id="LC24" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">include</span> <span class="pl-s"><span class="pl-pds">&quot;</span>WProgram.h<span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L25" class="blob-num js-line-number" data-line-number="25"></td> <td id="LC25" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">endif</span></td> </tr> <tr> <td id="L26" class="blob-num js-line-number" data-line-number="26"></td> <td id="LC26" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L27" class="blob-num js-line-number" data-line-number="27"></td> <td id="LC27" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">include</span> <span class="pl-s"><span class="pl-pds">&lt;</span>Wire.h<span class="pl-pds">&gt;</span></span></td> </tr> <tr> <td id="L28" class="blob-num js-line-number" data-line-number="28"></td> <td id="LC28" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L29" class="blob-num js-line-number" data-line-number="29"></td> <td id="LC29" class="blob-code blob-code-inner js-file-line">#<span class="pl-k">include</span> <span class="pl-s"><span class="pl-pds">&quot;</span>ADXL345.h<span class="pl-pds">&quot;</span></span></td> </tr> <tr> <td id="L30" class="blob-num js-line-number" data-line-number="30"></td> <td id="LC30" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L31" class="blob-num js-line-number" data-line-number="31"></td> <td id="LC31" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::begin</span>()</td> </tr> <tr> <td id="L32" class="blob-num js-line-number" data-line-number="32"></td> <td id="LC32" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L33" class="blob-num js-line-number" data-line-number="33"></td> <td id="LC33" class="blob-code blob-code-inner js-file-line"> f.<span class="pl-smi">XAxis</span> = <span class="pl-c1">0</span>;</td> </tr> <tr> <td id="L34" class="blob-num js-line-number" data-line-number="34"></td> <td id="LC34" class="blob-code blob-code-inner js-file-line"> f.<span class="pl-smi">YAxis</span> = <span class="pl-c1">0</span>;</td> </tr> <tr> <td id="L35" class="blob-num js-line-number" data-line-number="35"></td> <td id="LC35" class="blob-code blob-code-inner js-file-line"> f.<span class="pl-smi">ZAxis</span> = <span class="pl-c1">0</span>;</td> </tr> <tr> <td id="L36" class="blob-num js-line-number" data-line-number="36"></td> <td id="LC36" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L37" class="blob-num js-line-number" data-line-number="37"></td> <td id="LC37" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">begin</span>();</td> </tr> <tr> <td id="L38" class="blob-num js-line-number" data-line-number="38"></td> <td id="LC38" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L39" class="blob-num js-line-number" data-line-number="39"></td> <td id="LC39" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> Check ADXL345 REG DEVID</span></td> </tr> <tr> <td id="L40" class="blob-num js-line-number" data-line-number="40"></td> <td id="LC40" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (<span class="pl-c1">fastRegister8</span>(ADXL345_REG_DEVID) != <span class="pl-c1">0xE5</span>)</td> </tr> <tr> <td id="L41" class="blob-num js-line-number" data-line-number="41"></td> <td id="LC41" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L42" class="blob-num js-line-number" data-line-number="42"></td> <td id="LC42" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">false</span>;</td> </tr> <tr> <td id="L43" class="blob-num js-line-number" data-line-number="43"></td> <td id="LC43" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L44" class="blob-num js-line-number" data-line-number="44"></td> <td id="LC44" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L45" class="blob-num js-line-number" data-line-number="45"></td> <td id="LC45" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> Enable measurement mode (0b00001000)</span></td> </tr> <tr> <td id="L46" class="blob-num js-line-number" data-line-number="46"></td> <td id="LC46" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_POWER_CTL, <span class="pl-c1">0x08</span>);</td> </tr> <tr> <td id="L47" class="blob-num js-line-number" data-line-number="47"></td> <td id="LC47" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L48" class="blob-num js-line-number" data-line-number="48"></td> <td id="LC48" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">clearSettings</span>();</td> </tr> <tr> <td id="L49" class="blob-num js-line-number" data-line-number="49"></td> <td id="LC49" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L50" class="blob-num js-line-number" data-line-number="50"></td> <td id="LC50" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">true</span>;</td> </tr> <tr> <td id="L51" class="blob-num js-line-number" data-line-number="51"></td> <td id="LC51" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L52" class="blob-num js-line-number" data-line-number="52"></td> <td id="LC52" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L53" class="blob-num js-line-number" data-line-number="53"></td> <td id="LC53" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Range</span></td> </tr> <tr> <td id="L54" class="blob-num js-line-number" data-line-number="54"></td> <td id="LC54" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setRange</span>(<span class="pl-c1">adxl345_range_t</span> range)</td> </tr> <tr> <td id="L55" class="blob-num js-line-number" data-line-number="55"></td> <td id="LC55" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L56" class="blob-num js-line-number" data-line-number="56"></td> <td id="LC56" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> Get actual value register</span></td> </tr> <tr> <td id="L57" class="blob-num js-line-number" data-line-number="57"></td> <td id="LC57" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value = <span class="pl-c1">readRegister8</span>(ADXL345_REG_DATA_FORMAT);</td> </tr> <tr> <td id="L58" class="blob-num js-line-number" data-line-number="58"></td> <td id="LC58" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L59" class="blob-num js-line-number" data-line-number="59"></td> <td id="LC59" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> Update the data rate</span></td> </tr> <tr> <td id="L60" class="blob-num js-line-number" data-line-number="60"></td> <td id="LC60" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> (&amp;) 0b11110000 (0xF0 - Leave HSB)</span></td> </tr> <tr> <td id="L61" class="blob-num js-line-number" data-line-number="61"></td> <td id="LC61" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> (|) 0b0000xx?? (range - Set range)</span></td> </tr> <tr> <td id="L62" class="blob-num js-line-number" data-line-number="62"></td> <td id="LC62" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> (|) 0b00001000 (0x08 - Set Full Res)</span></td> </tr> <tr> <td id="L63" class="blob-num js-line-number" data-line-number="63"></td> <td id="LC63" class="blob-code blob-code-inner js-file-line"> value &amp;= <span class="pl-c1">0xF0</span>;</td> </tr> <tr> <td id="L64" class="blob-num js-line-number" data-line-number="64"></td> <td id="LC64" class="blob-code blob-code-inner js-file-line"> value |= range;</td> </tr> <tr> <td id="L65" class="blob-num js-line-number" data-line-number="65"></td> <td id="LC65" class="blob-code blob-code-inner js-file-line"> value |= <span class="pl-c1">0x08</span>;</td> </tr> <tr> <td id="L66" class="blob-num js-line-number" data-line-number="66"></td> <td id="LC66" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L67" class="blob-num js-line-number" data-line-number="67"></td> <td id="LC67" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_DATA_FORMAT, value);</td> </tr> <tr> <td id="L68" class="blob-num js-line-number" data-line-number="68"></td> <td id="LC68" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L69" class="blob-num js-line-number" data-line-number="69"></td> <td id="LC69" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L70" class="blob-num js-line-number" data-line-number="70"></td> <td id="LC70" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Range</span></td> </tr> <tr> <td id="L71" class="blob-num js-line-number" data-line-number="71"></td> <td id="LC71" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">adxl345_range_t</span> <span class="pl-en">ADXL345::getRange</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L72" class="blob-num js-line-number" data-line-number="72"></td> <td id="LC72" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L73" class="blob-num js-line-number" data-line-number="73"></td> <td id="LC73" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> (<span class="pl-c1">adxl345_range_t</span>)(<span class="pl-c1">readRegister8</span>(ADXL345_REG_DATA_FORMAT) &amp; <span class="pl-c1">0x03</span>);</td> </tr> <tr> <td id="L74" class="blob-num js-line-number" data-line-number="74"></td> <td id="LC74" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L75" class="blob-num js-line-number" data-line-number="75"></td> <td id="LC75" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L76" class="blob-num js-line-number" data-line-number="76"></td> <td id="LC76" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Data Rate</span></td> </tr> <tr> <td id="L77" class="blob-num js-line-number" data-line-number="77"></td> <td id="LC77" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setDataRate</span>(adxl345_dataRate_t dataRate)</td> </tr> <tr> <td id="L78" class="blob-num js-line-number" data-line-number="78"></td> <td id="LC78" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L79" class="blob-num js-line-number" data-line-number="79"></td> <td id="LC79" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_BW_RATE, dataRate);</td> </tr> <tr> <td id="L80" class="blob-num js-line-number" data-line-number="80"></td> <td id="LC80" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L81" class="blob-num js-line-number" data-line-number="81"></td> <td id="LC81" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L82" class="blob-num js-line-number" data-line-number="82"></td> <td id="LC82" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Data Rate</span></td> </tr> <tr> <td id="L83" class="blob-num js-line-number" data-line-number="83"></td> <td id="LC83" class="blob-code blob-code-inner js-file-line">adxl345_dataRate_t <span class="pl-en">ADXL345::getDataRate</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L84" class="blob-num js-line-number" data-line-number="84"></td> <td id="LC84" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L85" class="blob-num js-line-number" data-line-number="85"></td> <td id="LC85" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> (adxl345_dataRate_t)(<span class="pl-c1">readRegister8</span>(ADXL345_REG_BW_RATE) &amp; <span class="pl-c1">0x0F</span>);</td> </tr> <tr> <td id="L86" class="blob-num js-line-number" data-line-number="86"></td> <td id="LC86" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L87" class="blob-num js-line-number" data-line-number="87"></td> <td id="LC87" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L88" class="blob-num js-line-number" data-line-number="88"></td> <td id="LC88" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Low Pass Filter</span></td> </tr> <tr> <td id="L89" class="blob-num js-line-number" data-line-number="89"></td> <td id="LC89" class="blob-code blob-code-inner js-file-line">Vector <span class="pl-en">ADXL345::lowPassFilter</span>(Vector vector, <span class="pl-k">float</span> alpha)</td> </tr> <tr> <td id="L90" class="blob-num js-line-number" data-line-number="90"></td> <td id="LC90" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L91" class="blob-num js-line-number" data-line-number="91"></td> <td id="LC91" class="blob-code blob-code-inner js-file-line"> f.<span class="pl-smi">XAxis</span> = vector.<span class="pl-smi">XAxis</span> * alpha + (f.<span class="pl-smi">XAxis</span> * (<span class="pl-c1">1.0</span> - alpha));</td> </tr> <tr> <td id="L92" class="blob-num js-line-number" data-line-number="92"></td> <td id="LC92" class="blob-code blob-code-inner js-file-line"> f.<span class="pl-smi">YAxis</span> = vector.<span class="pl-smi">YAxis</span> * alpha + (f.<span class="pl-smi">YAxis</span> * (<span class="pl-c1">1.0</span> - alpha));</td> </tr> <tr> <td id="L93" class="blob-num js-line-number" data-line-number="93"></td> <td id="LC93" class="blob-code blob-code-inner js-file-line"> f.<span class="pl-smi">ZAxis</span> = vector.<span class="pl-smi">ZAxis</span> * alpha + (f.<span class="pl-smi">ZAxis</span> * (<span class="pl-c1">1.0</span> - alpha));</td> </tr> <tr> <td id="L94" class="blob-num js-line-number" data-line-number="94"></td> <td id="LC94" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> f;</td> </tr> <tr> <td id="L95" class="blob-num js-line-number" data-line-number="95"></td> <td id="LC95" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L96" class="blob-num js-line-number" data-line-number="96"></td> <td id="LC96" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L97" class="blob-num js-line-number" data-line-number="97"></td> <td id="LC97" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Read raw values</span></td> </tr> <tr> <td id="L98" class="blob-num js-line-number" data-line-number="98"></td> <td id="LC98" class="blob-code blob-code-inner js-file-line">Vector <span class="pl-en">ADXL345::readRaw</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L99" class="blob-num js-line-number" data-line-number="99"></td> <td id="LC99" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L100" class="blob-num js-line-number" data-line-number="100"></td> <td id="LC100" class="blob-code blob-code-inner js-file-line"> r.<span class="pl-smi">XAxis</span> = <span class="pl-c1">readRegister16</span>(ADXL345_REG_DATAX0);</td> </tr> <tr> <td id="L101" class="blob-num js-line-number" data-line-number="101"></td> <td id="LC101" class="blob-code blob-code-inner js-file-line"> r.<span class="pl-smi">YAxis</span> = <span class="pl-c1">readRegister16</span>(ADXL345_REG_DATAY0);</td> </tr> <tr> <td id="L102" class="blob-num js-line-number" data-line-number="102"></td> <td id="LC102" class="blob-code blob-code-inner js-file-line"> r.<span class="pl-smi">ZAxis</span> = <span class="pl-c1">readRegister16</span>(ADXL345_REG_DATAZ0);</td> </tr> <tr> <td id="L103" class="blob-num js-line-number" data-line-number="103"></td> <td id="LC103" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> r;</td> </tr> <tr> <td id="L104" class="blob-num js-line-number" data-line-number="104"></td> <td id="LC104" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L105" class="blob-num js-line-number" data-line-number="105"></td> <td id="LC105" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L106" class="blob-num js-line-number" data-line-number="106"></td> <td id="LC106" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Read normalized values</span></td> </tr> <tr> <td id="L107" class="blob-num js-line-number" data-line-number="107"></td> <td id="LC107" class="blob-code blob-code-inner js-file-line">Vector <span class="pl-en">ADXL345::readNormalize</span>(<span class="pl-k">float</span> gravityFactor)</td> </tr> <tr> <td id="L108" class="blob-num js-line-number" data-line-number="108"></td> <td id="LC108" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L109" class="blob-num js-line-number" data-line-number="109"></td> <td id="LC109" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">readRaw</span>();</td> </tr> <tr> <td id="L110" class="blob-num js-line-number" data-line-number="110"></td> <td id="LC110" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L111" class="blob-num js-line-number" data-line-number="111"></td> <td id="LC111" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> (4 mg/LSB scale factor in Full Res) * gravity factor</span></td> </tr> <tr> <td id="L112" class="blob-num js-line-number" data-line-number="112"></td> <td id="LC112" class="blob-code blob-code-inner js-file-line"> n.<span class="pl-smi">XAxis</span> = r.<span class="pl-smi">XAxis</span> * <span class="pl-c1">0.004</span> * gravityFactor;</td> </tr> <tr> <td id="L113" class="blob-num js-line-number" data-line-number="113"></td> <td id="LC113" class="blob-code blob-code-inner js-file-line"> n.<span class="pl-smi">YAxis</span> = r.<span class="pl-smi">YAxis</span> * <span class="pl-c1">0.004</span> * gravityFactor;</td> </tr> <tr> <td id="L114" class="blob-num js-line-number" data-line-number="114"></td> <td id="LC114" class="blob-code blob-code-inner js-file-line"> n.<span class="pl-smi">ZAxis</span> = r.<span class="pl-smi">ZAxis</span> * <span class="pl-c1">0.004</span> * gravityFactor;</td> </tr> <tr> <td id="L115" class="blob-num js-line-number" data-line-number="115"></td> <td id="LC115" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L116" class="blob-num js-line-number" data-line-number="116"></td> <td id="LC116" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> n;</td> </tr> <tr> <td id="L117" class="blob-num js-line-number" data-line-number="117"></td> <td id="LC117" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L118" class="blob-num js-line-number" data-line-number="118"></td> <td id="LC118" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L119" class="blob-num js-line-number" data-line-number="119"></td> <td id="LC119" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Read scaled values</span></td> </tr> <tr> <td id="L120" class="blob-num js-line-number" data-line-number="120"></td> <td id="LC120" class="blob-code blob-code-inner js-file-line">Vector <span class="pl-en">ADXL345::readScaled</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L121" class="blob-num js-line-number" data-line-number="121"></td> <td id="LC121" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L122" class="blob-num js-line-number" data-line-number="122"></td> <td id="LC122" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">readRaw</span>();</td> </tr> <tr> <td id="L123" class="blob-num js-line-number" data-line-number="123"></td> <td id="LC123" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L124" class="blob-num js-line-number" data-line-number="124"></td> <td id="LC124" class="blob-code blob-code-inner js-file-line"> <span class="pl-c"><span class="pl-c">//</span> (4 mg/LSB scale factor in Full Res)</span></td> </tr> <tr> <td id="L125" class="blob-num js-line-number" data-line-number="125"></td> <td id="LC125" class="blob-code blob-code-inner js-file-line"> n.<span class="pl-smi">XAxis</span> = r.<span class="pl-smi">XAxis</span> * <span class="pl-c1">0.004</span>;</td> </tr> <tr> <td id="L126" class="blob-num js-line-number" data-line-number="126"></td> <td id="LC126" class="blob-code blob-code-inner js-file-line"> n.<span class="pl-smi">YAxis</span> = r.<span class="pl-smi">YAxis</span> * <span class="pl-c1">0.004</span>;</td> </tr> <tr> <td id="L127" class="blob-num js-line-number" data-line-number="127"></td> <td id="LC127" class="blob-code blob-code-inner js-file-line"> n.<span class="pl-smi">ZAxis</span> = r.<span class="pl-smi">ZAxis</span> * <span class="pl-c1">0.004</span>;</td> </tr> <tr> <td id="L128" class="blob-num js-line-number" data-line-number="128"></td> <td id="LC128" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L129" class="blob-num js-line-number" data-line-number="129"></td> <td id="LC129" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> n;</td> </tr> <tr> <td id="L130" class="blob-num js-line-number" data-line-number="130"></td> <td id="LC130" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L131" class="blob-num js-line-number" data-line-number="131"></td> <td id="LC131" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L132" class="blob-num js-line-number" data-line-number="132"></td> <td id="LC132" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::clearSettings</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L133" class="blob-num js-line-number" data-line-number="133"></td> <td id="LC133" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L134" class="blob-num js-line-number" data-line-number="134"></td> <td id="LC134" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">setRange</span>(ADXL345_RANGE_2G);</td> </tr> <tr> <td id="L135" class="blob-num js-line-number" data-line-number="135"></td> <td id="LC135" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">setDataRate</span>(ADXL345_DATARATE_100HZ);</td> </tr> <tr> <td id="L136" class="blob-num js-line-number" data-line-number="136"></td> <td id="LC136" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L137" class="blob-num js-line-number" data-line-number="137"></td> <td id="LC137" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_TAP, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L138" class="blob-num js-line-number" data-line-number="138"></td> <td id="LC138" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_DUR, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L139" class="blob-num js-line-number" data-line-number="139"></td> <td id="LC139" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_LATENT, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L140" class="blob-num js-line-number" data-line-number="140"></td> <td id="LC140" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_WINDOW, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L141" class="blob-num js-line-number" data-line-number="141"></td> <td id="LC141" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_ACT, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L142" class="blob-num js-line-number" data-line-number="142"></td> <td id="LC142" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_INACT, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L143" class="blob-num js-line-number" data-line-number="143"></td> <td id="LC143" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_TIME_INACT, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L144" class="blob-num js-line-number" data-line-number="144"></td> <td id="LC144" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_FF, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L145" class="blob-num js-line-number" data-line-number="145"></td> <td id="LC145" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_TIME_FF, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L146" class="blob-num js-line-number" data-line-number="146"></td> <td id="LC146" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L147" class="blob-num js-line-number" data-line-number="147"></td> <td id="LC147" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L148" class="blob-num js-line-number" data-line-number="148"></td> <td id="LC148" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L149" class="blob-num js-line-number" data-line-number="149"></td> <td id="LC149" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(ADXL345_REG_ACT_INACT_CTL);</td> </tr> <tr> <td id="L150" class="blob-num js-line-number" data-line-number="150"></td> <td id="LC150" class="blob-code blob-code-inner js-file-line"> value &amp;= <span class="pl-c1">0b10001000</span>;</td> </tr> <tr> <td id="L151" class="blob-num js-line-number" data-line-number="151"></td> <td id="LC151" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_ACT_INACT_CTL, value);</td> </tr> <tr> <td id="L152" class="blob-num js-line-number" data-line-number="152"></td> <td id="LC152" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L153" class="blob-num js-line-number" data-line-number="153"></td> <td id="LC153" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(ADXL345_REG_TAP_AXES);</td> </tr> <tr> <td id="L154" class="blob-num js-line-number" data-line-number="154"></td> <td id="LC154" class="blob-code blob-code-inner js-file-line"> value &amp;= <span class="pl-c1">0b11111000</span>;</td> </tr> <tr> <td id="L155" class="blob-num js-line-number" data-line-number="155"></td> <td id="LC155" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_TAP_AXES, value);</td> </tr> <tr> <td id="L156" class="blob-num js-line-number" data-line-number="156"></td> <td id="LC156" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L157" class="blob-num js-line-number" data-line-number="157"></td> <td id="LC157" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L158" class="blob-num js-line-number" data-line-number="158"></td> <td id="LC158" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Tap Threshold (62.5mg / LSB)</span></td> </tr> <tr> <td id="L159" class="blob-num js-line-number" data-line-number="159"></td> <td id="LC159" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTapThreshold</span>(<span class="pl-k">float</span> threshold)</td> </tr> <tr> <td id="L160" class="blob-num js-line-number" data-line-number="160"></td> <td id="LC160" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L161" class="blob-num js-line-number" data-line-number="161"></td> <td id="LC161" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(threshold / <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L162" class="blob-num js-line-number" data-line-number="162"></td> <td id="LC162" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_TAP, scaled);</td> </tr> <tr> <td id="L163" class="blob-num js-line-number" data-line-number="163"></td> <td id="LC163" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L164" class="blob-num js-line-number" data-line-number="164"></td> <td id="LC164" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L165" class="blob-num js-line-number" data-line-number="165"></td> <td id="LC165" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Tap Threshold (62.5mg / LSB)</span></td> </tr> <tr> <td id="L166" class="blob-num js-line-number" data-line-number="166"></td> <td id="LC166" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getTapThreshold</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L167" class="blob-num js-line-number" data-line-number="167"></td> <td id="LC167" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L168" class="blob-num js-line-number" data-line-number="168"></td> <td id="LC168" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_THRESH_TAP) * <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>;</td> </tr> <tr> <td id="L169" class="blob-num js-line-number" data-line-number="169"></td> <td id="LC169" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L170" class="blob-num js-line-number" data-line-number="170"></td> <td id="LC170" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L171" class="blob-num js-line-number" data-line-number="171"></td> <td id="LC171" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Tap Duration (625us / LSB)</span></td> </tr> <tr> <td id="L172" class="blob-num js-line-number" data-line-number="172"></td> <td id="LC172" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTapDuration</span>(<span class="pl-k">float</span> duration)</td> </tr> <tr> <td id="L173" class="blob-num js-line-number" data-line-number="173"></td> <td id="LC173" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L174" class="blob-num js-line-number" data-line-number="174"></td> <td id="LC174" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(duration / <span class="pl-c1">0</span>.<span class="pl-c1">000625f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L175" class="blob-num js-line-number" data-line-number="175"></td> <td id="LC175" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_DUR, scaled);</td> </tr> <tr> <td id="L176" class="blob-num js-line-number" data-line-number="176"></td> <td id="LC176" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L177" class="blob-num js-line-number" data-line-number="177"></td> <td id="LC177" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L178" class="blob-num js-line-number" data-line-number="178"></td> <td id="LC178" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Tap Duration (625us / LSB)</span></td> </tr> <tr> <td id="L179" class="blob-num js-line-number" data-line-number="179"></td> <td id="LC179" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getTapDuration</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L180" class="blob-num js-line-number" data-line-number="180"></td> <td id="LC180" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L181" class="blob-num js-line-number" data-line-number="181"></td> <td id="LC181" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_DUR) * <span class="pl-c1">0</span>.<span class="pl-c1">000625f</span>;</td> </tr> <tr> <td id="L182" class="blob-num js-line-number" data-line-number="182"></td> <td id="LC182" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L183" class="blob-num js-line-number" data-line-number="183"></td> <td id="LC183" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L184" class="blob-num js-line-number" data-line-number="184"></td> <td id="LC184" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Double Tap Latency (1.25ms / LSB)</span></td> </tr> <tr> <td id="L185" class="blob-num js-line-number" data-line-number="185"></td> <td id="LC185" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setDoubleTapLatency</span>(<span class="pl-k">float</span> latency)</td> </tr> <tr> <td id="L186" class="blob-num js-line-number" data-line-number="186"></td> <td id="LC186" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L187" class="blob-num js-line-number" data-line-number="187"></td> <td id="LC187" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(latency / <span class="pl-c1">0</span>.<span class="pl-c1">00125f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L188" class="blob-num js-line-number" data-line-number="188"></td> <td id="LC188" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_LATENT, scaled);</td> </tr> <tr> <td id="L189" class="blob-num js-line-number" data-line-number="189"></td> <td id="LC189" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L190" class="blob-num js-line-number" data-line-number="190"></td> <td id="LC190" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L191" class="blob-num js-line-number" data-line-number="191"></td> <td id="LC191" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Double Tap Latency (1.25ms / LSB)</span></td> </tr> <tr> <td id="L192" class="blob-num js-line-number" data-line-number="192"></td> <td id="LC192" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getDoubleTapLatency</span>()</td> </tr> <tr> <td id="L193" class="blob-num js-line-number" data-line-number="193"></td> <td id="LC193" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L194" class="blob-num js-line-number" data-line-number="194"></td> <td id="LC194" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_LATENT) * <span class="pl-c1">0</span>.<span class="pl-c1">00125f</span>;</td> </tr> <tr> <td id="L195" class="blob-num js-line-number" data-line-number="195"></td> <td id="LC195" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L196" class="blob-num js-line-number" data-line-number="196"></td> <td id="LC196" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L197" class="blob-num js-line-number" data-line-number="197"></td> <td id="LC197" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Double Tap Window (1.25ms / LSB)</span></td> </tr> <tr> <td id="L198" class="blob-num js-line-number" data-line-number="198"></td> <td id="LC198" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setDoubleTapWindow</span>(<span class="pl-k">float</span> window)</td> </tr> <tr> <td id="L199" class="blob-num js-line-number" data-line-number="199"></td> <td id="LC199" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L200" class="blob-num js-line-number" data-line-number="200"></td> <td id="LC200" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(window / <span class="pl-c1">0</span>.<span class="pl-c1">00125f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L201" class="blob-num js-line-number" data-line-number="201"></td> <td id="LC201" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_WINDOW, scaled);</td> </tr> <tr> <td id="L202" class="blob-num js-line-number" data-line-number="202"></td> <td id="LC202" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L203" class="blob-num js-line-number" data-line-number="203"></td> <td id="LC203" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L204" class="blob-num js-line-number" data-line-number="204"></td> <td id="LC204" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Double Tap Window (1.25ms / LSB)</span></td> </tr> <tr> <td id="L205" class="blob-num js-line-number" data-line-number="205"></td> <td id="LC205" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getDoubleTapWindow</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L206" class="blob-num js-line-number" data-line-number="206"></td> <td id="LC206" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L207" class="blob-num js-line-number" data-line-number="207"></td> <td id="LC207" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_WINDOW) * <span class="pl-c1">0</span>.<span class="pl-c1">00125f</span>;</td> </tr> <tr> <td id="L208" class="blob-num js-line-number" data-line-number="208"></td> <td id="LC208" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L209" class="blob-num js-line-number" data-line-number="209"></td> <td id="LC209" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L210" class="blob-num js-line-number" data-line-number="210"></td> <td id="LC210" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Activity Threshold (62.5mg / LSB)</span></td> </tr> <tr> <td id="L211" class="blob-num js-line-number" data-line-number="211"></td> <td id="LC211" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setActivityThreshold</span>(<span class="pl-k">float</span> threshold)</td> </tr> <tr> <td id="L212" class="blob-num js-line-number" data-line-number="212"></td> <td id="LC212" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L213" class="blob-num js-line-number" data-line-number="213"></td> <td id="LC213" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(threshold / <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L214" class="blob-num js-line-number" data-line-number="214"></td> <td id="LC214" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_ACT, scaled);</td> </tr> <tr> <td id="L215" class="blob-num js-line-number" data-line-number="215"></td> <td id="LC215" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L216" class="blob-num js-line-number" data-line-number="216"></td> <td id="LC216" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L217" class="blob-num js-line-number" data-line-number="217"></td> <td id="LC217" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Activity Threshold (65.5mg / LSB)</span></td> </tr> <tr> <td id="L218" class="blob-num js-line-number" data-line-number="218"></td> <td id="LC218" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getActivityThreshold</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L219" class="blob-num js-line-number" data-line-number="219"></td> <td id="LC219" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L220" class="blob-num js-line-number" data-line-number="220"></td> <td id="LC220" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_THRESH_ACT) * <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>;</td> </tr> <tr> <td id="L221" class="blob-num js-line-number" data-line-number="221"></td> <td id="LC221" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L222" class="blob-num js-line-number" data-line-number="222"></td> <td id="LC222" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L223" class="blob-num js-line-number" data-line-number="223"></td> <td id="LC223" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Inactivity Threshold (65.5mg / LSB)</span></td> </tr> <tr> <td id="L224" class="blob-num js-line-number" data-line-number="224"></td> <td id="LC224" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setInactivityThreshold</span>(<span class="pl-k">float</span> threshold)</td> </tr> <tr> <td id="L225" class="blob-num js-line-number" data-line-number="225"></td> <td id="LC225" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L226" class="blob-num js-line-number" data-line-number="226"></td> <td id="LC226" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(threshold / <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L227" class="blob-num js-line-number" data-line-number="227"></td> <td id="LC227" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_INACT, scaled);</td> </tr> <tr> <td id="L228" class="blob-num js-line-number" data-line-number="228"></td> <td id="LC228" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L229" class="blob-num js-line-number" data-line-number="229"></td> <td id="LC229" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L230" class="blob-num js-line-number" data-line-number="230"></td> <td id="LC230" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Incactivity Threshold (65.5mg / LSB)</span></td> </tr> <tr> <td id="L231" class="blob-num js-line-number" data-line-number="231"></td> <td id="LC231" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getInactivityThreshold</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L232" class="blob-num js-line-number" data-line-number="232"></td> <td id="LC232" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L233" class="blob-num js-line-number" data-line-number="233"></td> <td id="LC233" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_THRESH_INACT) * <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>;</td> </tr> <tr> <td id="L234" class="blob-num js-line-number" data-line-number="234"></td> <td id="LC234" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L235" class="blob-num js-line-number" data-line-number="235"></td> <td id="LC235" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L236" class="blob-num js-line-number" data-line-number="236"></td> <td id="LC236" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Inactivity Time (s / LSB)</span></td> </tr> <tr> <td id="L237" class="blob-num js-line-number" data-line-number="237"></td> <td id="LC237" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTimeInactivity</span>(<span class="pl-c1">uint8_t</span> time)</td> </tr> <tr> <td id="L238" class="blob-num js-line-number" data-line-number="238"></td> <td id="LC238" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L239" class="blob-num js-line-number" data-line-number="239"></td> <td id="LC239" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_TIME_INACT, <span class="pl-c1">time</span>);</td> </tr> <tr> <td id="L240" class="blob-num js-line-number" data-line-number="240"></td> <td id="LC240" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L241" class="blob-num js-line-number" data-line-number="241"></td> <td id="LC241" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L242" class="blob-num js-line-number" data-line-number="242"></td> <td id="LC242" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Inactivity Time (s / LSB)</span></td> </tr> <tr> <td id="L243" class="blob-num js-line-number" data-line-number="243"></td> <td id="LC243" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">uint8_t</span> <span class="pl-en">ADXL345::getTimeInactivity</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L244" class="blob-num js-line-number" data-line-number="244"></td> <td id="LC244" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L245" class="blob-num js-line-number" data-line-number="245"></td> <td id="LC245" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_TIME_INACT);</td> </tr> <tr> <td id="L246" class="blob-num js-line-number" data-line-number="246"></td> <td id="LC246" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L247" class="blob-num js-line-number" data-line-number="247"></td> <td id="LC247" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L248" class="blob-num js-line-number" data-line-number="248"></td> <td id="LC248" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Free Fall Threshold (65.5mg / LSB)</span></td> </tr> <tr> <td id="L249" class="blob-num js-line-number" data-line-number="249"></td> <td id="LC249" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setFreeFallThreshold</span>(<span class="pl-k">float</span> threshold)</td> </tr> <tr> <td id="L250" class="blob-num js-line-number" data-line-number="250"></td> <td id="LC250" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L251" class="blob-num js-line-number" data-line-number="251"></td> <td id="LC251" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(threshold / <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L252" class="blob-num js-line-number" data-line-number="252"></td> <td id="LC252" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_THRESH_FF, scaled);</td> </tr> <tr> <td id="L253" class="blob-num js-line-number" data-line-number="253"></td> <td id="LC253" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L254" class="blob-num js-line-number" data-line-number="254"></td> <td id="LC254" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L255" class="blob-num js-line-number" data-line-number="255"></td> <td id="LC255" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Free Fall Threshold (65.5mg / LSB)</span></td> </tr> <tr> <td id="L256" class="blob-num js-line-number" data-line-number="256"></td> <td id="LC256" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getFreeFallThreshold</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L257" class="blob-num js-line-number" data-line-number="257"></td> <td id="LC257" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L258" class="blob-num js-line-number" data-line-number="258"></td> <td id="LC258" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_THRESH_FF) * <span class="pl-c1">0</span>.<span class="pl-c1">0625f</span>;</td> </tr> <tr> <td id="L259" class="blob-num js-line-number" data-line-number="259"></td> <td id="LC259" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L260" class="blob-num js-line-number" data-line-number="260"></td> <td id="LC260" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L261" class="blob-num js-line-number" data-line-number="261"></td> <td id="LC261" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Set Free Fall Duratiom (5ms / LSB)</span></td> </tr> <tr> <td id="L262" class="blob-num js-line-number" data-line-number="262"></td> <td id="LC262" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setFreeFallDuration</span>(<span class="pl-k">float</span> duration)</td> </tr> <tr> <td id="L263" class="blob-num js-line-number" data-line-number="263"></td> <td id="LC263" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L264" class="blob-num js-line-number" data-line-number="264"></td> <td id="LC264" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> scaled = <span class="pl-c1">constrain</span>(duration / <span class="pl-c1">0</span>.<span class="pl-c1">005f</span>, <span class="pl-c1">0</span>, <span class="pl-c1">255</span>);</td> </tr> <tr> <td id="L265" class="blob-num js-line-number" data-line-number="265"></td> <td id="LC265" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_TIME_FF, scaled);</td> </tr> <tr> <td id="L266" class="blob-num js-line-number" data-line-number="266"></td> <td id="LC266" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L267" class="blob-num js-line-number" data-line-number="267"></td> <td id="LC267" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L268" class="blob-num js-line-number" data-line-number="268"></td> <td id="LC268" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Get Free Fall Duratiom</span></td> </tr> <tr> <td id="L269" class="blob-num js-line-number" data-line-number="269"></td> <td id="LC269" class="blob-code blob-code-inner js-file-line"><span class="pl-k">float</span> <span class="pl-en">ADXL345::getFreeFallDuration</span>()</td> </tr> <tr> <td id="L270" class="blob-num js-line-number" data-line-number="270"></td> <td id="LC270" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L271" class="blob-num js-line-number" data-line-number="271"></td> <td id="LC271" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegister8</span>(ADXL345_REG_TIME_FF) * <span class="pl-c1">0</span>.<span class="pl-c1">005f</span>;</td> </tr> <tr> <td id="L272" class="blob-num js-line-number" data-line-number="272"></td> <td id="LC272" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L273" class="blob-num js-line-number" data-line-number="273"></td> <td id="LC273" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L274" class="blob-num js-line-number" data-line-number="274"></td> <td id="LC274" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setActivityX</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L275" class="blob-num js-line-number" data-line-number="275"></td> <td id="LC275" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L276" class="blob-num js-line-number" data-line-number="276"></td> <td id="LC276" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">6</span>, state);</td> </tr> <tr> <td id="L277" class="blob-num js-line-number" data-line-number="277"></td> <td id="LC277" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L278" class="blob-num js-line-number" data-line-number="278"></td> <td id="LC278" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L279" class="blob-num js-line-number" data-line-number="279"></td> <td id="LC279" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getActivityX</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L280" class="blob-num js-line-number" data-line-number="280"></td> <td id="LC280" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L281" class="blob-num js-line-number" data-line-number="281"></td> <td id="LC281" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">6</span>);</td> </tr> <tr> <td id="L282" class="blob-num js-line-number" data-line-number="282"></td> <td id="LC282" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L283" class="blob-num js-line-number" data-line-number="283"></td> <td id="LC283" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L284" class="blob-num js-line-number" data-line-number="284"></td> <td id="LC284" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setActivityY</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L285" class="blob-num js-line-number" data-line-number="285"></td> <td id="LC285" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L286" class="blob-num js-line-number" data-line-number="286"></td> <td id="LC286" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">5</span>, state);</td> </tr> <tr> <td id="L287" class="blob-num js-line-number" data-line-number="287"></td> <td id="LC287" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L288" class="blob-num js-line-number" data-line-number="288"></td> <td id="LC288" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L289" class="blob-num js-line-number" data-line-number="289"></td> <td id="LC289" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getActivityY</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L290" class="blob-num js-line-number" data-line-number="290"></td> <td id="LC290" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L291" class="blob-num js-line-number" data-line-number="291"></td> <td id="LC291" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">5</span>);</td> </tr> <tr> <td id="L292" class="blob-num js-line-number" data-line-number="292"></td> <td id="LC292" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L293" class="blob-num js-line-number" data-line-number="293"></td> <td id="LC293" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L294" class="blob-num js-line-number" data-line-number="294"></td> <td id="LC294" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setActivityZ</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L295" class="blob-num js-line-number" data-line-number="295"></td> <td id="LC295" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L296" class="blob-num js-line-number" data-line-number="296"></td> <td id="LC296" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">4</span>, state);</td> </tr> <tr> <td id="L297" class="blob-num js-line-number" data-line-number="297"></td> <td id="LC297" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L298" class="blob-num js-line-number" data-line-number="298"></td> <td id="LC298" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L299" class="blob-num js-line-number" data-line-number="299"></td> <td id="LC299" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getActivityZ</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L300" class="blob-num js-line-number" data-line-number="300"></td> <td id="LC300" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L301" class="blob-num js-line-number" data-line-number="301"></td> <td id="LC301" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">4</span>);</td> </tr> <tr> <td id="L302" class="blob-num js-line-number" data-line-number="302"></td> <td id="LC302" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L303" class="blob-num js-line-number" data-line-number="303"></td> <td id="LC303" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L304" class="blob-num js-line-number" data-line-number="304"></td> <td id="LC304" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setActivityXYZ</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L305" class="blob-num js-line-number" data-line-number="305"></td> <td id="LC305" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L306" class="blob-num js-line-number" data-line-number="306"></td> <td id="LC306" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L307" class="blob-num js-line-number" data-line-number="307"></td> <td id="LC307" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L308" class="blob-num js-line-number" data-line-number="308"></td> <td id="LC308" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(ADXL345_REG_ACT_INACT_CTL);</td> </tr> <tr> <td id="L309" class="blob-num js-line-number" data-line-number="309"></td> <td id="LC309" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L310" class="blob-num js-line-number" data-line-number="310"></td> <td id="LC310" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (state)</td> </tr> <tr> <td id="L311" class="blob-num js-line-number" data-line-number="311"></td> <td id="LC311" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L312" class="blob-num js-line-number" data-line-number="312"></td> <td id="LC312" class="blob-code blob-code-inner js-file-line"> value |= <span class="pl-c1">0b00111000</span>;</td> </tr> <tr> <td id="L313" class="blob-num js-line-number" data-line-number="313"></td> <td id="LC313" class="blob-code blob-code-inner js-file-line"> } <span class="pl-k">else</span></td> </tr> <tr> <td id="L314" class="blob-num js-line-number" data-line-number="314"></td> <td id="LC314" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L315" class="blob-num js-line-number" data-line-number="315"></td> <td id="LC315" class="blob-code blob-code-inner js-file-line"> value &amp;= <span class="pl-c1">0b11000111</span>;</td> </tr> <tr> <td id="L316" class="blob-num js-line-number" data-line-number="316"></td> <td id="LC316" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L317" class="blob-num js-line-number" data-line-number="317"></td> <td id="LC317" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L318" class="blob-num js-line-number" data-line-number="318"></td> <td id="LC318" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_ACT_INACT_CTL, value);</td> </tr> <tr> <td id="L319" class="blob-num js-line-number" data-line-number="319"></td> <td id="LC319" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L320" class="blob-num js-line-number" data-line-number="320"></td> <td id="LC320" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L321" class="blob-num js-line-number" data-line-number="321"></td> <td id="LC321" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L322" class="blob-num js-line-number" data-line-number="322"></td> <td id="LC322" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setInactivityX</span>(<span class="pl-k">bool</span> state) </td> </tr> <tr> <td id="L323" class="blob-num js-line-number" data-line-number="323"></td> <td id="LC323" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L324" class="blob-num js-line-number" data-line-number="324"></td> <td id="LC324" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">2</span>, state);</td> </tr> <tr> <td id="L325" class="blob-num js-line-number" data-line-number="325"></td> <td id="LC325" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L326" class="blob-num js-line-number" data-line-number="326"></td> <td id="LC326" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L327" class="blob-num js-line-number" data-line-number="327"></td> <td id="LC327" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getInactivityX</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L328" class="blob-num js-line-number" data-line-number="328"></td> <td id="LC328" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L329" class="blob-num js-line-number" data-line-number="329"></td> <td id="LC329" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">2</span>);</td> </tr> <tr> <td id="L330" class="blob-num js-line-number" data-line-number="330"></td> <td id="LC330" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L331" class="blob-num js-line-number" data-line-number="331"></td> <td id="LC331" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L332" class="blob-num js-line-number" data-line-number="332"></td> <td id="LC332" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setInactivityY</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L333" class="blob-num js-line-number" data-line-number="333"></td> <td id="LC333" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L334" class="blob-num js-line-number" data-line-number="334"></td> <td id="LC334" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">1</span>, state);</td> </tr> <tr> <td id="L335" class="blob-num js-line-number" data-line-number="335"></td> <td id="LC335" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L336" class="blob-num js-line-number" data-line-number="336"></td> <td id="LC336" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L337" class="blob-num js-line-number" data-line-number="337"></td> <td id="LC337" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getInactivityY</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L338" class="blob-num js-line-number" data-line-number="338"></td> <td id="LC338" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L339" class="blob-num js-line-number" data-line-number="339"></td> <td id="LC339" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L340" class="blob-num js-line-number" data-line-number="340"></td> <td id="LC340" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L341" class="blob-num js-line-number" data-line-number="341"></td> <td id="LC341" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L342" class="blob-num js-line-number" data-line-number="342"></td> <td id="LC342" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setInactivityZ</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L343" class="blob-num js-line-number" data-line-number="343"></td> <td id="LC343" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L344" class="blob-num js-line-number" data-line-number="344"></td> <td id="LC344" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">0</span>, state);</td> </tr> <tr> <td id="L345" class="blob-num js-line-number" data-line-number="345"></td> <td id="LC345" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L346" class="blob-num js-line-number" data-line-number="346"></td> <td id="LC346" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L347" class="blob-num js-line-number" data-line-number="347"></td> <td id="LC347" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getInactivityZ</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L348" class="blob-num js-line-number" data-line-number="348"></td> <td id="LC348" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L349" class="blob-num js-line-number" data-line-number="349"></td> <td id="LC349" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_ACT_INACT_CTL, <span class="pl-c1">0</span>);</td> </tr> <tr> <td id="L350" class="blob-num js-line-number" data-line-number="350"></td> <td id="LC350" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L351" class="blob-num js-line-number" data-line-number="351"></td> <td id="LC351" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L352" class="blob-num js-line-number" data-line-number="352"></td> <td id="LC352" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setInactivityXYZ</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L353" class="blob-num js-line-number" data-line-number="353"></td> <td id="LC353" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L354" class="blob-num js-line-number" data-line-number="354"></td> <td id="LC354" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L355" class="blob-num js-line-number" data-line-number="355"></td> <td id="LC355" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L356" class="blob-num js-line-number" data-line-number="356"></td> <td id="LC356" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(ADXL345_REG_ACT_INACT_CTL);</td> </tr> <tr> <td id="L357" class="blob-num js-line-number" data-line-number="357"></td> <td id="LC357" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L358" class="blob-num js-line-number" data-line-number="358"></td> <td id="LC358" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (state)</td> </tr> <tr> <td id="L359" class="blob-num js-line-number" data-line-number="359"></td> <td id="LC359" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L360" class="blob-num js-line-number" data-line-number="360"></td> <td id="LC360" class="blob-code blob-code-inner js-file-line"> value |= <span class="pl-c1">0b00000111</span>;</td> </tr> <tr> <td id="L361" class="blob-num js-line-number" data-line-number="361"></td> <td id="LC361" class="blob-code blob-code-inner js-file-line"> } <span class="pl-k">else</span></td> </tr> <tr> <td id="L362" class="blob-num js-line-number" data-line-number="362"></td> <td id="LC362" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L363" class="blob-num js-line-number" data-line-number="363"></td> <td id="LC363" class="blob-code blob-code-inner js-file-line"> value &amp;= <span class="pl-c1">0b11111000</span>;</td> </tr> <tr> <td id="L364" class="blob-num js-line-number" data-line-number="364"></td> <td id="LC364" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L365" class="blob-num js-line-number" data-line-number="365"></td> <td id="LC365" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L366" class="blob-num js-line-number" data-line-number="366"></td> <td id="LC366" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_ACT_INACT_CTL, value);</td> </tr> <tr> <td id="L367" class="blob-num js-line-number" data-line-number="367"></td> <td id="LC367" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L368" class="blob-num js-line-number" data-line-number="368"></td> <td id="LC368" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L369" class="blob-num js-line-number" data-line-number="369"></td> <td id="LC369" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTapDetectionX</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L370" class="blob-num js-line-number" data-line-number="370"></td> <td id="LC370" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L371" class="blob-num js-line-number" data-line-number="371"></td> <td id="LC371" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_TAP_AXES, <span class="pl-c1">2</span>, state);</td> </tr> <tr> <td id="L372" class="blob-num js-line-number" data-line-number="372"></td> <td id="LC372" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L373" class="blob-num js-line-number" data-line-number="373"></td> <td id="LC373" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L374" class="blob-num js-line-number" data-line-number="374"></td> <td id="LC374" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getTapDetectionX</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L375" class="blob-num js-line-number" data-line-number="375"></td> <td id="LC375" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L376" class="blob-num js-line-number" data-line-number="376"></td> <td id="LC376" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_TAP_AXES, <span class="pl-c1">2</span>);</td> </tr> <tr> <td id="L377" class="blob-num js-line-number" data-line-number="377"></td> <td id="LC377" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L378" class="blob-num js-line-number" data-line-number="378"></td> <td id="LC378" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L379" class="blob-num js-line-number" data-line-number="379"></td> <td id="LC379" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTapDetectionY</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L380" class="blob-num js-line-number" data-line-number="380"></td> <td id="LC380" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L381" class="blob-num js-line-number" data-line-number="381"></td> <td id="LC381" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_TAP_AXES, <span class="pl-c1">1</span>, state);</td> </tr> <tr> <td id="L382" class="blob-num js-line-number" data-line-number="382"></td> <td id="LC382" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L383" class="blob-num js-line-number" data-line-number="383"></td> <td id="LC383" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L384" class="blob-num js-line-number" data-line-number="384"></td> <td id="LC384" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getTapDetectionY</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L385" class="blob-num js-line-number" data-line-number="385"></td> <td id="LC385" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L386" class="blob-num js-line-number" data-line-number="386"></td> <td id="LC386" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_TAP_AXES, <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L387" class="blob-num js-line-number" data-line-number="387"></td> <td id="LC387" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L388" class="blob-num js-line-number" data-line-number="388"></td> <td id="LC388" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L389" class="blob-num js-line-number" data-line-number="389"></td> <td id="LC389" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTapDetectionZ</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L390" class="blob-num js-line-number" data-line-number="390"></td> <td id="LC390" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L391" class="blob-num js-line-number" data-line-number="391"></td> <td id="LC391" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegisterBit</span>(ADXL345_REG_TAP_AXES, <span class="pl-c1">0</span>, state);</td> </tr> <tr> <td id="L392" class="blob-num js-line-number" data-line-number="392"></td> <td id="LC392" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L393" class="blob-num js-line-number" data-line-number="393"></td> <td id="LC393" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L394" class="blob-num js-line-number" data-line-number="394"></td> <td id="LC394" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::getTapDetectionZ</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L395" class="blob-num js-line-number" data-line-number="395"></td> <td id="LC395" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L396" class="blob-num js-line-number" data-line-number="396"></td> <td id="LC396" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> <span class="pl-c1">readRegisterBit</span>(ADXL345_REG_TAP_AXES, <span class="pl-c1">0</span>);</td> </tr> <tr> <td id="L397" class="blob-num js-line-number" data-line-number="397"></td> <td id="LC397" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L398" class="blob-num js-line-number" data-line-number="398"></td> <td id="LC398" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L399" class="blob-num js-line-number" data-line-number="399"></td> <td id="LC399" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::setTapDetectionXYZ</span>(<span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L400" class="blob-num js-line-number" data-line-number="400"></td> <td id="LC400" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L401" class="blob-num js-line-number" data-line-number="401"></td> <td id="LC401" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L402" class="blob-num js-line-number" data-line-number="402"></td> <td id="LC402" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L403" class="blob-num js-line-number" data-line-number="403"></td> <td id="LC403" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(ADXL345_REG_TAP_AXES);</td> </tr> <tr> <td id="L404" class="blob-num js-line-number" data-line-number="404"></td> <td id="LC404" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L405" class="blob-num js-line-number" data-line-number="405"></td> <td id="LC405" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (state)</td> </tr> <tr> <td id="L406" class="blob-num js-line-number" data-line-number="406"></td> <td id="LC406" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L407" class="blob-num js-line-number" data-line-number="407"></td> <td id="LC407" class="blob-code blob-code-inner js-file-line"> value |= <span class="pl-c1">0b00000111</span>;</td> </tr> <tr> <td id="L408" class="blob-num js-line-number" data-line-number="408"></td> <td id="LC408" class="blob-code blob-code-inner js-file-line"> } <span class="pl-k">else</span></td> </tr> <tr> <td id="L409" class="blob-num js-line-number" data-line-number="409"></td> <td id="LC409" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L410" class="blob-num js-line-number" data-line-number="410"></td> <td id="LC410" class="blob-code blob-code-inner js-file-line"> value &amp;= <span class="pl-c1">0b11111000</span>;</td> </tr> <tr> <td id="L411" class="blob-num js-line-number" data-line-number="411"></td> <td id="LC411" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L412" class="blob-num js-line-number" data-line-number="412"></td> <td id="LC412" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L413" class="blob-num js-line-number" data-line-number="413"></td> <td id="LC413" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_TAP_AXES, value);</td> </tr> <tr> <td id="L414" class="blob-num js-line-number" data-line-number="414"></td> <td id="LC414" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L415" class="blob-num js-line-number" data-line-number="415"></td> <td id="LC415" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L416" class="blob-num js-line-number" data-line-number="416"></td> <td id="LC416" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L417" class="blob-num js-line-number" data-line-number="417"></td> <td id="LC417" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::useInterrupt</span>(<span class="pl-c1">adxl345_int_t</span> interrupt)</td> </tr> <tr> <td id="L418" class="blob-num js-line-number" data-line-number="418"></td> <td id="LC418" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L419" class="blob-num js-line-number" data-line-number="419"></td> <td id="LC419" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (interrupt == <span class="pl-c1">0</span>)</td> </tr> <tr> <td id="L420" class="blob-num js-line-number" data-line-number="420"></td> <td id="LC420" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L421" class="blob-num js-line-number" data-line-number="421"></td> <td id="LC421" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_INT_MAP, <span class="pl-c1">0x00</span>);</td> </tr> <tr> <td id="L422" class="blob-num js-line-number" data-line-number="422"></td> <td id="LC422" class="blob-code blob-code-inner js-file-line"> } <span class="pl-k">else</span></td> </tr> <tr> <td id="L423" class="blob-num js-line-number" data-line-number="423"></td> <td id="LC423" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L424" class="blob-num js-line-number" data-line-number="424"></td> <td id="LC424" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_INT_MAP, <span class="pl-c1">0xFF</span>);</td> </tr> <tr> <td id="L425" class="blob-num js-line-number" data-line-number="425"></td> <td id="LC425" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L426" class="blob-num js-line-number" data-line-number="426"></td> <td id="LC426" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L427" class="blob-num js-line-number" data-line-number="427"></td> <td id="LC427" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(ADXL345_REG_INT_ENABLE, <span class="pl-c1">0xFF</span>);</td> </tr> <tr> <td id="L428" class="blob-num js-line-number" data-line-number="428"></td> <td id="LC428" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L429" class="blob-num js-line-number" data-line-number="429"></td> <td id="LC429" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L430" class="blob-num js-line-number" data-line-number="430"></td> <td id="LC430" class="blob-code blob-code-inner js-file-line">Activites <span class="pl-en">ADXL345::readActivites</span>(<span class="pl-k">void</span>)</td> </tr> <tr> <td id="L431" class="blob-num js-line-number" data-line-number="431"></td> <td id="LC431" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L432" class="blob-num js-line-number" data-line-number="432"></td> <td id="LC432" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> data = <span class="pl-c1">readRegister8</span>(ADXL345_REG_INT_SOURCE);</td> </tr> <tr> <td id="L433" class="blob-num js-line-number" data-line-number="433"></td> <td id="LC433" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L434" class="blob-num js-line-number" data-line-number="434"></td> <td id="LC434" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isOverrun</span> = ((data &gt;&gt; ADXL345_OVERRUN) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L435" class="blob-num js-line-number" data-line-number="435"></td> <td id="LC435" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isWatermark</span> = ((data &gt;&gt; ADXL345_WATERMARK) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L436" class="blob-num js-line-number" data-line-number="436"></td> <td id="LC436" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isFreeFall</span> = ((data &gt;&gt; ADXL345_FREE_FALL) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L437" class="blob-num js-line-number" data-line-number="437"></td> <td id="LC437" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isInactivity</span> = ((data &gt;&gt; ADXL345_INACTIVITY) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L438" class="blob-num js-line-number" data-line-number="438"></td> <td id="LC438" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isActivity</span> = ((data &gt;&gt; ADXL345_ACTIVITY) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L439" class="blob-num js-line-number" data-line-number="439"></td> <td id="LC439" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isDoubleTap</span> = ((data &gt;&gt; ADXL345_DOUBLE_TAP) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L440" class="blob-num js-line-number" data-line-number="440"></td> <td id="LC440" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isTap</span> = ((data &gt;&gt; ADXL345_SINGLE_TAP) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L441" class="blob-num js-line-number" data-line-number="441"></td> <td id="LC441" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isDataReady</span> = ((data &gt;&gt; ADXL345_DATA_READY) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L442" class="blob-num js-line-number" data-line-number="442"></td> <td id="LC442" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L443" class="blob-num js-line-number" data-line-number="443"></td> <td id="LC443" class="blob-code blob-code-inner js-file-line"> data = <span class="pl-c1">readRegister8</span>(ADXL345_REG_ACT_TAP_STATUS);</td> </tr> <tr> <td id="L444" class="blob-num js-line-number" data-line-number="444"></td> <td id="LC444" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L445" class="blob-num js-line-number" data-line-number="445"></td> <td id="LC445" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isActivityOnX</span> = ((data &gt;&gt; <span class="pl-c1">6</span>) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L446" class="blob-num js-line-number" data-line-number="446"></td> <td id="LC446" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isActivityOnY</span> = ((data &gt;&gt; <span class="pl-c1">5</span>) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L447" class="blob-num js-line-number" data-line-number="447"></td> <td id="LC447" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isActivityOnZ</span> = ((data &gt;&gt; <span class="pl-c1">4</span>) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L448" class="blob-num js-line-number" data-line-number="448"></td> <td id="LC448" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isTapOnX</span> = ((data &gt;&gt; <span class="pl-c1">2</span>) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L449" class="blob-num js-line-number" data-line-number="449"></td> <td id="LC449" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isTapOnY</span> = ((data &gt;&gt; <span class="pl-c1">1</span>) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L450" class="blob-num js-line-number" data-line-number="450"></td> <td id="LC450" class="blob-code blob-code-inner js-file-line"> a.<span class="pl-smi">isTapOnZ</span> = ((data &gt;&gt; <span class="pl-c1">0</span>) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L451" class="blob-num js-line-number" data-line-number="451"></td> <td id="LC451" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L452" class="blob-num js-line-number" data-line-number="452"></td> <td id="LC452" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> a;</td> </tr> <tr> <td id="L453" class="blob-num js-line-number" data-line-number="453"></td> <td id="LC453" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L454" class="blob-num js-line-number" data-line-number="454"></td> <td id="LC454" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L455" class="blob-num js-line-number" data-line-number="455"></td> <td id="LC455" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Write byte to register</span></td> </tr> <tr> <td id="L456" class="blob-num js-line-number" data-line-number="456"></td> <td id="LC456" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::writeRegister8</span>(<span class="pl-c1">uint8_t</span> reg, <span class="pl-c1">uint8_t</span> value)</td> </tr> <tr> <td id="L457" class="blob-num js-line-number" data-line-number="457"></td> <td id="LC457" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L458" class="blob-num js-line-number" data-line-number="458"></td> <td id="LC458" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(ADXL345_ADDRESS);</td> </tr> <tr> <td id="L459" class="blob-num js-line-number" data-line-number="459"></td> <td id="LC459" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L460" class="blob-num js-line-number" data-line-number="460"></td> <td id="LC460" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(reg);</td> </tr> <tr> <td id="L461" class="blob-num js-line-number" data-line-number="461"></td> <td id="LC461" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(value);</td> </tr> <tr> <td id="L462" class="blob-num js-line-number" data-line-number="462"></td> <td id="LC462" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L463" class="blob-num js-line-number" data-line-number="463"></td> <td id="LC463" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">send</span>(reg);</td> </tr> <tr> <td id="L464" class="blob-num js-line-number" data-line-number="464"></td> <td id="LC464" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">send</span>(value);</td> </tr> <tr> <td id="L465" class="blob-num js-line-number" data-line-number="465"></td> <td id="LC465" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span></td> </tr> <tr> <td id="L466" class="blob-num js-line-number" data-line-number="466"></td> <td id="LC466" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L467" class="blob-num js-line-number" data-line-number="467"></td> <td id="LC467" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L468" class="blob-num js-line-number" data-line-number="468"></td> <td id="LC468" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L469" class="blob-num js-line-number" data-line-number="469"></td> <td id="LC469" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Read byte to register</span></td> </tr> <tr> <td id="L470" class="blob-num js-line-number" data-line-number="470"></td> <td id="LC470" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">uint8_t</span> <span class="pl-en">ADXL345::fastRegister8</span>(<span class="pl-c1">uint8_t</span> reg)</td> </tr> <tr> <td id="L471" class="blob-num js-line-number" data-line-number="471"></td> <td id="LC471" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L472" class="blob-num js-line-number" data-line-number="472"></td> <td id="LC472" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L473" class="blob-num js-line-number" data-line-number="473"></td> <td id="LC473" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(ADXL345_ADDRESS);</td> </tr> <tr> <td id="L474" class="blob-num js-line-number" data-line-number="474"></td> <td id="LC474" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L475" class="blob-num js-line-number" data-line-number="475"></td> <td id="LC475" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(reg);</td> </tr> <tr> <td id="L476" class="blob-num js-line-number" data-line-number="476"></td> <td id="LC476" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L477" class="blob-num js-line-number" data-line-number="477"></td> <td id="LC477" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">send</span>(reg);</td> </tr> <tr> <td id="L478" class="blob-num js-line-number" data-line-number="478"></td> <td id="LC478" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span></td> </tr> <tr> <td id="L479" class="blob-num js-line-number" data-line-number="479"></td> <td id="LC479" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L480" class="blob-num js-line-number" data-line-number="480"></td> <td id="LC480" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L481" class="blob-num js-line-number" data-line-number="481"></td> <td id="LC481" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">requestFrom</span>(ADXL345_ADDRESS, <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L482" class="blob-num js-line-number" data-line-number="482"></td> <td id="LC482" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L483" class="blob-num js-line-number" data-line-number="483"></td> <td id="LC483" class="blob-code blob-code-inner js-file-line"> value = Wire.<span class="pl-c1">read</span>();</td> </tr> <tr> <td id="L484" class="blob-num js-line-number" data-line-number="484"></td> <td id="LC484" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L485" class="blob-num js-line-number" data-line-number="485"></td> <td id="LC485" class="blob-code blob-code-inner js-file-line"> value = Wire.<span class="pl-c1">receive</span>();</td> </tr> <tr> <td id="L486" class="blob-num js-line-number" data-line-number="486"></td> <td id="LC486" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span>;</td> </tr> <tr> <td id="L487" class="blob-num js-line-number" data-line-number="487"></td> <td id="LC487" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L488" class="blob-num js-line-number" data-line-number="488"></td> <td id="LC488" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L489" class="blob-num js-line-number" data-line-number="489"></td> <td id="LC489" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> value;</td> </tr> <tr> <td id="L490" class="blob-num js-line-number" data-line-number="490"></td> <td id="LC490" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L491" class="blob-num js-line-number" data-line-number="491"></td> <td id="LC491" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L492" class="blob-num js-line-number" data-line-number="492"></td> <td id="LC492" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Read byte from register</span></td> </tr> <tr> <td id="L493" class="blob-num js-line-number" data-line-number="493"></td> <td id="LC493" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">uint8_t</span> <span class="pl-en">ADXL345::readRegister8</span>(<span class="pl-c1">uint8_t</span> reg)</td> </tr> <tr> <td id="L494" class="blob-num js-line-number" data-line-number="494"></td> <td id="LC494" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L495" class="blob-num js-line-number" data-line-number="495"></td> <td id="LC495" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L496" class="blob-num js-line-number" data-line-number="496"></td> <td id="LC496" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(ADXL345_ADDRESS);</td> </tr> <tr> <td id="L497" class="blob-num js-line-number" data-line-number="497"></td> <td id="LC497" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L498" class="blob-num js-line-number" data-line-number="498"></td> <td id="LC498" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(reg);</td> </tr> <tr> <td id="L499" class="blob-num js-line-number" data-line-number="499"></td> <td id="LC499" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L500" class="blob-num js-line-number" data-line-number="500"></td> <td id="LC500" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">send</span>(reg);</td> </tr> <tr> <td id="L501" class="blob-num js-line-number" data-line-number="501"></td> <td id="LC501" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span></td> </tr> <tr> <td id="L502" class="blob-num js-line-number" data-line-number="502"></td> <td id="LC502" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L503" class="blob-num js-line-number" data-line-number="503"></td> <td id="LC503" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L504" class="blob-num js-line-number" data-line-number="504"></td> <td id="LC504" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(ADXL345_ADDRESS);</td> </tr> <tr> <td id="L505" class="blob-num js-line-number" data-line-number="505"></td> <td id="LC505" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">requestFrom</span>(ADXL345_ADDRESS, <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L506" class="blob-num js-line-number" data-line-number="506"></td> <td id="LC506" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">while</span>(!Wire.<span class="pl-c1">available</span>()) {};</td> </tr> <tr> <td id="L507" class="blob-num js-line-number" data-line-number="507"></td> <td id="LC507" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L508" class="blob-num js-line-number" data-line-number="508"></td> <td id="LC508" class="blob-code blob-code-inner js-file-line"> value = Wire.<span class="pl-c1">read</span>();</td> </tr> <tr> <td id="L509" class="blob-num js-line-number" data-line-number="509"></td> <td id="LC509" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L510" class="blob-num js-line-number" data-line-number="510"></td> <td id="LC510" class="blob-code blob-code-inner js-file-line"> value = Wire.<span class="pl-c1">receive</span>();</td> </tr> <tr> <td id="L511" class="blob-num js-line-number" data-line-number="511"></td> <td id="LC511" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span>;</td> </tr> <tr> <td id="L512" class="blob-num js-line-number" data-line-number="512"></td> <td id="LC512" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L513" class="blob-num js-line-number" data-line-number="513"></td> <td id="LC513" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L514" class="blob-num js-line-number" data-line-number="514"></td> <td id="LC514" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> value;</td> </tr> <tr> <td id="L515" class="blob-num js-line-number" data-line-number="515"></td> <td id="LC515" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L516" class="blob-num js-line-number" data-line-number="516"></td> <td id="LC516" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L517" class="blob-num js-line-number" data-line-number="517"></td> <td id="LC517" class="blob-code blob-code-inner js-file-line"><span class="pl-c"><span class="pl-c">//</span> Read word from register</span></td> </tr> <tr> <td id="L518" class="blob-num js-line-number" data-line-number="518"></td> <td id="LC518" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">int16_t</span> <span class="pl-en">ADXL345::readRegister16</span>(<span class="pl-c1">uint8_t</span> reg)</td> </tr> <tr> <td id="L519" class="blob-num js-line-number" data-line-number="519"></td> <td id="LC519" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L520" class="blob-num js-line-number" data-line-number="520"></td> <td id="LC520" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">int16_t</span> value;</td> </tr> <tr> <td id="L521" class="blob-num js-line-number" data-line-number="521"></td> <td id="LC521" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(ADXL345_ADDRESS);</td> </tr> <tr> <td id="L522" class="blob-num js-line-number" data-line-number="522"></td> <td id="LC522" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L523" class="blob-num js-line-number" data-line-number="523"></td> <td id="LC523" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">write</span>(reg);</td> </tr> <tr> <td id="L524" class="blob-num js-line-number" data-line-number="524"></td> <td id="LC524" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L525" class="blob-num js-line-number" data-line-number="525"></td> <td id="LC525" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">send</span>(reg);</td> </tr> <tr> <td id="L526" class="blob-num js-line-number" data-line-number="526"></td> <td id="LC526" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span></td> </tr> <tr> <td id="L527" class="blob-num js-line-number" data-line-number="527"></td> <td id="LC527" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L528" class="blob-num js-line-number" data-line-number="528"></td> <td id="LC528" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L529" class="blob-num js-line-number" data-line-number="529"></td> <td id="LC529" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">beginTransmission</span>(ADXL345_ADDRESS);</td> </tr> <tr> <td id="L530" class="blob-num js-line-number" data-line-number="530"></td> <td id="LC530" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">requestFrom</span>(ADXL345_ADDRESS, <span class="pl-c1">2</span>);</td> </tr> <tr> <td id="L531" class="blob-num js-line-number" data-line-number="531"></td> <td id="LC531" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">while</span>(!Wire.<span class="pl-c1">available</span>()) {};</td> </tr> <tr> <td id="L532" class="blob-num js-line-number" data-line-number="532"></td> <td id="LC532" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">if</span> ARDUINO &gt;= 100</td> </tr> <tr> <td id="L533" class="blob-num js-line-number" data-line-number="533"></td> <td id="LC533" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> vla = Wire.<span class="pl-c1">read</span>();</td> </tr> <tr> <td id="L534" class="blob-num js-line-number" data-line-number="534"></td> <td id="LC534" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> vha = Wire.<span class="pl-c1">read</span>();</td> </tr> <tr> <td id="L535" class="blob-num js-line-number" data-line-number="535"></td> <td id="LC535" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">else</span></td> </tr> <tr> <td id="L536" class="blob-num js-line-number" data-line-number="536"></td> <td id="LC536" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> vla = Wire.<span class="pl-c1">receive</span>();</td> </tr> <tr> <td id="L537" class="blob-num js-line-number" data-line-number="537"></td> <td id="LC537" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> vha = Wire.<span class="pl-c1">receive</span>();</td> </tr> <tr> <td id="L538" class="blob-num js-line-number" data-line-number="538"></td> <td id="LC538" class="blob-code blob-code-inner js-file-line"> #<span class="pl-k">endif</span>;</td> </tr> <tr> <td id="L539" class="blob-num js-line-number" data-line-number="539"></td> <td id="LC539" class="blob-code blob-code-inner js-file-line"> Wire.<span class="pl-c1">endTransmission</span>();</td> </tr> <tr> <td id="L540" class="blob-num js-line-number" data-line-number="540"></td> <td id="LC540" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L541" class="blob-num js-line-number" data-line-number="541"></td> <td id="LC541" class="blob-code blob-code-inner js-file-line"> value = vha &lt;&lt; <span class="pl-c1">8</span> | vla;</td> </tr> <tr> <td id="L542" class="blob-num js-line-number" data-line-number="542"></td> <td id="LC542" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L543" class="blob-num js-line-number" data-line-number="543"></td> <td id="LC543" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> value;</td> </tr> <tr> <td id="L544" class="blob-num js-line-number" data-line-number="544"></td> <td id="LC544" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L545" class="blob-num js-line-number" data-line-number="545"></td> <td id="LC545" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L546" class="blob-num js-line-number" data-line-number="546"></td> <td id="LC546" class="blob-code blob-code-inner js-file-line"><span class="pl-k">void</span> <span class="pl-en">ADXL345::writeRegisterBit</span>(<span class="pl-c1">uint8_t</span> reg, <span class="pl-c1">uint8_t</span> pos, <span class="pl-k">bool</span> state)</td> </tr> <tr> <td id="L547" class="blob-num js-line-number" data-line-number="547"></td> <td id="LC547" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L548" class="blob-num js-line-number" data-line-number="548"></td> <td id="LC548" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L549" class="blob-num js-line-number" data-line-number="549"></td> <td id="LC549" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(reg);</td> </tr> <tr> <td id="L550" class="blob-num js-line-number" data-line-number="550"></td> <td id="LC550" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L551" class="blob-num js-line-number" data-line-number="551"></td> <td id="LC551" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> (state)</td> </tr> <tr> <td id="L552" class="blob-num js-line-number" data-line-number="552"></td> <td id="LC552" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L553" class="blob-num js-line-number" data-line-number="553"></td> <td id="LC553" class="blob-code blob-code-inner js-file-line"> value |= (<span class="pl-c1">1</span> &lt;&lt; pos);</td> </tr> <tr> <td id="L554" class="blob-num js-line-number" data-line-number="554"></td> <td id="LC554" class="blob-code blob-code-inner js-file-line"> } <span class="pl-k">else</span> </td> </tr> <tr> <td id="L555" class="blob-num js-line-number" data-line-number="555"></td> <td id="LC555" class="blob-code blob-code-inner js-file-line"> {</td> </tr> <tr> <td id="L556" class="blob-num js-line-number" data-line-number="556"></td> <td id="LC556" class="blob-code blob-code-inner js-file-line"> value &amp;= ~(<span class="pl-c1">1</span> &lt;&lt; pos);</td> </tr> <tr> <td id="L557" class="blob-num js-line-number" data-line-number="557"></td> <td id="LC557" class="blob-code blob-code-inner js-file-line"> }</td> </tr> <tr> <td id="L558" class="blob-num js-line-number" data-line-number="558"></td> <td id="LC558" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L559" class="blob-num js-line-number" data-line-number="559"></td> <td id="LC559" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">writeRegister8</span>(reg, value);</td> </tr> <tr> <td id="L560" class="blob-num js-line-number" data-line-number="560"></td> <td id="LC560" class="blob-code blob-code-inner js-file-line">}</td> </tr> <tr> <td id="L561" class="blob-num js-line-number" data-line-number="561"></td> <td id="LC561" class="blob-code blob-code-inner js-file-line"> </td> </tr> <tr> <td id="L562" class="blob-num js-line-number" data-line-number="562"></td> <td id="LC562" class="blob-code blob-code-inner js-file-line"><span class="pl-k">bool</span> <span class="pl-en">ADXL345::readRegisterBit</span>(<span class="pl-c1">uint8_t</span> reg, <span class="pl-c1">uint8_t</span> pos)</td> </tr> <tr> <td id="L563" class="blob-num js-line-number" data-line-number="563"></td> <td id="LC563" class="blob-code blob-code-inner js-file-line">{</td> </tr> <tr> <td id="L564" class="blob-num js-line-number" data-line-number="564"></td> <td id="LC564" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">uint8_t</span> value;</td> </tr> <tr> <td id="L565" class="blob-num js-line-number" data-line-number="565"></td> <td id="LC565" class="blob-code blob-code-inner js-file-line"> value = <span class="pl-c1">readRegister8</span>(reg);</td> </tr> <tr> <td id="L566" class="blob-num js-line-number" data-line-number="566"></td> <td id="LC566" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> ((value &gt;&gt; pos) &amp; <span class="pl-c1">1</span>);</td> </tr> <tr> <td id="L567" class="blob-num js-line-number" data-line-number="567"></td> <td id="LC567" class="blob-code blob-code-inner js-file-line">}</td> </tr> </table> <details class="details-reset details-overlay BlobToolbar position-absolute js-file-line-actions dropdown d-none" aria-hidden="true"> <summary class="btn-octicon ml-0 px-2 p-0 bg-white border border-gray-dark rounded-1" aria-label="Inline file action toolbar"> <svg class="octicon octicon-kebab-horizontal" viewBox="0 0 13 16" version="1.1" width="13" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M1.5 9a1.5 1.5 0 100-3 1.5 1.5 0 000 3zm5 0a1.5 1.5 0 100-3 1.5 1.5 0 000 3zM13 7.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0z"/></svg> </summary> <details-menu> <ul class="BlobToolbar-dropdown dropdown-menu dropdown-menu-se mt-2" style="width:185px"> <li> <clipboard-copy role="menuitem" class="dropdown-item" id="js-copy-lines" style="cursor:pointer;"> Copy lines </clipboard-copy> </li> <li> <clipboard-copy role="menuitem" class="dropdown-item" id="js-copy-permalink" style="cursor:pointer;"> Copy permalink </clipboard-copy> </li> <li><a class="dropdown-item js-update-url-with-hash" id="js-view-git-blame" role="menuitem" href="/jarzebski/Arduino-ADXL345/blame/37c67cdcf648d92ef608d4a4001edbdbc03c4ac4/ADXL345.cpp">View git blame</a></li> <li><a class="dropdown-item" id="js-new-issue" role="menuitem" href="/jarzebski/Arduino-ADXL345/issues/new">Reference in new issue</a></li> </ul> </details-menu> </details> </div> </div> <details class="details-reset details-overlay details-overlay-dark"> <summary data-hotkey="l" aria-label="Jump to line"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast linejump" aria-label="Jump to line"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="js-jump-to-line-form Box-body d-flex" action="" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="&#x2713;" /> <input class="form-control flex-auto mr-3 linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line&hellip;" aria-label="Jump to line" autofocus> <button type="submit" class="btn" data-close-dialog>Go</button> </form> </details-dialog> </details> </div> </div> </main> </div> </div> <div class="footer container-lg width-full p-responsive" role="contentinfo"> <div class="position-relative d-flex flex-row-reverse flex-lg-row flex-wrap flex-lg-nowrap flex-justify-center flex-lg-justify-between pt-6 pb-2 mt-6 f6 text-gray border-top border-gray-light "> <ul class="list-style-none d-flex flex-wrap col-12 col-lg-5 flex-justify-center flex-lg-justify-between mb-2 mb-lg-0"> <li class="mr-3 mr-lg-0">&copy; 2020 GitHub, Inc.</li> <li class="mr-3 mr-lg-0"><a data-ga-click="Footer, go to terms, text:terms" href="https://github.com/site/terms">Terms</a></li> <li class="mr-3 mr-lg-0"><a data-ga-click="Footer, go to privacy, text:privacy" href="https://github.com/site/privacy">Privacy</a></li> <li class="mr-3 mr-lg-0"><a data-ga-click="Footer, go to security, text:security" href="https://github.com/security">Security</a></li> <li class="mr-3 mr-lg-0"><a href="https://githubstatus.com/" data-ga-click="Footer, go to status, text:status">Status</a></li> <li><a data-ga-click="Footer, go to help, text:help" href="https://help.github.com">Help</a></li> </ul> <a aria-label="Homepage" title="GitHub" class="footer-octicon d-none d-lg-block mx-lg-4" href="https://github.com"> <svg height="24" class="octicon octicon-mark-github" viewBox="0 0 16 16" version="1.1" width="24" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg> </a> <ul class="list-style-none d-flex flex-wrap col-12 col-lg-5 flex-justify-center flex-lg-justify-between mb-2 mb-lg-0"> <li class="mr-3 mr-lg-0"><a data-ga-click="Footer, go to contact, text:contact" href="https://github.com/contact">Contact GitHub</a></li> <li class="mr-3 mr-lg-0"><a href="https://github.com/pricing" data-ga-click="Footer, go to Pricing, text:Pricing">Pricing</a></li> <li class="mr-3 mr-lg-0"><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li> <li class="mr-3 mr-lg-0"><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li> <li class="mr-3 mr-lg-0"><a href="https://github.blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li> <li><a data-ga-click="Footer, go to about, text:about" href="https://github.com/about">About</a></li> </ul> </div> <div class="d-flex flex-justify-center pb-6"> <span class="f6 text-gray-light"></span> </div> </div> <div id="ajax-error-message" class="ajax-error-message flash flash-error"> <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 000 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 00.01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"/></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> </button> You can’t perform that action at this time. </div> <script crossorigin="anonymous" integrity="sha512-44n3wlGLuUccx54xJCLuPnISUrN43Yp0sjk/Hv2yNTT0J0Cpt/pwdOoBajrT0yBBx7R2yqHMx2GeyvewiI1b1g==" type="application/javascript" src="https://github.githubassets.com/assets/compat-bootstrap-e389f7c2.js"></script> <script crossorigin="anonymous" integrity="sha512-mPag4dGrRHQ/tlJ2Ak20l1qtSfbXAgC4cK6/A6/HIPnpDmCmCI+FndqFWX3PntWBg1tv7i/y9eouyuHXOFr8OA==" type="application/javascript" src="https://github.githubassets.com/assets/frameworks-98f6a0e1.js"></script> <script crossorigin="anonymous" async="async" integrity="sha512-Og2wAC3ikUw0UeqHah3MJOf4Plped6TKtx1MAS5JoiLWQgigj/VbQtf+I0ZfvlEcliDAlR4ky1lohHxMjG+isA==" type="application/javascript" src="https://github.githubassets.com/assets/github-bootstrap-3a0db000.js"></script> <div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg class="octicon octicon-alert" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 000 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 00.01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z"/></svg> <span class="js-stale-session-flash-signed-in" hidden>You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span> <span class="js-stale-session-flash-signed-out" hidden>You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default text-gray-dark hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"/></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details> </template> <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box box-shadow-large" style="width:360px;"> </div> </div> <div class="js-notification-shelf-not-found-error" hidden></div> <div aria-live="polite" class="js-global-screen-reader-notice sr-only"></div> </body> </html>
61.613693
1,547
0.619922
[ "object", "vector", "solid" ]
974ea6163cb4e603aa647793697cb6fc0ec0443a
1,931
hpp
C++
libecole/include/ecole/environment/dynamics.hpp
lascavana/ecole
fc6ef27110f9eba9072ed303e8430a5184534eaf
[ "BSD-3-Clause" ]
null
null
null
libecole/include/ecole/environment/dynamics.hpp
lascavana/ecole
fc6ef27110f9eba9072ed303e8430a5184534eaf
[ "BSD-3-Clause" ]
null
null
null
libecole/include/ecole/environment/dynamics.hpp
lascavana/ecole
fc6ef27110f9eba9072ed303e8430a5184534eaf
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <random> #include <tuple> #include "ecole/scip/model.hpp" #include "ecole/scip/type.hpp" namespace ecole { namespace environment { using RandomEngine = std::mt19937; /** * Abstract class for environment Dynamics. * * A subclass defines the dynamics of the environment, that is the initial probability * distribution and state transition. * In other words, it defines an environment wihtout observations or rewards. * This class is used by @ref EnvironmentComposer to create the final environment with * state functions. * * @tparam Action The type of action recived by the environment. * @tparam ActionSet The type used to indicate what actions are accepted on the next * transtion. */ template <typename Action, typename ActionSet> class EnvironmentDynamics { public: virtual ~EnvironmentDynamics() = default; /** * Set random elements of the dynamics for the current episode. */ virtual void set_dynamics_random_state(scip::Model& model, RandomEngine& random_engine) { std::uniform_int_distribution<scip::Seed> seed_distrib{scip::min_seed, scip::max_seed}; model.set_param("randomization/permuteconss", true); model.set_param("randomization/permutevars", true); model.set_param("randomization/permutationseed", seed_distrib(random_engine)); model.set_param("randomization/randomseedshift", seed_distrib(random_engine)); model.set_param("randomization/lpseed", seed_distrib(random_engine)); } /** * Reset the Model to a new initial state. * * This method called by the environment on @ref Environment::reset. */ virtual std::tuple<bool, ActionSet> reset_dynamics(scip::Model& model) = 0; /** * Transition the Model. * * This method called by the environment on @ref Environment::step. */ virtual std::tuple<bool, ActionSet> step_dynamics(scip::Model& model, Action const& action) = 0; }; } // namespace environment } // namespace ecole
31.655738
97
0.747281
[ "model" ]
975186cdc5700de18c97e1f8e9bfe99a96ebf624
1,786
cpp
C++
online-judge/10189.cpp
kirillgashkov/cp-solutions
863603b076e94b324b0d44a9adff4099e3131513
[ "MIT" ]
null
null
null
online-judge/10189.cpp
kirillgashkov/cp-solutions
863603b076e94b324b0d44a9adff4099e3131513
[ "MIT" ]
null
null
null
online-judge/10189.cpp
kirillgashkov/cp-solutions
863603b076e94b324b0d44a9adff4099e3131513
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; #define vi vector<int> #define vvi vector<vi> void handle_mine(int& i, int& j, vvi& field, int& n, int& m) { vi i_list = {i-1, i, i+1, i-1, i+1, i-1, i, i+1}; vi j_list = {j-1, j-1, j-1, j, j, j+1, j+1, j+1}; for (int l = 0; l < 8; ++l) { int t_i = i_list[l]; int t_j = j_list[l]; if (t_i < 0 or t_i >= n) continue; if (t_j < 0 or t_j >= m) continue; if (field[t_i][t_j] != -1) { ++field[t_i][t_j]; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int case_count = 0; while (true) { ++case_count; int n, m; cin >> n >> m; if (n == 0 and m == 0) { break; } if (case_count != 1) cout << '\n'; cout << "Field #" << case_count << ":\n"; vvi field; for (int i = 0; i < n; ++i) { vi row; for (int j = 0; j < m; ++j) { char el; cin >> el; if (el == '*') { row.push_back(-1); } else { row.push_back(0); } } field.push_back(row); } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (field[i][j] == -1) { handle_mine(i, j, field, n, m); } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (field[i][j] == -1) { cout << '*'; } else { cout << field[i][j]; } } cout << '\n'; } } }
21.261905
62
0.342665
[ "vector" ]
9754a7fda610957b447e3eb7f155ab85a4137990
50,239
hxx
C++
include/__config.hxx
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
include/__config.hxx
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
include/__config.hxx
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
// -*- C++ -*- //===--------------------------- __config ---------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_CONFIG #define _LIBCPP_CONFIG #if defined(_MSC_VER) && !defined(__clang__) # if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # define _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER # endif #endif #ifndef _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER #pragma GCC system_header #endif #ifdef __cplusplus #ifdef __GNUC__ # define _GNUC_VER (__GNUC__ * 100 + __GNUC_MINOR__) // The _GNUC_VER_NEW macro better represents the new GCC versioning scheme // introduced in GCC 5.0. # define _GNUC_VER_NEW (_GNUC_VER * 10 + __GNUC_PATCHLEVEL__) #else # define _GNUC_VER 0 # define _GNUC_VER_NEW 0 #endif #define _LIBCPP_VERSION 10000 #ifndef _LIBCPP_ABI_VERSION # define _LIBCPP_ABI_VERSION 1 #endif #ifndef __STDC_HOSTED__ # define _LIBCPP_FREESTANDING #endif #ifndef _LIBCPP_STD_VER # if __cplusplus <= 201103L # define _LIBCPP_STD_VER 11 # elif __cplusplus <= 201402L # define _LIBCPP_STD_VER 14 # elif __cplusplus <= 201703L # define _LIBCPP_STD_VER 17 # else # define _LIBCPP_STD_VER 18 // current year, or date of c++2a ratification # endif #endif // _LIBCPP_STD_VER #if defined(__ELF__) # define _LIBCPP_OBJECT_FORMAT_ELF 1 #elif defined(__MACH__) # define _LIBCPP_OBJECT_FORMAT_MACHO 1 #elif defined(_WIN32) # define _LIBCPP_OBJECT_FORMAT_COFF 1 #elif defined(__wasm__) # define _LIBCPP_OBJECT_FORMAT_WASM 1 #else # error Unknown object file format #endif #if defined(_LIBCPP_ABI_UNSTABLE) || _LIBCPP_ABI_VERSION >= 2 // Change short string representation so that string data starts at offset 0, // improving its alignment in some cases. # define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT // Fix deque iterator type in order to support incomplete types. # define _LIBCPP_ABI_INCOMPLETE_TYPES_IN_DEQUE // Fix undefined behavior in how std::list stores its linked nodes. # define _LIBCPP_ABI_LIST_REMOVE_NODE_POINTER_UB // Fix undefined behavior in how __tree stores its end and parent nodes. # define _LIBCPP_ABI_TREE_REMOVE_NODE_POINTER_UB // Fix undefined behavior in how __hash_table stores its pointer types. # define _LIBCPP_ABI_FIX_UNORDERED_NODE_POINTER_UB # define _LIBCPP_ABI_FORWARD_LIST_REMOVE_NODE_POINTER_UB # define _LIBCPP_ABI_FIX_UNORDERED_CONTAINER_SIZE_TYPE // Don't use a nullptr_t simulation type in C++03 instead using C++11 nullptr // provided under the alternate keyword __nullptr, which changes the mangling // of nullptr_t. This option is ABI incompatible with GCC in C++03 mode. # define _LIBCPP_ABI_ALWAYS_USE_CXX11_NULLPTR // Define the `pointer_safety` enum as a C++11 strongly typed enumeration // instead of as a class simulating an enum. If this option is enabled // `pointer_safety` and `get_pointer_safety()` will no longer be available // in C++03. # define _LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE // Define a key function for `bad_function_call` in the library, to centralize // its vtable and typeinfo to libc++ rather than having all other libraries // using that class define their own copies. # define _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION // Enable optimized version of __do_get_(un)signed which avoids redundant copies. # define _LIBCPP_ABI_OPTIMIZED_LOCALE_NUM_GET // Use the smallest possible integer type to represent the index of the variant. // Previously libc++ used "unsigned int" exclusively. # define _LIBCPP_ABI_VARIANT_INDEX_TYPE_OPTIMIZATION // Unstable attempt to provide a more optimized std::function # define _LIBCPP_ABI_OPTIMIZED_FUNCTION // All the regex constants must be distinct and nonzero. # define _LIBCPP_ABI_REGEX_CONSTANTS_NONZERO #elif _LIBCPP_ABI_VERSION == 1 # if !defined(_LIBCPP_OBJECT_FORMAT_COFF) // Enable compiling copies of now inline methods into the dylib to support // applications compiled against older libraries. This is unnecessary with // COFF dllexport semantics, since dllexport forces a non-inline definition // of inline functions to be emitted anyway. Our own non-inline copy would // conflict with the dllexport-emitted copy, so we disable it. # define _LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS # endif // Feature macros for disabling pre ABI v1 features. All of these options // are deprecated. # if defined(__FreeBSD__) # define _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR # endif #endif #ifdef _LIBCPP_TRIVIAL_PAIR_COPY_CTOR #error "_LIBCPP_TRIVIAL_PAIR_COPY_CTOR" is no longer supported. \ use _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR instead #endif #define _LIBCPP_CONCAT1(_LIBCPP_X,_LIBCPP_Y) _LIBCPP_X##_LIBCPP_Y #define _LIBCPP_CONCAT(_LIBCPP_X,_LIBCPP_Y) _LIBCPP_CONCAT1(_LIBCPP_X,_LIBCPP_Y) #ifndef _LIBCPP_ABI_NAMESPACE # define _LIBCPP_ABI_NAMESPACE _LIBCPP_CONCAT(__,_LIBCPP_ABI_VERSION) #endif #if __cplusplus < 201103L #define _LIBCPP_CXX03_LANG #endif #ifndef __has_attribute #define __has_attribute(__x) 0 #endif #ifndef __has_builtin #define __has_builtin(__x) 0 #endif #ifndef __has_extension #define __has_extension(__x) 0 #endif #ifndef __has_feature #define __has_feature(__x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(__x) 0 #endif // '__is_identifier' returns '0' if '__x' is a reserved identifier provided by // the compiler and '1' otherwise. #ifndef __is_identifier #define __is_identifier(__x) 1 #endif #ifndef __has_declspec_attribute #define __has_declspec_attribute(__x) 0 #endif #define __has_keyword(__x) !(__is_identifier(__x)) #ifndef __has_include #define __has_include(...) 0 #endif #if defined(__clang__) # define _LIBCPP_COMPILER_CLANG # ifndef __apple_build_version__ # define _LIBCPP_CLANG_VER (__clang_major__ * 100 + __clang_minor__) # endif #elif defined(__GNUC__) # define _LIBCPP_COMPILER_GCC #elif defined(_MSC_VER) # define _LIBCPP_COMPILER_MSVC #elif defined(__IBMCPP__) # define _LIBCPP_COMPILER_IBM #endif #if defined(_LIBCPP_COMPILER_GCC) && __cplusplus < 201103L #error "libc++ does not support using GCC with C++03. Please enable C++11" #endif // FIXME: ABI detection should be done via compiler builtin macros. This // is just a placeholder until Clang implements such macros. For now assume // that Windows compilers pretending to be MSVC++ target the Microsoft ABI, // and allow the user to explicitly specify the ABI to handle cases where this // heuristic falls short. #if defined(_LIBCPP_ABI_FORCE_ITANIUM) && defined(_LIBCPP_ABI_FORCE_MICROSOFT) # error "Only one of _LIBCPP_ABI_FORCE_ITANIUM and _LIBCPP_ABI_FORCE_MICROSOFT can be defined" #elif defined(_LIBCPP_ABI_FORCE_ITANIUM) # define _LIBCPP_ABI_ITANIUM #elif defined(_LIBCPP_ABI_FORCE_MICROSOFT) # define _LIBCPP_ABI_MICROSOFT #else # if defined(_WIN32) && defined(_MSC_VER) # define _LIBCPP_ABI_MICROSOFT # else # define _LIBCPP_ABI_ITANIUM # endif #endif #if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_NO_VCRUNTIME) # define _LIBCPP_ABI_VCRUNTIME #endif // Need to detect which libc we're using if we're on Linux. #if defined(__linux__) # include <features.h> # if defined(__GLIBC_PREREQ) # define _LIBCPP_GLIBC_PREREQ(a, b) __GLIBC_PREREQ(a, b) # else # define _LIBCPP_GLIBC_PREREQ(a, b) 0 # endif // defined(__GLIBC_PREREQ) #endif // defined(__linux__) #ifdef __LITTLE_ENDIAN__ # if __LITTLE_ENDIAN__ # define _LIBCPP_LITTLE_ENDIAN # endif // __LITTLE_ENDIAN__ #endif // __LITTLE_ENDIAN__ #ifdef __BIG_ENDIAN__ # if __BIG_ENDIAN__ # define _LIBCPP_BIG_ENDIAN # endif // __BIG_ENDIAN__ #endif // __BIG_ENDIAN__ #ifdef __BYTE_ORDER__ # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define _LIBCPP_LITTLE_ENDIAN # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ # define _LIBCPP_BIG_ENDIAN # endif // __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #endif // __BYTE_ORDER__ #ifdef __FreeBSD__ # include <sys/endian.h> # if _BYTE_ORDER == _LITTLE_ENDIAN # define _LIBCPP_LITTLE_ENDIAN # else // _BYTE_ORDER == _LITTLE_ENDIAN # define _LIBCPP_BIG_ENDIAN # endif // _BYTE_ORDER == _LITTLE_ENDIAN # ifndef __LONG_LONG_SUPPORTED # define _LIBCPP_HAS_NO_LONG_LONG # endif // __LONG_LONG_SUPPORTED #endif // __FreeBSD__ #ifdef __NetBSD__ # include <sys/endian.h> # if _BYTE_ORDER == _LITTLE_ENDIAN # define _LIBCPP_LITTLE_ENDIAN # else // _BYTE_ORDER == _LITTLE_ENDIAN # define _LIBCPP_BIG_ENDIAN # endif // _BYTE_ORDER == _LITTLE_ENDIAN # define _LIBCPP_HAS_QUICK_EXIT #endif // __NetBSD__ #if defined(_WIN32) # define _LIBCPP_WIN32API # define _LIBCPP_LITTLE_ENDIAN # define _LIBCPP_SHORT_WCHAR 1 // Both MinGW and native MSVC provide a "MSVC"-like environment # define _LIBCPP_MSVCRT_LIKE // If mingw not explicitly detected, assume using MS C runtime only if // a MS compatibility version is specified. # if defined(_MSC_VER) && !defined(__MINGW32__) # define _LIBCPP_MSVCRT // Using Microsoft's C Runtime library # endif # if (defined(_M_AMD64) || defined(__x86_64__)) || (defined(_M_ARM) || defined(__arm__)) # define _LIBCPP_HAS_BITSCAN64 # endif # define _LIBCPP_HAS_OPEN_WITH_WCHAR # if defined(_LIBCPP_MSVCRT) # define _LIBCPP_HAS_QUICK_EXIT # endif // Some CRT APIs are unavailable to store apps # if defined(WINAPI_FAMILY) # include <winapifamily.h> # if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && \ (!defined(WINAPI_PARTITION_SYSTEM) || \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_SYSTEM)) # define _LIBCPP_WINDOWS_STORE_APP # endif # endif #endif // defined(_WIN32) #ifdef __sun__ # include <sys/isa_defs.h> # ifdef _LITTLE_ENDIAN # define _LIBCPP_LITTLE_ENDIAN # else # define _LIBCPP_BIG_ENDIAN # endif #endif // __sun__ #if defined(__CloudABI__) // Certain architectures provide arc4random(). Prefer using // arc4random() over /dev/{u,}random to make it possible to obtain // random data even when using sandboxing mechanisms such as chroots, // Capsicum, etc. # define _LIBCPP_USING_ARC4_RANDOM #elif defined(__Fuchsia__) || defined(__wasi__) # define _LIBCPP_USING_GETENTROPY #elif defined(__native_client__) // NaCl's sandbox (which PNaCl also runs in) doesn't allow filesystem access, // including accesses to the special files under /dev. C++11's // std::random_device is instead exposed through a NaCl syscall. # define _LIBCPP_USING_NACL_RANDOM #elif defined(_LIBCPP_WIN32API) # define _LIBCPP_USING_WIN32_RANDOM #else # define _LIBCPP_USING_DEV_RANDOM #endif #if !defined(_LIBCPP_LITTLE_ENDIAN) && !defined(_LIBCPP_BIG_ENDIAN) # include <endian.h> # if __BYTE_ORDER == __LITTLE_ENDIAN # define _LIBCPP_LITTLE_ENDIAN # elif __BYTE_ORDER == __BIG_ENDIAN # define _LIBCPP_BIG_ENDIAN # else // __BYTE_ORDER == __BIG_ENDIAN # error unable to determine endian # endif #endif // !defined(_LIBCPP_LITTLE_ENDIAN) && !defined(_LIBCPP_BIG_ENDIAN) #if __has_attribute(__no_sanitize__) && !defined(_LIBCPP_COMPILER_GCC) # define _LIBCPP_NO_CFI __attribute__((__no_sanitize__("cfi"))) #else # define _LIBCPP_NO_CFI #endif #if __ISO_C_VISIBLE >= 2011 || __cplusplus >= 201103L # if defined(__FreeBSD__) # define _LIBCPP_HAS_QUICK_EXIT # define _LIBCPP_HAS_C11_FEATURES # elif defined(__Fuchsia__) || defined(__wasi__) # define _LIBCPP_HAS_QUICK_EXIT # define _LIBCPP_HAS_TIMESPEC_GET # define _LIBCPP_HAS_C11_FEATURES # elif defined(__linux__) # if !defined(_LIBCPP_HAS_MUSL_LIBC) # if _LIBCPP_GLIBC_PREREQ(2, 15) || defined(__BIONIC__) # define _LIBCPP_HAS_QUICK_EXIT # endif # if _LIBCPP_GLIBC_PREREQ(2, 17) # define _LIBCPP_HAS_C11_FEATURES # define _LIBCPP_HAS_TIMESPEC_GET # endif # else // defined(_LIBCPP_HAS_MUSL_LIBC) # define _LIBCPP_HAS_QUICK_EXIT # define _LIBCPP_HAS_TIMESPEC_GET # define _LIBCPP_HAS_C11_FEATURES # endif # endif // __linux__ #endif #ifndef _LIBCPP_CXX03_LANG # define _LIBCPP_ALIGNOF(_Tp) alignof(_Tp) #elif defined(_LIBCPP_COMPILER_CLANG) # define _LIBCPP_ALIGNOF(_Tp) _Alignof(_Tp) #else // This definition is potentially buggy, but it's only taken with GCC in C++03, // which we barely support anyway. See llvm.org/PR39713 # define _LIBCPP_ALIGNOF(_Tp) __alignof(_Tp) #endif #define _LIBCPP_PREFERRED_ALIGNOF(_Tp) __alignof(_Tp) #if defined(_LIBCPP_COMPILER_CLANG) // _LIBCPP_ALTERNATE_STRING_LAYOUT is an old name for // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT left here for backward compatibility. #if (defined(__APPLE__) && !defined(__i386__) && !defined(__x86_64__) && \ (!defined(__arm__) || __ARM_ARCH_7K__ >= 2)) || \ defined(_LIBCPP_ALTERNATE_STRING_LAYOUT) #define _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT #endif #if __has_feature(cxx_alignas) # define _ALIGNAS_TYPE(x) alignas(x) # define _ALIGNAS(x) alignas(x) #else # define _ALIGNAS_TYPE(x) __attribute__((__aligned__(_LIBCPP_ALIGNOF(x)))) # define _ALIGNAS(x) __attribute__((__aligned__(x))) #endif #if __cplusplus < 201103L typedef __char16_t char16_t; typedef __char32_t char32_t; #endif #if !(__has_feature(cxx_exceptions)) && !defined(_LIBCPP_NO_EXCEPTIONS) #define _LIBCPP_NO_EXCEPTIONS #endif #if !(__has_feature(cxx_rtti)) && !defined(_LIBCPP_NO_RTTI) #define _LIBCPP_NO_RTTI #endif #if !(__has_feature(cxx_strong_enums)) #define _LIBCPP_HAS_NO_STRONG_ENUMS #endif #if __has_feature(cxx_attributes) # define _LIBCPP_NORETURN [[noreturn]] #else # define _LIBCPP_NORETURN __attribute__ ((noreturn)) #endif #if !(__has_feature(cxx_lambdas)) #define _LIBCPP_HAS_NO_LAMBDAS #endif #if !(__has_feature(cxx_nullptr)) # if (__has_extension(cxx_nullptr) || __has_keyword(__nullptr)) && defined(_LIBCPP_ABI_ALWAYS_USE_CXX11_NULLPTR) # define nullptr __nullptr # else # define _LIBCPP_HAS_NO_NULLPTR # endif #endif #if !(__has_feature(cxx_rvalue_references)) #define _LIBCPP_HAS_NO_RVALUE_REFERENCES #endif #if !(__has_feature(cxx_auto_type)) #define _LIBCPP_HAS_NO_AUTO_TYPE #endif #if !(__has_feature(cxx_variadic_templates)) #define _LIBCPP_HAS_NO_VARIADICS #endif // Objective-C++ features (opt-in) #if __has_feature(objc_arc) #define _LIBCPP_HAS_OBJC_ARC #endif #if __has_feature(objc_arc_weak) #define _LIBCPP_HAS_OBJC_ARC_WEAK #endif #if !(__has_feature(cxx_relaxed_constexpr)) #define _LIBCPP_HAS_NO_CXX14_CONSTEXPR #endif #if !(__has_feature(cxx_variable_templates)) #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #endif #if !(__has_feature(cxx_noexcept)) #define _LIBCPP_HAS_NO_NOEXCEPT #endif #if !defined(_LIBCPP_HAS_NO_ASAN) && !__has_feature(address_sanitizer) #define _LIBCPP_HAS_NO_ASAN #endif // Allow for build-time disabling of unsigned integer sanitization #if !defined(_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK) && __has_attribute(no_sanitize) #define _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK __attribute__((__no_sanitize__("unsigned-integer-overflow"))) #endif #if __has_builtin(__builtin_launder) #define _LIBCPP_COMPILER_HAS_BUILTIN_LAUNDER #endif #if !__is_identifier(__has_unique_object_representations) #define _LIBCPP_HAS_UNIQUE_OBJECT_REPRESENTATIONS #endif #define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__)) // Literal operators ""d and ""y are supported starting with LLVM Clang 8 and AppleClang 10.0.1 #if (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 800) || \ (defined(__apple_build_version__) && __apple_build_version__ < 10010000) #define _LIBCPP_HAS_NO_CXX20_CHRONO_LITERALS #endif #define _LIBCPP_DISABLE_EXTENSION_WARNING __extension__ #elif defined(_LIBCPP_COMPILER_GCC) #define _ALIGNAS(x) __attribute__((__aligned__(x))) #define _ALIGNAS_TYPE(x) __attribute__((__aligned__(_LIBCPP_ALIGNOF(x)))) #define _LIBCPP_NORETURN __attribute__((noreturn)) #if !__EXCEPTIONS && !defined(_LIBCPP_NO_EXCEPTIONS) #define _LIBCPP_NO_EXCEPTIONS #endif // Determine if GCC supports relaxed constexpr #if !defined(__cpp_constexpr) || __cpp_constexpr < 201304L #define _LIBCPP_HAS_NO_CXX14_CONSTEXPR #endif // GCC 5 supports variable templates #if !defined(__cpp_variable_templates) || __cpp_variable_templates < 201304L #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #endif #if !defined(_LIBCPP_HAS_NO_ASAN) && !defined(__SANITIZE_ADDRESS__) #define _LIBCPP_HAS_NO_ASAN #endif #if _GNUC_VER >= 700 #define _LIBCPP_COMPILER_HAS_BUILTIN_LAUNDER #endif #if _GNUC_VER >= 700 #define _LIBCPP_HAS_UNIQUE_OBJECT_REPRESENTATIONS #endif #define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__)) #define _LIBCPP_DISABLE_EXTENSION_WARNING __extension__ #elif defined(_LIBCPP_COMPILER_MSVC) #define _LIBCPP_TOSTRING2(x) #x #define _LIBCPP_TOSTRING(x) _LIBCPP_TOSTRING2(x) #define _LIBCPP_WARNING(x) __pragma(message(__FILE__ "(" _LIBCPP_TOSTRING(__LINE__) ") : warning note: " x)) #if _MSC_VER < 1900 #error "MSVC versions prior to Visual Studio 2015 are not supported" #endif #define _LIBCPP_HAS_NO_CXX14_CONSTEXPR #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #define __alignof__ __alignof #define _LIBCPP_NORETURN __declspec(noreturn) #define _ALIGNAS(x) __declspec(align(x)) #define _ALIGNAS_TYPE(x) alignas(x) #define _LIBCPP_WEAK #define _LIBCPP_HAS_NO_ASAN #define _LIBCPP_ALWAYS_INLINE __forceinline #define _LIBCPP_HAS_NO_VECTOR_EXTENSION #define _LIBCPP_DISABLE_EXTENSION_WARNING #elif defined(_LIBCPP_COMPILER_IBM) #define _ALIGNAS(x) __attribute__((__aligned__(x))) #define _ALIGNAS_TYPE(x) __attribute__((__aligned__(_LIBCPP_ALIGNOF(x)))) #define _ATTRIBUTE(x) __attribute__((x)) #define _LIBCPP_NORETURN __attribute__((noreturn)) #define _LIBCPP_HAS_NO_UNICODE_CHARS #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES #if defined(_AIX) #define __MULTILOCALE_API #endif #define _LIBCPP_HAS_NO_ASAN #define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__)) #define _LIBCPP_HAS_NO_VECTOR_EXTENSION #define _LIBCPP_DISABLE_EXTENSION_WARNING #endif // _LIBCPP_COMPILER_[CLANG|GCC|MSVC|IBM] #if defined(_LIBCPP_OBJECT_FORMAT_COFF) #ifdef _DLL # define _LIBCPP_CRT_FUNC __declspec(dllimport) #else # define _LIBCPP_CRT_FUNC #endif #if defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # define _LIBCPP_DLL_VIS # define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS # define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS # define _LIBCPP_OVERRIDABLE_FUNC_VIS # define _LIBCPP_EXPORTED_FROM_ABI #elif defined(_LIBCPP_BUILDING_LIBRARY) # define _LIBCPP_DLL_VIS __declspec(dllexport) # if defined(__MINGW32__) # define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS _LIBCPP_DLL_VIS # define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS # else # define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS # define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS _LIBCPP_DLL_VIS # endif # define _LIBCPP_OVERRIDABLE_FUNC_VIS _LIBCPP_DLL_VIS # define _LIBCPP_EXPORTED_FROM_ABI __declspec(dllexport) #else # define _LIBCPP_DLL_VIS __declspec(dllimport) # define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS _LIBCPP_DLL_VIS # define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS # define _LIBCPP_OVERRIDABLE_FUNC_VIS # define _LIBCPP_EXPORTED_FROM_ABI __declspec(dllimport) #endif #define _LIBCPP_TYPE_VIS _LIBCPP_DLL_VIS #define _LIBCPP_FUNC_VIS _LIBCPP_DLL_VIS #define _LIBCPP_EXCEPTION_ABI _LIBCPP_DLL_VIS #define _LIBCPP_HIDDEN #define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS #define _LIBCPP_TEMPLATE_VIS #define _LIBCPP_ENUM_VIS #endif // defined(_LIBCPP_OBJECT_FORMAT_COFF) #ifndef _LIBCPP_HIDDEN # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # define _LIBCPP_HIDDEN __attribute__ ((__visibility__("hidden"))) # else # define _LIBCPP_HIDDEN # endif #endif #ifndef _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) // The inline should be removed once PR32114 is resolved # define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS inline _LIBCPP_HIDDEN # else # define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS # endif #endif #ifndef _LIBCPP_FUNC_VIS # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # define _LIBCPP_FUNC_VIS __attribute__ ((__visibility__("default"))) # else # define _LIBCPP_FUNC_VIS # endif #endif #ifndef _LIBCPP_TYPE_VIS # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # define _LIBCPP_TYPE_VIS __attribute__ ((__visibility__("default"))) # else # define _LIBCPP_TYPE_VIS # endif #endif #ifndef _LIBCPP_TEMPLATE_VIS # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # if __has_attribute(__type_visibility__) # define _LIBCPP_TEMPLATE_VIS __attribute__ ((__type_visibility__("default"))) # else # define _LIBCPP_TEMPLATE_VIS __attribute__ ((__visibility__("default"))) # endif # else # define _LIBCPP_TEMPLATE_VIS # endif #endif #ifndef _LIBCPP_EXPORTED_FROM_ABI # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # define _LIBCPP_EXPORTED_FROM_ABI __attribute__((__visibility__("default"))) # else # define _LIBCPP_EXPORTED_FROM_ABI # endif #endif #ifndef _LIBCPP_OVERRIDABLE_FUNC_VIS #define _LIBCPP_OVERRIDABLE_FUNC_VIS _LIBCPP_FUNC_VIS #endif #ifndef _LIBCPP_EXCEPTION_ABI # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) # define _LIBCPP_EXCEPTION_ABI __attribute__ ((__visibility__("default"))) # else # define _LIBCPP_EXCEPTION_ABI # endif #endif #ifndef _LIBCPP_ENUM_VIS # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) && __has_attribute(__type_visibility__) # define _LIBCPP_ENUM_VIS __attribute__ ((__type_visibility__("default"))) # else # define _LIBCPP_ENUM_VIS # endif #endif #ifndef _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS # if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS) && __has_attribute(__type_visibility__) # define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS __attribute__ ((__visibility__("default"))) # else # define _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS # endif #endif #ifndef _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS #define _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS #endif #if __has_attribute(internal_linkage) # define _LIBCPP_INTERNAL_LINKAGE __attribute__ ((internal_linkage)) #else # define _LIBCPP_INTERNAL_LINKAGE _LIBCPP_ALWAYS_INLINE #endif #if __has_attribute(exclude_from_explicit_instantiation) # define _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION __attribute__ ((__exclude_from_explicit_instantiation__)) #else // Try to approximate the effect of exclude_from_explicit_instantiation // (which is that entities are not assumed to be provided by explicit // template instantiations in the dylib) by always inlining those entities. # define _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION _LIBCPP_ALWAYS_INLINE #endif #ifndef _LIBCPP_HIDE_FROM_ABI_PER_TU # ifndef _LIBCPP_HIDE_FROM_ABI_PER_TU_BY_DEFAULT # define _LIBCPP_HIDE_FROM_ABI_PER_TU 0 # else # define _LIBCPP_HIDE_FROM_ABI_PER_TU 1 # endif #endif #ifndef _LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT # ifdef _LIBCPP_OBJECT_FORMAT_COFF // Windows binaries can't merge typeinfos. # define _LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT 0 #else // TODO: This isn't strictly correct on ELF platforms due to llvm.org/PR37398 // And we should consider defaulting to OFF. # define _LIBCPP_HAS_MERGED_TYPEINFO_NAMES_DEFAULT 1 #endif #endif #ifndef _LIBCPP_HIDE_FROM_ABI # if _LIBCPP_HIDE_FROM_ABI_PER_TU # define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_INTERNAL_LINKAGE # else # define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION # endif #endif #ifdef _LIBCPP_BUILDING_LIBRARY # if _LIBCPP_ABI_VERSION > 1 # define _LIBCPP_HIDE_FROM_ABI_AFTER_V1 _LIBCPP_HIDE_FROM_ABI # else # define _LIBCPP_HIDE_FROM_ABI_AFTER_V1 # endif #else # define _LIBCPP_HIDE_FROM_ABI_AFTER_V1 _LIBCPP_HIDE_FROM_ABI #endif // Just so we can migrate to the new macros gradually. #define _LIBCPP_INLINE_VISIBILITY _LIBCPP_HIDE_FROM_ABI // Inline namespaces are available in Clang/GCC/MSVC regardless of C++ dialect. #define _LIBCPP_BEGIN_NAMESPACE_STD namespace std { inline namespace _LIBCPP_ABI_NAMESPACE { #define _LIBCPP_END_NAMESPACE_STD } } #define _VSTD std::_LIBCPP_ABI_NAMESPACE _LIBCPP_BEGIN_NAMESPACE_STD _LIBCPP_END_NAMESPACE_STD #if _LIBCPP_STD_VER >= 17 #define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \ _LIBCPP_BEGIN_NAMESPACE_STD inline namespace __fs { namespace filesystem { #else #define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \ _LIBCPP_BEGIN_NAMESPACE_STD namespace __fs { namespace filesystem { #endif #define _LIBCPP_END_NAMESPACE_FILESYSTEM \ _LIBCPP_END_NAMESPACE_STD } } #define _VSTD_FS _VSTD::__fs::filesystem #ifndef _LIBCPP_PREFERRED_OVERLOAD # if __has_attribute(__enable_if__) # define _LIBCPP_PREFERRED_OVERLOAD __attribute__ ((__enable_if__(true, ""))) # endif #endif #ifndef _LIBCPP_HAS_NO_NOEXCEPT # define _NOEXCEPT noexcept # define _NOEXCEPT_(x) noexcept(x) #else # define _NOEXCEPT throw() # define _NOEXCEPT_(x) #endif #ifdef _LIBCPP_HAS_NO_UNICODE_CHARS typedef unsigned short char16_t; typedef unsigned int char32_t; #endif // _LIBCPP_HAS_NO_UNICODE_CHARS #ifndef __SIZEOF_INT128__ #define _LIBCPP_HAS_NO_INT128 #endif #ifdef _LIBCPP_CXX03_LANG # define static_assert(...) _Static_assert(__VA_ARGS__) # define decltype(...) __decltype(__VA_ARGS__) #endif // _LIBCPP_CXX03_LANG #ifdef _LIBCPP_CXX03_LANG # define _LIBCPP_CONSTEXPR #else # define _LIBCPP_CONSTEXPR constexpr #endif #ifdef _LIBCPP_CXX03_LANG # define _LIBCPP_DEFAULT {} #else # define _LIBCPP_DEFAULT = default; #endif #ifdef _LIBCPP_CXX03_LANG # define _LIBCPP_EQUAL_DELETE #else # define _LIBCPP_EQUAL_DELETE = delete #endif #ifdef __GNUC__ # define _LIBCPP_NOALIAS __attribute__((__malloc__)) #else # define _LIBCPP_NOALIAS #endif #if __has_feature(cxx_explicit_conversions) || defined(__IBMCPP__) || \ (!defined(_LIBCPP_CXX03_LANG) && defined(__GNUC__)) // All supported GCC versions # define _LIBCPP_EXPLICIT explicit #else # define _LIBCPP_EXPLICIT #endif #if !__has_builtin(__builtin_operator_new) || !__has_builtin(__builtin_operator_delete) #define _LIBCPP_HAS_NO_BUILTIN_OPERATOR_NEW_DELETE #endif #ifdef _LIBCPP_HAS_NO_STRONG_ENUMS # define _LIBCPP_DECLARE_STRONG_ENUM(x) struct _LIBCPP_TYPE_VIS x { enum __lx # define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x) \ __lx __v_; \ _LIBCPP_INLINE_VISIBILITY x(__lx __v) : __v_(__v) {} \ _LIBCPP_INLINE_VISIBILITY explicit x(int __v) : __v_(static_cast<__lx>(__v)) {} \ _LIBCPP_INLINE_VISIBILITY operator int() const {return __v_;} \ }; #else // _LIBCPP_HAS_NO_STRONG_ENUMS # define _LIBCPP_DECLARE_STRONG_ENUM(x) enum class _LIBCPP_ENUM_VIS x # define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x) #endif // _LIBCPP_HAS_NO_STRONG_ENUMS #ifdef _LIBCPP_DEBUG # if _LIBCPP_DEBUG == 0 # define _LIBCPP_DEBUG_LEVEL 1 # elif _LIBCPP_DEBUG == 1 # define _LIBCPP_DEBUG_LEVEL 2 # else # error Supported values for _LIBCPP_DEBUG are 0 and 1 # endif # if !defined(_LIBCPP_BUILDING_LIBRARY) # define _LIBCPP_EXTERN_TEMPLATE(...) # endif #endif #ifdef _LIBCPP_DISABLE_EXTERN_TEMPLATE #define _LIBCPP_EXTERN_TEMPLATE(...) #define _LIBCPP_EXTERN_TEMPLATE2(...) #endif #ifndef _LIBCPP_EXTERN_TEMPLATE #define _LIBCPP_EXTERN_TEMPLATE(...) extern template __VA_ARGS__; #endif #ifndef _LIBCPP_EXTERN_TEMPLATE2 #define _LIBCPP_EXTERN_TEMPLATE2(...) extern template __VA_ARGS__; #endif #if defined(__APPLE__) || defined(__FreeBSD__) || defined(_LIBCPP_MSVCRT_LIKE) || \ defined(__sun__) || defined(__NetBSD__) || defined(__CloudABI__) #define _LIBCPP_LOCALE__L_EXTENSIONS 1 #endif #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) // Most unix variants have catopen. These are the specific ones that don't. # if !defined(__BIONIC__) && !defined(_NEWLIB_VERSION) # define _LIBCPP_HAS_CATOPEN 1 # endif #endif #ifdef __FreeBSD__ #define _DECLARE_C99_LDBL_MATH 1 #endif #if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_NO_VCRUNTIME) # define _LIBCPP_DEFER_NEW_TO_VCRUNTIME #endif // If we are getting operator new from the MSVC CRT, then allocation overloads // for align_val_t were added in 19.12, aka VS 2017 version 15.3. #if defined(_LIBCPP_MSVCRT) && defined(_MSC_VER) && _MSC_VER < 1912 # define _LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION #elif defined(_LIBCPP_DEFER_NEW_TO_VCRUNTIME) && !defined(__cpp_aligned_new) // We're defering to Microsoft's STL to provide aligned new et al. We don't // have it unless the language feature test macro is defined. # define _LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION #endif #if defined(__APPLE__) # if !defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) # define __MAC_OS_X_VERSION_MIN_REQUIRED __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ # endif #endif // defined(__APPLE__) #if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION) && \ (defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION) || \ (!defined(__cpp_aligned_new) || __cpp_aligned_new < 201606)) # define _LIBCPP_HAS_NO_ALIGNED_ALLOCATION #endif #if defined(__APPLE__) || defined(__FreeBSD__) #define _LIBCPP_HAS_DEFAULTRUNELOCALE #endif #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__sun__) #define _LIBCPP_WCTYPE_IS_MASK #endif #if _LIBCPP_STD_VER <= 17 || !defined(__cpp_char8_t) #define _LIBCPP_NO_HAS_CHAR8_T #endif // Deprecation macros. // // Deprecations warnings are always enabled, except when users explicitly opt-out // by defining _LIBCPP_DISABLE_DEPRECATION_WARNINGS. #if !defined(_LIBCPP_DISABLE_DEPRECATION_WARNINGS) # if __has_attribute(deprecated) # define _LIBCPP_DEPRECATED __attribute__ ((deprecated)) # elif _LIBCPP_STD_VER > 11 # define _LIBCPP_DEPRECATED [[deprecated]] # else # define _LIBCPP_DEPRECATED # endif #else # define _LIBCPP_DEPRECATED #endif #if !defined(_LIBCPP_CXX03_LANG) # define _LIBCPP_DEPRECATED_IN_CXX11 _LIBCPP_DEPRECATED #else # define _LIBCPP_DEPRECATED_IN_CXX11 #endif #if _LIBCPP_STD_VER >= 14 # define _LIBCPP_DEPRECATED_IN_CXX14 _LIBCPP_DEPRECATED #else # define _LIBCPP_DEPRECATED_IN_CXX14 #endif #if _LIBCPP_STD_VER >= 17 # define _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_DEPRECATED #else # define _LIBCPP_DEPRECATED_IN_CXX17 #endif #if _LIBCPP_STD_VER <= 11 # define _LIBCPP_EXPLICIT_AFTER_CXX11 #else # define _LIBCPP_EXPLICIT_AFTER_CXX11 explicit #endif #if _LIBCPP_STD_VER > 11 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) # define _LIBCPP_CONSTEXPR_AFTER_CXX11 constexpr #else # define _LIBCPP_CONSTEXPR_AFTER_CXX11 #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) # define _LIBCPP_CONSTEXPR_AFTER_CXX14 constexpr #else # define _LIBCPP_CONSTEXPR_AFTER_CXX14 #endif #if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) # define _LIBCPP_CONSTEXPR_AFTER_CXX17 constexpr #else # define _LIBCPP_CONSTEXPR_AFTER_CXX17 #endif // The _LIBCPP_NODISCARD_ATTRIBUTE should only be used to define other // NODISCARD macros to the correct attribute. #if __has_cpp_attribute(nodiscard) || defined(_LIBCPP_COMPILER_MSVC) # define _LIBCPP_NODISCARD_ATTRIBUTE [[nodiscard]] #elif defined(_LIBCPP_COMPILER_CLANG) && !defined(_LIBCPP_CXX03_LANG) # define _LIBCPP_NODISCARD_ATTRIBUTE [[clang::warn_unused_result]] #else // We can't use GCC's [[gnu::warn_unused_result]] and // __attribute__((warn_unused_result)), because GCC does not silence them via // (void) cast. # define _LIBCPP_NODISCARD_ATTRIBUTE #endif // _LIBCPP_NODISCARD_EXT may be used to apply [[nodiscard]] to entities not // specified as such as an extension. #if defined(_LIBCPP_ENABLE_NODISCARD) && !defined(_LIBCPP_DISABLE_NODISCARD_EXT) # define _LIBCPP_NODISCARD_EXT _LIBCPP_NODISCARD_ATTRIBUTE #else # define _LIBCPP_NODISCARD_EXT #endif #if !defined(_LIBCPP_DISABLE_NODISCARD_AFTER_CXX17) && \ (_LIBCPP_STD_VER > 17 || defined(_LIBCPP_ENABLE_NODISCARD)) # define _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_NODISCARD_ATTRIBUTE #else # define _LIBCPP_NODISCARD_AFTER_CXX17 #endif #if _LIBCPP_STD_VER > 14 && defined(__cpp_inline_variables) && (__cpp_inline_variables >= 201606L) # define _LIBCPP_INLINE_VAR inline #else # define _LIBCPP_INLINE_VAR #endif #ifdef _LIBCPP_HAS_NO_RVALUE_REFERENCES # define _LIBCPP_EXPLICIT_MOVE(x) _VSTD::move(x) #else # define _LIBCPP_EXPLICIT_MOVE(x) (x) #endif #ifndef _LIBCPP_CONSTEXPR_IF_NODEBUG #if defined(_LIBCPP_DEBUG) || defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR) #define _LIBCPP_CONSTEXPR_IF_NODEBUG #else #define _LIBCPP_CONSTEXPR_IF_NODEBUG constexpr #endif #endif #if __has_attribute(no_destroy) # define _LIBCPP_NO_DESTROY __attribute__((__no_destroy__)) #else # define _LIBCPP_NO_DESTROY #endif #ifndef _LIBCPP_HAS_NO_ASAN _LIBCPP_FUNC_VIS extern "C" void __sanitizer_annotate_contiguous_container( const void *, const void *, const void *, const void *); #endif // Try to find out if RTTI is disabled. // g++ and cl.exe have RTTI on by default and define a macro when it is. // g++ only defines the macro in 4.3.2 and onwards. #if !defined(_LIBCPP_NO_RTTI) # if defined(__GNUC__) && \ ((__GNUC__ >= 5) || \ (__GNUC__ == 4 && (__GNUC_MINOR__ >= 3 || __GNUC_PATCHLEVEL__ >= 2))) && \ !defined(__GXX_RTTI) # define _LIBCPP_NO_RTTI # elif defined(_LIBCPP_COMPILER_MSVC) && !defined(_CPPRTTI) # define _LIBCPP_NO_RTTI # endif #endif #ifndef _LIBCPP_WEAK #define _LIBCPP_WEAK __attribute__((__weak__)) #endif // Thread API #if !defined(_LIBCPP_HAS_NO_THREADS) && \ !defined(_LIBCPP_HAS_THREAD_API_PTHREAD) && \ !defined(_LIBCPP_HAS_THREAD_API_WIN32) && \ !defined(_LIBCPP_HAS_THREAD_API_EXTERNAL) # if defined(__FreeBSD__) || \ defined(__Fuchsia__) || \ defined(__wasi__) || \ defined(__NetBSD__) || \ defined(__linux__) || \ defined(__GNU__) || \ defined(__APPLE__) || \ defined(__CloudABI__) || \ defined(__sun__) || \ (defined(__MINGW32__) && __has_include(<pthread.h>)) # define _LIBCPP_HAS_THREAD_API_PTHREAD # elif defined(_LIBCPP_WIN32API) # define _LIBCPP_HAS_THREAD_API_WIN32 # else # error "No thread API" # endif // _LIBCPP_HAS_THREAD_API #endif // _LIBCPP_HAS_NO_THREADS #if defined(_LIBCPP_HAS_THREAD_API_PTHREAD) #if defined(__ANDROID__) && __ANDROID_API__ >= 30 #define _LIBCPP_HAS_COND_CLOCKWAIT #elif defined(_LIBCPP_GLIBC_PREREQ) #if _LIBCPP_GLIBC_PREREQ(2, 30) #define _LIBCPP_HAS_COND_CLOCKWAIT #endif #endif #endif #if defined(_LIBCPP_HAS_NO_THREADS) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD) #error _LIBCPP_HAS_THREAD_API_PTHREAD may only be defined when \ _LIBCPP_HAS_NO_THREADS is not defined. #endif #if defined(_LIBCPP_HAS_NO_THREADS) && defined(_LIBCPP_HAS_THREAD_API_EXTERNAL) #error _LIBCPP_HAS_THREAD_API_EXTERNAL may not be defined when \ _LIBCPP_HAS_NO_THREADS is defined. #endif #if defined(_LIBCPP_HAS_NO_MONOTONIC_CLOCK) && !defined(_LIBCPP_HAS_NO_THREADS) #error _LIBCPP_HAS_NO_MONOTONIC_CLOCK may only be defined when \ _LIBCPP_HAS_NO_THREADS is defined. #endif #if defined(__STDCPP_THREADS__) && defined(_LIBCPP_HAS_NO_THREADS) #error _LIBCPP_HAS_NO_THREADS cannot be set when __STDCPP_THREADS__ is set. #endif #if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(__STDCPP_THREADS__) #define __STDCPP_THREADS__ 1 #endif // The glibc and Bionic implementation of pthreads implements // pthread_mutex_destroy as nop for regular mutexes. Additionally, Win32 // mutexes have no destroy mechanism. // // This optimization can't be performed on Apple platforms, where // pthread_mutex_destroy can allow the kernel to release resources. // See https://llvm.org/D64298 for details. // // TODO(EricWF): Enable this optimization on Bionic after speaking to their // respective stakeholders. #if (defined(_LIBCPP_HAS_THREAD_API_PTHREAD) && defined(__GLIBC__)) \ || defined(_LIBCPP_HAS_THREAD_API_WIN32) # define _LIBCPP_HAS_TRIVIAL_MUTEX_DESTRUCTION #endif // Destroying a condvar is a nop on Windows. // // This optimization can't be performed on Apple platforms, where // pthread_cond_destroy can allow the kernel to release resources. // See https://llvm.org/D64298 for details. // // TODO(EricWF): This is potentially true for some pthread implementations // as well. #if defined(_LIBCPP_HAS_THREAD_API_WIN32) # define _LIBCPP_HAS_TRIVIAL_CONDVAR_DESTRUCTION #endif // Systems that use capability-based security (FreeBSD with Capsicum, // Nuxi CloudABI) may only provide local filesystem access (using *at()). // Functions like open(), rename(), unlink() and stat() should not be // used, as they attempt to access the global filesystem namespace. #ifdef __CloudABI__ #define _LIBCPP_HAS_NO_GLOBAL_FILESYSTEM_NAMESPACE #endif // CloudABI is intended for running networked services. Processes do not // have standard input and output channels. #ifdef __CloudABI__ #define _LIBCPP_HAS_NO_STDIN #define _LIBCPP_HAS_NO_STDOUT #endif // Some systems do not provide gets() in their C library, for security reasons. #ifndef _LIBCPP_C_HAS_NO_GETS # if defined(_LIBCPP_MSVCRT) || (defined(__FreeBSD__) && __FreeBSD__ >= 13) # define _LIBCPP_C_HAS_NO_GETS # endif #endif #if defined(__BIONIC__) || defined(__CloudABI__) || \ defined(__Fuchsia__) || defined(__wasi__) || defined(_LIBCPP_HAS_MUSL_LIBC) #define _LIBCPP_PROVIDES_DEFAULT_RUNE_TABLE #endif // Thread-unsafe functions such as strtok() and localtime() // are not available. #ifdef __CloudABI__ #define _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS #endif #if __has_feature(cxx_atomic) || __has_extension(c_atomic) || __has_keyword(_Atomic) # define _LIBCPP_HAS_C_ATOMIC_IMP #elif defined(_LIBCPP_COMPILER_GCC) # define _LIBCPP_HAS_GCC_ATOMIC_IMP #endif #if (!defined(_LIBCPP_HAS_C_ATOMIC_IMP) && \ !defined(_LIBCPP_HAS_GCC_ATOMIC_IMP) && \ !defined(_LIBCPP_HAS_EXTERNAL_ATOMIC_IMP)) \ || defined(_LIBCPP_HAS_NO_THREADS) # define _LIBCPP_HAS_NO_ATOMIC_HEADER #else # ifndef _LIBCPP_ATOMIC_FLAG_TYPE # define _LIBCPP_ATOMIC_FLAG_TYPE bool # endif # ifdef _LIBCPP_FREESTANDING # define _LIBCPP_ATOMIC_ONLY_USE_BUILTINS # endif #endif #ifndef _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK #define _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK #endif #if defined(_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS) # if defined(__clang__) && __has_attribute(acquire_capability) // Work around the attribute handling in clang. When both __declspec and // __attribute__ are present, the processing goes awry preventing the definition // of the types. # if !defined(_LIBCPP_OBJECT_FORMAT_COFF) # define _LIBCPP_HAS_THREAD_SAFETY_ANNOTATIONS # endif # endif #endif #if __has_attribute(require_constant_initialization) # define _LIBCPP_SAFE_STATIC __attribute__((__require_constant_initialization__)) #else # define _LIBCPP_SAFE_STATIC #endif #if !__has_builtin(__builtin_addressof) && _GNUC_VER < 700 #define _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF #endif #if !__has_builtin(__builtin_is_constant_evaluated) && _GNUC_VER < 900 #define _LIBCPP_HAS_NO_BUILTIN_IS_CONSTANT_EVALUATED #endif #if !defined(_LIBCPP_HAS_NO_OFF_T_FUNCTIONS) # if defined(_LIBCPP_MSVCRT) || defined(_NEWLIB_VERSION) # define _LIBCPP_HAS_NO_OFF_T_FUNCTIONS # endif #endif #if __has_attribute(diagnose_if) && !defined(_LIBCPP_DISABLE_ADDITIONAL_DIAGNOSTICS) # define _LIBCPP_DIAGNOSE_WARNING(...) \ __attribute__((diagnose_if(__VA_ARGS__, "warning"))) # define _LIBCPP_DIAGNOSE_ERROR(...) \ __attribute__((diagnose_if(__VA_ARGS__, "error"))) #else # define _LIBCPP_DIAGNOSE_WARNING(...) # define _LIBCPP_DIAGNOSE_ERROR(...) #endif // Use a function like macro to imply that it must be followed by a semicolon #if __cplusplus > 201402L && __has_cpp_attribute(fallthrough) # define _LIBCPP_FALLTHROUGH() [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) # define _LIBCPP_FALLTHROUGH() [[clang::fallthrough]] #elif __has_attribute(fallthough) || _GNUC_VER >= 700 # define _LIBCPP_FALLTHROUGH() __attribute__((__fallthrough__)) #else # define _LIBCPP_FALLTHROUGH() ((void)0) #endif #if __has_attribute(__nodebug__) #define _LIBCPP_NODEBUG __attribute__((__nodebug__)) #else #define _LIBCPP_NODEBUG #endif #ifndef _LIBCPP_NODEBUG_TYPE #if __has_attribute(__nodebug__) && \ (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER >= 900) #define _LIBCPP_NODEBUG_TYPE __attribute__((nodebug)) #else #define _LIBCPP_NODEBUG_TYPE #endif #endif // !defined(_LIBCPP_NODEBUG_TYPE) #if defined(_LIBCPP_ABI_MICROSOFT) && \ (defined(_LIBCPP_COMPILER_MSVC) || __has_declspec_attribute(empty_bases)) # define _LIBCPP_DECLSPEC_EMPTY_BASES __declspec(empty_bases) #else # define _LIBCPP_DECLSPEC_EMPTY_BASES #endif #if defined(_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES) #define _LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR #define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS #define _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE #define _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS #endif // _LIBCPP_ENABLE_CXX17_REMOVED_FEATURES #if !defined(__cpp_deduction_guides) || __cpp_deduction_guides < 201611 #define _LIBCPP_HAS_NO_DEDUCTION_GUIDES #endif #if !__has_keyword(__is_aggregate) && (_GNUC_VER_NEW < 7001) #define _LIBCPP_HAS_NO_IS_AGGREGATE #endif #if !defined(__cpp_coroutines) || __cpp_coroutines < 201703L #define _LIBCPP_HAS_NO_COROUTINES #endif // FIXME: Correct this macro when either (A) a feature test macro for the // spaceship operator is provided, or (B) a compiler provides a complete // implementation. #define _LIBCPP_HAS_NO_SPACESHIP_OPERATOR // Decide whether to use availability macros. #if !defined(_LIBCPP_BUILDING_LIBRARY) && \ !defined(_LIBCPP_DISABLE_AVAILABILITY) && \ __has_feature(attribute_availability_with_strict) && \ __has_feature(attribute_availability_in_templates) && \ __has_extension(pragma_clang_attribute_external_declaration) # ifdef __APPLE__ # define _LIBCPP_USE_AVAILABILITY_APPLE # endif #endif // Define availability macros. #if defined(_LIBCPP_USE_AVAILABILITY_APPLE) # define _LIBCPP_AVAILABILITY_SHARED_MUTEX \ __attribute__((availability(macosx,strict,introduced=10.12))) \ __attribute__((availability(ios,strict,introduced=10.0))) \ __attribute__((availability(tvos,strict,introduced=10.0))) \ __attribute__((availability(watchos,strict,introduced=3.0))) # define _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS \ __attribute__((availability(macosx,strict,introduced=10.14))) \ __attribute__((availability(ios,strict,introduced=12.0))) \ __attribute__((availability(tvos,strict,introduced=12.0))) \ __attribute__((availability(watchos,strict,introduced=5.0))) # define _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS \ _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS # define _LIBCPP_AVAILABILITY_BAD_ANY_CAST \ _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS # define _LIBCPP_AVAILABILITY_UNCAUGHT_EXCEPTIONS \ __attribute__((availability(macosx,strict,introduced=10.12))) \ __attribute__((availability(ios,strict,introduced=10.0))) \ __attribute__((availability(tvos,strict,introduced=10.0))) \ __attribute__((availability(watchos,strict,introduced=3.0))) # define _LIBCPP_AVAILABILITY_SIZED_NEW_DELETE \ __attribute__((availability(macosx,strict,introduced=10.12))) \ __attribute__((availability(ios,strict,introduced=10.0))) \ __attribute__((availability(tvos,strict,introduced=10.0))) \ __attribute__((availability(watchos,strict,introduced=3.0))) # define _LIBCPP_AVAILABILITY_FUTURE_ERROR \ __attribute__((availability(ios,strict,introduced=6.0))) # define _LIBCPP_AVAILABILITY_TYPEINFO_VTABLE \ __attribute__((availability(macosx,strict,introduced=10.9))) \ __attribute__((availability(ios,strict,introduced=7.0))) # define _LIBCPP_AVAILABILITY_LOCALE_CATEGORY \ __attribute__((availability(macosx,strict,introduced=10.9))) \ __attribute__((availability(ios,strict,introduced=7.0))) # define _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR \ __attribute__((availability(macosx,strict,introduced=10.9))) \ __attribute__((availability(ios,strict,introduced=7.0))) # define _LIBCPP_AVAILABILITY_FILESYSTEM \ __attribute__((availability(macosx,strict,introduced=10.15))) \ __attribute__((availability(ios,strict,introduced=13.0))) \ __attribute__((availability(tvos,strict,introduced=13.0))) \ __attribute__((availability(watchos,strict,introduced=6.0))) # define _LIBCPP_AVAILABILITY_FILESYSTEM_PUSH \ _Pragma("clang attribute push(__attribute__((availability(macosx,strict,introduced=10.15))), apply_to=any(function,record))") \ _Pragma("clang attribute push(__attribute__((availability(ios,strict,introduced=13.0))), apply_to=any(function,record))") \ _Pragma("clang attribute push(__attribute__((availability(tvos,strict,introduced=13.0))), apply_to=any(function,record))") \ _Pragma("clang attribute push(__attribute__((availability(watchos,strict,introduced=6.0))), apply_to=any(function,record))") # define _LIBCPP_AVAILABILITY_FILESYSTEM_POP \ _Pragma("clang attribute pop") \ _Pragma("clang attribute pop") \ _Pragma("clang attribute pop") \ _Pragma("clang attribute pop") #else # define _LIBCPP_AVAILABILITY_SHARED_MUTEX # define _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS # define _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS # define _LIBCPP_AVAILABILITY_BAD_ANY_CAST # define _LIBCPP_AVAILABILITY_UNCAUGHT_EXCEPTIONS # define _LIBCPP_AVAILABILITY_SIZED_NEW_DELETE # define _LIBCPP_AVAILABILITY_FUTURE_ERROR # define _LIBCPP_AVAILABILITY_TYPEINFO_VTABLE # define _LIBCPP_AVAILABILITY_LOCALE_CATEGORY # define _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR # define _LIBCPP_AVAILABILITY_FILESYSTEM # define _LIBCPP_AVAILABILITY_FILESYSTEM_PUSH # define _LIBCPP_AVAILABILITY_FILESYSTEM_POP #endif // Define availability that depends on _LIBCPP_NO_EXCEPTIONS. #ifdef _LIBCPP_NO_EXCEPTIONS # define _LIBCPP_AVAILABILITY_FUTURE # define _LIBCPP_AVAILABILITY_THROW_BAD_ANY_CAST # define _LIBCPP_AVAILABILITY_THROW_BAD_OPTIONAL_ACCESS # define _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS #else # define _LIBCPP_AVAILABILITY_FUTURE _LIBCPP_AVAILABILITY_FUTURE_ERROR # define _LIBCPP_AVAILABILITY_THROW_BAD_ANY_CAST _LIBCPP_AVAILABILITY_BAD_ANY_CAST # define _LIBCPP_AVAILABILITY_THROW_BAD_OPTIONAL_ACCESS _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS # define _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS #endif // The stream API was dropped and re-added in the dylib shipped on macOS // and iOS. We can only assume the dylib to provide these definitions for // macosx >= 10.9 and ios >= 7.0. Otherwise, the definitions are available // from the headers, but not from the dylib. Explicit instantiation // declarations for streams exist conditionally to this; if we provide // an explicit instantiation declaration and we try to deploy to a dylib // that does not provide those symbols, we'll get a load-time error. #if !defined(_LIBCPP_BUILDING_LIBRARY) && \ ((defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1090) || \ (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 70000)) # define _LIBCPP_DO_NOT_ASSUME_STREAMS_EXPLICIT_INSTANTIATION_IN_DYLIB #endif #if defined(_LIBCPP_COMPILER_IBM) #define _LIBCPP_HAS_NO_PRAGMA_PUSH_POP_MACRO #endif #if defined(_LIBCPP_HAS_NO_PRAGMA_PUSH_POP_MACRO) # define _LIBCPP_PUSH_MACROS # define _LIBCPP_POP_MACROS #else // Don't warn about macro conflicts when we can restore them at the // end of the header. # ifndef _LIBCPP_DISABLE_MACRO_CONFLICT_WARNINGS # define _LIBCPP_DISABLE_MACRO_CONFLICT_WARNINGS # endif # if defined(_LIBCPP_COMPILER_MSVC) # define _LIBCPP_PUSH_MACROS \ __pragma(push_macro("min")) \ __pragma(push_macro("max")) # define _LIBCPP_POP_MACROS \ __pragma(pop_macro("min")) \ __pragma(pop_macro("max")) # else # define _LIBCPP_PUSH_MACROS \ _Pragma("push_macro(\"min\")") \ _Pragma("push_macro(\"max\")") # define _LIBCPP_POP_MACROS \ _Pragma("pop_macro(\"min\")") \ _Pragma("pop_macro(\"max\")") # endif #endif // defined(_LIBCPP_HAS_NO_PRAGMA_PUSH_POP_MACRO) #ifndef _LIBCPP_NO_AUTO_LINK # if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY) # if defined(_DLL) # pragma comment(lib, "c++.lib") # else # pragma comment(lib, "libc++.lib") # endif # endif // defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY) #endif // _LIBCPP_NO_AUTO_LINK #define _LIBCPP_UNUSED_VAR(x) ((void)(x)) // Configures the fopen close-on-exec mode character, if any. This string will // be appended to any mode string used by fstream for fopen/fdopen. // // Not all platforms support this, but it helps avoid fd-leaks on platforms that // do. #if defined(__BIONIC__) # define _LIBCPP_FOPEN_CLOEXEC_MODE "e" #else # define _LIBCPP_FOPEN_CLOEXEC_MODE #endif #endif // __cplusplus #endif // _LIBCPP_CONFIG
34.129755
132
0.773742
[ "object" ]
9759857fd23be14941e1a47dc5360b46db47b2d5
4,628
cpp
C++
Libs/Library/Source/GameObjects/DefaultGameComponent/UIAnimation.cpp
butibuti/ButiEngine
0d5b68461060fdcf9049a4afd51211c84f3472d1
[ "MIT" ]
null
null
null
Libs/Library/Source/GameObjects/DefaultGameComponent/UIAnimation.cpp
butibuti/ButiEngine
0d5b68461060fdcf9049a4afd51211c84f3472d1
[ "MIT" ]
null
null
null
Libs/Library/Source/GameObjects/DefaultGameComponent/UIAnimation.cpp
butibuti/ButiEngine
0d5b68461060fdcf9049a4afd51211c84f3472d1
[ "MIT" ]
null
null
null
#include"stdafx.h" void ButiEngine::UIAnimation::SetInitTransform(std::shared_ptr<Transform> arg_shp_InitTransform) { shp_initTransform= arg_shp_InitTransform->Clone(); shp_initTransform->SetLocalPosition().x /= size.x; shp_initTransform->SetLocalPosition().y /= size.y; shp_initTransform->SetLocalScale().x /= size.x; shp_initTransform->SetLocalScale().y /= size.y; } void ButiEngine::UIAnimation::SetTargetTransform(std::shared_ptr<Transform> arg_shp_targetTransform) { shp_targetTransform = arg_shp_targetTransform->Clone(); shp_targetTransform->SetLocalPosition().x /= size.x; shp_targetTransform->SetLocalPosition().y /= size.y; shp_targetTransform->SetLocalScale().x /= size.x; shp_targetTransform->SetLocalScale().y /= size.y; } std::shared_ptr<ButiEngine::GameComponent> ButiEngine::UIAnimation::Clone() { return ObjectFactory::Create<UIAnimation>(); } void ButiEngine::UIAnimation::PositionSet() { if (!shp_targetTransform) { return; } if (!gameObject.lock()) { return; } float time = Easing::GetEase(t, easeType); gameObject.lock()->transform->SetLocalPosition(shp_initTransform->SetLocalPosition() + (shp_targetTransform->SetLocalPosition() - shp_initTransform->SetLocalPosition()) * time); gameObject.lock()->transform->SetLocalPosition().x *= size.x; gameObject.lock()->transform->SetLocalPosition().y *= size.y; gameObject.lock()->transform->SetLocalScale(shp_initTransform->GetLocalScale() + (shp_targetTransform->GetLocalScale() - shp_initTransform->GetLocalScale()) * time); gameObject.lock()->transform->SetLocalScale().x *= size.x; gameObject.lock()->transform->SetLocalScale().y *= size.y; gameObject.lock()->transform->SetLocalRotation(MathHelper::LearpQuat(shp_initTransform->GetLocalRotation().ToQuat(), shp_targetTransform->GetLocalRotation().ToQuat(), time).ToMatrix()); } void ButiEngine::UIAnimation::OnShowUI() { GUI::BulletText("Time"); if (GUI::SliderFloat("##time", &t, 0.0, 1.0f)) { PositionSet(); } GUI::BulletText("Speed"); if (GUI::DragFloat("##speed", &speed, 0.0005f, -500, 500, "%.4f")) { PositionSet(); } GUI::Checkbox("IsLoop", &isReverse); GUI::Text(Easing::EasingTypeNames[(int)easeType]); if (GUI::ArrowButton("##EaseType_UP", GUI::GuiDir_Up)) { easeType = ((Easing::EasingType)(((int)easeType) + 1)); if ((int)easeType > (int)Easing::EasingType::CubeRotate90) { easeType = Easing::EasingType::CubeRotate90; } } GUI::SameLine(); if (GUI::ArrowButton("##EaseType_Down", GUI::GuiDir_Down)) { easeType = ((Easing::EasingType)(((int)easeType) - 1)); if ((int)easeType < 0) { easeType = Easing::EasingType::EaseIn; } } if (GUI::TreeNode("InitTransform")) { if (shp_initTransform) { if (shp_initTransform->ShowUI()) { PositionSet(); } } GUI::TreePop(); } if (GUI::TreeNode("TargetTransform")) { if (shp_targetTransform) { if (shp_targetTransform->ShowUI()) { PositionSet(); } } else { if (GUI::Button("Attach New")) { shp_targetTransform = ObjectFactory::Create<Transform>(); } } std::string target = "Target:"; if (shp_targetTransform) { target += "Existence"; } else { target += "nullptr"; } GUI::BeginChild("##TargetTransform", Vector2((GUI::GetFontSize()) * (target.size() + 2), GUI::GetFontSize() * 2), true); GUI::BulletText((target).c_str()); if (shp_targetTransform) { GUI::SameLine(); if (GUI::Button("Detach")) { shp_targetTransform = nullptr; } } if (GUI::IsWindowHovered()) { auto obj = GUI::GetDraggingObject(); if (obj && obj->IsThis<GameObject>()) { auto trans = obj->GetThis<GameObject>()->transform; if (shp_targetTransform != trans) { shp_targetTransform = trans; } } } GUI::EndChild(); GUI::TreePop(); } } void ButiEngine::UIAnimation::OnSet() { if (!shp_initTransform) { shp_initTransform = gameObject.lock()->transform->Clone(); } size.x = gameObject.lock()->GetApplication().lock()->GetWindow()->GetSize().x; size.y= gameObject.lock()->GetApplication().lock()->GetWindow()->GetSize().y; }
31.482993
189
0.602636
[ "transform" ]
97678ebe3e94b3136f59947a2139a05550b83b3b
1,640
cc
C++
src/classifierWorker.cc
rikailabs/node-fasttext
991ffdcaa9191e424967375aa76f3817d110a2dc
[ "MIT" ]
null
null
null
src/classifierWorker.cc
rikailabs/node-fasttext
991ffdcaa9191e424967375aa76f3817d110a2dc
[ "MIT" ]
null
null
null
src/classifierWorker.cc
rikailabs/node-fasttext
991ffdcaa9191e424967375aa76f3817d110a2dc
[ "MIT" ]
null
null
null
#include <iostream> #include "classifierWorker.h" void ClassifierWorker::Execute () { try { wrapper_->loadModel(); result_ = wrapper_->predict(sentence_, k_); } catch (std::string errorMessage) { SetErrorMessage(errorMessage.c_str()); } catch (const char * str) { std::cout << "Exception: " << str << std::endl; SetErrorMessage(str); } catch(const std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; SetErrorMessage(e.what()); } } void ClassifierWorker::HandleErrorCallback () { Nan::HandleScope scope; auto res = GetFromPersistent("key").As<v8::Promise::Resolver>(); res->Reject( Nan::GetCurrentContext() , Nan::Error(ErrorMessage())); v8::Isolate::GetCurrent()->RunMicrotasks(); } void ClassifierWorker::HandleOKCallback () { Nan::HandleScope scope; v8::Local<v8::Array> result = Nan::New<v8::Array>(result_.size()); for(unsigned int i = 0; i < result_.size(); i++) { v8::Local<v8::Object> returnObject = Nan::New<v8::Object>(); returnObject->Set( Nan::New<v8::String>("label").ToLocalChecked(), Nan::New<v8::String>(result_[i].label.c_str()).ToLocalChecked() ); returnObject->Set( Nan::New<v8::String>("value").ToLocalChecked(), Nan::New<v8::Number>(result_[i].value) ); result->Set(i, returnObject); } // promise resolver auto res = GetFromPersistent("key").As<v8::Promise::Resolver>(); res->Resolve( Nan::GetCurrentContext() , result); v8::Isolate::GetCurrent()->RunMicrotasks(); }
31.538462
75
0.59939
[ "object" ]
976b30f385552c8d85edc5c0b9ec731308a614e0
2,273
hh
C++
src/fileb.hh
grencez/cx
91c4967edeaf7319185a4c91e44db1ab81ec6609
[ "0BSD" ]
2
2015-08-11T22:31:28.000Z
2021-02-27T23:22:49.000Z
src/fileb.hh
grencez/cx
91c4967edeaf7319185a4c91e44db1ab81ec6609
[ "0BSD" ]
null
null
null
src/fileb.hh
grencez/cx
91c4967edeaf7319185a4c91e44db1ab81ec6609
[ "0BSD" ]
null
null
null
#ifndef FileB_HH_ #define FileB_HH_ #include "ofile.hh" #include "xfile.hh" extern "C" { #include "fileb.h" } namespace Cx { namespace C { using ::OFileB; using ::XFileB; } class OFileB : public Cx::OFile { private: C::OFileB ofb; public: OFileB() : OFile( &ofb.of ) { init_OFileB (&ofb); } ~OFileB() { lose_OFileB (&ofb); } bool open(const String& pathname, const String& filename) { return open_FileB (&ofb.fb, pathname.cstr(), filename.cstr()); } bool open(const String& filename) { return this->open ("", filename); } /** Open a user-specified file, defaulting to stdout if the file is "-". * * \return The output file that must be used. * It is wise to construct a Cx::OFile object with this. **/ C::OFile* uopen(const String& dirname, const String& filename) { if (filename == "-") { return stdout_OFile (); } if (filename == "/dev/stdout") { return stdout_OFile (); } if (filename == "/dev/stderr") { return stderr_OFile (); } if (this->open(dirname, filename)) { return &ofb.of; } return 0; } C::OFile* uopen(const String& filename) { return this->uopen("", filename); } private: OFileB(const OFileB&); OFileB& operator=(const OFileB&); }; class XFileB : public Cx::XFile { private: C::XFileB xfb; public: XFileB() : XFile( &xfb.xf ) { init_XFileB (&xfb); } ~XFileB() { lose_XFileB (&xfb); } bool open(const String& pathname, const String& filename) { return open_FileB (&xfb.fb, pathname.cstr(), filename.cstr()); } bool open(const String& filename) { return this->open ("", filename); } /** Open a user-specified file, defaulting to stdout if the file is "-". * * \return The output file that must be used. * It is wise to construct a Cx::XFile object with this. **/ C::XFile* uopen(const String& dirname, const String& filename) { if (filename == "-") { return stdin_XFile (); } if (this->open(dirname, filename)) { return &xfb.xf; } return 0; } C::XFile* uopen(const String& filename) { return this->uopen("", filename); } private: XFileB(const XFileB&); XFileB& operator=(const XFileB&); }; } #endif
19.10084
74
0.600528
[ "object" ]
97712ce64968aba4ddb2d89a71045d2434ffe9e1
828
cpp
C++
homework/Kulagin/02/main.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
12
2018-02-20T15:25:12.000Z
2022-02-15T03:31:55.000Z
homework/Kulagin/02/main.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
1
2018-02-26T12:40:47.000Z
2018-02-26T12:40:47.000Z
homework/Kulagin/02/main.cpp
nkotelevskii/msu_cpp_spring_2018
b5d84447f9b8c7f3615b421c51cf4192f1b90342
[ "MIT" ]
33
2018-02-20T15:25:11.000Z
2019-02-13T22:33:36.000Z
#include <iostream> #include <vector> #include <cmath> #include "numbers.dat" using namespace std; int main(int argc, char** argv) { if (argc < 3 || argc % 2 == 0) { return -1; } int k1, k2; int n = 0; for (int a = 1; a < argc; a += 2) { k1 = atoi(argv[a]); k2 = atoi(argv[a + 1]); if (k1 > k2) { printf("0"); return 0; } n = max(n, k2); } vector<bool> prime(n, true); prime[0] = prime[1] = false; for (int i = 2; i * i <= n; i++) if (prime[i]) for (int j = i + i; j <= n; j += i) prime[j] = false; int prime_cnt; int i; for (int a = 1; a < argc; a += 2) { k1 = atoi(argv[a]); k2 = atoi(argv[a + 1]); prime_cnt = 0; i = 0; for (i = 0; Data[i] < k1; i++); while (Data[i] < k2) prime_cnt += prime[ Data[i++]]; printf("%d\n", prime_cnt); } return 0; }
13.354839
38
0.492754
[ "vector" ]
977357ea1cddb0af1b648c5d156bc6b87d2e1d6c
1,354
cpp
C++
src/AudioProcessorFactory.cpp
Kaayy-J/OHMComm-Light
08a67e20da3369d199a285071105404daeb33d6c
[ "MIT" ]
null
null
null
src/AudioProcessorFactory.cpp
Kaayy-J/OHMComm-Light
08a67e20da3369d199a285071105404daeb33d6c
[ "MIT" ]
1
2016-01-31T16:12:10.000Z
2016-01-31T16:12:10.000Z
src/AudioProcessorFactory.cpp
Kaayy-J/OHMComm
08a67e20da3369d199a285071105404daeb33d6c
[ "MIT" ]
null
null
null
/* * File: AudioProcessorFactory.cpp * Author: daniel * * Created on June 27, 2015, 10:15 AM */ #include "AudioProcessorFactory.h" #include "ProcessorOpus.h" #include "ProcessorWAV.h" #include "ProfilingAudioProcessor.h" const std::string AudioProcessorFactory::OPUS_CODEC = "Opus-Codec"; const std::string AudioProcessorFactory::WAV_WRITER = "wav-Writer"; AudioProcessor* AudioProcessorFactory::getAudioProcessor(const std::string name, bool createProfiler) { AudioProcessor* processor = nullptr; #ifdef PROCESSOROPUS_H if(name == OPUS_CODEC) { processor = new ProcessorOpus(OPUS_CODEC, OPUS_APPLICATION_VOIP); } #endif #ifdef PROCESSORWAV_H if(name == WAV_WRITER) { processor = new ProcessorWAV(WAV_WRITER); } #endif if(processor != nullptr) { if(createProfiler) { return new ProfilingAudioProcessor(processor); } return processor; } throw std::invalid_argument("No AudioProcessor for the given name"); } const std::vector<std::string> AudioProcessorFactory::getAudioProcessorNames() { std::vector<std::string> processorNames; #ifdef PROCESSOROPUS_H processorNames.push_back(OPUS_CODEC); #endif #ifdef PROCESSORWAV_H processorNames.push_back(WAV_WRITER); #endif return processorNames; }
24.618182
101
0.694978
[ "vector" ]
977816dcca8b77cefd3fcf16ee2c76e40c047fc3
3,482
cpp
C++
src/rendering/Renderer.cpp
ademuri/shadowbox
e9dd9cdf42970f67cb77e0e48c1ba2298e3a5653
[ "MIT" ]
null
null
null
src/rendering/Renderer.cpp
ademuri/shadowbox
e9dd9cdf42970f67cb77e0e48c1ba2298e3a5653
[ "MIT" ]
null
null
null
src/rendering/Renderer.cpp
ademuri/shadowbox
e9dd9cdf42970f67cb77e0e48c1ba2298e3a5653
[ "MIT" ]
null
null
null
#include "Renderer.hpp" #include <iostream> using namespace std; // Identifier for the solid color shader. static GLuint solidShaderProgram; // Index for the color property on the shader. static GLint solidShaderColorLoc; GLuint Renderer::LoadShader(GLenum type, const char *shaderSrc) { GLuint shader; GLint compiled; // Create the shader object shader = glCreateShader(type); if (shader == 0) { return 0; } // Load the shader source glShaderSource(shader, 1, &shaderSrc, NULL); // Compile the shader glCompileShader(shader); // Check the compile status glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen > 1) { char *infoLog = (char *)malloc(sizeof(char) * infoLen); glGetShaderInfoLog(shader, infoLen, NULL, infoLog); cout << "Error compiling shader:\n" << infoLog << endl; free(infoLog); } glDeleteShader(shader); return 0; } return shader; } int Renderer::Init() { char vShaderStr[] = "#version 300 es \n" "layout(location = 0) in vec2 position; \n" "void main() \n" "{ \n" " gl_Position = vec4(position, 0.0, 1.0); \n" "} \n"; char fShaderStr[] = "#version 300 es \n" "precision mediump float; \n" "uniform vec4 u_color; \n" "out vec4 fragColor; \n" "void main() \n" "{ \n" " fragColor = u_color; \n" "} \n"; GLuint vertexShader; GLuint fragmentShader; GLint linked; // Load the vertex/fragment shaders vertexShader = Renderer::LoadShader(GL_VERTEX_SHADER, vShaderStr); fragmentShader = Renderer::LoadShader(GL_FRAGMENT_SHADER, fShaderStr); // Create the program object solidShaderProgram = glCreateProgram(); if (solidShaderProgram == 0) { return 0; } glAttachShader(solidShaderProgram, vertexShader); glAttachShader(solidShaderProgram, fragmentShader); // Link the program glLinkProgram(solidShaderProgram); // Check the link status glGetProgramiv(solidShaderProgram, GL_LINK_STATUS, &linked); if (!linked) { GLint infoLen = 0; glGetProgramiv(solidShaderProgram, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen > 1) { char *infoLog = (char *)malloc(sizeof(char) * infoLen); glGetProgramInfoLog(solidShaderProgram, infoLen, NULL, infoLog); cout << "Error linking program:\n" << infoLog << endl; free(infoLog); } glDeleteProgram(solidShaderProgram); return 0; } solidShaderColorLoc = glGetUniformLocation(solidShaderProgram, "u_color"); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); return 1; } void Renderer::useSolidShader() { glUseProgram(solidShaderProgram); } void Renderer::setSolidShaderColor(float r, float g, float b, float a) { glUniform4f(solidShaderColorLoc, r, g, b, a); } GlPoint Renderer::pixelsToPoint(unsigned int x, unsigned int y) { return GlPoint{1.0 - x * 2.0 / 320, 1.0 - y * 2.0 / 240}; }
27.203125
76
0.576106
[ "object", "solid" ]
9782127cd6df6a08d61d01ad92658349992b31f1
13,211
cpp
C++
gamePlay.cpp
pattrickrice/valley-of-the-moon
bda0c305c2979eda1f0bc7a0fb32b7bbe21d0c40
[ "MIT" ]
null
null
null
gamePlay.cpp
pattrickrice/valley-of-the-moon
bda0c305c2979eda1f0bc7a0fb32b7bbe21d0c40
[ "MIT" ]
null
null
null
gamePlay.cpp
pattrickrice/valley-of-the-moon
bda0c305c2979eda1f0bc7a0fb32b7bbe21d0c40
[ "MIT" ]
null
null
null
/********************************************************************* * Author: Patrick Rice * Date: 12/1/2017 * Description: Implementation file for the gameState class *********************************************************************/ #include <cstdlib> #include "gamePlay.hpp" #include "utils/utilities.hpp" #include "space/keySpace.hpp" #include "space/doorSpace.hpp" using std::cout; using std::endl; using std::vector; using std::cin; using std::to_string; /********************************************************************* * Default constructor *********************************************************************/ GamePlay::GamePlay() { Player player(2, 2); this->player = player; this->width = 90; this->stepCounter = 0; this->stepsLeft = 1600; this->startingMap = "houseMap.txt"; this->mapState = HOUSE; } /********************************************************************* * Constructor * @param width is the width of the console output *********************************************************************/ GamePlay::GamePlay(int width) { Player player(0, 0); this->player = player; this->width = width; this->stepCounter = 0; this->stepsLeft = 1600; this->startingMap = "houseMap.txt"; this->mapState = HOUSE; } /********************************************************************* * Constructor for debugging specific maps * @param width is the width of the console output * @param fileName the of the map * @param mapState is the starting map state *********************************************************************/ GamePlay::GamePlay(int width, string fileName, MapState mapState) { Player player(0, 0); this->player = player; this->width = width; this->stepCounter = 0; this->stepsLeft = 1600; this->startingMap = fileName; this->mapState = mapState; } /********************************************************************* * Constructor for debugging specific maps * @param width is the width of the console output * @param fileName the of the map * @param player is the player object and can include starting * information such as its initial position. * @param mapState is the starting map state * @param player is the starting player *********************************************************************/ GamePlay::GamePlay(int width, string fileName, MapState mapState, Player player) { this->player = player; this->width = width; this->startingMap = fileName; this->mapState = mapState; this->stepCounter = 0; this->stepsLeft = 1600; } /********************************************************************* * Contains the game play for th game. Continues until the player * chooses to exit the game. *********************************************************************/ void GamePlay::play() { // declare variables char move = ' ', doorID = ' '; bool passedThroughDoor = false; bool couldMove = false, wonGame = false; KeySpace *keySpace; DoorSpace *doorSpace; string newKey; // key input instructions int size = 6; char acceptable[6] = {'a', 's', 'd', 'w', 'e', 'p'}; string instructions = "a = left, s = down, d = right, w = up, p = print keys, e = exit"; string keysList = "You have the following keys: "; // create all of the maps Map house("maps/houseMap.txt", "keys/houseKeys.txt", "doors/houseDoorKeys.txt", HOUSE); Map valley("maps/valley.txt", "keys/valleyKeys.txt", "doors/valleyDoorKeys.txt", VALLEY); Map forest("maps/forest.txt", "keys/forestKeys.txt", "doors/forestDoorKeys.txt", FOREST); Map deepForrest("maps/deepForest.txt", "keys/deepForestKeys.txt", "doors/deepForestDoorKeys.txt", DEEPFOREST); Map lake("maps/lake.txt", "keys/lakeKeys.txt", "doors/lakeDoorKeys.txt", LAKE); Map ranch("maps/ranch.txt", "keys/ranchKeys.txt", "doors/ranchDoorKeys.txt", RANCH); Map castle("maps/castle.txt", "keys/castleKeysKeys.txt", "doors/castleDoorKeys.txt", CASTLE); vector<Map *> maps; maps.push_back(&house); maps.push_back(&valley); maps.push_back(&forest); maps.push_back(&deepForrest); maps.push_back(&lake); maps.push_back(&ranch); maps.push_back(&castle); // initialize variables Map *map = &house; MapState mapState = HOUSE; // initialize character starting position Space *playerSpace = house.getSpace(player.getXCoord(), player.getYCoord()); player.setXCoord(house.getPlayerStartingX()); player.setYCoord(house.getPlayerStartingY()); house.printMap(player.getXCoord(), player.getYCoord()); // begin printing printStartingDialogue(map, player); system("clear"); house.printMap(player.getXCoord(), player.getYCoord()); // //DEBUG - use as shortcuts // player.pickUpKey("forestKey"); // player.pickUpKey("houseKey"); // player.pickUpKey("lakeKey"); // player.pickUpKey("ranchKey"); // player.pickUpKey("castleKey"); // width is the size of the board this->width = map->getBoardSizeX() - 2; while (move != 'e' && mapState != END && stepsLeft != 0) { // have the player make the move printInstructions(instructions, map->getBoardSizeX()); move = getCharacterNoReturn(acceptable, size); stepsLeft--; couldMove = player.makeMove(move, playerSpace, width); // display the result system("clear"); playerSpace = map->getSpace(player.getXCoord(), player.getYCoord()); map->printMap(player.getXCoord(), player.getYCoord()); // print space reaction if could not move if (!couldMove) { // print space reaction player.failedMoveReact(move, playerSpace, width); // show keys if (move == 'p') { keysList = "You have the following keys: "; player.getKeys(); if (player.getKeys().size() == 0) { keysList += "you have no keys!"; } for (const auto &key : player.getKeys()) { keysList += key + " "; } printMessage(keysList, width); } } // specific space functions switch (playerSpace->getSpaceType()) { case KEY: keySpace = dynamic_cast<KeySpace *>(playerSpace); keySpace->react(width); // if the player hasn't grabbed the key already if (keySpace->isKeyPresent()) { newKey = keySpace->takeKey(); player.pickUpKey(newKey); } break; case DOOR: doorSpace = dynamic_cast<DoorSpace *>(playerSpace); // check that player posesses key if (player.hasKey(doorSpace->getKey())) { mapState = doorSpace->getMapState(); passedThroughDoor = true; doorID = doorSpace->getDoorID(); } else { printMessage("You do not have the required key: " + doorSpace->getKey(), width); } break; case EXIT: playerSpace->react(width); mapState = END; wonGame = true; break; default: break; } // move maps if (passedThroughDoor) { system("clear"); map = getMap(maps, mapState); this->width = map->getBoardSizeX() - 2; // player just entered the map. Find their location player.setXCoord(map->getDoorXCoord(doorID)); player.setYCoord(map->getDoorYCoord(doorID)); playerSpace = map->getSpace(player.getXCoord(), player.getYCoord()); map->printMap(player.getXCoord(), player.getYCoord()); passedThroughDoor = false; } } if (wonGame) { printEndingDialogue(map, player); } else if (move == 'e') { printDialogue("Quiting game", width); } else { {} printDialogue("You have died from poisoning", width); } // ending screen system("clear"); printBorder(width); printLeftAligned( "Thank you for playing my project, this was made for Oregon State's CS 162 intro to computer science II", width); printLeftAligned("Credit: Patrick Rice", width); printCenterTitle("Goodbye", width); } /********************************************************************* * Returns the new map * @param maps is the list of the maps for the game * @param mapState is the new mapstate the game is in ********************************************************************/ Map *GamePlay::getMap(vector<Map *> maps, MapState mapState) { for (unsigned int i = 0; i < maps.size(); ++i) { if (maps.at(i)->getMapID() == mapState) { return maps.at(i); } } cout << "[ERROR] in moveMaps in GamePlay.cpp" << endl; return maps.at(0); } /********************************************************************* * prints the instructions on how to move the character * @param instructions is a built string with some instructions in it * @param width is the size of the console ********************************************************************/ void GamePlay::printInstructions(string instructions, int width) { width = width - 2; printBorder(width); printLeftAligned(instructions, width); printLeftAligned("Steps left: " + to_string(stepsLeft), width); printLeftAligned("Enter your move: ", width); printBorder(width); } /********************************************************************* * prints the dialogue on the screen * @param dialogue is the dialogue to be printed * @param width is the size of the console ********************************************************************/ void GamePlay::printDialogue(string dialogue, int width) { dialogue += "\n [Press enter to continue]"; printBorder(width); printLeftAligned(dialogue, width); printBorder(width); cin.ignore(); } /********************************************************************* * Prints the starting dialogue * @param map is the map that is displayed with the dialogue * @param player is the player *********************************************************************/ void GamePlay::printStartingDialogue(Map *map, Player player) { string speech[6] = {"Brother: I can't believe this is happening!", "Brother: Of all the thoughtless things you could have done...", "Brother: I told you to grab Queen Anne's Lace for some carrot tea, and you grabbed poison hemlock! It's just a matter of time before the poison's effects take hold on you...", "Brother: There's only one place you can get an antidote, the castle at the southern end of the Valley of the Moon.", "Brother: You're going to have find a key to get you access to it, and beware, every step you take is one step towards that poison taking your life", "Brother: Go now, find your way to the castle and save your self."}; for (int i = 0; i < 6; ++i) { advanceDialouge(speech[i], map, player); } } /********************************************************************* * prints the ending dialogue of the game * @param map is the map that is displayed with the dialogue * @param player is the player *********************************************************************/ void GamePlay::printEndingDialogue(Map *map, Player player) { string speech[6] = {"You found the antidote!", "With the little energy you have left, you open the bottle and drink until it's dry.", "...", "You can feel your energy coming back!", "Never again will you make the mistake between Queen Anne's Lace and poison hemlock!", "Remember, hemlock's stems are red with the blood of Socrates."}; for (int i = 0; i < 6; ++i) { advanceDialouge(speech[i], map, player); } } /********************************************************************* * Advances the dialogue without changing anything else * @param dialogue is the dialogue being printed out * @param map is the map that is displayed with the dialogue * @param player is the player *********************************************************************/ void GamePlay::advanceDialouge(string dialogue, Map *map, Player player) { int width = map->getBoardSizeX() - 2; system("clear"); map->printMap(player.getXCoord(), player.getYCoord()); printDialogue(dialogue, width); }
40.155015
201
0.519643
[ "object", "vector" ]
978a06c22dde65cbf8e23f9551fed909c0a0593b
5,671
cpp
C++
Sources/Graphics/RenderSystem/SyrinxModel.cpp
LeptusHe/SyrinxEngine
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
[ "MIT" ]
3
2020-04-24T07:58:52.000Z
2021-11-17T11:08:46.000Z
Sources/Graphics/RenderSystem/SyrinxModel.cpp
LeptusHe/SyrinxEngine
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
[ "MIT" ]
null
null
null
Sources/Graphics/RenderSystem/SyrinxModel.cpp
LeptusHe/SyrinxEngine
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
[ "MIT" ]
2
2019-10-02T01:49:46.000Z
2021-11-16T15:25:59.000Z
#include "RenderSystem/SyrinxModel.h" #include <iostream> #include <assimp/postprocess.h> #include <stb/stb_image.h> #include <Exception/SyrinxException.h> #include <FileSystem/SyrinxFileSystem.h> #include <Logging/SyrinxLogManager.h> namespace Syrinx { Model::Model(FileManager *fileManager, const std::string& modelFilePath) : mFileManager(fileManager) , mModelFileDirectory("") { SYRINX_ASSERT(!modelFilePath.empty()); SYRINX_ENSURE(mFileManager); loadModel(modelFilePath); } Model::~Model() { } void Model::loadModel(const std::string& modelFilePath) { SYRINX_ASSERT(!modelFilePath.empty()); auto [fileExist, filePath] = mFileManager->findFile(modelFilePath); if (!fileExist) { SYRINX_THROW_EXCEPTION_FMT(ExceptionCode::FileNotFound, "can not find file [{}]", modelFilePath); } Assimp::Importer importer; const auto scene = importer.ReadFile(filePath, aiProcess_Triangulate | aiProcess_GenNormals | aiProcess_FlipUVs); if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { SYRINX_THROW_EXCEPTION_FMT(ExceptionCode::InvalidState, "fail to read model [{}] because [{}]", filePath, importer.GetErrorString()); return; } auto fileSystem = mFileManager->getFileSystem(); mModelFileDirectory = fileSystem->getParentPath(filePath); SYRINX_ENSURE(!mModelFileDirectory.empty()); processNode(scene->mRootNode, scene); } void Model::processNode(aiNode *node, const aiScene *scene) { for (unsigned int i = 0; i < node->mNumMeshes; ++i) { auto mesh = scene->mMeshes[node->mMeshes[i]]; mMeshes.push_back(processMesh(mesh, scene)); } for (unsigned int i = 0; i < node->mNumChildren; ++i) { processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh *mesh, const aiScene *scene) { std::vector<Vertex> verticesSet; std::vector<unsigned int> indicesSet; std::vector<Texture> textureSet; for (unsigned int i = 0; i < mesh->mNumVertices; ++i) { Vertex vertex; vertex.position = glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z); vertex.normal = glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z); if (mesh->mTextureCoords[0]) { vertex.texCoords = glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y); } verticesSet.push_back(vertex); } for (unsigned int i = 0; i < mesh->mNumFaces; ++i) { auto face = mesh->mFaces[i]; for (unsigned int k = 0; k < face.mNumIndices; ++k) { indicesSet.push_back(face.mIndices[k]); } } if (mesh->mMaterialIndex >= 0) { auto material = scene->mMaterials[mesh->mMaterialIndex]; std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "uTextureDiffuse"); textureSet.insert(textureSet.end(), diffuseMaps.begin(), diffuseMaps.end()); std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "uTextureSpecular"); textureSet.insert(textureSet.end(), specularMaps.begin(), specularMaps.end()); } return Mesh(verticesSet, indicesSet, textureSet); } std::vector<Texture> Model::loadMaterialTextures(aiMaterial *material, aiTextureType type, std::string typeName) { auto fileSystem = mFileManager->getFileSystem(); std::vector<Texture> texturesSet; for (unsigned int i = 0; i < material->GetTextureCount(type); ++i) { aiString str; material->GetTexture(type, i, &str); std::string filePath = fileSystem->combine(mModelFileDirectory, str.C_Str()); bool skip = false; for (auto textureLoaded : mTexturesLoadedSet) { if (std::strcmp(textureLoaded.filePath.data(), filePath.c_str()) == 0) { texturesSet.push_back(textureLoaded); skip = true; break; } } if (!skip) { Texture texture; texture.id = loadTexture(filePath); texture.samplerName = typeName + std::to_string(i); texture.filePath = filePath; texturesSet.push_back(texture); mTexturesLoadedSet.push_back(texture); } } return texturesSet; } GLuint Model::loadTexture(const std::string& textureFilePath) { SYRINX_ASSERT(!textureFilePath.empty()); GLsizei textureWidth, textureHeight, channelCount; stbi_uc *textureSource = stbi_load(textureFilePath.c_str(), &textureWidth, &textureHeight, &channelCount, STBI_rgb_alpha); if (!textureSource) { SYRINX_THROW_EXCEPTION_FMT(ExceptionCode::InvalidParams, "fail to load texture [{}] because [{}]", textureFilePath, stbi_failure_reason()); } GLuint texture = 0; glCreateTextures(GL_TEXTURE_2D, 1, &texture); int maxSize = std::max(textureWidth, textureHeight); int maxLevel = static_cast<int>(std::ceil(std::log2(maxSize))); SYRINX_ENSURE(maxLevel > 0); glTextureStorage2D(texture, maxLevel, GL_RGBA8, textureWidth, textureHeight); glTextureSubImage2D(texture, 0, 0, 0, textureWidth, textureHeight, GL_RGBA, GL_UNSIGNED_BYTE, textureSource); glTextureParameteri(texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTextureParameteri(texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTextureParameteri(texture, GL_TEXTURE_WRAP_S, GL_REPEAT); glTextureParameteri(texture, GL_TEXTURE_WRAP_T, GL_REPEAT); glGenerateTextureMipmap(texture); glBindTexture(GL_TEXTURE_2D, 0); SYRINX_ENSURE(texture != 0); return texture; } } // namespace Syrinx
36.121019
147
0.677835
[ "mesh", "vector", "model" ]
978b45ee0ab7e519c12b125816c7340f73d98180
9,620
cpp
C++
test/Core/MPS.test.cpp
QianJianhua1/QPanda-2
a13c7b733031b1d0007dceaf1dae6ad447bb969c
[ "Apache-2.0" ]
null
null
null
test/Core/MPS.test.cpp
QianJianhua1/QPanda-2
a13c7b733031b1d0007dceaf1dae6ad447bb969c
[ "Apache-2.0" ]
null
null
null
test/Core/MPS.test.cpp
QianJianhua1/QPanda-2
a13c7b733031b1d0007dceaf1dae6ad447bb969c
[ "Apache-2.0" ]
null
null
null
#include <atomic> #include <chrono> #include <string> #include "QPanda.h" #include <algorithm> #include "gtest/gtest.h" #include "ThirdParty/rapidjson/writer.h" #include "ThirdParty/rapidjson/document.h" #include "ThirdParty/rapidjson/stringbuffer.h" #include "ThirdParty/Eigen/Dense" #include "ThirdParty/Eigen/Sparse" #include <EigenUnsupported/Eigen/KroneckerProduct> #define CHECK_RUN_TIME_BEGIN auto start_time = chrono::system_clock::now()\ #define CHECK_RUN_TIME_END_AND_COUT_SECONDS(argv) auto final_time = chrono::system_clock::now();\ auto duration = chrono::duration_cast<chrono::microseconds>(final_time - start_time);\ std::cout << argv << " -> run_time counts :" << double(duration.count()) * chrono::microseconds::period::num / chrono::microseconds::period::den << std::endl\ using namespace std; using namespace rapidjson; constexpr size_t SHOTS = 100; QCircuit qft_prog(const QVec& qvec) { QCircuit qft = CreateEmptyCircuit(); for (auto i = 0; i < qvec.size(); i++) { qft << H(qvec[qvec.size() - 1 - i]); for (auto j = i + 1; j < qvec.size(); j++) { qft << CR(qvec[qvec.size() - 1 - j], qvec[qvec.size() - 1 - i], 2 * PI / (1 << (j - i + 1))); } } return qft; } QProg ghz_prog(const QVec& q) { auto prog = QProg(); prog << H(q[0]); for (auto i = 0; i < q.size() - 1; ++i) { prog << CNOT(q[i], q[i + 1]); } return prog; } static std::string build_chain_typed_quantum_chip_config_data(size_t qubit_num) { rapidjson::Document arch_doc; arch_doc.SetObject(); rapidjson::Document::AllocatorType &arch_alloc = arch_doc.GetAllocator(); rapidjson::Value adj_object(rapidjson::kObjectType); for (SizeType qubit_addr = 0; qubit_addr < qubit_num; qubit_addr++) { rapidjson::Value qubit_array(rapidjson::kArrayType); if (qubit_addr != 0) { rapidjson::Value qubit_value(rapidjson::kObjectType); qubit_value.AddMember("v", qubit_addr - 1, arch_alloc); qubit_value.AddMember("w", 1.0, arch_alloc); qubit_array.PushBack(qubit_value, arch_alloc); } if (qubit_addr != (qubit_num - 1)) { rapidjson::Value qubit_value(rapidjson::kObjectType); qubit_value.AddMember("v", qubit_addr + 1, arch_alloc); qubit_value.AddMember("w", 1.0, arch_alloc); qubit_array.PushBack(qubit_value, arch_alloc); } std::string qubit_addr_str = to_string(qubit_addr); rapidjson::Value qubit_value(kStringType); qubit_value.SetString(qubit_addr_str.c_str(), (rapidjson::SizeType)qubit_addr_str.size(), arch_alloc); adj_object.AddMember(qubit_value, qubit_array, arch_alloc); } arch_doc.AddMember("adj", adj_object, arch_alloc); arch_doc.AddMember("QubitCount", (SizeType)qubit_num, arch_alloc); //construct final json rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType &alloc = doc.GetAllocator(); doc.AddMember("QuantumChipArch", arch_doc, alloc); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); return buffer.GetString(); } #if 0 void test_real_chip() { QCloudMachine QCM;; QCM.init("A0D08FA558CE45B2AF4F1DC122CF2589", true); QCM.set_qcloud_api("http://www.72bit.com"); auto q = QCM.allocateQubits(6); auto c = QCM.allocateCBits(6); //构建量子程序 auto measure_prog = QProg(); measure_prog << HadamardQCircuit(q) << RX(q[1], PI / 4) << RX(q[2], PI / 4) << RX(q[1], PI / 4) << CZ(q[0], q[1]) << CZ(q[1], q[2]) << Measure(q[0], c[0]) << Measure(q[1], c[1]); auto result = QCM.real_chip_measure(measure_prog, 1000, RealChipType::ORIGIN_WUYUAN_D4,true, true); for (auto val : result) { std::cout << val.first << " : " << val.second << std::endl; } auto result2 = QCM.get_state_tomography_density(measure_prog, 1000, RealChipType::ORIGIN_WUYUAN_D4); for (auto val : result2) { cout << val << endl; } auto result3 = QCM.get_state_fidelity(measure_prog, 1000, RealChipType::ORIGIN_WUYUAN_D4); cout << result3 << endl; QCM.finalize(); return; } void test_partial() { MPSQVM QCM;; QCM.init(); auto q = QCM.allocateQubits(6); auto c = QCM.allocateCBits(6); auto measure_prog = QProg(); auto measure_prog1 = QProg(); measure_prog1 << X(q[0]) << CZ(q[1], q[2]) << CZ(q[0], q[1]) << CZ(q[1], q[2]) << MeasureAll(q,c); QCM.set_noise_model(BIT_PHASE_FLIP_OPRATOR, GateType::CZ_GATE, 0.799); auto result = QCM.runWithConfiguration(measure_prog1, c, 10000); QCM.finalize(); return; } void test_qcloud() { try { QCloudMachine QCM; QCM.init("A0D08FA558CE45B2AF4F1DC122CF2589", true); QCM.set_qcloud_api("http://www.72bit.com"); //QCM.set_qcloud_api("http://10.10.10.39:8060"); auto q = QCM.allocateQubits(4); auto c = QCM.allocateCBits(4); std::vector<QProg> measure_prog_array(3); measure_prog_array[0] << H(q[0]) << MeasureAll(q, c); measure_prog_array[1] << H(q[0]) << CNOT(q[0], q[1]) << MeasureAll(q, c); measure_prog_array[2] << H(q[0]) << H(q[1]) << H(q[2]) << MeasureAll(q, c); std::vector<QProg> pmeasure_prog_array(3); pmeasure_prog_array[0] << H(q[0]) << H(q[1]); pmeasure_prog_array[1] << H(q[0]) << CNOT(q[0], q[1]); pmeasure_prog_array[2] << H(q[0]) << H(q[1]) << H(q[2]); //auto measure_result = QCM.full_amplitude_measure_batch(measure_prog_array, 10000); //TaskStatus status; //auto taskids = QCM.real_chip_measure_batch_commit(measure_prog_array, 10000, status); auto real_result = QCM.real_chip_measure_batch(measure_prog_array, 10000); //auto a = QCM.real_chip_measure_batch_query(taskids); //auto pmeasure_result = QCM.full_amplitude_pmeasure_batch(pmeasure_prog_array, { 0,1,2,3,4,5 }); //auto partial_pmeasure_result = QCM.partial_amplitude_pmeasure_batch(pmeasure_prog_array, { "0","1","2" }); //auto single_pmeasure_result = QCM.single_amplitude_pmeasure_batch(pmeasure_prog_array, "0"); //for (auto item : measure_result) //{ //for (auto val : item) //{ //cout << val.first << " : " << val.second << endl; //} //} //QCM.set_noise_model(NOISE_MODEL::BITFLIP_KRAUS_OPERATOR, { 0.9 }, { 0.9 }); //auto noise_measure_result = QCM.noise_measure(measure_prog_array[0], 10000); //for (auto item : measure_result) //{ //for (auto val : item) //{ //cout << val.first << " : " << val.second << endl; //} //} cout << "--------------" << endl; //for (auto item : real_measure_result) //{ //cout << "--------------" << endl; //for (auto val : item) //{ // cout << val.first << " : " << val.second << endl; //} //} cout << "--------------" << endl; //for (auto item : pmeasure_result) //{ //cout << "--------------" << endl; //for (auto val : item) //{ //cout << val.first << " : " << val.second << endl; //} //} cout << "--------------" << endl; cout << "--------------" << endl; //for (auto item : single_pmeasure_result) //{ // cout << item << endl; //} cout << "--------------" << endl; QCM.finalize(); } catch (const std::exception e) { cout << e.what() << endl; } return; } TEST(MPS, test) { //test_partial(); cout << 1222 << endl; test_partial(); MPSQVM qvm; qvm.init(); auto q = qvm.qAllocMany(2); auto c = qvm.cAllocMany(2); qvm.add_single_noise_model(NOISE_MODEL::PHASE_DAMPING_OPRATOR, GateType::PAULI_X_GATE, 0.8); qvm.add_single_noise_model(NOISE_MODEL::BITFLIP_KRAUS_OPERATOR, GateType::PAULI_X_GATE, 0.8); //qvm.add_single_noise_model(NOISE_MODEL::DEPOLARIZING_KRAUS_OPERATOR, GateType::PAULI_X_GATE, 0.99); //qvm.add_single_noise_model(NOISE_MODEL::DEPHASING_KRAUS_OPERATOR, GateType::PAULI_X_GATE, 0.49); //qvm.add_single_noise_model(NOISE_MODEL::DECOHERENCE_KRAUS_OPERATOR, GateType::PAULI_X_GATE, 5, 5, 0.9); //qvm.set_noise_model(NOISE_MODEL::BITFLIP_KRAUS_OPERATOR, GateType::CNOT_GATE, 0.1); //QVec qv0 = { q[0], q[1] }; //qvm.set_noise_model(NOISE_MODEL::DEPHASING_KRAUS_OPERATOR, GateType::HADAMARD_GATE, 0.1, qv0); //std::vector<QVec> qves = { {q[0], q[1]}, {q[1], q[2]} }; //qvm.set_noise_model(NOISE_MODEL::DAMPING_KRAUS_OPERATOR, GateType::CNOT_GATE, 0.1, qves); QProg prog; //prog << X(q[0]) << MeasureAll(q, c); prog << H(q[0]) << X(q[1]) << H(q[1]) << CNOT(q[0],q[1]) << H(q[0]) << Measure(q[0], c[0]); //auto noise_ptr = (NoiseQVM*)(&qvm); //auto noise_ptr = dynamic_cast<NoiseQVM*>(&qvm); //single_qubit_rb(&qvm, q[0], {6}, 1, 100); auto result = qvm.runWithConfiguration(prog, c, 10000); for (auto &item : result) { std::cout << item.first << " : " << item.second << std::endl; } return; } #endif
30.443038
210
0.580353
[ "vector" ]
978bcb105289b82582b40a5800f1edfd45de6251
3,050
hpp
C++
dsp/L1/tests/aie/inc/fft_ifft_dit_1ch_ref.hpp
dycz0fx/Vitis_Libraries
d3fc414b552493657101ddb5245f24528720823d
[ "Apache-2.0" ]
1
2021-09-11T01:05:01.000Z
2021-09-11T01:05:01.000Z
dsp/L1/tests/aie/inc/fft_ifft_dit_1ch_ref.hpp
maxpark/Vitis_Libraries
4bd100518d93a8842d1678046ad7457f94eb355c
[ "Apache-2.0" ]
null
null
null
dsp/L1/tests/aie/inc/fft_ifft_dit_1ch_ref.hpp
maxpark/Vitis_Libraries
4bd100518d93a8842d1678046ad7457f94eb355c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 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. */ #ifndef _DSPLIB_FFT_IFFT_DIT_1CH_REF_HPP_ #define _DSPLIB_FFT_IFFT_DIT_1CH_REF_HPP_ /* FFT/iFFT DIT single channel reference model */ #ifndef _DSPLIB_FFT_IFFT_DIT_1CH_REF_DEBUG_ //#define _DSPLIB_FFT_IFFT_DIT_1CH_REF_DEBUG_ #endif //_DSPLIB_FFT_IFFT_DIT_1CH_REF_DEBUG_ #include <adf.h> #include <limits> namespace xf { namespace dsp { namespace aie { namespace fft { namespace dit_1ch { #include "fft_ref_utils.hpp" constexpr int kFftDynHeadBytes = 32; //----------------------------------------------------------------------------------------------------- // FFT/iFFT DIT single channel reference model class template <typename TT_DATA, // type of data input and output typename TT_TWIDDLE, // type of twiddle factor unsigned int TP_POINT_SIZE, unsigned int TP_FFT_NIFFT, unsigned int TP_SHIFT, unsigned int TP_DYN_PT_SIZE, unsigned int TP_WINDOW_VSIZE = TP_POINT_SIZE> class fft_ifft_dit_1ch_ref { private: TT_TWIDDLE twiddles[TP_POINT_SIZE]; static constexpr unsigned int kMaxLogPtSize = 12; static constexpr unsigned int kRanks = fnGetPointSizePower<TP_POINT_SIZE>(); // while each rank is radix2 this is true void r2StageInt( T_int_data<TT_DATA>* samplesA, T_int_data<TT_DATA>* samplesB, TT_TWIDDLE* twiddles, int pptSize, bool inv); void r2StageFloat(T_int_data<TT_DATA>* samplesA, T_int_data<TT_DATA>* samplesB, TT_TWIDDLE* twiddles, unsigned int rank, int pptSize, bool inv); void r4StageInt(T_int_data<TT_DATA>* samplesIn, TT_TWIDDLE* twiddles1, TT_TWIDDLE* twiddles2, unsigned int n, unsigned int r, unsigned int shift, unsigned int rank, T_int_data<TT_DATA>* samplesOut, int pptSize, bool inv); public: // Constructor fft_ifft_dit_1ch_ref() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fft_ifft_dit_1ch_ref::fft); } // FFT void fft(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* outWindow); void nonBitAccfft(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* outWindow); }; } } } } } // namespace closing braces #endif // _DSPLIB_FFT_IFFT_DIT_1CH_REF_HPP_
34.269663
115
0.65082
[ "model" ]
978e72e24156bf65e713be5f7f0ad0cd85efb8c7
610
cpp
C++
tests/geometry/algorithm/polygon/max_distance.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
17
2018-08-22T06:48:20.000Z
2022-02-22T21:20:09.000Z
tests/geometry/algorithm/polygon/max_distance.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
tests/geometry/algorithm/polygon/max_distance.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
// Copyright 2018 Oleksandr Bacherikov. // // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #include <actl/geometry/algorithm/polygon/max_distance.hpp> #include "test.hpp" TEST_CASE("default") { convex_polygon<point<double>> poly{ {-0.9846, -1.53251}, {3.88558, -2.37188}, {3.92734, -2.37856}, {4.02136, -1.57843}, {0.79916, 0.98291}, {0.49946, 1.19525}}; auto dist = max_distance(poly); CHECK_NEAR(dist, distance(poly[0], poly[3]), 1e-12); }
27.727273
60
0.632787
[ "geometry" ]
979f84535caaacd849a2381d02d2e18e11aa05b9
3,556
hpp
C++
phosphor-rsyslog-config/server-conf.hpp
Alpana07/phosphor-logging
1be39849bd974c2f7df7fa932edcd7f71a2c6d59
[ "Apache-2.0" ]
5
2017-12-01T19:34:13.000Z
2020-12-29T10:50:32.000Z
phosphor-rsyslog-config/server-conf.hpp
Alpana07/phosphor-logging
1be39849bd974c2f7df7fa932edcd7f71a2c6d59
[ "Apache-2.0" ]
26
2017-02-02T08:20:10.000Z
2021-11-16T18:28:44.000Z
phosphor-rsyslog-config/server-conf.hpp
Alpana07/phosphor-logging
1be39849bd974c2f7df7fa932edcd7f71a2c6d59
[ "Apache-2.0" ]
28
2016-07-20T16:46:54.000Z
2022-03-16T11:20:03.000Z
#pragma once #include "xyz/openbmc_project/Network/Client/server.hpp" #include <phosphor-logging/log.hpp> #include <sdbusplus/bus.hpp> #include <sdbusplus/server/object.hpp> #include <string> namespace phosphor { namespace rsyslog_config { using namespace phosphor::logging; using NetworkClient = sdbusplus::xyz::openbmc_project::Network::server::Client; using Iface = sdbusplus::server::object::object<NetworkClient>; namespace sdbusRule = sdbusplus::bus::match::rules; /** @class Server * @brief Configuration for rsyslog server * @details A concrete implementation of the * xyz.openbmc_project.Network.Client API, in order to * provide remote rsyslog server's address and port. */ class Server : public Iface { public: Server() = delete; Server(const Server&) = delete; Server& operator=(const Server&) = delete; Server(Server&&) = delete; Server& operator=(Server&&) = delete; virtual ~Server() = default; /** @brief Constructor to put object onto bus at a dbus path. * @param[in] bus - Bus to attach to. * @param[in] path - Path to attach at. * @param[in] filePath - rsyslog remote logging config file */ Server(sdbusplus::bus::bus& bus, const std::string& path, const char* filePath) : Iface(bus, path.c_str(), true), configFilePath(filePath), hostnameChange( bus, sdbusRule::propertiesChanged("/org/freedesktop/hostname1", "org.freedesktop.hostname1"), std::bind(std::mem_fn(&Server::hostnameChanged), this, std::placeholders::_1)) { try { restore(configFilePath.c_str()); } catch (const std::exception& e) { log<level::ERR>(e.what()); } emit_object_added(); } using NetworkClient::address; using NetworkClient::port; /** @brief Override that updates rsyslog config file as well * @param[in] value - remote server address * @returns value of changed address */ virtual std::string address(std::string value) override; /** @brief Override that updates rsyslog config file as well * @param[in] value - remote server port * @returns value of changed port */ virtual uint16_t port(uint16_t value) override; /** @brief Restart rsyslog's systemd unit */ virtual void restart(); private: /** @brief Update remote server address and port in * rsyslog config file. * @param[in] serverAddress - remote server address * @param[in] serverPort - remote server port * @param[in] filePath - rsyslog config file path */ void writeConfig(const std::string& serverAddress, uint16_t serverPort, const char* filePath); /** @brief Checks if input IP address is valid (uses getaddrinfo) * @param[in] address - server address * @returns true if valid, false otherwise */ bool addressValid(const std::string& address); /** @brief Populate existing config into D-Bus properties * @param[in] filePath - rsyslog config file path */ void restore(const char* filePath); std::string configFilePath{}; /** @brief React to hostname change * @param[in] msg - sdbusplus message */ void hostnameChanged(sdbusplus::message::message& /*msg*/) { restart(); } sdbusplus::bus::match_t hostnameChange; }; } // namespace rsyslog_config } // namespace phosphor
29.882353
79
0.634702
[ "object" ]
97a102aa20a7b16088762c20d99bf06902504197
360,608
cpp
C++
prebuild/blst_wrap.cpp
g11tech/blst-ts
660cf96e1bc5d4044b6334985982999a77073541
[ "Apache-2.0" ]
12
2020-12-01T23:31:55.000Z
2021-11-20T19:59:43.000Z
prebuild/blst_wrap.cpp
g11tech/blst-ts
660cf96e1bc5d4044b6334985982999a77073541
[ "Apache-2.0" ]
20
2020-11-26T18:57:22.000Z
2022-03-08T04:42:57.000Z
prebuild/blst_wrap.cpp
g11tech/blst-ts
660cf96e1bc5d4044b6334985982999a77073541
[ "Apache-2.0" ]
6
2020-12-02T08:04:36.000Z
2022-03-15T12:41:04.000Z
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.1.0 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus # include "blst.hpp" using namespace blst; #else # include "blst.h" #endif static const char *const BLST_ERROR_str [] = { "BLST_ERROR: success", "BLST_ERROR: bad point encoding", "BLST_ERROR: point is not on curve", "BLST_ERROR: point is not in group", "BLST_ERROR: context type mismatch", "BLST_ERROR: verify failed", "BLST_ERROR: public key is infinite", }; #define SWIG_PYTHON_STRICT_BYTE_CHAR #ifdef _WIN32 # include <malloc.h> # ifndef alloca # define alloca(s) _alloca(s) # endif #endif #ifdef __cplusplus /* SwigValueWrapper is described in swig.swg */ template<typename T> class SwigValueWrapper { struct SwigMovePointer { T *ptr; SwigMovePointer(T *p) : ptr(p) { } ~SwigMovePointer() { delete ptr; } SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } } pointer; SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs); SwigValueWrapper(const SwigValueWrapper<T>& rhs); public: SwigValueWrapper() : pointer(0) { } SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } operator T&() const { return *pointer.ptr; } T *operator&() { return pointer.ptr; } }; template <typename T> T SwigValueInit() { return T(); } #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if defined(__GNUC__) # if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Deal with Apple's deprecated 'AssertMacros.h' from Carbon-framework */ #if defined(__APPLE__) && !defined(__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES) # define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0 #endif /* Intel's compiler complains if a variable which was never initialised is * cast to void, which is a common idiom which we use to indicate that we * are aware a variable isn't used. So we just silence that warning. * See: https://github.com/swig/swig/issues/192 for more discussion. */ #ifdef __INTEL_COMPILER # pragma warning disable 592 #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else #ifndef SWIG_V8_VERSION #define SWIG_V8_VERSION 0x060000 #endif #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" // Minimum supported Node.js version is v6.0, which is guaranteed // to have v8-version.h... # include <v8-version.h> # if __GNUC__>=8 && V8_MAJOR_VERSION<7 # pragma GCC diagnostic ignored "-Wcast-function-type" # endif #endif #include <node.h> //Older version of node.h does not include this #include <node_version.h> #include <v8.h> #if defined(__GNUC__) # pragma GCC diagnostic pop #endif #if defined(V8_MAJOR_VERSION) && defined(V8_MINOR_VERSION) #undef SWIG_V8_VERSION #define SWIG_V8_VERSION (V8_MAJOR_VERSION * 256 + V8_MINOR_VERSION) #endif #include <errno.h> #include <limits.h> #include <stdlib.h> #include <assert.h> class SWIGV8_ClientData; #define SWIG_CLIENT_DATA_TYPE SWIGV8_ClientData /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 #define SWIG_POINTER_NO_NULL 0x4 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return an integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); #ifndef SWIG_CLIENT_DATA_TYPE #define SWIG_CLIENT_DATA_TYPE void #endif /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ SWIG_CLIENT_DATA_TYPE *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { int equiv = 1; const char* te = tb + strlen(tb); const char* ne = nb; while (equiv != 0 && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = SWIG_TypeNameComp(nb, ne, tb, te); if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, SWIG_CLIENT_DATA_TYPE *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, SWIG_CLIENT_DATA_TYPE *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { size_t l = 0; size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; const unsigned char *u = (unsigned char *) ptr; const unsigned char *eu = u + sz; for (; u != eu; ++u) { unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { unsigned char *u = (unsigned char *) ptr; const unsigned char *eu = u + sz; for (; u != eu; ++u) { char d = *(c++); unsigned char uu; if ((d >= '0') && (d <= '9')) uu = (unsigned char)((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = (unsigned char)((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (unsigned char)(d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (unsigned char)(d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* --------------------------------------------------------------------------- * These typedefs and defines are used to deal with v8 API changes * * Useful table of versions: https://nodejs.org/en/download/releases/ * ---------------------------------------------------------------------------*/ // First v8 version that uses "SetWeak" and not "MakeWeak" #define SWIGV8_SETWEAK_VERSION 0x032224 #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031803) #define SWIGV8_STRING_NEW2(cstr, len) v8::String::New(cstr, len) #elif (SWIG_V8_VERSION < 0x0704) #define SWIGV8_STRING_NEW2(cstr, len) v8::String::NewFromUtf8(isolate, cstr, v8::String::kNormalString, len) #else #define SWIGV8_STRING_NEW2(cstr, len) (v8::String::NewFromUtf8(isolate, cstr, v8::NewStringType::kNormal, len)).ToLocalChecked() #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) typedef v8::Handle<v8::Value> SwigV8ReturnValue; typedef v8::Arguments SwigV8Arguments; typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; #define SWIGV8_RETURN(val) return scope.Close(val) #define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) #else typedef void SwigV8ReturnValue; typedef v8::FunctionCallbackInfo<v8::Value> SwigV8Arguments; typedef v8::PropertyCallbackInfo<v8::Value> SwigV8PropertyCallbackInfo; #define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return #define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return #endif /* * SWIGV8_HANDLESCOPE* macros imply |isolate| to be declared in current scope. * Most common way is to 'v8::Isolate* isolate = args.GetIsolate();' [in all * supported V8 versions]. */ #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032117) #define SWIGV8_HANDLESCOPE() v8::HandleScope scope #define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope #define SWIGV8_ESCAPE(val) return scope.Close(val) #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032224) #define SWIGV8_HANDLESCOPE() v8::HandleScope scope(isolate) #define SWIGV8_HANDLESCOPE_ESC() v8::HandleScope scope(isolate) #define SWIGV8_ESCAPE(val) return scope.Close(val) #else #define SWIGV8_HANDLESCOPE() v8::HandleScope scope(isolate) #define SWIGV8_HANDLESCOPE_ESC() v8::EscapableHandleScope scope(isolate) #define SWIGV8_ESCAPE(val) return scope.Escape(val) #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032224) #define SWIGV8_ADJUST_MEMORY(size) v8::V8::AdjustAmountOfExternalAllocatedMemory(size) #define SWIGV8_CURRENT_CONTEXT() v8::Context::GetCurrent() #define SWIGV8_CONTEXT(isolate) v8::Context::GetCurrent() #define SWIGV8_THROW_EXCEPTION(err) v8::ThrowException(err) #define SWIGV8_STRING_NEW(str) v8::String::New(str) #define SWIGV8_SYMBOL_NEW(sym) v8::String::NewSymbol(sym) #else #define SWIGV8_ADJUST_MEMORY(size) v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(size) #define SWIGV8_CURRENT_CONTEXT() v8::Isolate::GetCurrent()->GetCurrentContext() #define SWIGV8_CONTEXT(isolate) isolate->GetCurrentContext() #define SWIGV8_THROW_EXCEPTION(err) v8::Isolate::GetCurrent()->ThrowException(err) #if (SWIG_V8_VERSION < 0x0704) #define SWIGV8_STRING_NEW(str) v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str, v8::String::kNormalString) #define SWIGV8_SYMBOL_NEW(sym) v8::String::NewFromUtf8(isolate, sym, v8::String::kNormalString) #else #define SWIGV8_STRING_NEW(str) (v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), str, v8::NewStringType::kNormal)).ToLocalChecked() #define SWIGV8_SYMBOL_NEW(sym) (v8::String::NewFromUtf8(isolate, sym, v8::NewStringType::kNormal)).ToLocalChecked() #endif #endif #if (V8_MAJOR_VERSION-0) < 5 #define SWIGV8_MAYBE_CHECK(maybe) maybe #elif (SWIG_V8_VERSION < 0x0704) #define SWIGV8_MAYBE_CHECK(maybe) maybe.FromJust() #else #define SWIGV8_MAYBE_CHECK(maybe) maybe.Check() #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032318) /* internal use only */ #define SWIGV8_EXTERNAL_NEW(val) v8::External::New(val) #define SWIGV8_FUNCTEMPLATE_NEW(...) v8::FunctionTemplate::New(__VA_ARGS__) #define SWIGV8_FUNCTEMPLATE_NEW_VOID() v8::FunctionTemplate::New() #define SWIGV8_OBJECT_INEW() v8::Object::New() #define SWIGV8_ARRAY_NEW(size) v8::Array::New(size) #define SWIGV8_BOOLEAN_NEW(bool) v8::Boolean::New(bool) #define SWIGV8_INT32_NEW(num) v8::Int32::New(num) #define SWIGV8_INTEGER_NEW(num) v8::Integer::New(num) #define SWIGV8_INTEGER_NEW_UNS(num) v8::Integer::NewFromUnsigned(num) #define SWIGV8_NUMBER_NEW(num) v8::Number::New(num) #define SWIGV8_OBJECT_NEW() v8::Object::New() #define SWIGV8_UNDEFINED() v8::Undefined() #define SWIGV8_NULL() v8::Null() #define SWIGV8_ARRAY v8::Handle<v8::Array> #define SWIGV8_FUNCTION_TEMPLATE v8::Handle<v8::FunctionTemplate> #define SWIGV8_OBJECT v8::Handle<v8::Object> #define SWIGV8_OBJECT_TEMPLATE v8::Handle<v8::ObjectTemplate> #define SWIGV8_VALUE v8::Handle<v8::Value> #define SWIGV8_ARRAY_GET(array, index) (array)->Get(index) #define SWIGV8_ARRAY_SET(array, index, value) (array)->Set(index, value) #define SWIGV8_GETISOLATE(context) v8::Isolate::GetCurrent() #else /* internal use only, imply |isolate| to be declared in current scope */ #define SWIGV8_EXTERNAL_NEW(val) v8::External::New(isolate, val) #define SWIGV8_FUNCTEMPLATE_NEW(...) v8::FunctionTemplate::New(isolate, __VA_ARGS__) #define SWIGV8_FUNCTEMPLATE_NEW_VOID() v8::FunctionTemplate::New(isolate) #define SWIGV8_OBJECT_INEW() v8::Object::New(isolate) #define SWIGV8_ARRAY_NEW(size) v8::Array::New(v8::Isolate::GetCurrent(), size) #define SWIGV8_BOOLEAN_NEW(bool) v8::Boolean::New(v8::Isolate::GetCurrent(), bool) #define SWIGV8_INT32_NEW(num) v8::Int32::New(v8::Isolate::GetCurrent(), num) #define SWIGV8_INTEGER_NEW(num) v8::Integer::New(v8::Isolate::GetCurrent(), num) #define SWIGV8_INTEGER_NEW_UNS(num) v8::Integer::NewFromUnsigned(v8::Isolate::GetCurrent(), num) #define SWIGV8_NUMBER_NEW(num) v8::Number::New(v8::Isolate::GetCurrent(), num) #define SWIGV8_OBJECT_NEW() v8::Object::New(v8::Isolate::GetCurrent()) #define SWIGV8_UNDEFINED() v8::Undefined(v8::Isolate::GetCurrent()) #define SWIGV8_NULL() v8::Null(v8::Isolate::GetCurrent()) #define SWIGV8_ARRAY v8::Local<v8::Array> #define SWIGV8_FUNCTION_TEMPLATE v8::Local<v8::FunctionTemplate> #define SWIGV8_OBJECT v8::Local<v8::Object> #define SWIGV8_OBJECT_TEMPLATE v8::Local<v8::ObjectTemplate> #define SWIGV8_VALUE v8::Local<v8::Value> #define SWIGV8_ARRAY_GET(array, index) (array)->Get(SWIGV8_CURRENT_CONTEXT(), index).ToLocalChecked() #define SWIGV8_ARRAY_SET(array, index, value) SWIGV8_MAYBE_CHECK((array)->Set(SWIGV8_CURRENT_CONTEXT(), index, value)) #define SWIGV8_GETISOLATE(context) context->GetIsolate() #endif /* internal use only [imply |isolate| to be declared in current scope] */ #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ = v8::Persistent<v8::FunctionTemplate>::New(class); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ = v8::Persistent<v8::FunctionTemplate>::New(isolate, class); #else #define SWIGV8_SET_CLASS_TEMPL(class_templ, class) class_templ.Reset(isolate, class); #endif #if (V8_MAJOR_VERSION-0) < 6 || (SWIG_V8_VERSION < 0x0608) #define SWIGV8_TO_OBJECT(handle) (handle)->ToObject() #define SWIGV8_TO_STRING(handle) (handle)->ToString() #define SWIGV8_NUMBER_VALUE(handle) (handle)->NumberValue() #define SWIGV8_INTEGER_VALUE(handle) (handle)->IntegerValue() #define SWIGV8_BOOLEAN_VALUE(handle) (handle)->BooleanValue() #define SWIGV8_WRITE_UTF8(handle, buffer, len) (handle)->WriteUtf8(buffer, len) #define SWIGV8_UTF8_LENGTH(handle) (handle)->Utf8Length() #else #define SWIGV8_TO_OBJECT(handle) (handle)->ToObject(SWIGV8_CURRENT_CONTEXT()).ToLocalChecked() #define SWIGV8_TO_STRING(handle) (handle)->ToString(SWIGV8_CURRENT_CONTEXT()).ToLocalChecked() #define SWIGV8_NUMBER_VALUE(handle) (handle)->NumberValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() #define SWIGV8_INTEGER_VALUE(handle) (handle)->IntegerValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() #define SWIGV8_WRITE_UTF8(handle, buffer, len) (handle)->WriteUtf8(v8::Isolate::GetCurrent(), buffer, len) #define SWIGV8_UTF8_LENGTH(handle) (handle)->Utf8Length(v8::Isolate::GetCurrent()) #if (SWIG_V8_VERSION < 0x0704) #define SWIGV8_BOOLEAN_VALUE(handle) (handle)->BooleanValue(SWIGV8_CURRENT_CONTEXT()).ToChecked() #else #define SWIGV8_BOOLEAN_VALUE(handle) (handle)->BooleanValue(v8::Isolate::GetCurrent()) #endif #endif /* --------------------------------------------------------------------------- * Error handling * * ---------------------------------------------------------------------------*/ #define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) #define SWIG_exception(code, msg) do { SWIGV8_ErrorHandler.error(code, msg); SWIG_fail; } while (0) #define SWIG_fail goto fail #define SWIGV8_OVERLOAD false SWIGINTERN void SWIG_V8_Raise(const char *msg) { SWIGV8_THROW_EXCEPTION(v8::Exception::Error(SWIGV8_STRING_NEW(msg))); } /* Note: There are two contexts for handling errors. A static V8ErrorHandler is used in not overloaded methods. For overloaded methods the throwing type checking mechanism is used during dispatching. As V8 exceptions can not be reset properly the trick is to use a dynamic ErrorHandler with same local name as the global one. - See definition of SWIG_Error above. - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', and 'JS_function_dispatch_case' in javascriptcode.swg */ class V8ErrorHandler { public: virtual ~V8ErrorHandler() {} virtual void error(int code, const char *msg) { SWIG_V8_Raise(msg); } }; // this is used in usually SWIGRUNTIME V8ErrorHandler SWIGV8_ErrorHandler; // instances of this are used in overloaded functions class OverloadErrorHandler: public V8ErrorHandler { public: virtual void error(int code, const char *msg) { err = v8::Exception::Error(SWIGV8_STRING_NEW(msg)); if(code != SWIG_TypeError) { SWIGV8_THROW_EXCEPTION(err); } } SWIGV8_VALUE err; }; /* --------------------------------------------------------------------------- * Basic Proxy object * * ---------------------------------------------------------------------------*/ // Note: to trigger the v8 gc more often one can tell v8 about the memory consumption // TODO: we could add a v8 specific parameter to control this value #define SWIGV8_AVG_OBJ_SIZE 1000 class SWIGV8_Proxy { public: SWIGV8_Proxy(): swigCMemOwn(false), swigCObject(0), info(0) { SWIGV8_ADJUST_MEMORY(SWIGV8_AVG_OBJ_SIZE); }; ~SWIGV8_Proxy() { #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) handle.ClearWeak(); handle.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) handle.ClearWeak(v8::Isolate::GetCurrent()); handle.Dispose(v8::Isolate::GetCurrent()); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) handle.ClearWeak(); handle.Dispose(); #else handle.ClearWeak(); handle.Reset(); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) handle.Clear(); #endif SWIGV8_ADJUST_MEMORY(-SWIGV8_AVG_OBJ_SIZE); } bool swigCMemOwn; void *swigCObject; swig_type_info *info; v8::Persistent<v8::Object> handle; }; class SWIGV8_ClientData { private: v8::Persistent<v8::FunctionTemplate> clazz_templ; public: size_t index; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Value> object, void *parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); #elif (V8_MAJOR_VERSION-0) < 5 void (*dtor) (const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data); #else void (*dtor) (const v8::WeakCallbackInfo<SWIGV8_Proxy> &data); #endif SWIGV8_ClientData() : index(-1) {} #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) v8::Persistent<v8::FunctionTemplate> GetType(v8::Isolate* isolate, v8::Persistent<v8::FunctionTemplate>* v8_swig_types = NULL) { return clazz_templ; } #else SWIGV8_FUNCTION_TEMPLATE GetType(v8::Isolate* isolate, v8::Persistent<v8::FunctionTemplate>* v8_swig_types) { #if (V8_MAJOR_VERSION-0) >= 5 if (v8_swig_types != NULL) return SWIGV8_FUNCTION_TEMPLATE::New(isolate, v8_swig_types[index+1]); #endif return SWIGV8_FUNCTION_TEMPLATE::New(isolate, clazz_templ); } #endif bool IsTypeEmpty(v8::Persistent<v8::FunctionTemplate>* v8_swig_types) { #if (V8_MAJOR_VERSION-0) >= 5 if (v8_swig_types != NULL) return v8_swig_types[index+1].IsEmpty(); #endif return clazz_templ.IsEmpty(); } void SetType(SWIGV8_FUNCTION_TEMPLATE class_templ, v8::Isolate *isolate, v8::Persistent<v8::FunctionTemplate>* v8_swig_types) { #if (V8_MAJOR_VERSION-0) >= 5 if (v8_swig_types != NULL) { v8_swig_types[index+1].Reset(isolate, class_templ); return; } #endif if (clazz_templ.IsEmpty()) { SWIGV8_SET_CLASS_TEMPL(clazz_templ, class_templ); } } }; static SWIGV8_ClientData SWIGV8_SWIGTYPE_Proxy; SWIGRUNTIME int SWIG_V8_ConvertInstancePtr(SWIGV8_OBJECT objRef, void **ptr, swig_type_info *info, int flags) { if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) v8::Handle<v8::Value> cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast<SWIGV8_Proxy *>(v8::External::Unwrap(cdataRef)); #else SWIGV8_Proxy *cdata = static_cast<SWIGV8_Proxy *>(objRef->GetAlignedPointerFromInternalField(0)); #endif if(cdata == NULL) { return SWIG_ERROR; } if(cdata->info != info) { swig_cast_info *tc = SWIG_TypeCheckStruct(cdata->info, info); if (!tc && cdata->info->name) { tc = SWIG_TypeCheck(cdata->info->name, info); } bool type_valid = tc != 0; if(!type_valid) { return SWIG_TypeError; } int newmemory = 0; *ptr = SWIG_TypeCast(tc, cdata->swigCObject, &newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { *ptr = cdata->swigCObject; } if(flags & SWIG_POINTER_DISOWN) { cdata->swigCMemOwn = false; } return SWIG_OK; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #else SWIGRUNTIME void SWIGV8_Proxy_DefaultDtor(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif delete proxy; } SWIGRUNTIME int SWIG_V8_GetInstancePtr(SWIGV8_VALUE valRef, void **ptr) { if(!valRef->IsObject()) { return SWIG_TypeError; } SWIGV8_OBJECT objRef = SWIGV8_OBJECT::Cast(valRef); if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) v8::Handle<v8::Value> cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast<SWIGV8_Proxy *>(v8::External::Unwrap(cdataRef)); #else SWIGV8_Proxy *cdata = static_cast<SWIGV8_Proxy *>(objRef->GetAlignedPointerFromInternalField(0)); #endif if(cdata == NULL) { return SWIG_ERROR; } *ptr = cdata->swigCObject; return SWIG_OK; } SWIGRUNTIME void SWIGV8_SetPrivateData(SWIGV8_OBJECT obj, void *ptr, swig_type_info *info, int flags) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_Proxy *cdata = new SWIGV8_Proxy(); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) obj->SetPointerInInternalField(0, cdata); #else obj->SetAlignedPointerInInternalField(0, cdata); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle = v8::Persistent<v8::Object>::New(obj); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) cdata->handle = v8::Persistent<v8::Object>::New(isolate, obj); #else cdata->handle.Reset(isolate, obj); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn && info->clientdata) { cdata->handle.MakeWeak(cdata, info->clientdata->dtor); } else { cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); } #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031918) if(cdata->swigCMemOwn && info->clientdata { cdata->handle.MakeWeak(isolate, cdata, info->clientdata->dtor); } else { cdata->handle.MakeWeak(isolate, cdata, SWIGV8_Proxy_DefaultDtor); } #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) if(cdata->swigCMemOwn && info->clientdata) { cdata->handle.MakeWeak(cdata, info->clientdata->dtor); } else { cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); } #elif (V8_MAJOR_VERSION-0) < 5 if(cdata->swigCMemOwn && info->clientdata) { cdata->handle.SetWeak(cdata, info->clientdata->dtor); } else { cdata->handle.SetWeak(cdata, SWIGV8_Proxy_DefaultDtor); } #else if(cdata->swigCMemOwn && info->clientdata) { cdata->handle.SetWeak(cdata, info->clientdata->dtor, v8::WeakCallbackType::kParameter); } else { cdata->handle.SetWeak(cdata, SWIGV8_Proxy_DefaultDtor, v8::WeakCallbackType::kParameter); } #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle.MarkIndependent(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) cdata->handle.MarkIndependent(isolate); #elif (SWIG_V8_VERSION < 0x0704) cdata->handle.MarkIndependent(); // Looks like future versions do not require that anymore: // https://monorail-prod.appspot.com/p/chromium/issues/detail?id=923361#c11 #endif } SWIGRUNTIME int SWIG_V8_ConvertPtr(SWIGV8_VALUE valRef, void **ptr, swig_type_info *info, int flags) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_HANDLESCOPE(); /* special case: JavaScript null => C NULL pointer */ if(valRef->IsNull()) { *ptr=0; return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } if(!valRef->IsObject()) { return SWIG_TypeError; } SWIGV8_OBJECT objRef = SWIGV8_OBJECT::Cast(valRef); return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } SWIGRUNTIME SWIGV8_VALUE SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags, SWIGV8_VALUE data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_HANDLESCOPE_ESC(); v8::Persistent<v8::FunctionTemplate>* v8_swig_types = NULL; #if (V8_MAJOR_VERSION-0) >= 5 v8::Local<v8::ArrayBuffer> ab = v8::Local<v8::ArrayBuffer>::Cast(data); #if (V8_MAJOR_VERSION-0) >= 8 v8_swig_types = static_cast<v8::Persistent<v8::FunctionTemplate>*>(ab->GetBackingStore()->Data()); #else v8_swig_types = static_cast<v8::Persistent<v8::FunctionTemplate>*>(ab->GetContents().Data()); #endif #endif SWIGV8_FUNCTION_TEMPLATE class_templ; if (ptr == NULL) { SWIGV8_ESCAPE(v8::Null(isolate)); } if(info->clientdata != 0) { class_templ = info->clientdata->GetType(isolate, v8_swig_types); } else { class_templ = SWIGV8_SWIGTYPE_Proxy.GetType(isolate, v8_swig_types); } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) v8::Local<v8::Object> result = class_templ->InstanceTemplate()->NewInstance(); #else v8::Local<v8::Object> result = class_templ->InstanceTemplate()->NewInstance(SWIGV8_CONTEXT(isolate)).ToLocalChecked(); #endif SWIGV8_SetPrivateData(result, ptr, info, flags); SWIGV8_ESCAPE(result); } #define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) #define SWIG_NewPointerObj(ptr, info, flags) SWIG_V8_NewPointerObj(ptr, info, flags, jsdata) #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_V8_ConvertInstancePtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_V8_NewPointerObj(thisvalue, type, flags, jsdata) #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_V8_ConvertPtr(obj, pptr, type, 0) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_V8_NewPointerObj(ptr, type, 0, jsdata) #define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) SWIGRUNTIME SwigV8ReturnValue _SWIGV8_wrap_equals(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; void *arg1 = (void *) 0 ; void *arg2 = (void *) 0 ; bool result; int res1; int res2; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for equals."); res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for equals."); } res2 = SWIG_GetInstancePtr(args[0], &arg2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "equals" "', argument " "1"" of type '" "void *""'"); } result = (bool)(arg1 == arg2); jsresult = SWIGV8_BOOLEAN_NEW(result); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); } SWIGRUNTIME SwigV8ReturnValue _wrap_getCPtr(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; void *arg1 = (void *) 0 ; long result; int res1; res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getCPtr" "', argument " "1"" of type '" "void *""'"); } result = (long)arg1; jsresult = SWIGV8_NUMBER_NEW(result); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); } /* --------------------------------------------------------------------------- * PackedData object * * ---------------------------------------------------------------------------*/ class SwigV8PackedData { public: SwigV8PackedData(void *data, size_t size, swig_type_info *type): data(data), size(size), type(type) {}; ~SwigV8PackedData() { }; void *data; size_t size; swig_type_info *type; v8::Persistent<v8::Object> handle; }; SWIGRUNTIMEINLINE int SwigV8Packed_Check(SWIGV8_VALUE valRef) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT objRef = SWIGV8_TO_OBJECT(valRef); if(objRef->InternalFieldCount() < 1) return false; #if (V8_MAJOR_VERSION-0) < 5 v8::Handle<v8::Value> flag = objRef->GetHiddenValue(SWIGV8_STRING_NEW("__swig__packed_data__")); #else v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, SWIGV8_STRING_NEW("__swig__packed_data__")); v8::Local<v8::Value> flag; if (!objRef->GetPrivate(SWIGV8_CONTEXT(isolate), privateKey).ToLocal(&flag)) return false; #endif return (flag->IsBoolean() && SWIGV8_BOOLEAN_VALUE(flag)); } SWIGRUNTIME swig_type_info *SwigV8Packed_UnpackData(SWIGV8_VALUE valRef, void *ptr, size_t size) { if (SwigV8Packed_Check(valRef)) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_HANDLESCOPE(); SwigV8PackedData *sobj; SWIGV8_OBJECT objRef = SWIGV8_TO_OBJECT(valRef); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) v8::Handle<v8::Value> cdataRef = objRef->GetInternalField(0); sobj = static_cast<SwigV8PackedData*>(v8::External::Unwrap(cdataRef)); #else sobj = static_cast<SwigV8PackedData*>(objRef->GetAlignedPointerFromInternalField(0)); #endif if (sobj == NULL || sobj->size != size) return 0; memcpy(ptr, sobj->data, size); return sobj->type; } else { return 0; } } SWIGRUNTIME int SWIGV8_ConvertPacked(SWIGV8_VALUE valRef, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigV8Packed_UnpackData(valRef, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) { SwigV8PackedData *cdata = static_cast<SwigV8PackedData *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SwigV8PackedData *cdata = static_cast<SwigV8PackedData *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) SWIGRUNTIME void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent<v8::Object> *object, SwigV8PackedData *cdata) { #elif (V8_MAJOR_VERSION-0) < 5 SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackData<v8::Object, SwigV8PackedData> &data) { v8::Local<v8::Object> object = data.GetValue(); SwigV8PackedData *cdata = data.GetParameter(); #else SWIGRUNTIME void _wrap_SwigV8PackedData_delete(const v8::WeakCallbackInfo<SwigV8PackedData> &data) { SwigV8PackedData *cdata = data.GetParameter(); #endif delete cdata; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Clear(); object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Clear(); object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } SWIGRUNTIME SWIGV8_VALUE SWIGV8_NewPackedObj(void *data, size_t size, swig_type_info *type) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_HANDLESCOPE_ESC(); SwigV8PackedData *cdata = new SwigV8PackedData(data, size, type); v8::Local<v8::Object> obj = SWIGV8_OBJECT_INEW(); #if (V8_MAJOR_VERSION-0) < 5 obj->SetHiddenValue(SWIGV8_STRING_NEW("__swig__packed_data__"), SWIGV8_BOOLEAN_NEW(true)); #else v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, SWIGV8_STRING_NEW("__swig__packed_data__")); obj->SetPrivate(SWIGV8_CONTEXT(isolate), privateKey, v8::Boolean::New(isolate, true)); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031511) obj->SetPointerInInternalField(0, cdata); #else obj->SetAlignedPointerInInternalField(0, cdata); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle = v8::Persistent<v8::Object>::New(obj); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) cdata->handle = v8::Persistent<v8::Object>::New(isolate, obj); #else cdata->handle.Reset(isolate, obj); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031918) cdata->handle.MakeWeak(isolate, cdata, _wrap_SwigV8PackedData_delete); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); #elif (V8_MAJOR_VERSION-0) < 5 cdata->handle.SetWeak(cdata, _wrap_SwigV8PackedData_delete); // v8::V8::SetWeak(&cdata->handle, cdata, _wrap_SwigV8PackedData_delete); #else cdata->handle.SetWeak(cdata, _wrap_SwigV8PackedData_delete, v8::WeakCallbackType::kParameter); #endif #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) cdata->handle.MarkIndependent(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) cdata->handle.MarkIndependent(isolate); #elif (SWIG_V8_VERSION < 0x0704) cdata->handle.MarkIndependent(); // Looks like future versions do not require that anymore: // https://monorail-prod.appspot.com/p/chromium/issues/detail?id=923361#c11 #endif SWIGV8_ESCAPE(obj); } #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIGV8_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIGV8_NewPackedObj(ptr, sz, type) /* --------------------------------------------------------------------------- * Support for IN/OUTPUT typemaps (see Lib/typemaps/inoutlist.swg) * * ---------------------------------------------------------------------------*/ SWIGRUNTIME SWIGV8_VALUE SWIGV8_AppendOutput(SWIGV8_VALUE result, SWIGV8_VALUE obj) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); SWIGV8_HANDLESCOPE_ESC(); if (result->IsUndefined()) { result = SWIGV8_ARRAY_NEW(0); } else if (!result->IsArray()) { SWIGV8_ARRAY tmparr = SWIGV8_ARRAY_NEW(0); SWIGV8_ARRAY_SET(tmparr, 0, result); result = tmparr; } SWIGV8_ARRAY arr = SWIGV8_ARRAY::Cast(result); SWIGV8_ARRAY_SET(arr, arr->Length(), obj); SWIGV8_ESCAPE(arr); } // Note: since 3.19 there are new CallBack types, since 03.21.9 the old ones have been removed #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) typedef v8::InvocationCallback SwigV8FunctionCallback; typedef v8::AccessorGetter SwigV8AccessorGetterCallback; typedef v8::AccessorSetter SwigV8AccessorSetterCallback; typedef v8::AccessorInfo SwigV8PropertyCallbackInfoVoid; #elif (V8_MAJOR_VERSION-0) < 5 typedef v8::FunctionCallback SwigV8FunctionCallback; typedef v8::AccessorGetterCallback SwigV8AccessorGetterCallback; typedef v8::AccessorSetterCallback SwigV8AccessorSetterCallback; typedef v8::PropertyCallbackInfo<void> SwigV8PropertyCallbackInfoVoid; #else typedef v8::FunctionCallback SwigV8FunctionCallback; typedef v8::AccessorNameGetterCallback SwigV8AccessorGetterCallback; typedef v8::AccessorNameSetterCallback SwigV8AccessorSetterCallback; typedef v8::PropertyCallbackInfo<void> SwigV8PropertyCallbackInfoVoid; #endif /** * Creates a class template for a class with specified initialization function. */ SWIGRUNTIME SWIGV8_FUNCTION_TEMPLATE SWIGV8_CreateClassTemplate(const char* symbol, v8::Isolate* isolate, v8::Local<v8::Value> data) { SWIGV8_HANDLESCOPE_ESC(); v8::Local<v8::FunctionTemplate> class_templ = SWIGV8_FUNCTEMPLATE_NEW_VOID(); class_templ->SetClassName(SWIGV8_SYMBOL_NEW(symbol)); class_templ->InstanceTemplate()->SetInternalFieldCount(1); class_templ->PrototypeTemplate()->Set(SWIGV8_SYMBOL_NEW("equals"), SWIGV8_FUNCTEMPLATE_NEW(_SWIGV8_wrap_equals, data)); class_templ->PrototypeTemplate()->Set(SWIGV8_SYMBOL_NEW("getCPtr"), SWIGV8_FUNCTEMPLATE_NEW(_wrap_getCPtr, data)); SWIGV8_ESCAPE(class_templ); } /** * Registers a class method with given name for a given class template. */ SWIGRUNTIME void SWIGV8_AddMemberFunction(SWIGV8_FUNCTION_TEMPLATE class_templ, const char* symbol, SwigV8FunctionCallback _func, v8::Isolate* isolate, v8::Local<v8::Value> data) { class_templ->PrototypeTemplate()->Set(SWIGV8_SYMBOL_NEW(symbol), SWIGV8_FUNCTEMPLATE_NEW(_func, data)); } /** * Registers a class property with given name for a given class template. */ SWIGRUNTIME void SWIGV8_AddMemberVariable(SWIGV8_FUNCTION_TEMPLATE class_templ, const char* symbol, SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter, v8::Isolate* isolate, v8::Local<v8::Value> data) { class_templ->InstanceTemplate()->SetAccessor(SWIGV8_SYMBOL_NEW(symbol), getter, setter, data); } /** * Registers a class method with given name for a given object. */ SWIGRUNTIME void SWIGV8_AddStaticFunction(SWIGV8_OBJECT obj, const char* symbol, const SwigV8FunctionCallback& _func, v8::Local<v8::Context> context, v8::Local<v8::Value> data) { v8::Isolate* isolate = SWIGV8_GETISOLATE(context); #if (V8_MAJOR_VERSION-0) < 5 obj->Set(SWIGV8_SYMBOL_NEW(symbol), SWIGV8_FUNCTEMPLATE_NEW(_func, data)->GetFunction()); #else SWIGV8_MAYBE_CHECK(obj->Set(context, SWIGV8_SYMBOL_NEW(symbol), SWIGV8_FUNCTEMPLATE_NEW(_func, data)->GetFunction(context).ToLocalChecked())); #endif } /** * Registers a class method with given name for a given object. */ SWIGRUNTIME void SWIGV8_AddStaticVariable(SWIGV8_OBJECT obj, const char* symbol, SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter, v8::Local<v8::Context> context, v8::Local<v8::Value> data) { v8::Isolate* isolate = SWIGV8_GETISOLATE(context); #if (V8_MAJOR_VERSION-0) < 5 obj->SetAccessor(SWIGV8_SYMBOL_NEW(symbol), getter, setter, data); #else SWIGV8_MAYBE_CHECK(obj->SetAccessor(context, SWIGV8_SYMBOL_NEW(symbol), getter, setter, data)); #endif } #if (V8_MAJOR_VERSION-0) < 5 SWIGRUNTIME void JS_veto_set_variable(v8::Local<v8::String> property, v8::Local<v8::Value> value, const SwigV8PropertyCallbackInfoVoid& info) #else SWIGRUNTIME void JS_veto_set_variable(v8::Local<v8::Name> property, v8::Local<v8::Value> value, const SwigV8PropertyCallbackInfoVoid& info) #endif { char buffer[256]; char msg[512]; int res; #if (V8_MAJOR_VERSION-0) < 5 property->WriteUtf8(buffer, 256); res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); #else v8::Local<v8::String> sproperty; if (property->ToString(SWIGV8_CURRENT_CONTEXT()).ToLocal(&sproperty)) { SWIGV8_WRITE_UTF8(sproperty, buffer, 256); res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); } else { res = -1; } #endif if(res<0) { SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); } else { SWIG_exception(SWIG_ERROR, msg); } fail: ; } /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_BLST_ERROR swig_types[0] #define SWIGTYPE_p_blst__P1 swig_types[1] #define SWIGTYPE_p_blst__P1_Affine swig_types[2] #define SWIGTYPE_p_blst__P2 swig_types[3] #define SWIGTYPE_p_blst__P2_Affine swig_types[4] #define SWIGTYPE_p_blst__PT swig_types[5] #define SWIGTYPE_p_blst__Pairing swig_types[6] #define SWIGTYPE_p_blst__SecretKey swig_types[7] #define SWIGTYPE_p_byte swig_types[8] #define SWIGTYPE_p_char swig_types[9] #define SWIGTYPE_p_int swig_types[10] #define SWIGTYPE_p_long_long swig_types[11] #define SWIGTYPE_p_short swig_types[12] #define SWIGTYPE_p_signed_char swig_types[13] #define SWIGTYPE_p_unsigned_char swig_types[14] #define SWIGTYPE_p_unsigned_int swig_types[15] #define SWIGTYPE_p_unsigned_long_long swig_types[16] #define SWIGTYPE_p_unsigned_short swig_types[17] static swig_type_info *swig_types[19]; static swig_module_info swig_module = {swig_types, 18, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #define SWIGVERSION 0x040100 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) #include <stdexcept> #include <assert.h> #include <string> #include <stdint.h> // Use the C99 official header #if V8_MAJOR_VERSION >= 8 # define GetData() GetBackingStore()->Data() #else # define GetData() GetContents().Data() #endif SWIGINTERNINLINE SWIGV8_VALUE SWIG_From_int (int value) { return SWIGV8_INT32_NEW(value); } SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERN int SWIG_AsCharPtrAndSize(SWIGV8_VALUE valRef, char** cptr, size_t* psize, int *alloc) { if(valRef->IsString()) { #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) v8::Handle<v8::String> js_str = v8::Handle<v8::String>::Cast(valRef); #else v8::Local<v8::String> js_str = v8::Local<v8::String>::Cast(valRef); #endif size_t len = SWIGV8_UTF8_LENGTH(js_str) + 1; if(psize) *psize = len; if(cptr) { *cptr = new char[len]; SWIGV8_WRITE_UTF8(js_str, *cptr, len); if(alloc) *alloc = SWIG_NEWOBJ; } else if(alloc) { *alloc = SWIG_OLDOBJ; } return SWIG_OK; } else if(valRef->IsObject()) { SWIGV8_OBJECT obj = SWIGV8_OBJECT::Cast(valRef); // try if the object is a wrapped char[] swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if(pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } return SWIG_TypeError; } return SWIG_TypeError; } SWIGINTERN int SWIG_AsPtr_std_string (SWIGV8_VALUE obj, std::string **val) { char* buf = 0 ; size_t size = 0; int alloc = SWIG_OLDOBJ; if (SWIG_IsOK((SWIG_AsCharPtrAndSize(obj, &buf, &size, &alloc)))) { if (buf) { if (val) *val = new std::string(buf, size - 1); if (alloc == SWIG_NEWOBJ) delete[] buf; return SWIG_NEWOBJ; } else { if (val) *val = 0; return SWIG_OLDOBJ; } } else { static int init = 0; static swig_type_info* descriptor = 0; if (!init) { descriptor = SWIG_TypeQuery("std::string" " *"); init = 1; } if (descriptor) { std::string *vptr; int res = SWIG_ConvertPtr(obj, (void**)&vptr, descriptor, 0); if (SWIG_IsOK(res) && val) *val = vptr; return res; } } return SWIG_ERROR; } SWIGINTERN int SWIG_AsVal_double (SWIGV8_VALUE obj, double *val) { if(!obj->IsNumber()) { return SWIG_TypeError; } if(val) *val = SWIGV8_NUMBER_VALUE(obj); return SWIG_OK; } #include <float.h> #include <math.h> SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_unsigned_SS_long (SWIGV8_VALUE obj, unsigned long *val) { if(!obj->IsNumber()) { return SWIG_TypeError; } long longVal = (long) SWIGV8_NUMBER_VALUE(obj); if(longVal < 0) { return SWIG_OverflowError; } if(val) *val = longVal; return SWIG_OK; } #include <limits.h> #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif #if defined(LLONG_MAX) && !defined(SWIG_LONG_LONG_AVAILABLE) # define SWIG_LONG_LONG_AVAILABLE #endif #ifdef SWIG_LONG_LONG_AVAILABLE SWIGINTERN int SWIG_AsVal_unsigned_SS_long_SS_long (SWIGV8_VALUE obj, unsigned long long *val) { if(!obj->IsNumber()) { return SWIG_TypeError; } long long longVal = (long long) SWIGV8_NUMBER_VALUE(obj); if(longVal < 0) { return SWIG_OverflowError; } if(val) *val = longVal; return SWIG_OK; } #endif SWIGINTERNINLINE int SWIG_AsVal_size_t (SWIGV8_VALUE obj, size_t *val) { int res = SWIG_TypeError; #ifdef SWIG_LONG_LONG_AVAILABLE if (sizeof(size_t) <= sizeof(unsigned long)) { #endif unsigned long v; res = SWIG_AsVal_unsigned_SS_long (obj, val ? &v : 0); if (SWIG_IsOK(res) && val) *val = static_cast< size_t >(v); #ifdef SWIG_LONG_LONG_AVAILABLE } else if (sizeof(size_t) <= sizeof(unsigned long long)) { unsigned long long v; res = SWIG_AsVal_unsigned_SS_long_SS_long (obj, val ? &v : 0); if (SWIG_IsOK(res) && val) *val = static_cast< size_t >(v); } #endif return res; } SWIGINTERNINLINE SWIGV8_VALUE SWIG_From_bool (bool value) { return SWIGV8_BOOLEAN_NEW(value); } SWIGINTERN int SWIG_AsVal_long (SWIGV8_VALUE obj, long* val) { if (!obj->IsNumber()) { return SWIG_TypeError; } if(val) *val = (long) SWIGV8_INTEGER_VALUE(obj); return SWIG_OK; } SWIGINTERN int SWIG_AsVal_bool (SWIGV8_VALUE obj, bool *val) { if(!obj->IsBoolean()) { return SWIG_ERROR; } if (val) *val = SWIGV8_BOOLEAN_VALUE(obj); return SWIG_OK; } #define SWIGV8_INIT blst_initialize #define SWIGV8_JSNAME "blst" SWIGV8_ClientData _exports_SecretKey_clientData; SWIGV8_ClientData _exports_P1_Affine_clientData; SWIGV8_ClientData _exports_P1_clientData; SWIGV8_ClientData _exports_P2_Affine_clientData; SWIGV8_ClientData _exports_P2_clientData; SWIGV8_ClientData _exports_PT_clientData; SWIGV8_ClientData _exports_Pairing_clientData; #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_SUCCESS(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_SUCCESS(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_SUCCESS)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_BAD_ENCODING(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_BAD_ENCODING(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_BAD_ENCODING)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_POINT_NOT_ON_CURVE(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_POINT_NOT_ON_CURVE(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_POINT_NOT_ON_CURVE)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_POINT_NOT_IN_GROUP(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_POINT_NOT_IN_GROUP(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_POINT_NOT_IN_GROUP)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_AGGR_TYPE_MISMATCH(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_AGGR_TYPE_MISMATCH(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_AGGR_TYPE_MISMATCH)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_VERIFY_FAIL(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_VERIFY_FAIL(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_VERIFY_FAIL)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLST_PK_IS_INFINITY(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLST_PK_IS_INFINITY(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); jsresult = SWIG_From_int(static_cast< int >(BLST_PK_IS_INFINITY)); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey_keygen__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = (blst::SecretKey *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__SecretKey, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SecretKey_keygen" "', argument " "1"" of type '" "blst::SecretKey *""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'SecretKey_keygen', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "SecretKey_keygen" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "SecretKey_keygen" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } (arg1)->keygen((byte const *)arg2,arg3,(std::string const &)*arg4); jsresult = SWIGV8_UNDEFINED(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey_keygen__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = (blst::SecretKey *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__SecretKey, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SecretKey_keygen" "', argument " "1"" of type '" "blst::SecretKey *""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'SecretKey_keygen', " "expecting <Buffer> or <String>"); } (arg1)->keygen((byte const *)arg2,arg3); jsresult = SWIGV8_UNDEFINED(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey__wrap_SecretKey_keygen(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_SecretKey_keygen__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_SecretKey_keygen__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_SecretKey_keygen__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_SecretKey_keygen__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function keygen."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey_from_bendian(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = (blst::SecretKey *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_SecretKey_from_bendian."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__SecretKey, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SecretKey_from_bendian" "', argument " "1"" of type '" "blst::SecretKey *""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); if (av->ByteLength() != 32) SWIG_exception_fail(SWIG_IndexError, "in method 'SecretKey_from_bendian', " "expecting 32 bytes"); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'SecretKey_from_bendian', " "expecting <Buffer>"); } (arg1)->from_bendian((byte const (*))arg2); jsresult = SWIGV8_UNDEFINED(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey_from_lendian(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = (blst::SecretKey *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_SecretKey_from_lendian."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__SecretKey, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SecretKey_from_lendian" "', argument " "1"" of type '" "blst::SecretKey *""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); if (av->ByteLength() != 32) SWIG_exception_fail(SWIG_IndexError, "in method 'SecretKey_from_lendian', " "expecting 32 bytes"); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'SecretKey_from_lendian', " "expecting <Buffer>"); } (arg1)->from_lendian((byte const (*))arg2); jsresult = SWIGV8_UNDEFINED(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey_to_bendian(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = (blst::SecretKey *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[32] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_SecretKey_to_bendian."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__SecretKey, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SecretKey_to_bendian" "', argument " "1"" of type '" "blst::SecretKey const *""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); arg2 = temp2; ((blst::SecretKey const *)arg1)->to_bendian(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 32); memcpy(ab->GetData(), arg2, 32); jsresult = v8::Uint8Array::New(ab, 0, 32); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_SecretKey_to_lendian(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = (blst::SecretKey *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[32] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_SecretKey_to_lendian."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__SecretKey, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SecretKey_to_lendian" "', argument " "1"" of type '" "blst::SecretKey const *""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); arg2 = temp2; ((blst::SecretKey const *)arg1)->to_lendian(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 32); memcpy(ab->GetData(), arg2, 32); jsresult = v8::Uint8Array::New(ab, 0, 32); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_SecretKey(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_SecretKey."); if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_SecretKey."); result = (blst::SecretKey *)new blst::SecretKey(); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__SecretKey, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_SecretKey(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_SecretKey(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_SecretKey(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_SecretKey(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_SecretKey(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::SecretKey * arg1 = (blst::SecretKey *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_new_P1_Affine__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1_Affine__SWIG_0."); if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1_Affine__SWIG_0."); result = (blst::P1_Affine *)new blst::P1_Affine(); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1_Affine, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1_Affine__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); byte *arg1 = (byte *) 0 ; blst::P1_Affine *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1_Affine__SWIG_1."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1_Affine__SWIG_1."); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg1 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'new_P1_Affine', " "expecting <Buffer>"); } try { result = (blst::P1_Affine *)new blst::P1_Affine((byte const *)arg1); } catch(BLST_ERROR &_e) { SWIG_V8_Raise(BLST_ERROR_str[_e]); SWIG_fail; } SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1_Affine, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1_Affine__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::P1_Affine *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1_Affine__SWIG_2."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1_Affine__SWIG_2."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P1, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_P1_Affine" "', argument " "1"" of type '" "blst::P1 const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_P1_Affine" "', argument " "1"" of type '" "blst::P1 const &""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = (blst::P1_Affine *)new blst::P1_Affine((blst::P1 const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1_Affine, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1_Affine(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; SWIGV8_VALUE self; // switch all cases by means of series of if-returns. if(args.Length() == 0) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1_Affine__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1_Affine__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1_Affine__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1_Affine__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1_Affine__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1_Affine__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for construction of _exports_P1_Affine"); fail: SWIGV8_RETURN(v8::Undefined(isolate)); } static SwigV8ReturnValue _wrap_P1_Affine_dup(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1_Affine result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_dup."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_dup" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = ((blst::P1_Affine const *)arg1)->dup(); jsresult = SWIG_NewPointerObj((new blst::P1_Affine(static_cast< const blst::P1_Affine& >(result))), SWIGTYPE_p_blst__P1_Affine, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_to_jacobian(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_to_jacobian."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_to_jacobian" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = ((blst::P1_Affine const *)arg1)->to_jacobian(); jsresult = SWIG_NewPointerObj((new blst::P1(static_cast< const blst::P1& >(result))), SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_serialize(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[96] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_serialize."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_serialize" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); arg2 = temp2; ((blst::P1_Affine const *)arg1)->serialize(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 96); memcpy(ab->GetData(), arg2, 96); jsresult = v8::Uint8Array::New(ab, 0, 96); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_compress(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[48] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_compress."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_compress" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); arg2 = temp2; ((blst::P1_Affine const *)arg1)->compress(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 48); memcpy(ab->GetData(), arg2, 48); jsresult = v8::Uint8Array::New(ab, 0, 48); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_on_curve(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_on_curve."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_on_curve" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = (bool)((blst::P1_Affine const *)arg1)->on_curve(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_in_group(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_in_group."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_in_group" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = (bool)((blst::P1_Affine const *)arg1)->in_group(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_is_inf(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_is_inf."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_is_inf" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = (bool)((blst::P1_Affine const *)arg1)->is_inf(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_is_equal(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; blst::P1_Affine *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool result; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_is_equal."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_is_equal" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_Affine_is_equal" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_is_equal" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); result = (bool)((blst::P1_Affine const *)arg1)->is_equal((blst::P1_Affine const &)*arg2); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_core_verify__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; std::string *arg6 = 0 ; byte *arg7 = (byte *) 0 ; size_t arg8 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; int res6 = SWIG_OLDOBJ ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_core_verify" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P1_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_Affine_core_verify', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res6 = SWIG_AsPtr_std_string(args[3], &ptr); if (!SWIG_IsOK(res6)) { SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "P1_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } arg6 = ptr; } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg7 = (byte *)buf->GetData() + av->ByteOffset(); arg8 = av->ByteLength(); } else if (args[4]->IsString()) { auto str = SWIGV8_TO_STRING(args[4]); arg8 = SWIGV8_UTF8_LENGTH(str); arg7 = (byte *)alloca(arg8); SWIGV8_WRITE_UTF8(str, (char *)arg7, arg8); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_Affine_core_verify', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)((blst::P1_Affine const *)arg1)->core_verify((blst::P2_Affine const &)*arg2,arg3,(byte const *)arg4,arg5,(std::string const &)*arg6,(byte const *)arg7,arg8); jsresult = SWIG_From_int(static_cast< int >(result)); if (SWIG_IsNewObj(res6)) delete arg6; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_core_verify__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; std::string *arg6 = 0 ; byte *arg7 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; int res6 = SWIG_OLDOBJ ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_core_verify" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P1_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_Affine_core_verify', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res6 = SWIG_AsPtr_std_string(args[3], &ptr); if (!SWIG_IsOK(res6)) { SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "P1_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } arg6 = ptr; } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg7 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_Affine_core_verify', " "expecting <Buffer>"); } result = (BLST_ERROR)((blst::P1_Affine const *)arg1)->core_verify((blst::P2_Affine const &)*arg2,arg3,(byte const *)arg4,arg5,(std::string const &)*arg6,(byte const *)arg7); jsresult = SWIG_From_int(static_cast< int >(result)); if (SWIG_IsNewObj(res6)) delete arg6; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_core_verify__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; std::string *arg6 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; int res6 = SWIG_OLDOBJ ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_core_verify" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P1_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_Affine_core_verify', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res6 = SWIG_AsPtr_std_string(args[3], &ptr); if (!SWIG_IsOK(res6)) { SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "P1_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } arg6 = ptr; } result = (BLST_ERROR)((blst::P1_Affine const *)arg1)->core_verify((blst::P2_Affine const &)*arg2,arg3,(byte const *)arg4,arg5,(std::string const &)*arg6); jsresult = SWIG_From_int(static_cast< int >(result)); if (SWIG_IsNewObj(res6)) delete arg6; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_core_verify__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_Affine_core_verify" "', argument " "1"" of type '" "blst::P1_Affine const *""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_Affine_core_verify" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P1_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_Affine_core_verify', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)((blst::P1_Affine const *)arg1)->core_verify((blst::P2_Affine const &)*arg2,arg3,(byte const *)arg4,arg5); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine__wrap_P1_Affine_core_verify(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_Affine_core_verify__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_Affine_core_verify__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_Affine_core_verify__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_Affine_core_verify__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_Affine_core_verify__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_Affine_core_verify__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_Affine_core_verify__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_Affine_core_verify__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function core_verify."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_Affine_generator(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_Affine_generator."); result = blst::P1_Affine::generator(); jsresult = SWIG_NewPointerObj((new blst::P1_Affine(static_cast< const blst::P1_Affine& >(result))), SWIGTYPE_p_blst__P1_Affine, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_P1_Affine(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_P1_Affine(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_P1_Affine(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_P1_Affine(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_P1_Affine(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::P1_Affine * arg1 = (blst::P1_Affine *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_new_P1__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P1 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1__SWIG_0."); if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1__SWIG_0."); result = (blst::P1 *)new blst::P1(); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::P1 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1__SWIG_1."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1__SWIG_1."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__SecretKey, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_P1" "', argument " "1"" of type '" "blst::SecretKey const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_P1" "', argument " "1"" of type '" "blst::SecretKey const &""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); result = (blst::P1 *)new blst::P1((blst::SecretKey const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); byte *arg1 = (byte *) 0 ; blst::P1 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1__SWIG_2."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1__SWIG_2."); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg1 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'new_P1', " "expecting <Buffer>"); } try { result = (blst::P1 *)new blst::P1((byte const *)arg1); } catch(BLST_ERROR &_e) { SWIG_V8_Raise(BLST_ERROR_str[_e]); SWIG_fail; } SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::P1 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P1__SWIG_3."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P1__SWIG_3."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_P1" "', argument " "1"" of type '" "blst::P1_Affine const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_P1" "', argument " "1"" of type '" "blst::P1_Affine const &""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = (blst::P1 *)new blst::P1((blst::P1_Affine const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P1(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; SWIGV8_VALUE self; // switch all cases by means of series of if-returns. if(args.Length() == 0) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P1__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P1__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for construction of _exports_P1"); fail: SWIGV8_RETURN(v8::Undefined(isolate)); } static SwigV8ReturnValue _wrap_P1_dup(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_dup."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_dup" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = ((blst::P1 const *)arg1)->dup(); jsresult = SWIG_NewPointerObj((new blst::P1(static_cast< const blst::P1& >(result))), SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_to_affine(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1_Affine result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_to_affine."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_to_affine" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = ((blst::P1 const *)arg1)->to_affine(); jsresult = SWIG_NewPointerObj((new blst::P1_Affine(static_cast< const blst::P1_Affine& >(result))), SWIGTYPE_p_blst__P1_Affine, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_serialize(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[96] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_serialize."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_serialize" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); arg2 = temp2; ((blst::P1 const *)arg1)->serialize(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 96); memcpy(ab->GetData(), arg2, 96); jsresult = v8::Uint8Array::New(ab, 0, 96); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_compress(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[48] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_compress."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_compress" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); arg2 = temp2; ((blst::P1 const *)arg1)->compress(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 48); memcpy(ab->GetData(), arg2, 48); jsresult = v8::Uint8Array::New(ab, 0, 48); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_on_curve(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_on_curve."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_on_curve" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = (bool)((blst::P1 const *)arg1)->on_curve(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_in_group(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_in_group."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_in_group" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = (bool)((blst::P1 const *)arg1)->in_group(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_is_inf(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_is_inf."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_is_inf" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = (bool)((blst::P1 const *)arg1)->is_inf(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_is_equal(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; blst::P1 *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool result; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_is_equal."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_is_equal" "', argument " "1"" of type '" "blst::P1 const *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_is_equal" "', argument " "2"" of type '" "blst::P1 const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_is_equal" "', argument " "2"" of type '" "blst::P1 const &""'"); } arg2 = reinterpret_cast< blst::P1 * >(argp2); result = (bool)((blst::P1 const *)arg1)->is_equal((blst::P1 const &)*arg2); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_aggregate(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; blst::P1_Affine *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_aggregate."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_aggregate" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); try { (arg1)->aggregate((blst::P1_Affine const &)*arg2); } catch(BLST_ERROR &_e) { SWIG_V8_Raise(BLST_ERROR_str[_e]); SWIG_fail; } jsresult = SWIGV8_UNDEFINED(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_sign_with(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; blst::SecretKey *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::P1 *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_sign_with."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_sign_with" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__SecretKey, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_sign_with" "', argument " "2"" of type '" "blst::SecretKey const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_sign_with" "', argument " "2"" of type '" "blst::SecretKey const &""'"); } arg2 = reinterpret_cast< blst::SecretKey * >(argp2); result = (blst::P1 *)(arg1)->sign_with((blst::SecretKey const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_hash_to__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; size_t arg6 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_hash_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_hash_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P1_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); arg6 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg6 = SWIGV8_UTF8_LENGTH(str); arg5 = (byte *)alloca(arg6); SWIGV8_WRITE_UTF8(str, (char *)arg5, arg6); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_hash_to', " "expecting <Buffer> or <String>"); } result = (blst::P1 *)(arg1)->hash_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5,arg6); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_hash_to__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_hash_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_hash_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P1_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_hash_to', " "expecting <Buffer>"); } result = (blst::P1 *)(arg1)->hash_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_hash_to__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_hash_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_hash_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P1_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } result = (blst::P1 *)(arg1)->hash_to((byte const *)arg2,arg3,(std::string const &)*arg4); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_hash_to__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_hash_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_hash_to', " "expecting <Buffer> or <String>"); } result = (blst::P1 *)(arg1)->hash_to((byte const *)arg2,arg3); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1__wrap_P1_hash_to(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_hash_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_hash_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_hash_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_hash_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_hash_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_hash_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_hash_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_hash_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function hash_to."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_encode_to__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; size_t arg6 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_encode_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_encode_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P1_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); arg6 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg6 = SWIGV8_UTF8_LENGTH(str); arg5 = (byte *)alloca(arg6); SWIGV8_WRITE_UTF8(str, (char *)arg5, arg6); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_encode_to', " "expecting <Buffer> or <String>"); } result = (blst::P1 *)(arg1)->encode_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5,arg6); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_encode_to__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_encode_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_encode_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P1_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_encode_to', " "expecting <Buffer>"); } result = (blst::P1 *)(arg1)->encode_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_encode_to__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_encode_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_encode_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P1_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } result = (blst::P1 *)(arg1)->encode_to((byte const *)arg2,arg3,(std::string const &)*arg4); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_encode_to__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_encode_to" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_encode_to', " "expecting <Buffer> or <String>"); } result = (blst::P1 *)(arg1)->encode_to((byte const *)arg2,arg3); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1__wrap_P1_encode_to(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_encode_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_encode_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_encode_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_encode_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_encode_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_encode_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_encode_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_encode_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function encode_to."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_mult(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_mult."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_mult" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[0]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[0]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg3 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'P1_mult', " "expecting unsigned value"); arg2 = (byte *)words; arg3 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg2; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P1_mult', " "expecting <Buffer> or <BigInt>"); } result = (blst::P1 *)(arg1)->mult((byte const *)arg2,arg3); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_cneg(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; bool arg2 ; void *argp1 = 0 ; int res1 = 0 ; bool val2 ; int ecode2 = 0 ; blst::P1 *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_cneg."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_cneg" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); ecode2 = SWIG_AsVal_bool(args[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "P1_cneg" "', argument " "2"" of type '" "bool""'"); } arg2 = static_cast< bool >(val2); result = (blst::P1 *)(arg1)->cneg(arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_neg(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 *result = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_neg."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_neg" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = (blst::P1 *)(arg1)->neg(); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_add__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; blst::P1 *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_add" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_add" "', argument " "2"" of type '" "blst::P1 const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_add" "', argument " "2"" of type '" "blst::P1 const &""'"); } arg2 = reinterpret_cast< blst::P1 * >(argp2); result = (blst::P1 *)(arg1)->add((blst::P1 const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_add__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; blst::P1_Affine *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::P1 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_add" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P1_add" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P1_add" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); result = (blst::P1 *)(arg1)->add((blst::P1_Affine const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1__wrap_P1_add(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_add__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_add__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P1_add__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P1_add__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function add."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_dbl(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 *arg1 = (blst::P1 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P1 *result = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_dbl."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P1, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P1_dbl" "', argument " "1"" of type '" "blst::P1 *""'"); } arg1 = reinterpret_cast< blst::P1 * >(argp1); result = (blst::P1 *)(arg1)->dbl(); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P1_generator(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P1_generator."); result = blst::P1::generator(); jsresult = SWIG_NewPointerObj((new blst::P1(static_cast< const blst::P1& >(result))), SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_P1(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_P1(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_P1(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_P1(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_P1(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::P1 * arg1 = (blst::P1 *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_new_P2_Affine__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2_Affine__SWIG_0."); if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2_Affine__SWIG_0."); result = (blst::P2_Affine *)new blst::P2_Affine(); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2_Affine, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2_Affine__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); byte *arg1 = (byte *) 0 ; blst::P2_Affine *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2_Affine__SWIG_1."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2_Affine__SWIG_1."); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg1 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'new_P2_Affine', " "expecting <Buffer>"); } try { result = (blst::P2_Affine *)new blst::P2_Affine((byte const *)arg1); } catch(BLST_ERROR &_e) { SWIG_V8_Raise(BLST_ERROR_str[_e]); SWIG_fail; } SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2_Affine, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2_Affine__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::P2_Affine *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2_Affine__SWIG_2."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2_Affine__SWIG_2."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P2, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_P2_Affine" "', argument " "1"" of type '" "blst::P2 const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_P2_Affine" "', argument " "1"" of type '" "blst::P2 const &""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = (blst::P2_Affine *)new blst::P2_Affine((blst::P2 const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2_Affine, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2_Affine(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; SWIGV8_VALUE self; // switch all cases by means of series of if-returns. if(args.Length() == 0) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2_Affine__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2_Affine__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2_Affine__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2_Affine__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2_Affine__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2_Affine__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for construction of _exports_P2_Affine"); fail: SWIGV8_RETURN(v8::Undefined(isolate)); } static SwigV8ReturnValue _wrap_P2_Affine_dup(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2_Affine result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_dup."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_dup" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = ((blst::P2_Affine const *)arg1)->dup(); jsresult = SWIG_NewPointerObj((new blst::P2_Affine(static_cast< const blst::P2_Affine& >(result))), SWIGTYPE_p_blst__P2_Affine, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_to_jacobian(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_to_jacobian."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_to_jacobian" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = ((blst::P2_Affine const *)arg1)->to_jacobian(); jsresult = SWIG_NewPointerObj((new blst::P2(static_cast< const blst::P2& >(result))), SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_serialize(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[192] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_serialize."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_serialize" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); arg2 = temp2; ((blst::P2_Affine const *)arg1)->serialize(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 192); memcpy(ab->GetData(), arg2, 192); jsresult = v8::Uint8Array::New(ab, 0, 192); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_compress(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[96] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_compress."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_compress" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); arg2 = temp2; ((blst::P2_Affine const *)arg1)->compress(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 96); memcpy(ab->GetData(), arg2, 96); jsresult = v8::Uint8Array::New(ab, 0, 96); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_on_curve(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_on_curve."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_on_curve" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = (bool)((blst::P2_Affine const *)arg1)->on_curve(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_in_group(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_in_group."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_in_group" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = (bool)((blst::P2_Affine const *)arg1)->in_group(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_is_inf(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_is_inf."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_is_inf" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = (bool)((blst::P2_Affine const *)arg1)->is_inf(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_is_equal(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; blst::P2_Affine *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool result; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_is_equal."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_is_equal" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_Affine_is_equal" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_is_equal" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); result = (bool)((blst::P2_Affine const *)arg1)->is_equal((blst::P2_Affine const &)*arg2); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_core_verify__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; std::string *arg6 = 0 ; byte *arg7 = (byte *) 0 ; size_t arg8 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; int res6 = SWIG_OLDOBJ ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_core_verify" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P2_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_Affine_core_verify', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res6 = SWIG_AsPtr_std_string(args[3], &ptr); if (!SWIG_IsOK(res6)) { SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "P2_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } arg6 = ptr; } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg7 = (byte *)buf->GetData() + av->ByteOffset(); arg8 = av->ByteLength(); } else if (args[4]->IsString()) { auto str = SWIGV8_TO_STRING(args[4]); arg8 = SWIGV8_UTF8_LENGTH(str); arg7 = (byte *)alloca(arg8); SWIGV8_WRITE_UTF8(str, (char *)arg7, arg8); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_Affine_core_verify', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)((blst::P2_Affine const *)arg1)->core_verify((blst::P1_Affine const &)*arg2,arg3,(byte const *)arg4,arg5,(std::string const &)*arg6,(byte const *)arg7,arg8); jsresult = SWIG_From_int(static_cast< int >(result)); if (SWIG_IsNewObj(res6)) delete arg6; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_core_verify__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; std::string *arg6 = 0 ; byte *arg7 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; int res6 = SWIG_OLDOBJ ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_core_verify" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P2_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_Affine_core_verify', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res6 = SWIG_AsPtr_std_string(args[3], &ptr); if (!SWIG_IsOK(res6)) { SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "P2_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } arg6 = ptr; } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg7 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_Affine_core_verify', " "expecting <Buffer>"); } result = (BLST_ERROR)((blst::P2_Affine const *)arg1)->core_verify((blst::P1_Affine const &)*arg2,arg3,(byte const *)arg4,arg5,(std::string const &)*arg6,(byte const *)arg7); jsresult = SWIG_From_int(static_cast< int >(result)); if (SWIG_IsNewObj(res6)) delete arg6; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_core_verify__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; std::string *arg6 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; int res6 = SWIG_OLDOBJ ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_core_verify" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P2_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_Affine_core_verify', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res6 = SWIG_AsPtr_std_string(args[3], &ptr); if (!SWIG_IsOK(res6)) { SWIG_exception_fail(SWIG_ArgError(res6), "in method '" "P2_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "6"" of type '" "std::string const &""'"); } arg6 = ptr; } result = (BLST_ERROR)((blst::P2_Affine const *)arg1)->core_verify((blst::P1_Affine const &)*arg2,arg3,(byte const *)arg4,arg5,(std::string const &)*arg6); jsresult = SWIG_From_int(static_cast< int >(result)); if (SWIG_IsNewObj(res6)) delete arg6; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_core_verify__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg2 = 0 ; bool arg3 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool val3 ; int ecode3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_Affine_core_verify" "', argument " "1"" of type '" "blst::P2_Affine const *""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_Affine_core_verify" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); ecode3 = SWIG_AsVal_bool(args[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "P2_Affine_core_verify" "', argument " "3"" of type '" "bool""'"); } arg3 = static_cast< bool >(val3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_Affine_core_verify', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)((blst::P2_Affine const *)arg1)->core_verify((blst::P1_Affine const &)*arg2,arg3,(byte const *)arg4,arg5); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine__wrap_P2_Affine_core_verify(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_Affine_core_verify__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_Affine_core_verify__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_Affine_core_verify__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_Affine_core_verify__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_Affine_core_verify__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_Affine_core_verify__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_Affine_core_verify__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_Affine_core_verify__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function core_verify."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_Affine_generator(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_Affine_generator."); result = blst::P2_Affine::generator(); jsresult = SWIG_NewPointerObj((new blst::P2_Affine(static_cast< const blst::P2_Affine& >(result))), SWIGTYPE_p_blst__P2_Affine, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_P2_Affine(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_P2_Affine(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_P2_Affine(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_P2_Affine(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_P2_Affine(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::P2_Affine * arg1 = (blst::P2_Affine *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_new_P2__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P2 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2__SWIG_0."); if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2__SWIG_0."); result = (blst::P2 *)new blst::P2(); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::SecretKey *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::P2 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2__SWIG_1."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2__SWIG_1."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__SecretKey, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_P2" "', argument " "1"" of type '" "blst::SecretKey const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_P2" "', argument " "1"" of type '" "blst::SecretKey const &""'"); } arg1 = reinterpret_cast< blst::SecretKey * >(argp1); result = (blst::P2 *)new blst::P2((blst::SecretKey const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); byte *arg1 = (byte *) 0 ; blst::P2 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2__SWIG_2."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2__SWIG_2."); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg1 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'new_P2', " "expecting <Buffer>"); } try { result = (blst::P2 *)new blst::P2((byte const *)arg1); } catch(BLST_ERROR &_e) { SWIG_V8_Raise(BLST_ERROR_str[_e]); SWIG_fail; } SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::P2 *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_P2__SWIG_3."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_P2__SWIG_3."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_P2" "', argument " "1"" of type '" "blst::P2_Affine const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_P2" "', argument " "1"" of type '" "blst::P2_Affine const &""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = (blst::P2 *)new blst::P2((blst::P2_Affine const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_P2(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; SWIGV8_VALUE self; // switch all cases by means of series of if-returns. if(args.Length() == 0) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_P2__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_P2__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for construction of _exports_P2"); fail: SWIGV8_RETURN(v8::Undefined(isolate)); } static SwigV8ReturnValue _wrap_P2_dup(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_dup."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_dup" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = ((blst::P2 const *)arg1)->dup(); jsresult = SWIG_NewPointerObj((new blst::P2(static_cast< const blst::P2& >(result))), SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_to_affine(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2_Affine result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_to_affine."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_to_affine" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = ((blst::P2 const *)arg1)->to_affine(); jsresult = SWIG_NewPointerObj((new blst::P2_Affine(static_cast< const blst::P2_Affine& >(result))), SWIGTYPE_p_blst__P2_Affine, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_serialize(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[192] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_serialize."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_serialize" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); arg2 = temp2; ((blst::P2 const *)arg1)->serialize(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 192); memcpy(ab->GetData(), arg2, 192); jsresult = v8::Uint8Array::New(ab, 0, 192); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_compress(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 ; void *argp1 = 0 ; int res1 = 0 ; byte temp2[96] ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_compress."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_compress" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); arg2 = temp2; ((blst::P2 const *)arg1)->compress(arg2); jsresult = SWIGV8_UNDEFINED(); { auto ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 96); memcpy(ab->GetData(), arg2, 96); jsresult = v8::Uint8Array::New(ab, 0, 96); } SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_on_curve(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_on_curve."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_on_curve" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = (bool)((blst::P2 const *)arg1)->on_curve(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_in_group(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_in_group."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_in_group" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = (bool)((blst::P2 const *)arg1)->in_group(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_is_inf(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_is_inf."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_is_inf" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = (bool)((blst::P2 const *)arg1)->is_inf(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_is_equal(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; blst::P2 *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool result; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_is_equal."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_is_equal" "', argument " "1"" of type '" "blst::P2 const *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_is_equal" "', argument " "2"" of type '" "blst::P2 const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_is_equal" "', argument " "2"" of type '" "blst::P2 const &""'"); } arg2 = reinterpret_cast< blst::P2 * >(argp2); result = (bool)((blst::P2 const *)arg1)->is_equal((blst::P2 const &)*arg2); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_aggregate(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; blst::P2_Affine *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_aggregate."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_aggregate" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); try { (arg1)->aggregate((blst::P2_Affine const &)*arg2); } catch(BLST_ERROR &_e) { SWIG_V8_Raise(BLST_ERROR_str[_e]); SWIG_fail; } jsresult = SWIGV8_UNDEFINED(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_sign_with(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; blst::SecretKey *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::P2 *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_sign_with."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_sign_with" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__SecretKey, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_sign_with" "', argument " "2"" of type '" "blst::SecretKey const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_sign_with" "', argument " "2"" of type '" "blst::SecretKey const &""'"); } arg2 = reinterpret_cast< blst::SecretKey * >(argp2); result = (blst::P2 *)(arg1)->sign_with((blst::SecretKey const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_hash_to__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; size_t arg6 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_hash_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_hash_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P2_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); arg6 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg6 = SWIGV8_UTF8_LENGTH(str); arg5 = (byte *)alloca(arg6); SWIGV8_WRITE_UTF8(str, (char *)arg5, arg6); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_hash_to', " "expecting <Buffer> or <String>"); } result = (blst::P2 *)(arg1)->hash_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5,arg6); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_hash_to__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_hash_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_hash_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P2_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_hash_to', " "expecting <Buffer>"); } result = (blst::P2 *)(arg1)->hash_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_hash_to__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_hash_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_hash_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P2_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_hash_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } result = (blst::P2 *)(arg1)->hash_to((byte const *)arg2,arg3,(std::string const &)*arg4); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_hash_to__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_hash_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_hash_to', " "expecting <Buffer> or <String>"); } result = (blst::P2 *)(arg1)->hash_to((byte const *)arg2,arg3); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2__wrap_P2_hash_to(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_hash_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_hash_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_hash_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_hash_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_hash_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_hash_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_hash_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_hash_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function hash_to."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_encode_to__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; size_t arg6 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_encode_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_encode_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P2_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); arg6 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg6 = SWIGV8_UTF8_LENGTH(str); arg5 = (byte *)alloca(arg6); SWIGV8_WRITE_UTF8(str, (char *)arg5, arg6); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_encode_to', " "expecting <Buffer> or <String>"); } result = (blst::P2 *)(arg1)->encode_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5,arg6); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_encode_to__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; byte *arg5 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_encode_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_encode_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P2_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg5 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_encode_to', " "expecting <Buffer>"); } result = (blst::P2 *)(arg1)->encode_to((byte const *)arg2,arg3,(std::string const &)*arg4,(byte const *)arg5); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_encode_to__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; std::string *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; int res4 = SWIG_OLDOBJ ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_encode_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_encode_to', " "expecting <Buffer> or <String>"); } { std::string *ptr = (std::string *)0; res4 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "P2_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_encode_to" "', argument " "4"" of type '" "std::string const &""'"); } arg4 = ptr; } result = (blst::P2 *)(arg1)->encode_to((byte const *)arg2,arg3,(std::string const &)*arg4); (void)result; jsresult = args.Holder(); if (SWIG_IsNewObj(res4)) delete arg4; SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_encode_to__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_encode_to" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[0]->IsString()) { auto str = SWIGV8_TO_STRING(args[0]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_encode_to', " "expecting <Buffer> or <String>"); } result = (blst::P2 *)(arg1)->encode_to((byte const *)arg2,arg3); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2__wrap_P2_encode_to(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_encode_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_encode_to__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_encode_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_encode_to__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_encode_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_encode_to__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_encode_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_encode_to__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function encode_to."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_mult(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_mult."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_mult" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); if (args[0]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[0]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[0]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[0]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg3 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'P2_mult', " "expecting unsigned value"); arg2 = (byte *)words; arg3 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg2; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'P2_mult', " "expecting <Buffer> or <BigInt>"); } result = (blst::P2 *)(arg1)->mult((byte const *)arg2,arg3); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_cneg(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; bool arg2 ; void *argp1 = 0 ; int res1 = 0 ; bool val2 ; int ecode2 = 0 ; blst::P2 *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_cneg."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_cneg" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); ecode2 = SWIG_AsVal_bool(args[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "P2_cneg" "', argument " "2"" of type '" "bool""'"); } arg2 = static_cast< bool >(val2); result = (blst::P2 *)(arg1)->cneg(arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_neg(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 *result = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_neg."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_neg" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = (blst::P2 *)(arg1)->neg(); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_add__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; blst::P2 *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_add" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_add" "', argument " "2"" of type '" "blst::P2 const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_add" "', argument " "2"" of type '" "blst::P2 const &""'"); } arg2 = reinterpret_cast< blst::P2 * >(argp2); result = (blst::P2 *)(arg1)->add((blst::P2 const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_add__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; blst::P2_Affine *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::P2 *result = 0 ; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_add" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "P2_add" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "P2_add" "', argument " "2"" of type '" "blst::P2_Affine const &""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); result = (blst::P2 *)(arg1)->add((blst::P2_Affine const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2__wrap_P2_add(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_add__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_add__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_P2_add__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_P2_add__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function add."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_dbl(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 *arg1 = (blst::P2 *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::P2 *result = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_dbl."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__P2, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "P2_dbl" "', argument " "1"" of type '" "blst::P2 *""'"); } arg1 = reinterpret_cast< blst::P2 * >(argp1); result = (blst::P2 *)(arg1)->dbl(); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_P2_generator(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_P2_generator."); result = blst::P2::generator(); jsresult = SWIG_NewPointerObj((new blst::P2(static_cast< const blst::P2& >(result))), SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_P2(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_P2(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_P2(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_P2(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_P2(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::P2 * arg1 = (blst::P2 *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_G1(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P1 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_G1."); result = blst::G1(); jsresult = SWIG_NewPointerObj((new blst::P1(static_cast< const blst::P1& >(result))), SWIGTYPE_p_blst__P1, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_G2(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::P2 result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_G2."); result = blst::G2(); jsresult = SWIG_NewPointerObj((new blst::P2(static_cast< const blst::P2& >(result))), SWIGTYPE_p_blst__P2, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_PT__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P1_Affine *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::PT *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_PT__SWIG_0."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_PT__SWIG_0."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_PT" "', argument " "1"" of type '" "blst::P1_Affine const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_PT" "', argument " "1"" of type '" "blst::P1_Affine const &""'"); } arg1 = reinterpret_cast< blst::P1_Affine * >(argp1); result = (blst::PT *)new blst::PT((blst::P1_Affine const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__PT, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_PT__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = 0 ; void *argp1 ; int res1 = 0 ; blst::PT *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_PT__SWIG_1."); if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_PT__SWIG_1."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_PT" "', argument " "1"" of type '" "blst::P2_Affine const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_PT" "', argument " "1"" of type '" "blst::P2_Affine const &""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); result = (blst::PT *)new blst::PT((blst::P2_Affine const &)*arg1); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__PT, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_PT__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); blst::P2_Affine *arg1 = 0 ; blst::P1_Affine *arg2 = 0 ; void *argp1 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::PT *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_PT__SWIG_2."); if(args.Length() != 2) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_PT__SWIG_2."); res1 = SWIG_ConvertPtr(args[0], &argp1, SWIGTYPE_p_blst__P2_Affine, 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_PT" "', argument " "1"" of type '" "blst::P2_Affine const &""'"); } if (!argp1) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_PT" "', argument " "1"" of type '" "blst::P2_Affine const &""'"); } arg1 = reinterpret_cast< blst::P2_Affine * >(argp1); res2 = SWIG_ConvertPtr(args[1], &argp2, SWIGTYPE_p_blst__P1_Affine, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new_PT" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_PT" "', argument " "2"" of type '" "blst::P1_Affine const &""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); result = (blst::PT *)new blst::PT((blst::P2_Affine const &)*arg1,(blst::P1_Affine const &)*arg2); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__PT, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_PT(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; SWIGV8_VALUE self; // switch all cases by means of series of if-returns. if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_PT__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_PT__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_PT__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_PT__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_PT__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_PT__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for construction of _exports_PT"); fail: SWIGV8_RETURN(v8::Undefined(isolate)); } static SwigV8ReturnValue _wrap_PT_dup(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::PT *arg1 = (blst::PT *) 0 ; void *argp1 = 0 ; int res1 = 0 ; SwigValueWrapper< blst::PT > result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_PT_dup."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "PT_dup" "', argument " "1"" of type '" "blst::PT const *""'"); } arg1 = reinterpret_cast< blst::PT * >(argp1); result = ((blst::PT const *)arg1)->dup(); jsresult = SWIG_NewPointerObj((new blst::PT(static_cast< const blst::PT& >(result))), SWIGTYPE_p_blst__PT, SWIG_POINTER_OWN | 0 ); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_PT_is_one(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::PT *arg1 = (blst::PT *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_PT_is_one."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "PT_is_one" "', argument " "1"" of type '" "blst::PT const *""'"); } arg1 = reinterpret_cast< blst::PT * >(argp1); result = (bool)((blst::PT const *)arg1)->is_one(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_PT_is_equal(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::PT *arg1 = (blst::PT *) 0 ; blst::PT *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; bool result; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_PT_is_equal."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "PT_is_equal" "', argument " "1"" of type '" "blst::PT const *""'"); } arg1 = reinterpret_cast< blst::PT * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__PT, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "PT_is_equal" "', argument " "2"" of type '" "blst::PT const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "PT_is_equal" "', argument " "2"" of type '" "blst::PT const &""'"); } arg2 = reinterpret_cast< blst::PT * >(argp2); result = (bool)((blst::PT const *)arg1)->is_equal((blst::PT const &)*arg2); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_PT_sqr(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::PT *arg1 = (blst::PT *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::PT *result = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_PT_sqr."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "PT_sqr" "', argument " "1"" of type '" "blst::PT *""'"); } arg1 = reinterpret_cast< blst::PT * >(argp1); result = (blst::PT *)(arg1)->sqr(); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_PT_mul(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::PT *arg1 = (blst::PT *) 0 ; blst::PT *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; blst::PT *result = 0 ; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_PT_mul."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "PT_mul" "', argument " "1"" of type '" "blst::PT *""'"); } arg1 = reinterpret_cast< blst::PT * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2, SWIGTYPE_p_blst__PT, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "PT_mul" "', argument " "2"" of type '" "blst::PT const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "PT_mul" "', argument " "2"" of type '" "blst::PT const &""'"); } arg2 = reinterpret_cast< blst::PT * >(argp2); result = (blst::PT *)(arg1)->mul((blst::PT const &)*arg2); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_PT_final_exp(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::PT *arg1 = (blst::PT *) 0 ; void *argp1 = 0 ; int res1 = 0 ; blst::PT *result = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_PT_final_exp."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "PT_final_exp" "', argument " "1"" of type '" "blst::PT *""'"); } arg1 = reinterpret_cast< blst::PT * >(argp1); result = (blst::PT *)(arg1)->final_exp(); (void)result; jsresult = args.Holder(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_PT(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_PT(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_PT(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_PT(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_PT(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::PT * arg1 = (blst::PT *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_new_Pairing__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); bool arg1 ; byte *arg2 = (byte *) 0 ; size_t arg3 ; bool val1 ; int ecode1 = 0 ; blst::Pairing *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_Pairing__SWIG_0."); if(args.Length() != 2) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_Pairing__SWIG_0."); ecode1 = SWIG_AsVal_bool(args[0], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_Pairing" "', argument " "1"" of type '" "bool""'"); } arg1 = static_cast< bool >(val1); if (args[1]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[1]); auto buf = av->Buffer(); arg2 = (byte *)buf->GetData() + av->ByteOffset(); arg3 = av->ByteLength(); } else if (args[1]->IsString()) { auto str = SWIGV8_TO_STRING(args[1]); arg3 = SWIGV8_UTF8_LENGTH(str); arg2 = (byte *)alloca(arg3); SWIGV8_WRITE_UTF8(str, (char *)arg2, arg3); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'new_Pairing', " "expecting <Buffer> or <String>"); } result = (blst::Pairing *)new blst::Pairing(arg1,(byte const *)arg2,arg3); SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__Pairing, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_Pairing__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_OBJECT self = args.Holder(); SWIGV8_VALUE jsdata = args.Data(); bool arg1 ; std::string *arg2 = 0 ; bool val1 ; int ecode1 = 0 ; int res2 = SWIG_OLDOBJ ; blst::Pairing *result; if(self->InternalFieldCount() < 1) SWIG_exception_fail(SWIG_ERROR, "Illegal call of constructor _wrap_new_Pairing__SWIG_1."); if(args.Length() != 2) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_new_Pairing__SWIG_1."); ecode1 = SWIG_AsVal_bool(args[0], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_Pairing" "', argument " "1"" of type '" "bool""'"); } arg1 = static_cast< bool >(val1); { std::string *ptr = (std::string *)0; res2 = SWIG_AsPtr_std_string(args[1], &ptr); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new_Pairing" "', argument " "2"" of type '" "std::string const &""'"); } if (!ptr) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new_Pairing" "', argument " "2"" of type '" "std::string const &""'"); } arg2 = ptr; } result = (blst::Pairing *)new blst::Pairing(arg1,(std::string const &)*arg2); if (SWIG_IsNewObj(res2)) delete arg2; SWIGV8_SetPrivateData(self, result, SWIGTYPE_p_blst__Pairing, SWIG_POINTER_OWN); SWIGV8_RETURN(self); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_new_Pairing(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); OverloadErrorHandler errorHandler; SWIGV8_VALUE self; // switch all cases by means of series of if-returns. if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_Pairing__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_Pairing__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 2) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) self = _wrap_new_Pairing__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(self); } #else _wrap_new_Pairing__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for construction of _exports_Pairing"); fail: SWIGV8_RETURN(v8::Undefined(isolate)); } #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) static void _wrap_delete_Pairing(v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) static void _wrap_delete_Pairing(v8::Isolate *isolate, v8::Persistent<v8::Value> object, void *parameter) { SWIGV8_Proxy *proxy = static_cast<SWIGV8_Proxy *>(parameter); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) static void _wrap_delete_Pairing(v8::Isolate *isolate, v8::Persistent< v8::Object> *object, SWIGV8_Proxy *proxy) { #elif (V8_MAJOR_VERSION-0) < 5 static void _wrap_delete_Pairing(const v8::WeakCallbackData<v8::Object, SWIGV8_Proxy> &data) { v8::Local<v8::Object> object = data.GetValue(); SWIGV8_Proxy *proxy = data.GetParameter(); #else static void _wrap_delete_Pairing(const v8::WeakCallbackInfo<SWIGV8_Proxy> &data) { SWIGV8_Proxy *proxy = data.GetParameter(); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { blst::Pairing * arg1 = (blst::Pairing *)proxy->swigCObject; delete arg1; } delete proxy; #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031710) object.Dispose(); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031900) object.Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); #elif (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < SWIGV8_SETWEAK_VERSION) object->Dispose(); #elif (V8_MAJOR_VERSION-0) < 5 object.Clear(); #endif } static SwigV8ReturnValue _wrap_Pairing_aggregate__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P1_Affine *arg2 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg3 = (blst::P2_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const *""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_aggregate" "', argument " "3"" of type '" "blst::P2_Affine const *""'"); } arg3 = reinterpret_cast< blst::P2_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->aggregate((blst::P1_Affine const *)arg2,(blst::P2_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_aggregate__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P1_Affine *arg2 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg3 = (blst::P2_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const *""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_aggregate" "', argument " "3"" of type '" "blst::P2_Affine const *""'"); } arg3 = reinterpret_cast< blst::P2_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer>"); } result = (BLST_ERROR)(arg1)->aggregate((blst::P1_Affine const *)arg2,(blst::P2_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_aggregate__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P1_Affine *arg2 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg3 = (blst::P2_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const *""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_aggregate" "', argument " "3"" of type '" "blst::P2_Affine const *""'"); } arg3 = reinterpret_cast< blst::P2_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->aggregate((blst::P1_Affine const *)arg2,(blst::P2_Affine const *)arg3,(byte const *)arg4,arg5); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_aggregate__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P2_Affine *arg2 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg3 = (blst::P1_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const *""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_aggregate" "', argument " "3"" of type '" "blst::P1_Affine const *""'"); } arg3 = reinterpret_cast< blst::P1_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->aggregate((blst::P2_Affine const *)arg2,(blst::P1_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_aggregate__SWIG_4(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P2_Affine *arg2 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg3 = (blst::P1_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const *""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_aggregate" "', argument " "3"" of type '" "blst::P1_Affine const *""'"); } arg3 = reinterpret_cast< blst::P1_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer>"); } result = (BLST_ERROR)(arg1)->aggregate((blst::P2_Affine const *)arg2,(blst::P1_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_aggregate__SWIG_5(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P2_Affine *arg2 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg3 = (blst::P1_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const *""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_aggregate" "', argument " "3"" of type '" "blst::P1_Affine const *""'"); } arg3 = reinterpret_cast< blst::P1_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = av->ByteLength(); } else if (args[2]->IsString()) { auto str = SWIGV8_TO_STRING(args[2]); arg5 = SWIGV8_UTF8_LENGTH(str); arg4 = (byte *)alloca(arg5); SWIGV8_WRITE_UTF8(str, (char *)arg4, arg5); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->aggregate((blst::P2_Affine const *)arg2,(blst::P1_Affine const *)arg3,(byte const *)arg4,arg5); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing__wrap_Pairing_aggregate(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_aggregate__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_aggregate__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_aggregate__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_aggregate__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_aggregate__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_aggregate__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_aggregate__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_aggregate__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_aggregate__SWIG_4(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_aggregate__SWIG_4(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 3) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_aggregate__SWIG_5(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_aggregate__SWIG_5(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function aggregate."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_mul_n_aggregate__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P1_Affine *arg2 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg3 = (blst::P2_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; byte *arg8 = (byte *) 0 ; size_t arg9 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_mul_n_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_mul_n_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const *""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_mul_n_aggregate" "', argument " "3"" of type '" "blst::P2_Affine const *""'"); } arg3 = reinterpret_cast< blst::P2_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[2]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[2]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg5 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting unsigned value"); arg4 = (byte *)words; arg5 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg4; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <BigInt>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg8 = (byte *)buf->GetData() + av->ByteOffset(); arg9 = av->ByteLength(); } else if (args[4]->IsString()) { auto str = SWIGV8_TO_STRING(args[4]); arg9 = SWIGV8_UTF8_LENGTH(str); arg8 = (byte *)alloca(arg9); SWIGV8_WRITE_UTF8(str, (char *)arg8, arg9); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->mul_n_aggregate((blst::P1_Affine const *)arg2,(blst::P2_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7,(byte const *)arg8,arg9); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_mul_n_aggregate__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P1_Affine *arg2 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg3 = (blst::P2_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; byte *arg8 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_mul_n_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_mul_n_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const *""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_mul_n_aggregate" "', argument " "3"" of type '" "blst::P2_Affine const *""'"); } arg3 = reinterpret_cast< blst::P2_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[2]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[2]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg5 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting unsigned value"); arg4 = (byte *)words; arg5 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg4; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <BigInt>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg8 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer>"); } result = (BLST_ERROR)(arg1)->mul_n_aggregate((blst::P1_Affine const *)arg2,(blst::P2_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7,(byte const *)arg8); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_mul_n_aggregate__SWIG_2(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P1_Affine *arg2 = (blst::P1_Affine *) 0 ; blst::P2_Affine *arg3 = (blst::P2_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_mul_n_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_mul_n_aggregate" "', argument " "2"" of type '" "blst::P1_Affine const *""'"); } arg2 = reinterpret_cast< blst::P1_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_mul_n_aggregate" "', argument " "3"" of type '" "blst::P2_Affine const *""'"); } arg3 = reinterpret_cast< blst::P2_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[2]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[2]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg5 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting unsigned value"); arg4 = (byte *)words; arg5 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg4; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <BigInt>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->mul_n_aggregate((blst::P1_Affine const *)arg2,(blst::P2_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_mul_n_aggregate__SWIG_3(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P2_Affine *arg2 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg3 = (blst::P1_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; byte *arg8 = (byte *) 0 ; size_t arg9 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_mul_n_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_mul_n_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const *""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_mul_n_aggregate" "', argument " "3"" of type '" "blst::P1_Affine const *""'"); } arg3 = reinterpret_cast< blst::P1_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[2]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[2]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg5 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting unsigned value"); arg4 = (byte *)words; arg5 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg4; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <BigInt>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg8 = (byte *)buf->GetData() + av->ByteOffset(); arg9 = av->ByteLength(); } else if (args[4]->IsString()) { auto str = SWIGV8_TO_STRING(args[4]); arg9 = SWIGV8_UTF8_LENGTH(str); arg8 = (byte *)alloca(arg9); SWIGV8_WRITE_UTF8(str, (char *)arg8, arg9); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->mul_n_aggregate((blst::P2_Affine const *)arg2,(blst::P1_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7,(byte const *)arg8,arg9); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_mul_n_aggregate__SWIG_4(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P2_Affine *arg2 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg3 = (blst::P1_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; byte *arg8 = (byte *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_mul_n_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_mul_n_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const *""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_mul_n_aggregate" "', argument " "3"" of type '" "blst::P1_Affine const *""'"); } arg3 = reinterpret_cast< blst::P1_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[2]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[2]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg5 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting unsigned value"); arg4 = (byte *)words; arg5 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg4; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <BigInt>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } if (args[4]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[4]); auto buf = av->Buffer(); arg8 = (byte *)buf->GetData() + av->ByteOffset(); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer>"); } result = (BLST_ERROR)(arg1)->mul_n_aggregate((blst::P2_Affine const *)arg2,(blst::P1_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7,(byte const *)arg8); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_mul_n_aggregate__SWIG_5(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::P2_Affine *arg2 = (blst::P2_Affine *) 0 ; blst::P1_Affine *arg3 = (blst::P1_Affine *) 0 ; byte *arg4 = (byte *) 0 ; size_t arg5 ; byte *arg6 = (byte *) 0 ; size_t arg7 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; BLST_ERROR result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_mul_n_aggregate" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_mul_n_aggregate" "', argument " "2"" of type '" "blst::P2_Affine const *""'"); } arg2 = reinterpret_cast< blst::P2_Affine * >(argp2); res3 = SWIG_ConvertPtr(args[1], &argp3,SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "Pairing_mul_n_aggregate" "', argument " "3"" of type '" "blst::P1_Affine const *""'"); } arg3 = reinterpret_cast< blst::P1_Affine * >(argp3); if (args[2]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[2]); auto buf = av->Buffer(); arg4 = (byte *)buf->GetData() + av->ByteOffset(); arg5 = 8*av->ByteLength(); #if V8_MAJOR_VERSION >=6 && V8_MINOR_VERSION >= 8 } else if (args[2]->IsBigInt()) { auto bi = v8::Local<v8::BigInt>::Cast(args[2]); int sign, word_count = bi->WordCount(); uint64_t* words = (uint64_t*)alloca(arg5 = word_count*sizeof(uint64_t)); bi->ToWordsArray(&sign, &word_count, words); if (sign) SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting unsigned value"); arg4 = (byte *)words; arg5 *= 8; const union { long one; char little; } is_endian = { 1 }; if (!is_endian.little) { byte* p = arg4; for (int i = 0; i < word_count; i++) { uint64_t val = words[i]; for (size_t j = 0; j < sizeof(val); j++, val >>= 8) *p++ = (byte)val; } } #endif } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <BigInt>"); } if (args[3]->IsArrayBufferView()) { auto av = v8::Local<v8::ArrayBufferView>::Cast(args[3]); auto buf = av->Buffer(); arg6 = (byte *)buf->GetData() + av->ByteOffset(); arg7 = av->ByteLength(); } else if (args[3]->IsString()) { auto str = SWIGV8_TO_STRING(args[3]); arg7 = SWIGV8_UTF8_LENGTH(str); arg6 = (byte *)alloca(arg7); SWIGV8_WRITE_UTF8(str, (char *)arg6, arg7); } else { SWIG_exception_fail(SWIG_TypeError, "in method 'Pairing_mul_n_aggregate', " "expecting <Buffer> or <String>"); } result = (BLST_ERROR)(arg1)->mul_n_aggregate((blst::P2_Affine const *)arg2,(blst::P1_Affine const *)arg3,(byte const *)arg4,arg5,(byte const *)arg6,arg7); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing__wrap_Pairing_mul_n_aggregate(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_mul_n_aggregate__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_mul_n_aggregate__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_mul_n_aggregate__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_mul_n_aggregate__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_mul_n_aggregate__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_mul_n_aggregate__SWIG_2(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_mul_n_aggregate__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_mul_n_aggregate__SWIG_3(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 5) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_mul_n_aggregate__SWIG_4(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_mul_n_aggregate__SWIG_4(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 4) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_mul_n_aggregate__SWIG_5(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_mul_n_aggregate__SWIG_5(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function mul_n_aggregate."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_commit(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; void *argp1 = 0 ; int res1 = 0 ; if(args.Length() != 0) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_Pairing_commit."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_commit" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); (arg1)->commit(); jsresult = SWIGV8_UNDEFINED(); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_merge(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::Pairing *arg2 = (blst::Pairing *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; BLST_ERROR result; if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_Pairing_merge."); res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_merge" "', argument " "1"" of type '" "blst::Pairing *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_merge" "', argument " "2"" of type '" "blst::Pairing const *""'"); } arg2 = reinterpret_cast< blst::Pairing * >(argp2); result = (BLST_ERROR)(arg1)->merge((blst::Pairing const *)arg2); jsresult = SWIG_From_int(static_cast< int >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_finalverify__SWIG_0(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; blst::PT *arg2 = (blst::PT *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; bool result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_finalverify" "', argument " "1"" of type '" "blst::Pairing const *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); res2 = SWIG_ConvertPtr(args[0], &argp2,SWIGTYPE_p_blst__PT, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Pairing_finalverify" "', argument " "2"" of type '" "blst::PT const *""'"); } arg2 = reinterpret_cast< blst::PT * >(argp2); result = (bool)((blst::Pairing const *)arg1)->finalverify((blst::PT const *)arg2); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing_finalverify__SWIG_1(const SwigV8Arguments &args, V8ErrorHandler &SWIGV8_ErrorHandler) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); blst::Pairing *arg1 = (blst::Pairing *) 0 ; void *argp1 = 0 ; int res1 = 0 ; bool result; res1 = SWIG_ConvertPtr(args.Holder(), &argp1,SWIGTYPE_p_blst__Pairing, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Pairing_finalverify" "', argument " "1"" of type '" "blst::Pairing const *""'"); } arg1 = reinterpret_cast< blst::Pairing * >(argp1); result = (bool)((blst::Pairing const *)arg1)->finalverify(); jsresult = SWIG_From_bool(static_cast< bool >(result)); SWIGV8_RETURN(jsresult); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } static SwigV8ReturnValue _wrap_Pairing__wrap_Pairing_finalverify(const SwigV8Arguments &args) { v8::Isolate* isolate = args.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = args.Data(); OverloadErrorHandler errorHandler; if(args.Length() == 1) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_finalverify__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_finalverify__SWIG_0(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } if(args.Length() == 0) { errorHandler.err.Clear(); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) jsresult = _wrap_Pairing_finalverify__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { SWIGV8_ESCAPE(jsresult); } #else _wrap_Pairing_finalverify__SWIG_1(args, errorHandler); if(errorHandler.err.IsEmpty()) { return; } #endif } SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function finalverify."); goto fail; fail: SWIGV8_RETURN(v8::Undefined(isolate)); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLS12_381_G1_get(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLS12_381_G1_get(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); blst::P1_Affine *result = 0 ; result = (blst::P1_Affine *)&BLS12_381_G1; jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLS12_381_NEG_G1_get(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLS12_381_NEG_G1_get(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); blst::P1_Affine *result = 0 ; result = (blst::P1_Affine *)&BLS12_381_NEG_G1; jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_blst__P1_Affine, 0 | 0 ); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLS12_381_G2_get(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLS12_381_G2_get(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); blst::P2_Affine *result = 0 ; result = (blst::P2_Affine *)&BLS12_381_G2; jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #if (V8_MAJOR_VERSION-0) < 5 static SwigV8ReturnValue _wrap_BLS12_381_NEG_G2_get(v8::Local<v8::String> property, const SwigV8PropertyCallbackInfo &info) { #else static SwigV8ReturnValue _wrap_BLS12_381_NEG_G2_get(v8::Local<v8::Name> property, const SwigV8PropertyCallbackInfo &info) { #endif v8::Isolate* isolate = info.GetIsolate(); SWIGV8_HANDLESCOPE(); SWIGV8_VALUE jsresult; SWIGV8_VALUE jsdata = info.Data(); blst::P2_Affine *result = 0 ; result = (blst::P2_Affine *)&BLS12_381_NEG_G2; jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_blst__P2_Affine, 0 | 0 ); SWIGV8_RETURN_INFO(jsresult, info); goto fail; fail: SWIGV8_RETURN_INFO(v8::Undefined(isolate), info); (void)jsdata; } #undef NODE_MODULE #define NODE_MODULE NODE_MODULE_CONTEXT_AWARE /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_BLST_ERROR = {"_p_BLST_ERROR", "enum BLST_ERROR *|BLST_ERROR *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__P1 = {"_p_blst__P1", "p_blst__P1|blst::P1 *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__P1_Affine = {"_p_blst__P1_Affine", "p_blst__P1_Affine|blst::P1_Affine *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__P2 = {"_p_blst__P2", "p_blst__P2|blst::P2 *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__P2_Affine = {"_p_blst__P2_Affine", "p_blst__P2_Affine|blst::P2_Affine *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__PT = {"_p_blst__PT", "p_blst__PT|blst::PT *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__Pairing = {"_p_blst__Pairing", "p_blst__Pairing|blst::Pairing *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_blst__SecretKey = {"_p_blst__SecretKey", "blst::SecretKey *|p_blst__SecretKey", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_byte = {"_p_byte", "byte *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_int = {"_p_int", "intptr_t *|int *|int_least32_t *|int_fast32_t *|int32_t *|int_fast16_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_short = {"_p_short", "short *|int_least16_t *|int16_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_signed_char = {"_p_signed_char", "signed char *|int_least8_t *|int_fast8_t *|int8_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_unsigned_char = {"_p_unsigned_char", "unsigned char *|uint_least8_t *|uint_fast8_t *|uint8_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uintptr_t *|uint_least32_t *|uint_fast32_t *|uint32_t *|unsigned int *|uint_fast16_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_unsigned_long_long = {"_p_unsigned_long_long", "uint_least64_t *|uint_fast64_t *|uint64_t *|unsigned long long *|uintmax_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info _swigt__p_unsigned_short = {"_p_unsigned_short", "unsigned short *|uint_least16_t *|uint16_t *", 0, 0, (SWIG_CLIENT_DATA_TYPE*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_BLST_ERROR, &_swigt__p_blst__P1, &_swigt__p_blst__P1_Affine, &_swigt__p_blst__P2, &_swigt__p_blst__P2_Affine, &_swigt__p_blst__PT, &_swigt__p_blst__Pairing, &_swigt__p_blst__SecretKey, &_swigt__p_byte, &_swigt__p_char, &_swigt__p_int, &_swigt__p_long_long, &_swigt__p_short, &_swigt__p_signed_char, &_swigt__p_unsigned_char, &_swigt__p_unsigned_int, &_swigt__p_unsigned_long_long, &_swigt__p_unsigned_short, }; static swig_cast_info _swigc__p_BLST_ERROR[] = { {&_swigt__p_BLST_ERROR, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__P1[] = { {&_swigt__p_blst__P1, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__P1_Affine[] = { {&_swigt__p_blst__P1_Affine, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__P2[] = { {&_swigt__p_blst__P2, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__P2_Affine[] = { {&_swigt__p_blst__P2_Affine, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__PT[] = { {&_swigt__p_blst__PT, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__Pairing[] = { {&_swigt__p_blst__Pairing, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_blst__SecretKey[] = { {&_swigt__p_blst__SecretKey, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_byte[] = { {&_swigt__p_byte, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_short[] = { {&_swigt__p_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_signed_char[] = { {&_swigt__p_signed_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_char[] = { {&_swigt__p_unsigned_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_long_long[] = { {&_swigt__p_unsigned_long_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_short[] = { {&_swigt__p_unsigned_short, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_BLST_ERROR, _swigc__p_blst__P1, _swigc__p_blst__P1_Affine, _swigc__p_blst__P2, _swigc__p_blst__P2_Affine, _swigc__p_blst__PT, _swigc__p_blst__Pairing, _swigc__p_blst__SecretKey, _swigc__p_byte, _swigc__p_char, _swigc__p_int, _swigc__p_long_long, _swigc__p_short, _swigc__p_signed_char, _swigc__p_unsigned_char, _swigc__p_unsigned_int, _swigc__p_unsigned_long_long, _swigc__p_unsigned_short, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ SWIGRUNTIME void SWIG_V8_SetModule(v8::Local<v8::Context> context, swig_module_info *swig_module) { v8::Isolate* isolate = SWIGV8_GETISOLATE(context); v8::Local<v8::Object> global_obj = context->Global(); v8::Local<v8::External> mod = SWIGV8_EXTERNAL_NEW(swig_module); assert(!mod.IsEmpty()); #if (V8_MAJOR_VERSION-0) < 5 global_obj->SetHiddenValue(SWIGV8_STRING_NEW("swig_module_info_data"), mod); #else v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, SWIGV8_STRING_NEW("swig_module_info_data")); global_obj->SetPrivate(context, privateKey, mod); #endif } SWIGRUNTIME swig_module_info * SWIG_V8_GetModule(v8::Local<v8::Context> context) { v8::Isolate* isolate = SWIGV8_GETISOLATE(context); v8::Local<v8::Object> global_obj = context->Global(); #if (V8_MAJOR_VERSION-0) < 5 v8::Local<v8::Value> moduleinfo = global_obj->GetHiddenValue(SWIGV8_STRING_NEW("swig_module_info_data")); #else v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, SWIGV8_STRING_NEW("swig_module_info_data")); v8::Local<v8::Value> moduleinfo; if (!global_obj->GetPrivate(context, privateKey).ToLocal(&moduleinfo)) return 0; #endif if (moduleinfo.IsEmpty() || moduleinfo->IsNull() || moduleinfo->IsUndefined()) { // It's not yet loaded return 0; } v8::Local<v8::External> moduleinfo_extern = v8::Local<v8::External>::Cast(moduleinfo); if (moduleinfo_extern.IsEmpty() || moduleinfo_extern->IsNull() || moduleinfo_extern->IsUndefined()) { // Something's not right return 0; } void *ptr = moduleinfo_extern->Value(); assert(ptr); swig_module_info *retptr = static_cast<swig_module_info *>(ptr); assert(retptr); return retptr; } #define SWIG_GetModule(clientdata) SWIG_V8_GetModule(clientdata) #define SWIG_SetModule(clientdata, pointer) SWIG_V8_SetModule(clientdata, pointer) #define SWIG_INIT_CLIENT_DATA_TYPE v8::Local<v8::Context> /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned statically to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif #ifndef SWIG_INIT_CLIENT_DATA_TYPE #define SWIG_INIT_CLIENT_DATA_TYPE void * #endif SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { size_t i; swig_module_info *module_head, *iter; int init; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ iter=module_head; do { if (iter==&swig_module) { /* Our module is already in the list, so there's nothing more to do. */ return; } iter=iter->next; } while (iter!= module_head); /* otherwise we must add our module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpreters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) #include <mutex> #endif #if !defined(NODE_MODULE_VERSION) || (NODE_MODULE_VERSION < 12) // Note: 'extern "C"'' disables name mangling which makes it easier to load the symbol manually extern "C" void SWIGV8_INIT (SWIGV8_OBJECT exports_obj) #elif (NODE_MODULE_VERSION < 64) void SWIGV8_INIT (SWIGV8_OBJECT exports_obj, SWIGV8_VALUE /*module*/, void*) #else void SWIGV8_INIT (SWIGV8_OBJECT exports_obj, SWIGV8_VALUE /*module*/, v8::Local<v8::Context> context, void*) #endif { #if !defined(NODE_MODULE_VERSION) || NODE_MODULE_VERSION < 64 v8::Local<v8::Context> context = SWIGV8_CURRENT_CONTEXT(); #endif v8::Isolate* isolate = SWIGV8_GETISOLATE(context); SWIGV8_HANDLESCOPE(); #if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) static std::mutex guard; const std::lock_guard<std::mutex> lock(guard); #endif SWIG_InitializeModule(context); #if (V8_MAJOR_VERSION-0) < 5 // Multiple threads are not supported, everything is saved in globals. v8::Persistent<v8::FunctionTemplate>* v8_swig_types = NULL; v8::Local<v8::Value> v8_swig_types_as_data; #else // Formally speaking SWIGV8_INIT has // // - things to do just once, initialize global variables; // - things to do in each |isolate|, create Persistent<Template>-s; // - things to do in each |context|, instantiate |export_obj|; // // However, if you examine the generated code below, you'll notice that all // the things-to-do are executed always on each invocation. As for globals, // the arrangement in the V8_MAJOR_VERSION>=5 case is such that the // assignments are constant and hence can be executed multiple times // without side effects. And as for templates, it's reckoned that cases // when multiple contexts get created per isolate are rare, and occasional // template duplicates are tolerable. Just in case for reference, each // Node.js Worker thread is executed in own |isolate|, which is the most // common case when SWIGV8_INIT would be called multiple times. // Per-context array that holds Persistent<Template>-s size_t sz = sizeof(v8::Persistent<v8::FunctionTemplate>) * (sizeof(swig_types)/sizeof(swig_types[0]) + 1); v8::Local<v8::ArrayBuffer> v8_swig_types_as_data = v8::ArrayBuffer::New(isolate, sz); v8::Persistent<v8::FunctionTemplate>* v8_swig_types = #if (V8_MAJOR_VERSION-0) >= 8 static_cast<v8::Persistent<v8::FunctionTemplate>*>(v8_swig_types_as_data->GetBackingStore()->Data()); #else static_cast<v8::Persistent<v8::FunctionTemplate>*>(v8_swig_types_as_data->GetContents().Data()); #endif // Anchor the array, so that it won't be garbage-collected v8::Local<v8::Private> priv = v8::Private::ForApi(isolate, SWIGV8_SYMBOL_NEW("__swig_types__" SWIGV8_JSNAME)); exports_obj->SetPrivate(context, priv, v8_swig_types_as_data); #endif // a class template for creating proxies of undefined types SWIGV8_SWIGTYPE_Proxy.SetType(SWIGV8_CreateClassTemplate("SwigProxy", isolate, v8_swig_types_as_data), isolate, v8_swig_types); /* create objects for namespaces */ /* create class templates */ /* Name: _exports_SecretKey, Type: p_blst__SecretKey, Dtor: _wrap_delete_SecretKey */ SWIGV8_FUNCTION_TEMPLATE _exports_SecretKey_class = SWIGV8_CreateClassTemplate("_exports_SecretKey", isolate, v8_swig_types_as_data); _exports_SecretKey_clientData.index = &SWIGTYPE_p_blst__SecretKey - &swig_types[0]; _exports_SecretKey_clientData.dtor = _wrap_delete_SecretKey; _exports_SecretKey_clientData.SetType(_exports_SecretKey_class, isolate, v8_swig_types); SWIGTYPE_p_blst__SecretKey->clientdata = &_exports_SecretKey_clientData; /* Name: _exports_P1_Affine, Type: p_blst__P1_Affine, Dtor: _wrap_delete_P1_Affine */ SWIGV8_FUNCTION_TEMPLATE _exports_P1_Affine_class = SWIGV8_CreateClassTemplate("_exports_P1_Affine", isolate, v8_swig_types_as_data); _exports_P1_Affine_clientData.index = &SWIGTYPE_p_blst__P1_Affine - &swig_types[0]; _exports_P1_Affine_clientData.dtor = _wrap_delete_P1_Affine; _exports_P1_Affine_clientData.SetType(_exports_P1_Affine_class, isolate, v8_swig_types); SWIGTYPE_p_blst__P1_Affine->clientdata = &_exports_P1_Affine_clientData; /* Name: _exports_P1, Type: p_blst__P1, Dtor: _wrap_delete_P1 */ SWIGV8_FUNCTION_TEMPLATE _exports_P1_class = SWIGV8_CreateClassTemplate("_exports_P1", isolate, v8_swig_types_as_data); _exports_P1_clientData.index = &SWIGTYPE_p_blst__P1 - &swig_types[0]; _exports_P1_clientData.dtor = _wrap_delete_P1; _exports_P1_clientData.SetType(_exports_P1_class, isolate, v8_swig_types); SWIGTYPE_p_blst__P1->clientdata = &_exports_P1_clientData; /* Name: _exports_P2_Affine, Type: p_blst__P2_Affine, Dtor: _wrap_delete_P2_Affine */ SWIGV8_FUNCTION_TEMPLATE _exports_P2_Affine_class = SWIGV8_CreateClassTemplate("_exports_P2_Affine", isolate, v8_swig_types_as_data); _exports_P2_Affine_clientData.index = &SWIGTYPE_p_blst__P2_Affine - &swig_types[0]; _exports_P2_Affine_clientData.dtor = _wrap_delete_P2_Affine; _exports_P2_Affine_clientData.SetType(_exports_P2_Affine_class, isolate, v8_swig_types); SWIGTYPE_p_blst__P2_Affine->clientdata = &_exports_P2_Affine_clientData; /* Name: _exports_P2, Type: p_blst__P2, Dtor: _wrap_delete_P2 */ SWIGV8_FUNCTION_TEMPLATE _exports_P2_class = SWIGV8_CreateClassTemplate("_exports_P2", isolate, v8_swig_types_as_data); _exports_P2_clientData.index = &SWIGTYPE_p_blst__P2 - &swig_types[0]; _exports_P2_clientData.dtor = _wrap_delete_P2; _exports_P2_clientData.SetType(_exports_P2_class, isolate, v8_swig_types); SWIGTYPE_p_blst__P2->clientdata = &_exports_P2_clientData; /* Name: _exports_PT, Type: p_blst__PT, Dtor: _wrap_delete_PT */ SWIGV8_FUNCTION_TEMPLATE _exports_PT_class = SWIGV8_CreateClassTemplate("_exports_PT", isolate, v8_swig_types_as_data); _exports_PT_clientData.index = &SWIGTYPE_p_blst__PT - &swig_types[0]; _exports_PT_clientData.dtor = _wrap_delete_PT; _exports_PT_clientData.SetType(_exports_PT_class, isolate, v8_swig_types); SWIGTYPE_p_blst__PT->clientdata = &_exports_PT_clientData; /* Name: _exports_Pairing, Type: p_blst__Pairing, Dtor: _wrap_delete_Pairing */ SWIGV8_FUNCTION_TEMPLATE _exports_Pairing_class = SWIGV8_CreateClassTemplate("_exports_Pairing", isolate, v8_swig_types_as_data); _exports_Pairing_clientData.index = &SWIGTYPE_p_blst__Pairing - &swig_types[0]; _exports_Pairing_clientData.dtor = _wrap_delete_Pairing; _exports_Pairing_clientData.SetType(_exports_Pairing_class, isolate, v8_swig_types); SWIGTYPE_p_blst__Pairing->clientdata = &_exports_Pairing_clientData; /* register wrapper functions */ SWIGV8_AddStaticVariable(exports_obj, "BLST_SUCCESS", _wrap_BLST_SUCCESS, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLST_BAD_ENCODING", _wrap_BLST_BAD_ENCODING, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLST_POINT_NOT_ON_CURVE", _wrap_BLST_POINT_NOT_ON_CURVE, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLST_POINT_NOT_IN_GROUP", _wrap_BLST_POINT_NOT_IN_GROUP, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLST_AGGR_TYPE_MISMATCH", _wrap_BLST_AGGR_TYPE_MISMATCH, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLST_VERIFY_FAIL", _wrap_BLST_VERIFY_FAIL, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLST_PK_IS_INFINITY", _wrap_BLST_PK_IS_INFINITY, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_SecretKey_class, "keygen", _wrap_SecretKey__wrap_SecretKey_keygen, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_SecretKey_class, "from_bendian", _wrap_SecretKey_from_bendian, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_SecretKey_class, "from_lendian", _wrap_SecretKey_from_lendian, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_SecretKey_class, "to_bendian", _wrap_SecretKey_to_bendian, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_SecretKey_class, "to_lendian", _wrap_SecretKey_to_lendian, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "dup", _wrap_P1_Affine_dup, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "to_jacobian", _wrap_P1_Affine_to_jacobian, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "serialize", _wrap_P1_Affine_serialize, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "compress", _wrap_P1_Affine_compress, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "on_curve", _wrap_P1_Affine_on_curve, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "in_group", _wrap_P1_Affine_in_group, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "is_inf", _wrap_P1_Affine_is_inf, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "is_equal", _wrap_P1_Affine_is_equal, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_Affine_class, "core_verify", _wrap_P1_Affine__wrap_P1_Affine_core_verify, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "dup", _wrap_P1_dup, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "to_affine", _wrap_P1_to_affine, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "serialize", _wrap_P1_serialize, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "compress", _wrap_P1_compress, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "on_curve", _wrap_P1_on_curve, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "in_group", _wrap_P1_in_group, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "is_inf", _wrap_P1_is_inf, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "is_equal", _wrap_P1_is_equal, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "aggregate", _wrap_P1_aggregate, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "sign_with", _wrap_P1_sign_with, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "hash_to", _wrap_P1__wrap_P1_hash_to, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "encode_to", _wrap_P1__wrap_P1_encode_to, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "mult", _wrap_P1_mult, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "cneg", _wrap_P1_cneg, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "neg", _wrap_P1_neg, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "add", _wrap_P1__wrap_P1_add, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P1_class, "dbl", _wrap_P1_dbl, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "dup", _wrap_P2_Affine_dup, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "to_jacobian", _wrap_P2_Affine_to_jacobian, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "serialize", _wrap_P2_Affine_serialize, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "compress", _wrap_P2_Affine_compress, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "on_curve", _wrap_P2_Affine_on_curve, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "in_group", _wrap_P2_Affine_in_group, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "is_inf", _wrap_P2_Affine_is_inf, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "is_equal", _wrap_P2_Affine_is_equal, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_Affine_class, "core_verify", _wrap_P2_Affine__wrap_P2_Affine_core_verify, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "dup", _wrap_P2_dup, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "to_affine", _wrap_P2_to_affine, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "serialize", _wrap_P2_serialize, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "compress", _wrap_P2_compress, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "on_curve", _wrap_P2_on_curve, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "in_group", _wrap_P2_in_group, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "is_inf", _wrap_P2_is_inf, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "is_equal", _wrap_P2_is_equal, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "aggregate", _wrap_P2_aggregate, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "sign_with", _wrap_P2_sign_with, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "hash_to", _wrap_P2__wrap_P2_hash_to, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "encode_to", _wrap_P2__wrap_P2_encode_to, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "mult", _wrap_P2_mult, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "cneg", _wrap_P2_cneg, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "neg", _wrap_P2_neg, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "add", _wrap_P2__wrap_P2_add, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_P2_class, "dbl", _wrap_P2_dbl, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_PT_class, "dup", _wrap_PT_dup, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_PT_class, "is_one", _wrap_PT_is_one, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_PT_class, "is_equal", _wrap_PT_is_equal, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_PT_class, "sqr", _wrap_PT_sqr, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_PT_class, "mul", _wrap_PT_mul, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_PT_class, "final_exp", _wrap_PT_final_exp, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_Pairing_class, "aggregate", _wrap_Pairing__wrap_Pairing_aggregate, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_Pairing_class, "mul_n_aggregate", _wrap_Pairing__wrap_Pairing_mul_n_aggregate, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_Pairing_class, "commit", _wrap_Pairing_commit, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_Pairing_class, "merge", _wrap_Pairing_merge, isolate, v8_swig_types_as_data); SWIGV8_AddMemberFunction(_exports_Pairing_class, "finalverify", _wrap_Pairing__wrap_Pairing_finalverify, isolate, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLS12_381_G1", _wrap_BLS12_381_G1_get, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLS12_381_NEG_G1", _wrap_BLS12_381_NEG_G1_get, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLS12_381_G2", _wrap_BLS12_381_G2_get, JS_veto_set_variable, context, v8_swig_types_as_data); SWIGV8_AddStaticVariable(exports_obj, "BLS12_381_NEG_G2", _wrap_BLS12_381_NEG_G2_get, JS_veto_set_variable, context, v8_swig_types_as_data); /* setup inheritances */ /* class instances */ /* Class: SecretKey (_exports_SecretKey) */ SWIGV8_FUNCTION_TEMPLATE _exports_SecretKey_class_0 = SWIGV8_CreateClassTemplate("SecretKey", isolate, v8_swig_types_as_data); _exports_SecretKey_class_0->SetCallHandler(_wrap_new_SecretKey, v8_swig_types_as_data); _exports_SecretKey_class_0->Inherit(_exports_SecretKey_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_SecretKey_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_SecretKey_obj = _exports_SecretKey_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_SecretKey_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_SecretKey_obj = _exports_SecretKey_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_SecretKey_obj = _exports_SecretKey_class_0->GetFunction(context).ToLocalChecked(); #endif /* Class: P1_Affine (_exports_P1_Affine) */ SWIGV8_FUNCTION_TEMPLATE _exports_P1_Affine_class_0 = SWIGV8_CreateClassTemplate("P1_Affine", isolate, v8_swig_types_as_data); _exports_P1_Affine_class_0->SetCallHandler(_wrap_new_P1_Affine, v8_swig_types_as_data); _exports_P1_Affine_class_0->Inherit(_exports_P1_Affine_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_P1_Affine_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_P1_Affine_obj = _exports_P1_Affine_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_P1_Affine_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_P1_Affine_obj = _exports_P1_Affine_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_P1_Affine_obj = _exports_P1_Affine_class_0->GetFunction(context).ToLocalChecked(); #endif /* Class: P1 (_exports_P1) */ SWIGV8_FUNCTION_TEMPLATE _exports_P1_class_0 = SWIGV8_CreateClassTemplate("P1", isolate, v8_swig_types_as_data); _exports_P1_class_0->SetCallHandler(_wrap_new_P1, v8_swig_types_as_data); _exports_P1_class_0->Inherit(_exports_P1_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_P1_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_P1_obj = _exports_P1_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_P1_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_P1_obj = _exports_P1_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_P1_obj = _exports_P1_class_0->GetFunction(context).ToLocalChecked(); #endif /* Class: P2_Affine (_exports_P2_Affine) */ SWIGV8_FUNCTION_TEMPLATE _exports_P2_Affine_class_0 = SWIGV8_CreateClassTemplate("P2_Affine", isolate, v8_swig_types_as_data); _exports_P2_Affine_class_0->SetCallHandler(_wrap_new_P2_Affine, v8_swig_types_as_data); _exports_P2_Affine_class_0->Inherit(_exports_P2_Affine_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_P2_Affine_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_P2_Affine_obj = _exports_P2_Affine_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_P2_Affine_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_P2_Affine_obj = _exports_P2_Affine_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_P2_Affine_obj = _exports_P2_Affine_class_0->GetFunction(context).ToLocalChecked(); #endif /* Class: P2 (_exports_P2) */ SWIGV8_FUNCTION_TEMPLATE _exports_P2_class_0 = SWIGV8_CreateClassTemplate("P2", isolate, v8_swig_types_as_data); _exports_P2_class_0->SetCallHandler(_wrap_new_P2, v8_swig_types_as_data); _exports_P2_class_0->Inherit(_exports_P2_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_P2_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_P2_obj = _exports_P2_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_P2_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_P2_obj = _exports_P2_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_P2_obj = _exports_P2_class_0->GetFunction(context).ToLocalChecked(); #endif /* Class: PT (_exports_PT) */ SWIGV8_FUNCTION_TEMPLATE _exports_PT_class_0 = SWIGV8_CreateClassTemplate("PT", isolate, v8_swig_types_as_data); _exports_PT_class_0->SetCallHandler(_wrap_new_PT, v8_swig_types_as_data); _exports_PT_class_0->Inherit(_exports_PT_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_PT_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_PT_obj = _exports_PT_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_PT_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_PT_obj = _exports_PT_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_PT_obj = _exports_PT_class_0->GetFunction(context).ToLocalChecked(); #endif /* Class: Pairing (_exports_Pairing) */ SWIGV8_FUNCTION_TEMPLATE _exports_Pairing_class_0 = SWIGV8_CreateClassTemplate("Pairing", isolate, v8_swig_types_as_data); _exports_Pairing_class_0->SetCallHandler(_wrap_new_Pairing, v8_swig_types_as_data); _exports_Pairing_class_0->Inherit(_exports_Pairing_class); #if (V8_MAJOR_VERSION-0) < 4 && (SWIG_V8_VERSION < 0x031903) _exports_Pairing_class_0->SetHiddenPrototype(true); v8::Handle<v8::Object> _exports_Pairing_obj = _exports_Pairing_class_0->GetFunction(); #elif (SWIG_V8_VERSION < 0x0704) _exports_Pairing_class_0->SetHiddenPrototype(true); v8::Local<v8::Object> _exports_Pairing_obj = _exports_Pairing_class_0->GetFunction(); #else v8::Local<v8::Object> _exports_Pairing_obj = _exports_Pairing_class_0->GetFunction(context).ToLocalChecked(); #endif /* add static class functions and variables */ SWIGV8_AddStaticFunction(_exports_P1_Affine_obj, "generator", _wrap_P1_Affine_generator, context, v8_swig_types_as_data); SWIGV8_AddStaticFunction(_exports_P1_obj, "generator", _wrap_P1_generator, context, v8_swig_types_as_data); SWIGV8_AddStaticFunction(_exports_P2_Affine_obj, "generator", _wrap_P2_Affine_generator, context, v8_swig_types_as_data); SWIGV8_AddStaticFunction(_exports_P2_obj, "generator", _wrap_P2_generator, context, v8_swig_types_as_data); SWIGV8_AddStaticFunction(exports_obj, "G1", _wrap_G1, context, v8_swig_types_as_data); SWIGV8_AddStaticFunction(exports_obj, "G2", _wrap_G2, context, v8_swig_types_as_data); /* register classes */ #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("SecretKey"), _exports_SecretKey_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("SecretKey"), _exports_SecretKey_obj)); #endif #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("P1_Affine"), _exports_P1_Affine_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("P1_Affine"), _exports_P1_Affine_obj)); #endif #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("P1"), _exports_P1_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("P1"), _exports_P1_obj)); #endif #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("P2_Affine"), _exports_P2_Affine_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("P2_Affine"), _exports_P2_Affine_obj)); #endif #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("P2"), _exports_P2_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("P2"), _exports_P2_obj)); #endif #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("PT"), _exports_PT_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("PT"), _exports_PT_obj)); #endif #if (V8_MAJOR_VERSION-0) < 5 exports_obj->Set(SWIGV8_SYMBOL_NEW("Pairing"), _exports_Pairing_obj); #else SWIGV8_MAYBE_CHECK(exports_obj->Set(context, SWIGV8_SYMBOL_NEW("Pairing"), _exports_Pairing_obj)); #endif /* create and register namespace objects */ } #if defined(BUILDING_NODE_EXTENSION) #if (NODE_MODULE_VERSION < 64) NODE_MODULE(blst, blst_initialize) #else #ifndef NODE_GYP_MODULE_NAME # define NODE_GYP_MODULE_NAME blst #endif #if defined(__GNUC__) && __GNUC__>=8 // NODE_MODULE_INIT is not self-consistent in all supported Node.js versions :-( # pragma GCC diagnostic ignored "-Wcast-function-type" #endif NODE_MODULE_INIT() { blst_initialize(exports, module, context, NULL); } #endif #endif
33.110642
195
0.676857
[ "object" ]
97acba937eea3ec1c0a15d509a3c4b964540097f
5,338
cpp
C++
CookieEngine/src/UI/Widgets/EditorWs/WorldSettingsWidget.cpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/src/UI/Widgets/EditorWs/WorldSettingsWidget.cpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/src/UI/Widgets/EditorWs/WorldSettingsWidget.cpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#include "Scene.hpp" #include "ResourcesManager.hpp" #include "Light.hpp" #include "AIBehavior.hpp" #include "Drawers/Skybox.hpp" #include "WorldSettingsWidget.hpp" #include "MapExplorerHelper.hpp" #include <imgui.h> #include <ImGuizmo.h> using namespace ImGui; using namespace Cookie::UIwidget; using namespace Cookie::Resources; using namespace Cookie::Gameplay; void WorldSettingsWidget::WindowDisplay() { TryBeginWindow() { if (TreeNode("Map settings")) { // Scale { Cookie::Core::Math::Vec3& mapScale = scene->map.trs.scale; static float xzMapScale[2] = {mapScale.x, mapScale.z}; Text("X/Z Scale:"); SameLine(); if (DragFloat2("##SCALE", xzMapScale, 0.25)) { if (xzMapScale[0] > 0 && xzMapScale[1] > 0) { mapScale = { xzMapScale[0], mapScale.y, xzMapScale[1] }; scene->map.ScaleHasChanged(); } } if (xzMapScale[0] <= 0.01 || xzMapScale[1] <= 0.01) { PushStyleColor(ImGuiCol_Text, {1, 0, 0, 1}); TextWrapped("Please refrain from inputing very low/negative values."); PopStyleColor(); } } // Tiles { Cookie::Core::Math::Vec2& mapTilesNb = scene->map.tilesNb; static float xzMapTilesNb[2] = {mapTilesNb.e[0], mapTilesNb.e[1]}; Text("Tiles in X/Z:"); SameLine(); if (DragFloat2("##TILES", xzMapTilesNb, 1.f, NULL, NULL, "%.0f")) { if (xzMapTilesNb[0] > 1 && xzMapTilesNb[1] > 1) { mapTilesNb = {{ xzMapTilesNb[0], xzMapTilesNb[1] }}; scene->map.TileNbHasChanged(); } } if (xzMapTilesNb[0] <= 1 || xzMapTilesNb[1] <= 1) { PushStyleColor(ImGuiCol_Text, { 1, 0, 0, 1 }); TextWrapped("Please refrain from inputing very low/negative values."); PopStyleColor(); } } // Model { Text("Map albedo:"); SameLine(110); ResourceMapExplorer<Texture>("texture", std::move("##MAPTEXTSELECT"), resources.textures2D, scene->map.model.albedo); Text("Map normal:"); SameLine(110); ResourceMapExplorer<Texture>("normal texture", std::move("##MAPNORMSELECT"), resources.textures2D, scene->map.model.normal); ImGui::Custom::TextSnip("Map metallic-Roughness", 9); SameLine(); Text(":"); SameLine(110); ResourceMapExplorer<Texture>("metallic-rough texture", std::move("##MAPMRSELECT"), resources.textures2D, scene->map.model.metallicRoughness); } TreePop(); } if (TreeNode("Lights setting")) { if (TreeNode("World dir light")) { static Render::DirLight& dirLight = lights.dirLight; Text("Direction:"); DragFloat3("##DIRLIGHTROT", dirLight.dir.e); NewLine(); Text("Casts shadows:"); SameLine(); Checkbox("##DIRSHADOWS", &dirLight.castShadow); NewLine(); Text("Coloration:"); ColorEdit3("##DIRCOLOR", dirLight.color.e, ImGuiColorEditFlags_Float | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_PickerHueWheel); TreePop(); } if (TreeNode("Other lights")) { SliderInt("##POINTLIGHTNB", (int*)&lights.usedPoints, 0, POINT_LIGHT_MAX_NB, "Nb of Light: %d", ImGuiSliderFlags_AlwaysClamp); static int lightIndex = 1; static Render::PointLight* selectedPtLight = &lights.pointLights[0]; if (lights.usedPoints > 0) { if (SliderInt("##POINTLIGHTSELECT", &lightIndex, 1, lights.usedPoints, "Editing light N%d", ImGuiSliderFlags_AlwaysClamp)) { selectedPtLight = &lights.pointLights[lightIndex - 1]; } NewLine(); Text("Position:"); DragFloat3("##POINTPOS", selectedPtLight->pos.e, 0.25f, NULL, NULL, "%.2f"); NewLine(); Text("Light radius:"); DragFloat("##POINTRADIUS", &selectedPtLight->radius, 0.5f, NULL, NULL, "%.1f"); NewLine(); Text("Coloration:"); ColorEdit3("##POINTCOLOR", selectedPtLight->color.e, ImGuiColorEditFlags_Float | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_PickerHueWheel); } TreePop(); } TreePop(); } if (TreeNode("Skybox settings")) { Text("Skybox texture:"); ResourceMapExplorer<Texture>("cubic texture", std::move("##SKYBOXSELECT"), resources.skyboxes, skybox.texture); TreePop(); } if (TreeNode("AI settings")) { static const char* armyNames[] = { "Default", "Player", "AI1" }; for (int i = 0; i < scene->armyHandler.livingArmies; ++i) { Gameplay::E_ARMY_NAME currentArmyName = scene->armyHandler.armies[i].name; Text("%s", armyNames[currentArmyName]); //if an AI army if (currentArmyName > Gameplay::E_ARMY_NAME::E_PLAYER) { //if there is already a coordinator ArmyCoordinator* currentArmyCoordinator = scene->armyHandler.GetArmyCoordinator(currentArmyName); if (currentArmyCoordinator) { SameLine(); if (SmallButton("Remove##REMOVE_COORDINATOR")) scene->armyHandler.RemoveArmyCoordinator(currentArmyName); ResourceMapExplorer<AIBehavior>("AIBehavior", std::move("##AIBEHAVIOR"), resources.aiBehaviors, currentArmyCoordinator->behavior); } else { SameLine(); if (SmallButton("Add##ADD_COORDINATOR")) scene->armyHandler.AddArmyCoordinator(currentArmyName, nullptr); } } else { SameLine(); Text(" Can't add an AI"); } NewLine(); } TreePop(); } } ImGui::End(); }
26.295567
186
0.646497
[ "render", "model" ]
97add8e419169dc15325dd506656162cb6e5a005
7,048
cpp
C++
src/SockAddr.cpp
FTPlus/AGSsock
2a1ce84b420b4c119154c9504f3b6f01c6fad34b
[ "Zlib" ]
2
2020-11-19T13:57:25.000Z
2021-03-01T13:15:21.000Z
src/SockAddr.cpp
ericoporto/AGSsock
832ecb76e9fd6a33f0a9a233e29066a0847eab7d
[ "Zlib" ]
1
2021-01-04T23:39:23.000Z
2021-01-17T01:08:55.000Z
src/SockAddr.cpp
FTPlus/AGSsock
2a1ce84b420b4c119154c9504f3b6f01c6fad34b
[ "Zlib" ]
1
2020-11-19T13:58:14.000Z
2020-11-19T13:58:14.000Z
/********************************************************************* * Socket address interface -- See header file for more information. * *********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include "SockAddr.h" namespace AGSSock { //------------------------------------------------------------------------------ void decode_type(ags_t &type) { if (type == -1) type = AF_INET; else if (type == -2) type = AF_INET6; } //------------------------------------------------------------------------------ int AGSSockAddr::Dispose(const char *addr, bool force) { delete (SockAddr *) addr; return 1; } //------------------------------------------------------------------------------ int AGSSockAddr::Serialize(const char *addr, char *buffer, int size) { size = MIN(size, sizeof (SockAddr)); memcpy(buffer, addr, size); return size; } //------------------------------------------------------------------------------ void AGSSockAddr::Unserialize(int key, const char *buffer, int size) { size = MIN(size, sizeof (SockAddr)); SockAddr *addr = new SockAddr; // Default-initialized by design memcpy(addr, buffer, size); AGS_RESTORE(SockAddr, addr, key); } //============================================================================== SockAddr *SockAddr_Create(ags_t type) { decode_type(type); SockAddr *addr = new SockAddr; // by design AGS_OBJECT(SockAddr, addr); memset(addr, 0, sizeof (SockAddr)); ADDR_INIT(addr, type); // update definition when new address types are added addr->ss_family = type; return addr; } //------------------------------------------------------------------------------ SockAddr *SockAddr_CreateFromString(const char *str, ags_t type) { decode_type(type); SockAddr *addr = SockAddr_Create(type); SockAddr_set_Address(addr, str); return addr; } //------------------------------------------------------------------------------ SockAddr *SockAddr_CreateFromData(const SockData *data) { SockAddr *addr = new SockAddr; // by design AGS_OBJECT(SockAddr, addr); memcpy(addr, data->data.data(), MIN(data->data.size(), sizeof (SockAddr))); return addr; } //------------------------------------------------------------------------------ SockAddr *SockAddr_CreateIP(const char *ip, ags_t port) { SockAddr *addr = SockAddr_Create(AF_INET); SockAddr_set_IP(addr, ip); SockAddr_set_Port(addr, port); return addr; } //------------------------------------------------------------------------------ SockAddr *SockAddr_CreateIPv6(const char *ip, ags_t port) { SockAddr *addr = SockAddr_Create(AF_INET6); SockAddr_set_IP(addr, ip); SockAddr_set_Port(addr, port); return addr; } //------------------------------------------------------------------------------ ags_t SockAddr_get_Port(SockAddr *sa) { if (sa->ss_family == AF_INET) { sockaddr_in *addr = reinterpret_cast<sockaddr_in *> (sa); return ntohs(addr->sin_port); } else if (sa->ss_family == AF_INET6) { sockaddr_in6 *addr = reinterpret_cast<sockaddr_in6 *> (sa); return ntohs(addr->sin6_port); } else return 0; } //------------------------------------------------------------------------------ void SockAddr_set_Port(SockAddr *sa, ags_t port) { if (sa->ss_family == AF_INET) { sockaddr_in *addr = reinterpret_cast<sockaddr_in *> (sa); addr->sin_port = htons(port); } else if (sa->ss_family == AF_INET6) { sockaddr_in6 *addr = reinterpret_cast<sockaddr_in6 *> (sa); addr->sin6_port = htons(port); } } //------------------------------------------------------------------------------ const char *SockAddr_get_Address(SockAddr *sa) { std::string addr; char host[NI_MAXHOST]; char serv[NI_MAXSERV]; if (getnameinfo(ADDR(sa), ADDR_SIZE(sa), host, sizeof (host), serv, sizeof (serv), 0)) { // It failed: let's try without service names if (getnameinfo(ADDR(sa), ADDR_SIZE(sa), host, sizeof (host), NULL, 0, 0)) { // Handle error: // we'll just return an empty string, that will be comforting enough } else { sprintf(serv, "%d", SockAddr_get_Port(sa)); addr = (std::string(host) + ":") + serv; } } else { if (!serv[0] || (serv[0] == '0' && !serv[1])) addr = host; else if (atof(serv) == 0.0) // A bit wonky but does the trick addr = (std::string(serv) + "://") + host; else addr = (std::string(host) + ":") + serv; } return AGS_STRING(addr.c_str()); } //------------------------------------------------------------------------------ void SockAddr_set_Address(SockAddr *sa, const char *addr) { std::string node = addr, service; size_t index; if ((index = node.find("://")) != std::string::npos) { service = node.substr(0, index); node = node.substr(index + 3); } if ((sa->ss_family != AF_INET6) && ((index = node.rfind(':')) != std::string::npos)) { service = node.substr(index + 1); node.resize(index); } addrinfo hint, *result = nullptr; memset(&hint, 0, sizeof (addrinfo)); hint.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED | (node.empty() ? AI_PASSIVE : 0); hint.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC; if (getaddrinfo(node.c_str(), service.c_str(), &hint, &result) || !result) { // Handle error: // We'll simply do nothing when address resolving failed; // Users will figure out that the address object is empty, // so the address string supplied is most likely invalid. return; } memcpy(sa, result->ai_addr, result->ai_addrlen); freeaddrinfo(result); } //------------------------------------------------------------------------------ const char *SockAddr_get_IP(SockAddr *sa) { if (sa->ss_family == AF_INET) { char buffer[INET_ADDRSTRLEN] = ""; sockaddr_in *addr = reinterpret_cast<sockaddr_in *> (sa); inet_ntop(sa->ss_family, &addr->sin_addr, buffer, sizeof (buffer)); return AGS_STRING(buffer); } else if (sa->ss_family == AF_INET6) { char buffer[INET6_ADDRSTRLEN] = ""; sockaddr_in6 *addr = reinterpret_cast<sockaddr_in6 *> (sa); inet_ntop(sa->ss_family, &addr->sin6_addr, buffer, sizeof (buffer)); return AGS_STRING(buffer); } return nullptr; } //------------------------------------------------------------------------------ void SockAddr_set_IP(SockAddr *sa, const char *ip) { if (sa->ss_family == AF_INET) { sockaddr_in *addr = reinterpret_cast<sockaddr_in *> (sa); inet_pton(sa->ss_family, ip, &addr->sin_addr); } else if (sa->ss_family == AF_INET6) { sockaddr_in6 *addr = reinterpret_cast<sockaddr_in6 *> (sa); inet_pton(sa->ss_family, ip, &addr->sin6_addr); } } //------------------------------------------------------------------------------ SockData *SockAddr_GetData(SockAddr *sa) { SockData *data = new SockData(); AGS_OBJECT(SockData, data); data->data = std::string(reinterpret_cast<char *> (sa), ADDR_SIZE(sa)); return data; } //------------------------------------------------------------------------------ } /* namespace AGSSock */ //..............................................................................
26.496241
80
0.524404
[ "object" ]
97b1724de8b366ade2a9fcb3711964f08d731f77
69,241
cpp
C++
Development/Src/Editor/Src/UnEdSrv.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/Src/Editor/Src/UnEdSrv.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/Src/Editor/Src/UnEdSrv.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
/*============================================================================= UnEdSrv.cpp: UEditorEngine implementation, the Unreal editing server Copyright 1997-1999 Epic Games, Inc. All Rights Reserved. Revision history: * Created by Tim Sweeney =============================================================================*/ #include "EditorPrivate.h" #include "UnPath.h" #include "EnginePhysicsClasses.h" extern FRebuildTools GRebuildTools; /*----------------------------------------------------------------------------- UnrealEd safe command line. -----------------------------------------------------------------------------*/ void UEditorEngine::RedrawAllViewports( UBOOL bLevelViewportsOnly ) { for(UINT ViewportIndex = 0;ViewportIndex < (UINT)ViewportClients.Num();ViewportIndex++) { if(!bLevelViewportsOnly || ViewportClients(ViewportIndex)->GetLevel() == Level) ViewportClients(ViewportIndex)->Viewport->Invalidate(); } } // // Execute a macro. // void UEditorEngine::ExecMacro( const TCHAR* Filename, FOutputDevice& Ar ) { // Create text buffer and prevent garbage collection. UTextBuffer* Text = ImportObject<UTextBuffer>( GEditor->Level, GetTransientPackage(), NAME_None, 0, Filename ); if( Text ) { Text->AddToRoot(); debugf( TEXT("Execing %s"), Filename ); TCHAR Temp[MAX_EDCMD]; const TCHAR* Data = *Text->Text; while( ParseLine( &Data, Temp, ARRAY_COUNT(Temp) ) ) Exec( Temp, Ar ); Text->RemoveFromRoot(); delete Text; } else Ar.Logf( NAME_ExecWarning, *LocalizeError("FileNotFound",TEXT("Editor")), Filename ); } // // Execute a command that is safe for rebuilds. // UBOOL UEditorEngine::SafeExec( const TCHAR* InStr, FOutputDevice& Ar ) { TCHAR TempFname[MAX_EDCMD]; const TCHAR* Str=InStr; if( ParseCommand(&Str,TEXT("MACRO")) || ParseCommand(&Str,TEXT("EXEC")) )//oldver (exec) { TCHAR Filename[MAX_EDCMD]; if( ParseToken( Str, Filename, ARRAY_COUNT(Filename), 0 ) ) ExecMacro( Filename, Ar ); return 1; } else if( ParseCommand(&Str,TEXT("NEW")) ) { // Generalized object importing. DWORD Flags = RF_Public|RF_Standalone; if( ParseCommand(&Str,TEXT("STANDALONE")) ) Flags = RF_Public|RF_Standalone; else if( ParseCommand(&Str,TEXT("PUBLIC")) ) Flags = RF_Public; else if( ParseCommand(&Str,TEXT("PRIVATE")) ) Flags = 0; FString ClassName = ParseToken(Str,0); UClass* Class = FindObject<UClass>( ANY_PACKAGE, *ClassName ); if( !Class ) { Ar.Logf( NAME_ExecWarning, TEXT("Unrecognized or missing factor class %s"), *ClassName ); return 1; } FString PackageName = ParentContext ? ParentContext->GetName() : TEXT(""); FString GroupName = TEXT(""); FString FileName = TEXT(""); FString ObjectName = TEXT(""); UClass* ContextClass = NULL; UObject* Context = NULL; Parse( Str, TEXT("Package="), PackageName ); Parse( Str, TEXT("Group="), GroupName ); Parse( Str, TEXT("File="), FileName ); ParseObject( Str, TEXT("ContextClass="), UClass::StaticClass(), *(UObject**)&ContextClass, NULL ); ParseObject( Str, TEXT("Context="), ContextClass, Context, NULL ); if ( !Parse( Str, TEXT("Name="), ObjectName ) && FileName!=TEXT("") ) { // Deduce object name from filename. ObjectName = FileName; for( ; ; ) { INT i=ObjectName.InStr(PATH_SEPARATOR); if( i==-1 ) i=ObjectName.InStr(TEXT("/")); if( i==-1 ) break; ObjectName = ObjectName.Mid( i+1 ); } if( ObjectName.InStr(TEXT("."))>=0 ) ObjectName = ObjectName.Left( ObjectName.InStr(TEXT(".")) ); } UFactory* Factory = NULL; if( Class->IsChildOf(UFactory::StaticClass()) ) Factory = ConstructObject<UFactory>( Class ); UObject* Object = UFactory::StaticImportObject ( GEditor->Level, Factory ? Factory->SupportedClass : Class, CreatePackage(NULL,*(GroupName != TEXT("") ? (PackageName+TEXT(".")+GroupName) : PackageName)), *ObjectName, Flags, *FileName, Context, Factory, Str, GWarn ); if( !Object ) Ar.Logf( NAME_ExecWarning, TEXT("Failed factoring: %s"), InStr ); return 1; } else if( ParseCommand( &Str, TEXT("LOAD") ) ) { // Object file loading. if( Parse( Str, TEXT("FILE="), TempFname, 256) ) { TCHAR PackageName[256]=TEXT(""); UObject* Pkg=NULL; if( Parse( Str, TEXT("Package="), PackageName, ARRAY_COUNT(PackageName) ) ) { TCHAR Temp[256], *End; appStrcpy( Temp, PackageName ); End = appStrchr(Temp,'.'); if( End ) *End++ = 0; Pkg = CreatePackage( NULL, PackageName ); } Pkg = LoadPackage( Pkg, TempFname, GIsUCCMake ? LOAD_FindIfFail : 0 ); if( *PackageName ) ResetLoaders( Pkg, 0, 1 ); if( !ParentContext ) RedrawLevel(Level); } else Ar.Log( NAME_ExecWarning, TEXT("Missing filename") ); return 1; } else if( ParseCommand(&Str,TEXT("OBJ")) )//oldver { UClass* Type; if( ParseCommand( &Str, TEXT("LOAD") ) )//oldver return SafeExec( *(US+TEXT("LOAD ")+Str), Ar ); else if( ParseCommand(&Str,TEXT("IMPORT")) )//oldver if( ParseObject<UClass>( Str, TEXT("TYPE="), Type, ANY_PACKAGE ) ) return SafeExec( *(US+TEXT("NEW STANDALONE ")+Type->GetName()+TEXT(" ")+Str), Ar ); return 0; } else if( ParseCommand( &Str, TEXT("MESHMAP")) ) { appErrorf(TEXT("Deprecated command executed: %s"),Str); } else if( ParseCommand(&Str,TEXT("ANIM")) ) { appErrorf(TEXT("Deprecated command executed: %s"),Str); } else if( ParseCommand(&Str,TEXT("MESH")) ) { appErrorf(TEXT("Deprecated command executed: %s"),Str); } else if( ParseCommand( &Str, TEXT("AUDIO")) ) { appErrorf(TEXT("Deprecated command executed: %s"),Str); } return 0; } /*----------------------------------------------------------------------------- UnrealEd command line. -----------------------------------------------------------------------------*/ //@hack: this needs to be cleaned up! static UModel* GBrush = NULL; static const TCHAR* GStream = NULL; static TCHAR TempStr[MAX_EDCMD], TempFname[MAX_EDCMD], TempName[MAX_EDCMD], Temp[MAX_EDCMD]; static _WORD Word1, Word2, Word4; UBOOL UEditorEngine::Exec_StaticMesh( const TCHAR* Str, FOutputDevice& Ar ) { if(ParseCommand(&Str,TEXT("FROM"))) { if(ParseCommand(&Str,TEXT("SELECTION"))) // STATICMESH FROM SELECTION PACKAGE=<name> NAME=<name> { Trans->Begin(TEXT("STATICMESH FROM SELECTION")); Level->Modify(); FinishAllSnaps(Level); FName PkgName = NAME_None; Parse( Str, TEXT("PACKAGE="), PkgName ); FName Name = NAME_None; Parse( Str, TEXT("NAME="), Name ); if( PkgName != NAME_None ) { UPackage* Pkg = CreatePackage(NULL,*PkgName); Pkg->bDirty = 1; FName GroupName = NAME_None; if( Parse( Str, TEXT("GROUP="), GroupName ) && GroupName!=NAME_None ) Pkg = CreatePackage(Pkg,*GroupName); TArray<FStaticMeshTriangle> Triangles; TArray<FStaticMeshMaterial> Materials; for( TSelectedActorIterator It( GetLevel() ) ; It ; ++It ) { AActor* Actor = *It; // // Brush // if( Actor->IsBrush() ) { ABrush* Brush = Cast<ABrush>(Actor); check(Brush); TArray<FStaticMeshTriangle> TempTriangles; GetBrushTriangles( TempTriangles, Materials, Brush, Brush->Brush ); // Transform the static meshes triangles into worldspace. FMatrix LocalToWorld = Brush->LocalToWorld(); for( INT x = 0 ; x < TempTriangles.Num() ; ++x ) { FStaticMeshTriangle* Tri = &TempTriangles(x); for( INT y = 0 ; y < 3 ; ++y ) { Tri->Vertices[y] = Brush->LocalToWorld().TransformFVector( Tri->Vertices[y] ); Tri->Vertices[y] -= GetPivotLocation() - Actor->PrePivot; } } Triangles += TempTriangles; } } // Create the static mesh if( Triangles.Num() ) CreateStaticMesh(Triangles,Materials,Pkg,Name); } Trans->End(); RedrawLevel(Level); return 1; } } else if(ParseCommand(&Str,TEXT("TO"))) { if(ParseCommand(&Str,TEXT("BRUSH"))) { Trans->Begin(TEXT("STATICMESH TO BRUSH")); GBrush->Modify(); // Find the first selected static mesh actor. AStaticMeshActor* SelectedActor = NULL; for(INT ActorIndex = 0;ActorIndex < Level->Actors.Num();ActorIndex++) if(Level->Actors(ActorIndex) && GSelectionTools.IsSelected( Level->Actors(ActorIndex) ) && Cast<AStaticMeshActor>(Level->Actors(ActorIndex)) != NULL) { SelectedActor = Cast<AStaticMeshActor>(Level->Actors(ActorIndex)); break; } if(SelectedActor) { Level->Brush()->Location = SelectedActor->Location; SelectedActor->Location = FVector(0,0,0); CreateModelFromStaticMesh(Level->Brush()->Brush,SelectedActor); SelectedActor->Location = Level->Brush()->Location; } else Ar.Logf(TEXT("No suitable actors found.")); Trans->End(); RedrawLevel(Level); return 1; } } else if(ParseCommand(&Str,TEXT("REBUILD"))) // STATICMESH REBUILD { // // Forces a rebuild of the selected static mesh. // Trans->Begin(TEXT("staticmesh rebuild")); GWarn->BeginSlowTask(TEXT("Staticmesh rebuilding"),1 ); UStaticMesh* sm = GSelectionTools.GetTop<UStaticMesh>(); if( sm ) { sm->Modify(); sm->Build(); } GWarn->EndSlowTask(); Trans->End(); } else if(ParseCommand(&Str,TEXT("SMOOTH"))) // STATICMESH SMOOTH { // // Hack to set the smoothing mask of the triangles in the selected static meshes to 1. // Trans->Begin(TEXT("staticmesh smooth")); GWarn->BeginSlowTask(TEXT("Smoothing static meshes"),1); for(INT ActorIndex = 0;ActorIndex < Level->Actors.Num();ActorIndex++) { AStaticMeshActor* Actor = Cast<AStaticMeshActor>(Level->Actors(ActorIndex)); if(Actor && GSelectionTools.IsSelected( Actor ) && Actor->StaticMeshComponent->StaticMesh) { UStaticMesh* StaticMesh = Actor->StaticMeshComponent->StaticMesh; StaticMesh->Modify(); // Generate smooth normals. if(!StaticMesh->RawTriangles.Num()) StaticMesh->RawTriangles.Load(); for(INT i = 0;i < StaticMesh->RawTriangles.Num();i++) StaticMesh->RawTriangles(i).SmoothingMask = 1; StaticMesh->Build(); StaticMesh->RawTriangles.Detach(); } } GWarn->EndSlowTask(); Trans->End(); } else if(ParseCommand(&Str,TEXT("UNSMOOTH"))) // STATICMESH UNSMOOTH { // // Hack to set the smoothing mask of the triangles in the selected static meshes to 0. // Trans->Begin(TEXT("staticmesh unsmooth")); GWarn->BeginSlowTask(TEXT("Unsmoothing static meshes"),1); for(INT ActorIndex = 0;ActorIndex < Level->Actors.Num();ActorIndex++) { AStaticMeshActor* Actor = Cast<AStaticMeshActor>(Level->Actors(ActorIndex)); if(Actor && GSelectionTools.IsSelected( Actor ) && Actor->StaticMeshComponent->StaticMesh) { UStaticMesh* StaticMesh = Actor->StaticMeshComponent->StaticMesh; if(!StaticMesh->RawTriangles.Num()) StaticMesh->RawTriangles.Load(); StaticMesh->Modify(); // Generate smooth normals. for(INT i = 0;i < StaticMesh->RawTriangles.Num();i++) { FStaticMeshTriangle& Triangle1 = StaticMesh->RawTriangles(i); Triangle1.SmoothingMask = 0; } StaticMesh->Build(); StaticMesh->RawTriangles.Detach(); } } GWarn->EndSlowTask(); Trans->End(); } else if( ParseCommand(&Str,TEXT("DEFAULT")) ) // STATICMESH DEFAULT NAME=<name> { GSelectionTools.SelectNone<UStaticMesh>(); UStaticMesh* sm; ParseObject<UStaticMesh>(Str,TEXT("NAME="),sm,ANY_PACKAGE); GSelectionTools.Select( sm ); return 1; } // Take the currently selected static mesh, and save the builder brush as its // low poly collision model. else if( ParseCommand(&Str,TEXT("SAVEBRUSHASCOLLISION")) ) { // First, find the currently selected actor with a static mesh. // Fail if more than one actor with staticmesh is selected. UStaticMesh* StaticMesh = NULL; FMatrix MeshToWorld; for( TSelectedActorIterator It( Level ) ; It ; ++It ) { AActor* Actor = *It; UStaticMesh* FoundMesh = NULL; AStaticMeshActor* SMActor = Cast<AStaticMeshActor>(Actor); if(SMActor) { FoundMesh = SMActor->StaticMeshComponent->StaticMesh; } if(FoundMesh) { // If we find multiple actors with static meshes, warn and do nothing. if(StaticMesh) { appMsgf( 0, TEXT("Please select just one Actor with a StaticMesh.") ); return 1; } StaticMesh = FoundMesh; MeshToWorld = SMActor->StaticMeshComponent->LocalToWorld; } } // If no static-mesh-toting actor found, warn and do nothing. if(!StaticMesh) { appMsgf( 0, TEXT("No Actor found with a StaticMesh.") ); return 1; } // If we already have a collision model for this staticmesh, ask if we want to replace it. if(StaticMesh->CollisionModel) { UBOOL doReplace = appMsgf(1, TEXT("Static Mesh already has a collision model. \nDo you want to replace it with Builder Brush?")); if(doReplace) StaticMesh->CollisionModel = NULL; else return 1; } // Now get the builder brush. UModel* builderModel = Level->Brush()->Brush; // Need the transform between builder brush space and static mesh actor space. FMatrix BrushL2W = Level->Brush()->LocalToWorld(); FMatrix MeshW2L = MeshToWorld.Inverse(); FMatrix SMToBB = BrushL2W * MeshW2L; // Copy the current builder brush into the static mesh. StaticMesh->CollisionModel = new(StaticMesh->GetOuter()) UModel(NULL,1); StaticMesh->CollisionModel->Polys = new(StaticMesh->GetOuter()) UPolys; StaticMesh->CollisionModel->Polys->Element = builderModel->Polys->Element; // Now transform each poly into local space for the selected static mesh. for(INT i=0; i<StaticMesh->CollisionModel->Polys->Element.Num(); i++) { FPoly* Poly = &StaticMesh->CollisionModel->Polys->Element(i); for(INT j=0; j<Poly->NumVertices; j++ ) { Poly->Vertex[j] = SMToBB.TransformFVector(Poly->Vertex[j]); } Poly->Normal = SMToBB.TransformNormal(Poly->Normal); Poly->Normal.Normalize(); // SmToBB might have scaling in it. } // Build bounding box. StaticMesh->CollisionModel->BuildBound(); // Build BSP for the brush. GEditor->bspBuild(StaticMesh->CollisionModel,BSP_Good,15,70,1,0); GEditor->bspRefresh(StaticMesh->CollisionModel,1); GEditor->bspBuildBounds(StaticMesh->CollisionModel); // Now - use this as the Rigid Body collision for this static mesh as well. // If we dont already have physics props, construct them here. if(!StaticMesh->BodySetup) { StaticMesh->BodySetup = ConstructObject<URB_BodySetup>(URB_BodySetup::StaticClass(), StaticMesh); } // Convert collision model into a collection of convex hulls. // NB: This removes any convex hulls that were already part of the collision data. KModelToHulls(&StaticMesh->BodySetup->AggGeom, StaticMesh->CollisionModel, FVector(0, 0, 0)); // Finally mark the parent package as 'dirty', so user will be prompted if they want to save it etc. StaticMesh->MarkPackageDirty(); Ar.Logf(TEXT("Added collision model to StaticMesh %s."), StaticMesh->GetName() ); } return 0; } UBOOL UEditorEngine::Exec_Brush( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("APPLYTRANSFORM")) ) return Exec( TEXT("ACTOR APPLYTRANSFORM" ) ); else if( ParseCommand(&Str,TEXT("SET")) ) { Trans->Begin( TEXT("Brush Set") ); GBrush->Modify(); FRotator Temp(0.0f,0.0f,0.0f); Constraints.Snap( NULL, Level->Brush()->Location, FVector(0.f,0.f,0.f), Temp ); Level->Brush()->Location -= Level->Brush()->PrePivot; Level->Brush()->PrePivot = FVector(0.f,0.f,0.f); GBrush->Polys->Element.Empty(); UPolysFactory* It = new UPolysFactory; It->FactoryCreateText( Level,UPolys::StaticClass(), GBrush->Polys->GetOuter(), GBrush->Polys->GetName(), 0, GBrush->Polys, TEXT("t3d"), GStream, GStream+appStrlen(GStream), GWarn ); // Do NOT merge faces. bspValidateBrush( GBrush, 0, 1 ); GBrush->BuildBound(); Trans->End(); NoteSelectionChange( Level ); return 1; } else if( ParseCommand(&Str,TEXT("MORE")) ) { Trans->Continue(); GBrush->Modify(); UPolysFactory* It = new UPolysFactory; It->FactoryCreateText( Level,UPolys::StaticClass(), GBrush->Polys->GetOuter(), GBrush->Polys->GetName(), 0, GBrush->Polys, TEXT("t3d"), GStream, GStream+appStrlen(GStream), GWarn ); // Do NOT merge faces. bspValidateBrush( Level->Brush()->Brush, 0, 1 ); GBrush->BuildBound(); Trans->End(); RedrawLevel( Level ); return 1; } else if( ParseCommand(&Str,TEXT("RESET")) ) { Trans->Begin( TEXT("Brush Reset") ); Level->Brush()->Modify(); Level->Brush()->InitPosRotScale(); Trans->End(); RedrawLevel(Level); return 1; } else if( ParseCommand(&Str,TEXT("SCALE")) ) { Trans->Begin( TEXT("Brush Scale") ); FVector Scale; GetFVECTOR( Str, Scale ); if( !Scale.X ) Scale.X = 1; if( !Scale.Y ) Scale.Y = 1; if( !Scale.Z ) Scale.Z = 1; FVector InvScale( 1 / Scale.X, 1 / Scale.Y, 1 / Scale.Z ); for( INT i=0; i<Level->Actors.Num(); i++ ) { ABrush* Brush = Cast<ABrush>(Level->Actors(i)); if( Brush && GSelectionTools.IsSelected( Brush ) && Brush->IsBrush() ) { Brush->Brush->Modify(); Brush->Brush->Polys->Element.ModifyAllItems(); for( INT poly = 0 ; poly < Brush->Brush->Polys->Element.Num() ; poly++ ) { FPoly* Poly = &(Brush->Brush->Polys->Element(poly)); Poly->TextureU *= InvScale; Poly->TextureV *= InvScale; Poly->Base = ((Poly->Base - Brush->PrePivot) * Scale) + Brush->PrePivot; for( INT vtx = 0 ; vtx < Poly->NumVertices ; vtx++ ) Poly->Vertex[vtx] = ((Poly->Vertex[vtx] - Brush->PrePivot) * Scale) + Brush->PrePivot; Poly->CalcNormal(); } Brush->Brush->BuildBound(); } } Trans->End(); RedrawLevel(Level); return 1; } else if( ParseCommand(&Str,TEXT("MOVETO")) ) { Trans->Begin( TEXT("Brush MoveTo") ); Level->Brush()->Modify(); GetFVECTOR( Str, Level->Brush()->Location ); Trans->End(); RedrawLevel(Level); return 1; } else if( ParseCommand(&Str,TEXT("MOVEREL")) ) { Trans->Begin( TEXT("Brush MoveRel") ); Level->Brush()->Modify(); FVector TempVector( 0, 0, 0 ); GetFVECTOR( Str, TempVector ); Level->Brush()->Location.AddBounded( TempVector, HALF_WORLD_MAX1 ); Trans->End(); RedrawLevel(Level); return 1; } else if (ParseCommand(&Str,TEXT("ADD"))) { Trans->Begin( TEXT("Brush Add") ); FinishAllSnaps(Level); INT DWord1=0; Parse( Str, TEXT("FLAGS="), DWord1 ); Level->Modify(); ABrush* NewBrush = csgAddOperation( Level->Brush(), Level, DWord1, CSG_Add ); if( NewBrush ) bspBrushCSG( NewBrush, Level->Model, DWord1, CSG_Add, 1 ); Trans->End(); Level->InvalidateModelGeometry(); Level->UpdateComponents(); RedrawLevel(Level); return 1; } else if (ParseCommand(&Str,TEXT("ADDVOLUME"))) // BRUSH ADDVOLUME { Trans->Begin( TEXT("Brush AddVolume") ); Level->Modify(); FinishAllSnaps( Level ); UClass* VolumeClass = NULL; ParseObject<UClass>( Str, TEXT("CLASS="), VolumeClass, ANY_PACKAGE ); if( !VolumeClass || !VolumeClass->IsChildOf(AVolume::StaticClass()) ) VolumeClass = AVolume::StaticClass(); Level->Modify(); AVolume* Actor = (AVolume*)Level->SpawnActor(VolumeClass,NAME_None,Level->Brush()->Location); if( Actor ) { Actor->PreEditChange(); csgCopyBrush ( Actor, Level->Brush(), 0, RF_Transactional, 1 ); // Set the texture on all polys to NULL. This stops invisible texture // dependencies from being formed on volumes. if( Actor->Brush ) for( INT poly = 0 ; poly < Actor->Brush->Polys->Element.Num() ; ++poly ) { FPoly* Poly = &(Actor->Brush->Polys->Element(poly)); Poly->Material = NULL; } Actor->PostEditChange(NULL); } Trans->End(); RedrawLevel(Level); return 1; } else if (ParseCommand(&Str,TEXT("SUBTRACT"))) // BRUSH SUBTRACT { Trans->Begin( TEXT("Brush Subtract") ); FinishAllSnaps(Level); Level->Modify(); ABrush* NewBrush = csgAddOperation(Level->Brush(),Level,0,CSG_Subtract); // Layer if( NewBrush ) bspBrushCSG( NewBrush, Level->Model, 0, CSG_Subtract, 1 ); Trans->End(); Level->InvalidateModelGeometry(); Level->UpdateComponents(); RedrawLevel(Level); return 1; } else if (ParseCommand(&Str,TEXT("FROM"))) // BRUSH FROM INTERSECTION/DEINTERSECTION { if( ParseCommand(&Str,TEXT("INTERSECTION")) ) { Ar.Log( TEXT("Brush from intersection") ); Trans->Begin( TEXT("Brush From Intersection") ); GBrush->Modify(); FinishAllSnaps( Level ); bspBrushCSG( Level->Brush(), Level->Model, 0, CSG_Intersect, 0 ); Trans->End(); Level->Brush()->ClearComponents(); Level->Brush()->UpdateComponents(); RedrawLevel( Level ); return 1; } else if( ParseCommand(&Str,TEXT("DEINTERSECTION")) ) { Ar.Log( TEXT("Brush from deintersection") ); Trans->Begin( TEXT("Brush From Deintersection") ); GBrush->Modify(); FinishAllSnaps( Level ); bspBrushCSG( Level->Brush(), Level->Model, 0, CSG_Deintersect, 0 ); Trans->End(); Level->Brush()->ClearComponents(); Level->Brush()->UpdateComponents(); RedrawLevel( Level ); return 1; } } else if( ParseCommand (&Str,TEXT("NEW")) ) { Trans->Begin( TEXT("Brush New") ); GBrush->Modify(); GBrush->Polys->Element.Empty(); Trans->End(); RedrawLevel( Level ); return 1; } else if( ParseCommand (&Str,TEXT("LOAD")) ) // BRUSH LOAD { if( Parse( Str, TEXT("FILE="), TempFname, 256 ) ) { Trans->Reset( TEXT("loading brush") ); FVector TempVector = Level->Brush()->Location; LoadPackage( Level->GetOuter(), TempFname, 0 ); Level->Brush()->Location = TempVector; bspValidateBrush( Level->Brush()->Brush, 0, 1 ); Cleanse( 1, TEXT("loading brush") ); return 1; } } else if( ParseCommand( &Str, TEXT("SAVE") ) ) { if( Parse(Str,TEXT("FILE="),TempFname, 256) ) { Ar.Logf( TEXT("Saving %s"), TempFname ); SavePackage( Level->GetOuter(), GBrush, 0, TempFname, GWarn ); } else Ar.Log( NAME_ExecWarning, TEXT("Missing filename") ); return 1; } else if( ParseCommand( &Str, TEXT("IMPORT")) ) { if( Parse(Str,TEXT("FILE="),TempFname, 256) ) { GWarn->BeginSlowTask( TEXT("Importing brush"), 1); Trans->Begin( TEXT("Brush Import") ); GBrush->Polys->Modify(); GBrush->Polys->Element.Empty(); DWORD Flags=0; UBOOL Merge=0; ParseUBOOL( Str, TEXT("MERGE="), Merge ); Parse( Str, TEXT("FLAGS="), Flags ); GBrush->Linked = 0; ImportObject<UPolys>( GEditor->Level, GBrush->Polys->GetOuter(), GBrush->Polys->GetName(), 0, TempFname ); if( Flags ) for( Word2=0; Word2<TempModel->Polys->Element.Num(); Word2++ ) GBrush->Polys->Element(Word2).PolyFlags |= Flags; for( INT i=0; i<GBrush->Polys->Element.Num(); i++ ) GBrush->Polys->Element(i).iLink = i; if( Merge ) { bspMergeCoplanars( GBrush, 0, 1 ); bspValidateBrush( GBrush, 0, 1 ); } Trans->End(); GWarn->EndSlowTask(); } else Ar.Log( NAME_ExecWarning, TEXT("Missing filename") ); return 1; } else if (ParseCommand(&Str,TEXT("EXPORT"))) { if( Parse(Str,TEXT("FILE="),TempFname, 256) ) { GWarn->BeginSlowTask( TEXT("Exporting brush"), 1); UExporter::ExportToFile( GBrush->Polys, NULL, TempFname, 0 ); GWarn->EndSlowTask(); } else Ar.Log(NAME_ExecWarning,TEXT("Missing filename")); return 1; } else if( ParseCommand(&Str,TEXT("MERGEPOLYS")) ) // BRUSH MERGEPOLYS { // Merges the polys on all selected brushes GWarn->BeginSlowTask( TEXT(""), 1); for( INT i=0; i<Level->Actors.Num(); i++ ) { GWarn->StatusUpdatef( i, Level->Actors.Num(), TEXT("Merging polys on selected brushes") ); ABrush* Actor = Cast<ABrush>(Level->Actors(i)); if( Actor && GSelectionTools.IsSelected( Actor ) && Actor->IsBrush() ) bspValidateBrush( Actor->Brush, 1, 1 ); } RedrawLevel( Level ); GWarn->EndSlowTask(); } else if( ParseCommand(&Str,TEXT("SEPARATEPOLYS")) ) // BRUSH SEPARATEPOLYS { GWarn->BeginSlowTask( TEXT(""), 1); for( INT i=0; i<Level->Actors.Num(); i++ ) { GWarn->StatusUpdatef( i, Level->Actors.Num(), TEXT("Separating polys on selected brushes") ); ABrush* Actor = Cast<ABrush>(Level->Actors(i)); if( Actor && GSelectionTools.IsSelected( Actor ) && Actor->IsBrush() ) bspUnlinkPolys( Actor->Brush ); } RedrawLevel( Level ); GWarn->EndSlowTask(); } return 0; } UBOOL UEditorEngine::Exec_Paths( const TCHAR* Str, FOutputDevice& Ar ) { if (ParseCommand(&Str,TEXT("UNDEFINE"))) { FPathBuilder builder; Trans->Reset( TEXT("Paths") ); builder.undefinePaths( Level ); RedrawLevel(Level); return 1; } else if (ParseCommand(&Str,TEXT("DEFINE"))) { FPathBuilder builder; Trans->Reset( TEXT("Paths") ); builder.definePaths( Level ); RedrawLevel(Level); return 1; } else if (ParseCommand(&Str,TEXT("REVIEW"))) { FPathBuilder builder; Trans->Reset( TEXT("Paths") ); builder.ReviewPaths( Level ); RedrawLevel(Level); return 1; } return 0; } UBOOL UEditorEngine::Exec_BSP( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand( &Str, TEXT("REBUILD")) ) // Bsp REBUILD [LAME/GOOD/OPTIMAL] [BALANCE=0-100] [LIGHTS] [MAPS] [REJECT] { Trans->Reset( TEXT("Rebuilding Bsp") ); // Not tracked transactionally Ar.Log(TEXT("Bsp Rebuild")); FRebuildOptions* Options = GRebuildTools.GetCurrent(); GWarn->BeginSlowTask( TEXT("Building polygons"), 1); bspBuildFPolys( Level->Model, 1, 0 ); GWarn->StatusUpdatef( 0, 0, TEXT("Merging planars") ); bspMergeCoplanars( Level->Model, 0, 0 ); GWarn->StatusUpdatef( 0, 0, TEXT("Partitioning") ); bspBuild( Level->Model, Options->BspOpt, Options->Balance, Options->PortalBias, 0, 0 ); GWarn->StatusUpdatef( 0, 0, TEXT("Building visibility zones") ); TestVisibility( Level, Level->Model, 0, 0 ); GWarn->StatusUpdatef( 0, 0, TEXT("Optimizing geometry") ); bspOptGeom( Level->Model ); // Empty EdPolys. Level->Model->Polys->Element.Empty(); GWarn->EndSlowTask(); RedrawLevel(Level); GCallback->Send( CALLBACK_MapChange, 0 ); Level->InvalidateModelGeometry(); return 1; } return 0; } UBOOL UEditorEngine::Exec_Light( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand( &Str, TEXT("APPLY") ) ) { shadowIlluminateBsp(Level); RedrawLevel( Level ); return 1; } return 0; } UBOOL UEditorEngine::Exec_Map( const TCHAR* Str, FOutputDevice& Ar ) { if (ParseCommand(&Str,TEXT("ROTGRID"))) // MAP ROTGRID [PITCH=..] [YAW=..] [ROLL=..] { FinishAllSnaps (Level); if( GetFROTATOR( Str, Constraints.RotGridSize, 1 ) ) RedrawLevel(Level); GCallback->Send( CALLBACK_UpdateUI ); return 1; } else if (ParseCommand(&Str,TEXT("SELECT"))) { Trans->Begin( TEXT("Select") ); if( ParseCommand(&Str,TEXT("ADDS")) ) mapSelectOperation( Level, CSG_Add ); else if( ParseCommand(&Str,TEXT("SUBTRACTS")) ) mapSelectOperation( Level, CSG_Subtract ); else if( ParseCommand(&Str,TEXT("SEMISOLIDS")) ) mapSelectFlags( Level, PF_Semisolid ); else if( ParseCommand(&Str,TEXT("NONSOLIDS")) ) mapSelectFlags( Level, PF_NotSolid ); Trans->End (); RedrawLevel( Level ); return 1; } else if( ParseCommand(&Str,TEXT("DELETE")) ) { Exec( TEXT("ACTOR DELETE"), Ar ); return 1; } else if( ParseCommand(&Str,TEXT("BRUSH")) ) { if( ParseCommand (&Str,TEXT("GET")) ) { Trans->Begin( TEXT("Brush Get") ); mapBrushGet( Level ); Trans->End(); RedrawLevel( Level ); return 1; } else if( ParseCommand (&Str,TEXT("PUT")) ) { Trans->Begin( TEXT("Brush Put") ); mapBrushPut( Level ); Trans->End(); RedrawLevel( Level ); return 1; } } else if (ParseCommand(&Str,TEXT("SENDTO"))) { if( ParseCommand(&Str,TEXT("FIRST")) ) { Trans->Begin( TEXT("Map SendTo Front") ); mapSendToFirst( Level ); Trans->End(); RedrawLevel( Level ); return 1; } else if( ParseCommand(&Str,TEXT("LAST")) ) { Trans->Begin( TEXT("Map SendTo Back") ); mapSendToLast( Level ); Trans->End(); RedrawLevel( Level ); return 1; } else if( ParseCommand(&Str,TEXT("SWAP")) ) { Trans->Begin( TEXT("Map SendTo Swap") ); mapSendToSwap( Level ); Trans->End(); RedrawLevel( Level ); return 1; } } else if( ParseCommand(&Str,TEXT("REBUILD")) ) { Trans->Reset( TEXT("rebuilding map") ); GWarn->BeginSlowTask( TEXT("Rebuilding geometry"), 1); Level->GetLevelInfo()->bPathsRebuilt = 0; csgRebuild( Level ); Level->InvalidateModelGeometry(); GWarn->StatusUpdatef( 0, 0, TEXT("Cleaning up...") ); RedrawLevel( Level ); GCallback->Send( CALLBACK_MapChange, 1 ); GWarn->EndSlowTask(); return 1; } else if( ParseCommand (&Str,TEXT("NEW")) ) { Trans->Reset( TEXT("clearing map") ); ResetLoaders( Level->GetOuter(), 0, 1 ); ClearComponents(); Level->CleanupLevel(); if ( ParseCommand( &Str, TEXT( "NOOUTSIDE" ) ) ) { Level = new( Level->GetOuter(), TEXT("MyLevel") )ULevel( this, 0 ); } else { Level = new( Level->GetOuter(), TEXT("MyLevel") )ULevel( this, 1 ); } NoteSelectionChange( Level ); GCallback->Send( CALLBACK_MapChange, 1 ); Cleanse( 1, TEXT("starting new map") ); return 1; } else if( ParseCommand( &Str, TEXT("LOAD") ) ) { if( Parse( Str, TEXT("FILE="), TempFname, 256 ) ) { Trans->Reset( TEXT("loading map") ); GWarn->BeginSlowTask( TEXT("Loading map"), 1); ResetLoaders( Level->GetOuter(), 0, 1 ); EdClearLoadErrors(); ClearComponents(); Level->CleanupLevel(); LoadPackage( Level->GetOuter(), TempFname, 0 ); Level->Engine = this; //GTerrainTools.Init(); bspValidateBrush( Level->Brush()->Brush, 0, 1 ); GWarn->EndSlowTask(); // Hack fix for actor location being undefined (NAN) for ( INT i=0; i<Level->Actors.Num(); i++ ) if ( Level->Actors(i) && (Level->Actors(i)->Location != Level->Actors(i)->Location) ) Level->DestroyActor(Level->Actors(i)); GCallback->Send( CALLBACK_MapChange, 1 ); NoteSelectionChange( Level ); Level->SetFlags( RF_Transactional ); Level->Model->SetFlags( RF_Transactional ); if( Level->Model->Polys ) Level->Model->Polys->SetFlags( RF_Transactional ); Cleanse( 0, TEXT("loading map") ); // Look for 'orphan' actors - that is, actors which are in the Package of the level we just loaded, but not in the Actors array. // If we find any, set bDeleteMe to 'true', so that PendingKill will return 'true' for them DOUBLE StartTime = appSeconds(); UObject* LevelPackage = Level->GetOutermost(); for( TObjectIterator<AActor> It; It; ++It ) { UObject* Obj = *It; AActor* Actor = CastChecked<AActor>(Obj); // If Actor is part of the level we are loading's package, but not in Actor list, clear it if( (Actor->GetOutermost() == LevelPackage) && !Level->Actors.ContainsItem(Actor) && !Actor->bDeleteMe ) { debugf( TEXT("Destroying orphan Actor: %s"), Actor->GetName() ); Actor->bDeleteMe = true; } } debugf( TEXT("Finished looking for orphan Actors (%3.3lf secs)"), appSeconds() - StartTime ); // Ensure there are no pointers to any PendingKill objects. for( TObjectIterator<UObject> It; It; ++It ) { UObject* Obj = *It; Obj->GetClass()->CleanupDestroyed( (BYTE*)Obj, Obj ); } // Set Transactional flag and call PostEditLoad on all Actors in level for( INT i=0; i<Level->Actors.Num(); i++) { AActor* Actor = Level->Actors(i); if(Actor) { Actor->SetFlags( RF_Transactional ); Actor->PostEditLoad(); } } // rebuild the list of currently selected objects GSelectionTools.RebuildSelectedList(); if( GEdLoadErrors.Num() ) GCallback->Send( CALLBACK_DisplayLoadErrors ); } else Ar.Log( NAME_ExecWarning, TEXT("Missing filename") ); GCallback->Send( CALLBACK_MapChange, 1 ); return 1; } else if( ParseCommand (&Str,TEXT("SAVE")) ) { if( Parse(Str,TEXT("FILE="),TempFname, 256) ) { FString SpacesTest = TempFname; if( SpacesTest.InStr( TEXT(" ") ) != INDEX_NONE ) if( appMsgf( 0, TEXT("The filename you specified has one or more spaces in it. Unreal filenames cannot contain spaces.") ) ) return 0; INT Autosaving = 0; // Are we autosaving? Parse(Str,TEXT("AUTOSAVE="),Autosaving); Level->ShrinkLevel(); Level->CleanupDestroyed( 1 ); ALevelInfo* OldInfo = FindObject<ALevelInfo>(Level->GetOuter(),TEXT("LevelInfo0")); if( OldInfo && OldInfo!=Level->GetLevelInfo() ) OldInfo->Rename(); if( Level->GetLevelInfo()!=OldInfo ) Level->GetLevelInfo()->Rename(TEXT("LevelInfo0")); ULevelSummary* Summary = Level->GetLevelInfo()->Summary = new(Level->GetOuter(),TEXT("LevelSummary"),RF_Public)ULevelSummary; Summary->Title = Level->GetLevelInfo()->Title; Summary->Author = Level->GetLevelInfo()->Author; // Reset actor creation times. for(INT ActorIndex = 0;ActorIndex < Level->Actors.Num();ActorIndex++) if(Level->Actors(ActorIndex)) Level->Actors(ActorIndex)->CreationTime = 0.0f; // Check for duplicate actor indices. INT NumDuplicates = 0; for(INT ActorIndex = 0;ActorIndex < Level->Actors.Num();ActorIndex++) { AActor* Actor = Level->Actors(ActorIndex); if(Actor) for(INT OtherActorIndex = ActorIndex + 1;OtherActorIndex < Level->Actors.Num();OtherActorIndex++) if(Level->Actors(OtherActorIndex) == Actor) { Level->Actors(OtherActorIndex) = NULL; NumDuplicates++; } } Level->CompactActors(); debugf(TEXT("Removed duplicate actor indices: %u duplicates found."),NumDuplicates); if( !Autosaving ) GWarn->BeginSlowTask( TEXT("Saving map"), 1); if( !SavePackage( Level->GetOuter(), Level, 0, TempFname, GWarn ) ) appMsgf( 0, TEXT("Couldn't save package - maybe file is read-only?") ); if( !Autosaving ) GWarn->EndSlowTask(); } else Ar.Log( NAME_ExecWarning, TEXT("Missing filename") ); return 1; } else if( ParseCommand( &Str, TEXT("IMPORT") ) ) { Word1=1; DoImportMap: if( Parse( Str, TEXT("FILE="), TempFname, 256) ) { Trans->Reset( TEXT("importing map") ); GWarn->BeginSlowTask( TEXT("Importing map"), 1); ClearComponents(); if( Level ) Level->CleanupLevel(); if( Word1 ) Level = new( Level->GetOuter(), TEXT("MyLevel") )ULevel( this, 1 ); ImportObject<ULevel>( Level, Level->GetOuter(), Level->GetFName(), RF_Transactional, TempFname ); if( Word1 ) SelectNone( Level, 0 ); GWarn->EndSlowTask(); GCallback->Send( CALLBACK_MapChange, 1 ); NoteSelectionChange( Level ); Cleanse( 1, TEXT("importing map") ); } else Ar.Log(NAME_ExecWarning,TEXT("Missing filename")); return 1; } else if( ParseCommand( &Str, TEXT("IMPORTADD") ) ) { Word1=0; SelectNone( Level, 0 ); goto DoImportMap; } else if (ParseCommand (&Str,TEXT("EXPORT"))) { if (Parse(Str,TEXT("FILE="),TempFname, 256)) { GWarn->BeginSlowTask( TEXT("Exporting map"), 1); UBOOL bSelectedOnly = 0; ParseUBOOL( Str, TEXT("SELECTEDONLY="), bSelectedOnly ); UExporter::ExportToFile( Level, NULL, TempFname, bSelectedOnly ); GWarn->EndSlowTask(); } else Ar.Log(NAME_ExecWarning,TEXT("Missing filename")); return 1; } else if (ParseCommand (&Str,TEXT("SETBRUSH"))) // MAP SETBRUSH (set properties of all selected brushes) { Trans->Begin( TEXT("Set Brush Properties") ); Word1 = 0; // Properties mask INT DWord1 = 0; // Set flags INT DWord2 = 0; // Clear flags INT CSGOper = 0; // CSG Operation INT DrawType = 0; // Draw type FName GroupName=NAME_None; if (Parse(Str,TEXT("CSGOPER="),CSGOper)) Word1 |= MSB_CSGOper; if (Parse(Str,TEXT("COLOR="),Word2)) Word1 |= MSB_BrushColor; if (Parse(Str,TEXT("GROUP="),GroupName)) Word1 |= MSB_Group; if (Parse(Str,TEXT("SETFLAGS="),DWord1)) Word1 |= MSB_PolyFlags; if (Parse(Str,TEXT("CLEARFLAGS="),DWord2)) Word1 |= MSB_PolyFlags; mapSetBrush(Level,(EMapSetBrushFlags)Word1,Word2,GroupName,DWord1,DWord2,CSGOper,DrawType); Trans->End(); RedrawLevel(Level); return 1; } else if (ParseCommand (&Str,TEXT("CHECK"))) { // Checks the map for common errors GWarn->MapCheck_Show(); GWarn->MapCheck_Clear(); GWarn->BeginSlowTask( TEXT("Checking map"), 1); for( INT i=0; i<GEditor->Level->Actors.Num(); i++ ) { GWarn->StatusUpdatef( 0, i, TEXT("Checking map") ); AActor* pActor = GEditor->Level->Actors(i); if( pActor ) pActor->CheckForErrors(); } GWarn->EndSlowTask(); return 1; } else if (ParseCommand (&Str,TEXT("SCALE"))) { FLOAT Factor = 1; if( !Parse(Str,TEXT("FACTOR="),Factor) ) return 0; Trans->Begin( TEXT("Map Scaling") ); UBOOL bAdjustLights=0; ParseUBOOL( Str, TEXT("ADJUSTLIGHTS="), bAdjustLights ); UBOOL bScaleSprites=0; ParseUBOOL( Str, TEXT("SCALESPRITES="), bScaleSprites ); UBOOL bScaleLocations=0; ParseUBOOL( Str, TEXT("SCALELOCATIONS="), bScaleLocations ); UBOOL bScaleCollision=0; ParseUBOOL( Str, TEXT("SCALECOLLISION="), bScaleCollision ); GWarn->BeginSlowTask( TEXT("Scaling"), 1); NoteActorMovement( Level ); for( INT i=0; i<GEditor->Level->Actors.Num(); i++ ) { GWarn->StatusUpdatef( 0, i, TEXT("Scaling") ); AActor* Actor = GEditor->Level->Actors(i); if( Actor && GSelectionTools.IsSelected( Actor ) ) { Actor->PreEditChange(); Actor->Modify(); if( Actor->IsBrush() ) { ABrush* Brush = Cast<ABrush>(Actor); Brush->Brush->Polys->Element.ModifyAllItems(); for( INT poly = 0 ; poly < Brush->Brush->Polys->Element.Num() ; poly++ ) { FPoly* Poly = &(Brush->Brush->Polys->Element(poly)); Poly->TextureU /= Factor; Poly->TextureV /= Factor; Poly->Base = ((Poly->Base - Brush->PrePivot) * Factor) + Brush->PrePivot; for( INT vtx = 0 ; vtx < Poly->NumVertices ; vtx++ ) Poly->Vertex[vtx] = ((Poly->Vertex[vtx] - Brush->PrePivot) * Factor) + Brush->PrePivot; Poly->CalcNormal(); } Brush->Brush->BuildBound(); } else { Actor->DrawScale *= Factor; } if( bScaleLocations ) { Actor->Location.X *= Factor; Actor->Location.Y *= Factor; Actor->Location.Z *= Factor; } if( bScaleCollision ) { // JAG_COLRADIUS_HACK //Actor->CollisionHeight *= Factor; //Actor->CollisionRadius *= Factor; } Actor->PostEditChange(NULL); } } GWarn->EndSlowTask(); Trans->End(); return 1; } return 0; } UBOOL UEditorEngine::Exec_Select( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("NONE")) ) { Trans->Begin( TEXT("Select None") ); SelectNone( Level, 1 ); Trans->End(); RedrawLevel( Level ); return 1; } return 0; } UBOOL UEditorEngine::Exec_Poly( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("SELECT")) ) // POLY SELECT [ALL/NONE/INVERSE] FROM [LEVEL/SOLID/GROUP/ITEM/ADJACENT/MATCHING] { appSprintf( TempStr, TEXT("POLY SELECT %s"), Str ); if( ParseCommand(&Str,TEXT("NONE")) ) { return Exec( TEXT("SELECT NONE") ); } else if( ParseCommand(&Str,TEXT("ALL")) ) { Trans->Begin( TempStr ); SelectNone( Level, 0 ); polySelectAll( Level->Model ); NoteSelectionChange( Level ); Trans->End(); return 1; } else if( ParseCommand(&Str,TEXT("REVERSE")) ) { Trans->Begin( TempStr ); polySelectReverse (Level->Model); GCallback->Send( CALLBACK_SelChange ); Trans->End(); return 1; } else if( ParseCommand(&Str,TEXT("MATCHING")) ) { Trans->Begin( TempStr ); if (ParseCommand(&Str,TEXT("GROUPS"))) polySelectMatchingGroups(Level->Model); else if (ParseCommand(&Str,TEXT("ITEMS"))) polySelectMatchingItems(Level->Model); else if (ParseCommand(&Str,TEXT("BRUSH"))) polySelectMatchingBrush(Level->Model); else if (ParseCommand(&Str,TEXT("TEXTURE"))) polySelectMatchingTexture(Level->Model); GCallback->Send( CALLBACK_SelChange ); Trans->End(); return 1; } else if( ParseCommand(&Str,TEXT("ADJACENT")) ) { Trans->Begin( TempStr ); if (ParseCommand(&Str,TEXT("ALL"))) polySelectAdjacents( Level->Model ); else if (ParseCommand(&Str,TEXT("COPLANARS"))) polySelectCoplanars( Level->Model ); else if (ParseCommand(&Str,TEXT("WALLS"))) polySelectAdjacentWalls( Level->Model ); else if (ParseCommand(&Str,TEXT("FLOORS"))) polySelectAdjacentFloors( Level->Model ); else if (ParseCommand(&Str,TEXT("CEILINGS"))) polySelectAdjacentFloors( Level->Model ); else if (ParseCommand(&Str,TEXT("SLANTS"))) polySelectAdjacentSlants( Level->Model ); GCallback->Send( CALLBACK_SelChange ); Trans->End(); return 1; } else if( ParseCommand(&Str,TEXT("MEMORY")) ) { Trans->Begin( TempStr ); if (ParseCommand(&Str,TEXT("SET"))) polyMemorizeSet( Level->Model ); else if (ParseCommand(&Str,TEXT("RECALL"))) polyRememberSet( Level->Model ); else if (ParseCommand(&Str,TEXT("UNION"))) polyUnionSet( Level->Model ); else if (ParseCommand(&Str,TEXT("INTERSECT"))) polyIntersectSet( Level->Model ); else if (ParseCommand(&Str,TEXT("XOR"))) polyXorSet( Level->Model ); GCallback->Send( CALLBACK_SelChange ); Trans->End(); return 1; } else if( ParseCommand(&Str,TEXT("ZONE")) ) { Trans->Begin( TempStr ); polySelectZone(Level->Model); GCallback->Send( CALLBACK_SelChange ); Trans->End(); return 1; } RedrawLevel(Level); } else if( ParseCommand(&Str,TEXT("DEFAULT")) ) // POLY DEFAULT <variable>=<value>... { //CurrentMaterial=NULL; //ParseObject<UMaterial>(Str,TEXT("TEXTURE="),CurrentMaterial,ANY_PACKAGE); return 1; } else if( ParseCommand(&Str,TEXT("EXTRUDE")) ) // POLY EXTRUDE DEPTH=<value> { Trans->Begin( TEXT("Poly Extrude") ); INT Depth; Parse( Str, TEXT("DEPTH="), Depth ); Level->Modify(); // Get a list of all the selected polygons. TArray<FPoly> SelectedPolys; // The selected polygons. TArray<ABrush*> ActorList; // The actors that own the polys (in synch with SelectedPolys) for( INT x = 0 ; x < Level->Model->Surfs.Num() ; x++ ) { FBspSurf* Surf = &(Level->Model->Surfs(x)); check(Surf->Actor); if( Surf->PolyFlags & PF_Selected ) { FPoly Poly; if( polyFindMaster( Level->Model, x, Poly ) ) { new( SelectedPolys )FPoly( Poly ); ActorList.AddItem( Surf->Actor ); } } } for( INT x = 0 ; x < SelectedPolys.Num() ; x++ ) { ActorList(x)->Brush->Polys->Element.ModifyAllItems(); // Find all the polys which are linked to create this surface. TArray<FPoly> PolyList; polyGetLinkedPolys( (ABrush*)ActorList(x), &SelectedPolys(x), &PolyList ); // Get a list of the outer edges of this surface. TArray<FEdge> EdgeList; polyGetOuterEdgeList( &PolyList, &EdgeList ); // Create new polys from the edges of the selected surface. for( INT edge = 0 ; edge < EdgeList.Num() ; edge++ ) { FEdge* Edge = &EdgeList(edge); FVector v1 = Edge->Vertex[0], v2 = Edge->Vertex[1]; FPoly NewPoly; NewPoly.Init(); NewPoly.NumVertices = 4; NewPoly.Vertex[0] = v1; NewPoly.Vertex[1] = v2; NewPoly.Vertex[2] = v2 + (SelectedPolys(x).Normal * Depth); NewPoly.Vertex[3] = v1 + (SelectedPolys(x).Normal * Depth); new(ActorList(x)->Brush->Polys->Element)FPoly( NewPoly ); } // Create the cap polys. for( INT pl = 0 ; pl < PolyList.Num() ; pl++ ) { FPoly* PolyFromList = &PolyList(pl); for( INT poly = 0 ; poly < ActorList(x)->Brush->Polys->Element.Num() ; poly++ ) if( *PolyFromList == ActorList(x)->Brush->Polys->Element(poly) ) { FPoly* Poly = &(ActorList(x)->Brush->Polys->Element(poly)); for( INT vtx = 0 ; vtx < Poly->NumVertices ; vtx++ ) Poly->Vertex[vtx] += (SelectedPolys(x).Normal * Depth); break; } } // Clean up the polys. for( INT poly = 0 ; poly < ActorList(x)->Brush->Polys->Element.Num() ; poly++ ) { FPoly* Poly = &(ActorList(x)->Brush->Polys->Element(poly)); Poly->iLink = poly; Poly->Normal = FVector(0,0,0); Poly->Finalize(ActorList(x),0); Poly->Base = Poly->Vertex[0]; } ActorList(x)->Brush->BuildBound(); } GCallback->Send( CALLBACK_RedrawAllViewports ); Trans->End(); } else if( ParseCommand(&Str,TEXT("BEVEL")) ) // POLY BEVEL DEPTH=<value> BEVEL=<value> { Trans->Begin( TEXT("Poly Bevel") ); INT Depth, Bevel; Parse( Str, TEXT("DEPTH="), Depth ); Parse( Str, TEXT("BEVEL="), Bevel ); Level->Modify(); // Get a list of all the selected polygons. TArray<FPoly> SelectedPolys; // The selected polygons. TArray<ABrush*> ActorList; // The actors that own the polys (in synch with SelectedPolys) for( INT x = 0 ; x < Level->Model->Surfs.Num() ; x++ ) { FBspSurf* Surf = &(Level->Model->Surfs(x)); check(Surf->Actor); if( Surf->PolyFlags & PF_Selected ) { FPoly Poly; if( polyFindMaster( Level->Model, x, Poly ) ) { new( SelectedPolys )FPoly( Poly ); ActorList.AddItem( Surf->Actor ); } } } for( INT x = 0 ; x < SelectedPolys.Num() ; x++ ) { ActorList(x)->Brush->Polys->Element.ModifyAllItems(); // Find all the polys which are linked to create this surface. TArray<FPoly> PolyList; polyGetLinkedPolys( (ABrush*)ActorList(x), &SelectedPolys(x), &PolyList ); // Get a list of the outer edges of this surface. TArray<FEdge> EdgeList; polyGetOuterEdgeList( &PolyList, &EdgeList ); // Figure out where the center of the poly is. FVector PolyCenter = FVector(0,0,0); for( INT edge = 0 ; edge < EdgeList.Num() ; edge++ ) PolyCenter += EdgeList(edge).Vertex[0]; PolyCenter /= EdgeList.Num(); // Create new polys from the edges of the selected surface. for( INT edge = 0 ; edge < EdgeList.Num() ; edge++ ) { FEdge* Edge = &EdgeList(edge); FVector v1 = Edge->Vertex[0], v2 = Edge->Vertex[1]; FPoly NewPoly; NewPoly.Init(); NewPoly.NumVertices = 4; NewPoly.Vertex[0] = v1; NewPoly.Vertex[1] = v2; FVector CenterDir = PolyCenter - v2; CenterDir.Normalize(); NewPoly.Vertex[2] = v2 + (SelectedPolys(x).Normal * Depth) + (CenterDir * Bevel); CenterDir = PolyCenter - v1; CenterDir.Normalize(); NewPoly.Vertex[3] = v1 + (SelectedPolys(x).Normal * Depth) + (CenterDir * Bevel); new(ActorList(x)->Brush->Polys->Element)FPoly( NewPoly ); } // Create the cap polys. for( INT pl = 0 ; pl < PolyList.Num() ; pl++ ) { FPoly* PolyFromList = &PolyList(pl); for( INT poly = 0 ; poly < ActorList(x)->Brush->Polys->Element.Num() ; poly++ ) if( *PolyFromList == ActorList(x)->Brush->Polys->Element(poly) ) { FPoly* Poly = &(ActorList(x)->Brush->Polys->Element(poly)); for( INT vtx = 0 ; vtx < Poly->NumVertices ; vtx++ ) { FVector CenterDir = PolyCenter - Poly->Vertex[vtx]; CenterDir.Normalize(); Poly->Vertex[vtx] += (CenterDir * Bevel); Poly->Vertex[vtx] += (SelectedPolys(x).Normal * Depth); } break; } } // Clean up the polys. for( INT poly = 0 ; poly < ActorList(x)->Brush->Polys->Element.Num() ; poly++ ) { FPoly* Poly = &(ActorList(x)->Brush->Polys->Element(poly)); Poly->iLink = poly; Poly->Normal = FVector(0,0,0); Poly->Finalize(ActorList(x),0); Poly->Base = Poly->Vertex[0]; } ActorList(x)->Brush->BuildBound(); } GCallback->Send( CALLBACK_RedrawAllViewports ); Trans->End(); } else if( ParseCommand(&Str,TEXT("SETMATERIAL")) ) { Trans->Begin( TEXT("Poly SetMaterial") ); Level->Model->ModifySelectedSurfs(1); for( INT Index1=0; Index1<Level->Model->Surfs.Num(); Index1++ ) { if( Level->Model->Surfs(Index1).PolyFlags & PF_Selected ) { Level->Model->Surfs(Index1).Material = GSelectionTools.GetTop<UMaterialInstance>(); polyUpdateMaster( Level->Model, Index1, 0 ); } } Trans->End(); RedrawLevel(Level); return 1; } else if( ParseCommand(&Str,TEXT("SET")) ) // POLY SET <variable>=<value>... { Trans->Begin( TEXT("Poly Set") ); Level->Model->ModifySelectedSurfs( 1 ); DWORD Ptr; if( !Parse(Str,TEXT("TEXTURE="),Ptr) ) Ptr = 0; UMaterialInstance* Material = (UMaterialInstance*)Ptr; if( Material ) { for( INT x = 0 ; x < Level->Model->Surfs.Num() ; ++x ) { if( Level->Model->Surfs(x).PolyFlags & PF_Selected ) { Level->Model->Surfs(x).Material = Material; polyUpdateMaster( Level->Model, x, 0 ); } } } Word4 = 0; INT DWord1 = 0; INT DWord2 = 0; if (Parse(Str,TEXT("SETFLAGS="),DWord1)) Word4=1; if (Parse(Str,TEXT("CLEARFLAGS="),DWord2)) Word4=1; if (Word4) polySetAndClearPolyFlags (Level->Model,DWord1,DWord2,1,1); // Update selected polys' flags Trans->End(); RedrawLevel(Level); return 1; } else if( ParseCommand(&Str,TEXT("TEXSCALE")) ) // POLY TEXSCALE [U=..] [V=..] [UV=..] [VU=..] { Trans->Begin( TEXT("Poly Texscale") ); Level->Model->ModifySelectedSurfs( 1 ); Word2 = 1; // Scale absolute if( ParseCommand(&Str,TEXT("RELATIVE")) ) Word2=0; TexScale: // Ensure each polygon has unique texture vector indices. for(INT SurfaceIndex = 0;SurfaceIndex < Level->Model->Surfs.Num();SurfaceIndex++) { FBspSurf& Surf = Level->Model->Surfs(SurfaceIndex); if(Surf.PolyFlags & PF_Selected) { FVector TextureU = Level->Model->Vectors(Surf.vTextureU), TextureV = Level->Model->Vectors(Surf.vTextureV); Surf.vTextureU = Level->Model->Vectors.AddItem(TextureU); Surf.vTextureV = Level->Model->Vectors.AddItem(TextureV); } } FLOAT UU,UV,VU,VV; UU=1.0; Parse (Str,TEXT("UU="),UU); UV=0.0; Parse (Str,TEXT("UV="),UV); VU=0.0; Parse (Str,TEXT("VU="),VU); VV=1.0; Parse (Str,TEXT("VV="),VV); polyTexScale( Level->Model, UU, UV, VU, VV, Word2 ); Trans->End(); RedrawLevel( Level ); return 1; } else if( ParseCommand(&Str,TEXT("TEXMULT")) ) // POLY TEXMULT [U=..] [V=..] { Trans->Begin( TEXT("Poly Texmult") ); Level->Model->ModifySelectedSurfs( 1 ); Word2 = 0; // Scale relative; goto TexScale; } else if( ParseCommand(&Str,TEXT("TEXPAN")) ) // POLY TEXPAN [RESET] [U=..] [V=..] { Trans->Begin( TEXT("Poly Texpan") ); Level->Model->ModifySelectedSurfs( 1 ); // Ensure each polygon has a unique base point index. for(INT SurfaceIndex = 0;SurfaceIndex < Level->Model->Surfs.Num();SurfaceIndex++) { FBspSurf& Surf = Level->Model->Surfs(SurfaceIndex); if(Surf.PolyFlags & PF_Selected) { FVector Base = Level->Model->Points(Surf.pBase); Surf.pBase = Level->Model->Points.AddItem(Base); } } if( ParseCommand (&Str,TEXT("RESET")) ) polyTexPan( Level->Model, 0, 0, 1 ); INT PanU = 0; Parse (Str,TEXT("U="),PanU); INT PanV = 0; Parse (Str,TEXT("V="),PanV); polyTexPan( Level->Model, PanU, PanV, 0 ); Trans->End(); RedrawLevel( Level ); return 1; } return 0; } UBOOL UEditorEngine::Exec_Transaction( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("UNDO")) ) { if( Trans->Undo() ) { RedrawLevel( Level ); } GCallback->Send( CALLBACK_Undo ); return 1; } else if( ParseCommand(&Str,TEXT("REDO")) ) { if( Trans->Redo() ) { RedrawLevel(Level); } GCallback->Send( CALLBACK_Undo ); return 1; } return 0; } UBOOL UEditorEngine::Exec_Obj( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("EXPORT")) )//oldver { FName Package=NAME_None; UClass* Type; UObject* Res; Parse( Str, TEXT("PACKAGE="), Package ); if ( ParseObject<UClass>( Str, TEXT("TYPE="), Type, ANY_PACKAGE ) && Parse( Str, TEXT("FILE="), TempFname, 256 ) && ParseObject( Str, TEXT("NAME="), Type, Res, ANY_PACKAGE ) ) { for( FObjectIterator It; It; ++It ) It->ClearFlags( RF_TagImp | RF_TagExp ); UExporter* Exporter = UExporter::FindExporter( Res, appFExt(TempFname) ); if( Exporter ) { Exporter->ParseParms( Str ); UExporter::ExportToFile( Res, Exporter, TempFname, 0 ); delete Exporter; } } else Ar.Log( NAME_ExecWarning, TEXT("Missing file, name, or type") ); return 1; } else if( ParseCommand(&Str,TEXT("SavePackage")) ) { UPackage* Pkg; UBOOL bSilent; if ( Parse( Str, TEXT("FILE="), TempFname, 256 ) && ParseObject<UPackage>( Str, TEXT("Package="), Pkg, NULL ) ) { ParseUBOOL( Str, TEXT("SILENT="), bSilent ); FString SpacesTest = TempFname; if( SpacesTest.InStr( TEXT(" ") ) != INDEX_NONE ) if( appMsgf( 0, TEXT("The filename you specified has one or more spaces in it. Unreal filenames cannot contain spaces.") ) ) return 0; if( !bSilent ) { GWarn->BeginSlowTask( TEXT("Saving package"), 1); GWarn->StatusUpdatef( 1, 1, TEXT("Saving package...") ); } SavePackage( Pkg, NULL, RF_Standalone, TempFname, GWarn ); Pkg->bDirty = 0; if( !bSilent ) GWarn->EndSlowTask(); } else Ar.Log( NAME_ExecWarning, TEXT("Missing filename") ); return 1; } else if( ParseCommand(&Str,TEXT("Rename")) ) { UObject* Object=NULL; UObject* OldPackage=NULL, *OldGroup=NULL; FString NewName, NewGroup, NewPackage; ParseObject<UObject>( Str, TEXT("OLDPACKAGE="), OldPackage, NULL ); ParseObject<UObject>( Str, TEXT("OLDGROUP="), OldGroup, OldPackage ); Cast<UPackage>(OldPackage)->bDirty = 1; if( OldGroup ) OldPackage = OldGroup; ParseObject<UObject>( Str, TEXT("OLDNAME="), Object, OldPackage ); Parse( Str, TEXT("NEWPACKAGE="), NewPackage ); UPackage* Pkg = CreatePackage(NULL,*NewPackage); Pkg->bDirty = 1; if( Parse(Str,TEXT("NEWGROUP="),NewGroup) && NewGroup!=NAME_None ) Pkg = CreatePackage( Pkg, *NewGroup ); Parse( Str, TEXT("NEWNAME="), NewName ); if( Object ) { Object->Rename( *NewName, Pkg ); Object->SetFlags(RF_Public|RF_Standalone); } return 1; } return 0; } UBOOL UEditorEngine::Exec_Class( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("SPEW")) ) { GWarn->BeginSlowTask( TEXT("Exporting scripts"), 0); UObject* Package = NULL; ParseObject( Str, TEXT("PACKAGE="), Package, ANY_PACKAGE ); for( TObjectIterator<UClass> It; It; ++It ) { if( It->ScriptText ) { // Check package if( Package ) { UObject* Outer = It->GetOuter(); while( Outer && Outer->GetOuter() ) Outer = Outer->GetOuter(); if( Outer != Package ) continue; } // Create directory. FString Directory = appGameDir() + TEXT("ExportedScript\\") + It->GetOuter()->GetName() + TEXT("\\Classes\\"); GFileManager->MakeDirectory( *Directory, 1 ); // Save file. FString Filename = Directory + It->GetName() + TEXT(".uc"); debugf( NAME_Log, TEXT("Spewing: %s"), Filename ); UExporter::ExportToFile( *It, NULL, *Filename, 0 ); } } GWarn->EndSlowTask(); return 1; } return 0; } UBOOL UEditorEngine::Exec_Camera( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("ALIGN") ) ) { // select the named actor if( Parse( Str, TEXT("NAME="), TempStr, NAME_SIZE ) ) { AActor* Actor = NULL; for( INT i=0; i<Level->Actors.Num(); i++ ) { Actor = Level->Actors(i); if( Actor && appStricmp( Actor->GetName(), TempStr ) == 0 && Actor!=Level->GetLevelInfo() ) { if (Actor->IsHiddenEd()) { GSelectionTools.Select( Actor, 1 ); } else { SelectActor(Level,Actor,1); } break; } } } FVector NewLocation; if( Parse( Str, TEXT("X="), NewLocation.X ) ) { Parse( Str, TEXT("Y="), NewLocation.Y ); Parse( Str, TEXT("Z="), NewLocation.Z ); for( INT i = 0; i < ViewportClients.Num(); i++ ) { ViewportClients(i)->ViewLocation = NewLocation; } } else { // find the first selected actor as the target for the viewport cameras AActor* Target = NULL; for( INT i = 0; i < Level->Actors.Num(); i++ ) { if( Level->Actors(i) && GSelectionTools.IsSelected( Level->Actors(i) ) ) { Target = Level->Actors(i); break; } } if( Target == NULL ) { Ar.Log( TEXT("Can't find target (viewport or selected actor)") ); return 0; } // move all viewport cameras to the target actor FVector camLocation = Target->Location; // @todo attempt to find a good viewpoint for this actor camLocation += Target->Rotation.Vector() * -128.f + FVector(0,0,1) * 128.f; // and point the camera at the actor FRotator camRotation = (Target->Location-camLocation).Rotation(); // and update all the viewports for( INT i = 0; i < ViewportClients.Num(); i++ ) { if(ViewportClients(i)->GetLevel() == Level) { if (ViewportClients(i)->IsOrtho()) { ViewportClients(i)->ViewLocation = Target->Location; } else { ViewportClients(i)->ViewLocation = camLocation; ViewportClients(i)->ViewRotation = camRotation; } } } } Ar.Log( TEXT("Aligned camera on the current target.") ); RedrawAllViewports(1); NoteSelectionChange( Level ); return 1; } else if( ParseCommand(&Str,TEXT("SELECT") ) ) { if( Parse( Str, TEXT("NAME="), TempStr,NAME_SIZE ) ) { AActor* Actor = NULL; for( INT i=0; i<Level->Actors.Num(); i++ ) { Actor = Level->Actors(i); if( Actor && appStrcmp( Actor->GetName(), TempStr ) == 0 ) { SelectActor( Level, Actor, 1, 0 ); break; } } if( Actor == NULL ) { Ar.Log( TEXT("Can't find the specified name.") ); return 0; } for( INT i = 0; i < ViewportClients.Num(); i++ ) { if(ViewportClients(i)->GetLevel() == Level) ViewportClients(i)->ViewLocation = Actor->Location - ViewportClients(i)->ViewRotation.Vector() * 48; } Ar.Log( TEXT("Aligned camera on named object.") ); NoteSelectionChange( Level ); return 1; } } return 0; } UBOOL UEditorEngine::Exec_Level( const TCHAR* Str, FOutputDevice& Ar ) { if( ParseCommand(&Str,TEXT("REDRAW")) ) { RedrawLevel(Level); return 1; } else if( ParseCommand(&Str,TEXT("LINKS")) ) { Results->Text.Empty(); INT Internal=0,External=0; Results->Logf( TEXT("Level links:\r\n") ); for( INT i=0; i<Level->Actors.Num(); i++ ) { if( Cast<ATeleporter>(Level->Actors(i)) ) { ATeleporter& Teleporter = *(ATeleporter *)Level->Actors(i); Results->Logf( TEXT(" %s\r\n"), *Teleporter.URL ); if( appStrchr(*Teleporter.URL,'//') ) External++; else Internal++; } } Results->Logf( TEXT("End, %i internal link(s), %i external.\r\n"), Internal, External ); return 1; } else if( ParseCommand(&Str,TEXT("VALIDATE")) ) { // Validate the level. Results->Text.Empty(); Results->Log( TEXT("Level validation:\r\n") ); // Make sure it's not empty. if( Level->Model->Nodes.Num() == 0 ) { Results->Log( TEXT("Error: Level is empty!\r\n") ); return 1; } // Find playerstart. INT i; for( i=0; i<Level->Actors.Num(); i++ ) if( Cast<APlayerStart>(Level->Actors(i)) ) break; if( i == Level->Actors.Num() ) { Results->Log( TEXT("Error: Missing PlayerStart actor!\r\n") ); return 1; } // Make sure PlayerStarts are outside. for( i=0; i<Level->Actors.Num(); i++ ) { if( Cast<APlayerStart>(Level->Actors(i)) ) { FCheckResult Hit(0.0f); if( !Level->Model->PointCheck( Hit, NULL, Level->Actors(i)->Location, FVector(0.f,0.f,0.f) ) ) { Results->Log( TEXT("Error: PlayerStart doesn't fit!\r\n") ); return 1; } } } // Check level title. if( Level->GetLevelInfo()->Title==TEXT("") ) { Results->Logf( TEXT("Error: Level is missing a title!") ); return 1; } else if( Level->GetLevelInfo()->Title==TEXT("Untitled") ) { Results->Logf( TEXT("Warning: Level is untitled\r\n") ); } // Check actors. for( i=0; i<Level->Actors.Num(); i++ ) { AActor* Actor = Level->Actors(i); if( Actor ) { check(Actor->GetClass()!=NULL); check(Actor->GetStateFrame()); check(Actor->GetStateFrame()->Object==Actor); check(Actor->Level!=NULL); check(Actor->GetLevel()!=NULL); check(Actor->GetLevel()==Level); check(Actor->GetLevel()->Actors(0)!=NULL); check(Actor->GetLevel()->Actors(0)==Actor->Level); } } // Success. Results->Logf( TEXT("Success: Level validation succeeded!\r\n") ); return 1; } return 0; } // // Process an incoming network message meant for the editor server // UBOOL UEditorEngine::Exec( const TCHAR* Stream, FOutputDevice& Ar ) { //debugf("GEditor Exec: %s",Stream); TCHAR CommandTemp[MAX_EDCMD]; TCHAR ErrorTemp[256]=TEXT("Setup: "); UBOOL Processed=0; // Echo the command to the log window if( appStrlen(Stream)<200 ) { appStrcat( ErrorTemp, Stream ); debugf( NAME_Cmd, Stream ); } GStream = Stream; GBrush = Level ? Level->Brush()->Brush : NULL; appStrncpy( CommandTemp, Stream, 512 ); const TCHAR* Str = &CommandTemp[0]; appStrncpy( ErrorTemp, Str, 79 ); ErrorTemp[79]=0; if( SafeExec( Stream, Ar ) ) { return 1; } //------------------------------------------------------------------------------------ // MISC // else if( ParseCommand(&Str,TEXT("EDCALLBACK")) ) { if( ParseCommand(&Str,TEXT("SURFPROPS")) ) GCallback->Send( CALLBACK_SurfProps ); else if( ParseCommand(&Str,TEXT("ACTORPROPS")) ) GCallback->Send( CALLBACK_ActorProps ); } else if(ParseCommand(&Str,TEXT("STATICMESH"))) { if( Exec_StaticMesh( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // BRUSH // else if( ParseCommand(&Str,TEXT("BRUSH")) ) { if( Exec_Brush( Str, Ar ) ) return 1; } //---------------------------------------------------------------------------------- // PATHS // else if( ParseCommand(&Str,TEXT("PATHS")) ) { if( Exec_Paths( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // BSP // else if( ParseCommand( &Str, TEXT("BSP") ) ) { if( Exec_BSP( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // LIGHT // else if( ParseCommand( &Str, TEXT("LIGHT") ) ) { if( Exec_Light( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // MAP // else if (ParseCommand(&Str,TEXT("MAP"))) { if( Exec_Map( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // SELECT: Rerouted to mode-specific command // else if( ParseCommand(&Str,TEXT("SELECT")) ) { if( Exec_Select( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // DELETE: Rerouted to mode-specific command // else if (ParseCommand(&Str,TEXT("DELETE"))) { // Give the current mode a chance to handle this command. If it doesn't, // do the default processing. if( !GEditorModeTools.GetCurrentMode()->ExecDelete() ) { return Exec( TEXT("ACTOR DELETE") ); } return 1; } //------------------------------------------------------------------------------------ // DUPLICATE: Rerouted to mode-specific command // else if (ParseCommand(&Str,TEXT("DUPLICATE"))) { return Exec( TEXT("ACTOR DUPLICATE") ); } //------------------------------------------------------------------------------------ // POLY: Polygon adjustment and mapping // else if( ParseCommand(&Str,TEXT("POLY")) ) { if( Exec_Poly( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // ANIM: All mesh/animation management. // else if( ParseCommand(&Str,TEXT("NEWANIM")) ) { appErrorf(TEXT("Deprecated command executed: %s"),Str); } //------------------------------------------------------------------------------------ // Transaction tracking and control // else if( ParseCommand(&Str,TEXT("TRANSACTION")) ) { if( Exec_Transaction( Str, Ar ) ) { NoteSelectionChange( Level ); GCallback->Send( CALLBACK_MapChange, 1 ); return 1; } } //------------------------------------------------------------------------------------ // General objects // else if( ParseCommand(&Str,TEXT("OBJ")) ) { if( Exec_Obj( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // CLASS functions // else if( ParseCommand(&Str,TEXT("CLASS")) ) { if( Exec_Class( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // CAMERA: cameras // else if( ParseCommand(&Str,TEXT("CAMERA")) ) { if( Exec_Camera( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // LEVEL // if( ParseCommand(&Str,TEXT("LEVEL")) ) { if( Exec_Level( Str, Ar ) ) return 1; } //------------------------------------------------------------------------------------ // Other handlers. // else if( Level && Level->Exec(Stream,Ar) ) { // The level handled it. Processed = 1; } else if( UEngine::Exec(Stream,Ar) ) { // The engine handled it. Processed = 1; } else if( ParseCommand(&Str,TEXT("SELECTNAME")) ) { FName FindName=NAME_None; Parse( Str, TEXT("NAME="), FindName ); for( INT i=0; i<Level->Actors.Num(); i++ ) if( Level->Actors(i) ) SelectActor( Level, Level->Actors(i), Level->Actors(i)->GetFName()==FindName, 0 ); Processed = 1; } else if( ParseCommand(&Str,TEXT("DUMPINT")) ) { while( *Str==' ' ) Str++; UObject* Pkg = LoadPackage( NULL, Str, LOAD_AllowDll ); if( Pkg ) { TCHAR Tmp[512],Loc[512]; appStrcpy( Tmp, Str ); if( appStrchr(Tmp,'.') ) *appStrchr(Tmp,'.') = 0; appStrcat( Tmp, TEXT(".int") ); appStrcpy( Loc, appBaseDir() ); appStrcat( Loc, Tmp ); for( FObjectIterator It; It; ++It ) { if( It->IsIn(Pkg) ) { UClass* Class = Cast<UClass>( *It ); if( Class ) { if( Class->ClassFlags&CLASS_Localized ) { // Generate localizable class defaults. for( TFieldIterator<UProperty> ItP(Class); ItP; ++ItP ) { if( ItP->PropertyFlags & CPF_Localized ) { for( INT i=0; i<ItP->ArrayDim; i++ ) { FString Value; if( ItP->ExportText( i, Value, &Class->Defaults(0), ItP->GetOuter()!=Class ? &Class->GetSuperClass()->Defaults(0) : NULL, Class, 0 ) ) { FString Key; if( ItP->ArrayDim!=1 ) Key = FString::Printf( TEXT("%s[%i]"), ItP->GetName(), i ); else Key = ItP->GetName(); // Put strings with whitespace in quotes. if(Value.InStr(TEXT(" ")) != INDEX_NONE || Value.InStr(TEXT("\t")) != INDEX_NONE) Value = FString::Printf(TEXT("\"%s\""),*Value); GConfig->SetString( Class->GetName(), *Key, *Value, Loc ); } } } } } } else { if( It->GetClass()->ClassFlags&CLASS_Localized ) { // Generate localizable object properties. for( TFieldIterator<UProperty> ItP(It->GetClass()); ItP; ++ItP ) { if( ItP->PropertyFlags & CPF_Localized ) { for( INT i=0; i<ItP->ArrayDim; i++ ) { FString Value; if( ItP->ExportText( i, Value, (BYTE*)*It, &It->GetClass()->Defaults(0), *It, 0 ) ) { FString Key; if( ItP->ArrayDim!=1 ) Key = FString::Printf( TEXT("%s[%i]"), ItP->GetName(), i ); else Key = ItP->GetName(); // Put strings with whitespace in quotes. if(Value.InStr(TEXT(" ")) != INDEX_NONE || Value.InStr(TEXT("\t")) != INDEX_NONE) Value = FString::Printf(TEXT("\"%s\""),*Value); GConfig->SetString( Class->GetName(), *Key, *Value, Loc ); } } } } } } } } GConfig->Flush( 0 ); Ar.Logf( TEXT("Generated %s"), Loc ); } else Ar.Logf( TEXT("LoadPackage failed") ); return 1; } else if( ParseCommand(&Str,TEXT("JUMPTO")) ) { TCHAR A[32], B[32], C[32]; ParseToken( Str, A, ARRAY_COUNT(A), 0 ); ParseToken( Str, B, ARRAY_COUNT(B), 0 ); ParseToken( Str, C, ARRAY_COUNT(C), 0 ); for( INT i=0; i<ViewportClients.Num(); i++ ) if(ViewportClients(i)->GetLevel() == Level) ViewportClients(i)->ViewLocation = FVector(appAtoi(A),appAtoi(B),appAtoi(C)); return 1; } else if( ParseCommand(&Str,TEXT("SETCULLDISTANCE")) ) { // SETCULLDISTANCE CULLDISTANCE=<cull distance> // Sets the CullDistance of the selected actors' PrimitiveComponents. FLOAT CullDistance = 0.0f; if( Parse(Str,TEXT("CULLDISTANCE="),CullDistance) ) { for(INT ActorIndex = 0;ActorIndex < Level->Actors.Num();ActorIndex++) { AActor* Actor = Level->Actors(ActorIndex); if(Actor && GSelectionTools.IsSelected(Actor)) { for(INT ComponentIndex = 0;ComponentIndex < Actor->Components.Num();ComponentIndex++) { UPrimitiveComponent* Primitive = Cast<UPrimitiveComponent>(Actor->Components(ComponentIndex)); if(Primitive) { Primitive->CullDistance = CullDistance; } } } } } } return Processed; } /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/
28.482517
183
0.612657
[ "mesh", "geometry", "object", "vector", "model", "transform", "solid" ]
97b760ae166504ee3c622db905c880b91746cdba
3,366
cpp
C++
qpushjet.cpp
weatherhead99/Qpushjet
baf219fbb721d7c404399b0fb7067a4ebe921040
[ "MIT" ]
1
2018-09-10T13:58:35.000Z
2018-09-10T13:58:35.000Z
qpushjet.cpp
weatherhead99/Qpushjet
baf219fbb721d7c404399b0fb7067a4ebe921040
[ "MIT" ]
null
null
null
qpushjet.cpp
weatherhead99/Qpushjet
baf219fbb721d7c404399b0fb7067a4ebe921040
[ "MIT" ]
null
null
null
#include "qpushjet.h" #include <QWidget> #include <QSystemTrayIcon> #include <QMenu> #include <QAction> #include <QIcon> #include <QSettings> #include "device.h" #include <QPushButton> #include <QMessageBox> #include "notifications.h" #include "model.h" #include "client.h" const string RESOURCE_ICON_PATH = ":/resources/pushjet.svg"; qpushjet::qpushjet(QWidget* parent, bool opensettings) : QDialog(parent) { _ui.setupUi(this); _uuid = get_or_create_device_uuid(); _ui.uuidLine->setReadOnly(true); _ui.uuidLine->setText(_uuid.toString()); setuptrayicon(); _systrayicon->show(); _ui.debug_options->setVisible(false); _notifier = new desktop_notifier; _services = new services_model; _ui.serviceTable->setModel(_services); _ui.serverUrl->setText(get_server_url().toString()); connect(_ui.addServiceButton, &QPushButton::pressed, _services, &services_model::addEmptyService); connect(_ui.generateuuidButton, &QPushButton::pressed, this, &qpushjet::new_device_uuid); connect(_ui.buttonBox, &QDialogButtonBox::accepted, this, &qpushjet::savesettings); connect(_ui.buttonBox, &QDialogButtonBox::accepted, _services, &services_model::syncServicesToFile); connect(_ui.buttonBox, &QDialogButtonBox::rejected, this, &qpushjet::revertsettings); if(opensettings) { _settingsaction->trigger(); } } qpushjet::~qpushjet() { if(_notifier) { delete _notifier; } if(_services) { delete _services; } } void qpushjet::setuptrayicon() { _quitaction = new QAction(tr("quit"),this); connect(_quitaction,&QAction::triggered,this,&QApplication::quit); _settingsaction = new QAction(tr("settings..."),this); connect(_settingsaction,&QAction::triggered,this,&QDialog::show); _systrayicon = new QSystemTrayIcon(this); _systraymenu = new QMenu(this); _systraymenu->addAction(_settingsaction); _systraymenu->addAction(_quitaction); _systrayicon->setContextMenu(_systraymenu); _systrayicon->setIcon(QIcon(RESOURCE_ICON_PATH.c_str())); } void qpushjet::new_device_uuid() { QMessageBox::StandardButton areyousure = QMessageBox::question(this, "Confirm new uuid" , "This will create a new device uuid, your old uuid will be lost. Are you sure?", QMessageBox::Yes | QMessageBox::No); if(areyousure == QMessageBox::Yes) { auto newuuid = QUuid::createUuid(); QSettings settings; _ui.uuidLine->setText(newuuid.toString()); } } void qpushjet::savesettings() { QSettings settings; settings.setValue("device/uuid",_ui.uuidLine->text()); settings.setValue("client/apiurl",_ui.serverUrl->text()); } void qpushjet::revertsettings() { QSettings settings; _ui.uuidLine->setText(settings.value("device/uuid").toString()); _ui.serverUrl->setText(settings.value("client/apiurl").toString()); } qpushjet_debugmode::qpushjet_debugmode(QWidget* parent, bool opensettings) : qpushjet(parent,opensettings) { _ui.debug_options->setVisible(true); QObject::connect(_ui.testNotificationButton, &QPushButton::pressed, _notifier, &desktop_notifier::send_test_notify); }
24.042857
147
0.673203
[ "model" ]
b6350e05a8c0f72e27e7f5fa948f6e14a2889f06
16,859
cpp
C++
apps/Autonomous_Carm/autocarm_reproj_jigpts/autocarm_reproj_jigpts_main.cpp
gaocong13/Orthopedic-Robot-Navigation
bf36f7de116c1c99b86c9ba50f111c3796336af0
[ "MIT" ]
13
2021-11-16T08:17:39.000Z
2022-02-11T11:08:55.000Z
apps/Autonomous_Carm/autocarm_reproj_jigpts/autocarm_reproj_jigpts_main.cpp
gaocong13/Orthopedic-Robot-Navigation
bf36f7de116c1c99b86c9ba50f111c3796336af0
[ "MIT" ]
null
null
null
apps/Autonomous_Carm/autocarm_reproj_jigpts/autocarm_reproj_jigpts_main.cpp
gaocong13/Orthopedic-Robot-Navigation
bf36f7de116c1c99b86c9ba50f111c3796336af0
[ "MIT" ]
1
2021-11-16T08:17:42.000Z
2021-11-16T08:17:42.000Z
// STD #include <iostream> #include <vector> #include <fmt/format.h> #include "xregProgOptUtils.h" #include "xregFCSVUtils.h" #include "xregITKIOUtils.h" #include "xregITKLabelUtils.h" #include "xregITKMathOps.h" #include "xregLandmarkMapUtils.h" #include "xregAnatCoordFrames.h" #include "xregH5ProjDataIO.h" #include "xregRayCastProgOpts.h" #include "xregRayCastInterface.h" #include "xregImgSimMetric2DPatchCommon.h" #include "xregImgSimMetric2DGradImgParamInterface.h" #include "xregImgSimMetric2DProgOpts.h" #include "xregHUToLinAtt.h" #include "xregProjPreProc.h" #include "xregCIOSFusionDICOM.h" #include "xregPnPUtils.h" #include "xregMultiObjMultiLevel2D3DRegi.h" #include "xregMultiObjMultiLevel2D3DRegiDebug.h" #include "xregSE3OptVars.h" #include "xregIntensity2D3DRegiExhaustive.h" #include "xregIntensity2D3DRegiCMAES.h" #include "xregIntensity2D3DRegiBOBYQA.h" #include "xregRegi2D3DPenaltyFnSE3Mag.h" #include "xregFoldNormDist.h" #include "xregHipSegUtils.h" #include "xregHDF5.h" #include "xregPAODrawBones.h" #include "xregRigidUtils.h" #include "bigssMath.h" using namespace xreg; constexpr int kEXIT_VAL_SUCCESS = 0; constexpr int kEXIT_VAL_BAD_USE = 1; constexpr bool kSAVE_REGI_DEBUG = true; using size_type = std::size_t; using Pt3 = Eigen::Matrix<CoordScalar,3,1>; using Pt2 = Eigen::Matrix<CoordScalar,2,1>; FrameTransform ConvertSlicerToITK(std::vector<float> slicer_vec){ FrameTransform RAS2LPS; RAS2LPS(0, 0) = -1; RAS2LPS(0, 1) = 0; RAS2LPS(0, 2) = 0; RAS2LPS(0, 3) = 0; RAS2LPS(1, 0) = 0; RAS2LPS(1, 1) = -1;RAS2LPS(1, 2) = 0; RAS2LPS(1, 3) = 0; RAS2LPS(2, 0) = 0; RAS2LPS(2, 1) = 0; RAS2LPS(2, 2) = 1; RAS2LPS(2, 3) = 0; RAS2LPS(3, 0) = 0; RAS2LPS(3, 1) = 0; RAS2LPS(3, 2) = 0; RAS2LPS(3, 3) = 1; FrameTransform ITK_xform; for(size_type idx=0; idx<4; ++idx) { for(size_type idy=0; idy<3; ++idy) { ITK_xform(idy, idx) = slicer_vec[idx*3+idy]; } ITK_xform(3, idx) = 0.0; } ITK_xform(3, 3) = 1.0; ITK_xform= RAS2LPS * ITK_xform * RAS2LPS; float tmp1, tmp2, tmp3; tmp1 = ITK_xform(0,0)*ITK_xform(0,3) + ITK_xform(0,1)*ITK_xform(1,3) + ITK_xform(0,2)*ITK_xform(2,3); tmp2 = ITK_xform(1,0)*ITK_xform(0,3) + ITK_xform(1,1)*ITK_xform(1,3) + ITK_xform(1,2)*ITK_xform(2,3); tmp3 = ITK_xform(2,0)*ITK_xform(0,3) + ITK_xform(2,1)*ITK_xform(1,3) + ITK_xform(2,2)*ITK_xform(2,3); ITK_xform(0,3) = -tmp1; ITK_xform(1,3) = -tmp2; ITK_xform(2,3) = -tmp3; return ITK_xform; } // Manually annotated polaris fiducial marker center in each 2D X-ray image std::vector< std::vector<float> > fid_center_annot{ { 573.5, 1059.5, 799.5, 609.5, 1256.5, 892.5, 949.5, 1233.5 }, { 513.5, 1067.5, 745.5, 593.5, 1193.5, 891.5, 894.5, 1243.5 }, { 509.5, 1076.5, 736.5, 587.5, 1163.5, 890.5, 877.5, 1253.5 }, { 611.5, 1079.5, 826.5, 580.5, 1217.5, 887.5, 954.5, 1257.5 }, { 628.5, 1090.5, 828.5, 575.5, 1190.5, 892.5, 949.5, 1268.5 }, { 900.5, 1082.5, 1066.5, 580.5, 1358.5, 885.5, 1161.5, 1255.5 }, { 1064.5, 1068.5, 1198.5, 578.5, 1427.5, 876.5, 1271.5, 1237.5 }, { 1132.5, 1069.5, 1224.5, 579.5, 1379.5, 875.5, 1271.5, 1232.5 }, { 771.5, 894.5, 987.5, 477.5, 1421.5, 756.5, 1118.5, 1073.5 }, { 306.5, 615.5, 505.5, 161.5, 978.5, 421.5, 688.5, 772.5 }, { 516.5, 1085.5, 698.5, 611.5, 1161.5, 873.5, 903.5, 1238.5 }, { 646.5, 652.5, 879.5, 188.5, 1305.5, 467.5, 1004.5, 813.5 }, { 552.5, 1002.5, 804.5, 553.5, 1204.5, 810.5, 894.5, 1143.5 }, { 453.5, 1009.5, 725.5, 540.5, 1085.5, 809.5, 774.5, 1154.5 }, { 595.5, 1019.5, 865.5, 539.5, 1144.5, 810.5, 857.5, 1162.5 }, { 572.5, 1029.5, 842.5, 525.5, 1045.5, 810.5, 776.5, 1177.5 }, { 596.5, 1043.5, 859.5, 518.5, 986.5, 811.5, 744.5, 1193.5 }, { 577.5, 848.5, 893.5, 351.5, 988.5, 650.5, 708.5, 1007.5 }, { 655.5, 903.5, 976.5, 419.5, 1148.5, 704.5, 845.5, 1052.5 }, { 656.5, 899.5, 974.5, 430.5, 1210.5, 707.5, 893.5, 1046.5 }, { 685.5, 892.5, 993.5, 438.5, 1286.5, 708.5, 959.5, 1035.5 }, { 755.5, 889.5, 1046.5, 451.5, 1395.5, 710.5, 1067.5, 1030.5 }, { 801.5, 1033.5, 1061.5, 583.5, 1440.5, 840.5, 1130.5, 1174.5 }, { 574.5, 1031.5, 817.5, 584.5, 1248.5, 842.5, 935.5, 1175.5 }, { 562.5, 1019.5, 771.5, 594.5, 1228.5, 842.5, 931.5, 1163.5 }, { 383.5, 1006.5, 540.5, 601.5, 994.5, 839.5, 734.5, 1145.5 }, { 416.5, 1147.5, 570.5, 731.5, 1032.5, 981.5, 777.5, 1299.5 }, { 519.5, 943.5, 626.5, 505.5, 1057.5, 667.5, 854.5, 1036.5 }, { 387.5, 829.5, 448.5, 370.5, 917.5, 542.5, 740.5, 924.5 }, { 530.5, 979.5, 643.5, 535.5, 1042.5, 700.5, 837.5, 1078.5} }; // 4 polaris marker center coordinates in marker origin frame Pt3 polaris1_pt_3d = { 68.8633f, 68.7579f, 0.0337f }; // #1 Pt3 polaris2_pt_3d = { 74.7105f, 0.0000f, -0.0252f }; // #2 Pt3 polaris3_pt_3d = { 0.0000f, 0.0000f, 0.0287f }; // #3 Pt3 polaris4_pt_3d = { 11.8127f, 62.1510f, -0.0373f }; // #4 int main(int argc, char* argv[]) { ProgOpts po; xregPROG_OPTS_SET_COMPILE_DATE(po); po.set_help("Single view registration of the pelvis and femur. Femur registration is initialized by pelvis registration."); po.set_arg_usage("< Meta data path > < pelvis X-ray name txt file > < calibration X-ray name txt file > < pelvis registration xform > " "< pelvis X-ray image DCM folder > < calibration X-ray image DCM folder > < handeyeX > < Tracker data folder >" "< marker pnp xform folder > < output folder >"); po.set_min_num_pos_args(5); po.add("pelvis-label", ProgOpts::kNO_SHORT_FLAG, ProgOpts::kSTORE_UINT32, "pelvis-label", "Label voxel value of the pelvis segmentation, default is 1.") << ProgOpts::uint32(1); po.add_backend_flags(); try { po.parse(argc, argv); } catch (const ProgOpts::Exception& e) { std::cerr << "Error parsing command line arguments: " << e.what() << std::endl; po.print_usage(std::cerr); return kEXIT_VAL_BAD_USE; } if (po.help_set()) { po.print_usage(std::cout); po.print_help(std::cout); return kEXIT_VAL_SUCCESS; } const bool verbose = po.get("verbose"); std::ostream& vout = po.vout(); const std::string meta_data_path = po.pos_args()[0]; // Meta Data Folder containing CT, Segmentation and 3D landmark annotations const std::string pelvis_xray_id_txt_path = po.pos_args()[1]; // Experiment list file path, containing name of the pelvis X-ray image const std::string calibration_xray_id_txt_path = po.pos_args()[2]; // Experiment list file path, containing name of the calibration X-ray image const std::string pelvis_regi_xform_path = po.pos_args()[3]; // Pelvis registration transformation in 1st image view const std::string pelvis_dicom_path = po.pos_args()[4]; // Pelvis Dicom X-ray image folder path const std::string calibration_dicom_path = po.pos_args()[5]; // Dicom X-ray image folder path const std::string handeyeX_path = po.pos_args()[6]; // Path to handeyeX matrix const std::string calibraion_tracker_path = po.pos_args()[7]; // Path to calibration tracker data const std::string marker_pnp_path = po.pos_args()[8]; // Path to pnp xform folder const std::string output_path = po.pos_args()[9]; // Output path const std::string spec_vol_path = meta_data_path + "/Spec22-2181-CT-Bone-1mm.nii.gz"; const std::string spec_seg_path = meta_data_path + "/Spec22-2181-Seg-Bone-1mm.nii.gz"; const std::string pelvis_3d_fcsv_path = meta_data_path + "/pelvis_3D_landmarks.fcsv"; unsigned char pelvis_label = po.get("pelvis-label").as_uint32(); const size_type num_pelvis_views = 1; // This is single-view pelvis registration const bool use_seg = true; auto se3_vars = std::make_shared<SE3OptVarsLieAlg>(); auto so3_vars = std::make_shared<SO3OptVarsLieAlg>(); std::cout << "reading pelvis anatomical landmarks from FCSV file..." << std::endl; auto pelvis_3d_fcsv = ReadFCSVFileNamePtMap(pelvis_3d_fcsv_path); ConvertRASToLPS(&pelvis_3d_fcsv); vout << "reading pelvis CT volume..." << std::endl; auto vol_hu = ReadITKImageFromDisk<RayCaster::Vol>(spec_vol_path); vout << " HU --> Att. ..." << std::endl; auto vol_att = HUToLinAtt(vol_hu.GetPointer()); auto vol_seg = ReadITKImageFromDisk<itk::Image<unsigned char,3>>(spec_seg_path); vout << "cropping intensity volume tightly around labels:" << "\n Pelvis: " << static_cast<int>(pelvis_label) << std::endl; vout << "extracting pelvis att. volume..." << std::endl; auto pelvis_vol = ApplyMaskToITKImage(vol_att.GetPointer(), vol_seg.GetPointer(), pelvis_label, float(0), true); // Read Pelvis X-ray Image std::vector<std::string> pelvis_xray_ID_list; int pelvis_lineNumber = 0; /* Read exp ID list from file */ { std::ifstream expIDFile(pelvis_xray_id_txt_path); // Make sure the file is open if(!expIDFile.is_open()) throw std::runtime_error("Could not open pelvis X-ray ID file"); std::string line, csvItem; while(std::getline(expIDFile, line)){ std::istringstream myline(line); while(getline(myline, csvItem)){ pelvis_xray_ID_list.push_back(csvItem); } pelvis_lineNumber++; } } if(pelvis_lineNumber!=pelvis_xray_ID_list.size()) throw std::runtime_error("Exp ID list size mismatch!!!"); if(pelvis_lineNumber!=num_pelvis_views) throw std::runtime_error("More than One image parsed!!!"); // Read Calibration X-ray Image std::vector<std::string> calibration_xray_ID_list; int calibration_lineNumber = 0; /* Read exp ID list from file */ { std::ifstream expIDFile(calibration_xray_id_txt_path); // Make sure the file is open if(!expIDFile.is_open()) throw std::runtime_error("Could not open calibration X-ray ID file"); std::string line, csvItem; while(std::getline(expIDFile, line)){ std::istringstream myline(line); while(getline(myline, csvItem)){ calibration_xray_ID_list.push_back(csvItem); } calibration_lineNumber++; } } const auto default_cam = NaiveCamModelFromCIOSFusion(MakeNaiveCIOSFusionMetaDR(), true); const std::string pel_xray_ID = pelvis_xray_ID_list[0]; const std::string pelvis_img_path = pelvis_dicom_path + "/" + pel_xray_ID; const std::string cal_xray_01_ID = calibration_xray_ID_list[0]; const std::string cal_xray_02_ID = calibration_xray_ID_list[1]; const std::string cal_img_01_path = calibration_dicom_path + "/" + cal_xray_01_ID; const std::string cal_img_02_path = calibration_dicom_path + "/" + cal_xray_02_ID; // Find relative geometry between cal img 01 and 02 auto handeyeX_xform = ReadITKAffineTransformFromFile(handeyeX_path); FrameTransformList cal_RB4_wrt_CarmFid_xform_list; FrameTransformList cal_pnp_xform_list; vout << "Reading calibration tracker data..." << std::endl; for(size_type cal_id = 0; cal_id < calibration_xray_ID_list.size(); ++cal_id) { const std::string RB4_xform_path = calibraion_tracker_path + "/" + calibration_xray_ID_list[cal_id] + "/RB4.h5"; H5::H5File h5_RB4(RB4_xform_path, H5F_ACC_RDWR); H5::Group RB4_transform_group = h5_RB4.openGroup("TransformGroup"); H5::Group RB4_group0 = RB4_transform_group.openGroup("0"); std::vector<float> RB4_slicer = ReadVectorH5Float("TranformParameters", RB4_group0); FrameTransform RB4_xform = ConvertSlicerToITK(RB4_slicer); const std::string CarmFid_xform_path = calibraion_tracker_path + "/" + calibration_xray_ID_list[cal_id] + "/BayviewSiemensCArm.h5"; H5::H5File h5_CarmFid(CarmFid_xform_path, H5F_ACC_RDWR); H5::Group CarmFid_transform_group = h5_CarmFid.openGroup("TransformGroup"); H5::Group CarmFid_group0 = CarmFid_transform_group.openGroup("0"); std::vector<float> CarmFid_slicer = ReadVectorH5Float("TranformParameters", CarmFid_group0); FrameTransform CarmFid_xform = ConvertSlicerToITK(CarmFid_slicer); FrameTransform RB4_wrt_CarmFid = RB4_xform.inverse() * CarmFid_xform; cal_RB4_wrt_CarmFid_xform_list.push_back(RB4_wrt_CarmFid); const std::string pnp_xform_path = marker_pnp_path + "/pnp_xform" + calibration_xray_ID_list[cal_id] + ".h5"; FrameTransform pnp_xform = ReadITKAffineTransformFromFile(pnp_xform_path); cal_pnp_xform_list.push_back(pnp_xform); } FrameTransform rel_carm_xform = handeyeX_xform.inverse() * cal_RB4_wrt_CarmFid_xform_list[0].inverse() * cal_RB4_wrt_CarmFid_xform_list[1] * handeyeX_xform; const std::string rel_carm_xform_file = output_path + "/rel_carm_xform.h5"; WriteITKAffineTransform(rel_carm_xform_file, rel_carm_xform); ProjDataF32 pel_img; ProjDataF32 cal_img01; ProjDataF32 cal_img02; std::vector<CIOSFusionDICOMInfo> pel_cios_metas(1), cal_cios_metas(1); { std::tie(pel_img.img, pel_cios_metas[0]) = ReadCIOSFusionDICOMFloat(pelvis_img_path); std::tie(cal_img01.img, cal_cios_metas[0]) = ReadCIOSFusionDICOMFloat(cal_img_01_path); std::tie(cal_img02.img, cal_cios_metas[0]) = ReadCIOSFusionDICOMFloat(cal_img_02_path); } // Artificually add two images together for the first calibration image vout << "Adding pelvis and calibration images ..." << std::endl; pel_img.img = ITKAddImages(pel_img.img.GetPointer(), cal_img01.img.GetPointer()); WriteITKImageRemap8bpp(pel_img.img.GetPointer(), output_path + "/real" + pel_xray_ID + ".png"); FrameTransform pelvis_regi_xform = ReadITKAffineTransformFromFile(pelvis_regi_xform_path); FrameTransform pelvis_carm2_xform = pelvis_regi_xform * rel_carm_xform; { auto ray_caster = LineIntRayCasterFromProgOpts(po); ray_caster->set_camera_model(default_cam); ray_caster->use_proj_store_replace_method(); ray_caster->set_volume(vol_att); ray_caster->set_num_projs(1); ray_caster->allocate_resources(); ray_caster->xform_cam_to_itk_phys(0) = pelvis_carm2_xform; ray_caster->compute(0); // pel_carm2_drr->SetSpacing(cal_img02.img->GetSpacing()); // auto added_pel_cal_carm2 = ITKAddImages(pel_carm2_drr, cal_img02.img.GetPointer()); WriteITKImageRemap8bpp(ray_caster->proj(0).GetPointer(), output_path + "/carm2_pelvis_drr.png"); WriteITKImageRemap8bpp(cal_img02.img.GetPointer(), output_path + "/real_calibration_02.png"); } //Reproject 3D marker landmark using 1st view pnp xform and 2nd view rel_carm_xform std::ofstream marker_reproj_file; marker_reproj_file.open(output_path + "/marker_reproj.txt", std::ios::trunc); for(size_type idx = 0; idx < calibration_xray_ID_list.size(); ++idx) { FrameTransform marker_xform; if(idx == 0) marker_xform = cal_pnp_xform_list[0]; else marker_xform = cal_pnp_xform_list[0] * rel_carm_xform; Pt3 polaris1_reproj = default_cam.intrins * default_cam.extrins * marker_xform.inverse() * polaris1_pt_3d; Pt3 polaris2_reproj = default_cam.intrins * default_cam.extrins * marker_xform.inverse() * polaris2_pt_3d; Pt3 polaris3_reproj = default_cam.intrins * default_cam.extrins * marker_xform.inverse() * polaris3_pt_3d; Pt3 polaris4_reproj = default_cam.intrins * default_cam.extrins * marker_xform.inverse() * polaris4_pt_3d; // Difference of opencv convention image coordinate v.s. ITK marker_reproj_file << 1536 - polaris1_reproj(0)/polaris1_reproj(2) << ' ' << 1536 - polaris1_reproj(1)/polaris1_reproj(2) << ' ' << 1536 - polaris2_reproj(0)/polaris2_reproj(2) << ' ' << 1536 - polaris2_reproj(1)/polaris2_reproj(2) << ' ' << 1536 - polaris3_reproj(0)/polaris3_reproj(2) << ' ' << 1536 - polaris3_reproj(1)/polaris3_reproj(2) << ' ' << 1536 - polaris4_reproj(0)/polaris4_reproj(2) << ' ' << 1536 - polaris4_reproj(1)/polaris4_reproj(2) << '\n'; } vout << default_cam.intrins << std::endl; marker_reproj_file.close(); // Transform Polaris points to pelvis CT frame { FrameTransform marker_xform = cal_pnp_xform_list[0]; Pt3 polaris1_pelvis = pelvis_regi_xform * marker_xform.inverse() * polaris1_pt_3d; Pt3 polaris2_pelvis = pelvis_regi_xform * marker_xform.inverse() * polaris2_pt_3d; Pt3 polaris3_pelvis = pelvis_regi_xform * marker_xform.inverse() * polaris3_pt_3d; Pt3 polaris4_pelvis = pelvis_regi_xform * marker_xform.inverse() * polaris4_pt_3d; LandMap3 polaris_pts_map; polaris_pts_map.emplace("polaris1", polaris1_pelvis); polaris_pts_map.emplace("polaris2", polaris2_pelvis); polaris_pts_map.emplace("polaris3", polaris3_pelvis); polaris_pts_map.emplace("polaris4", polaris4_pelvis); ConvertRASToLPS(&polaris_pts_map); const std::string polaris_pelvis_fcsv_file = output_path + "/polaris_pts_pelvis.fcsv"; WriteFCSVFileFromNamePtMap(polaris_pelvis_fcsv_file, polaris_pts_map); } return 0; }
44.249344
158
0.693873
[ "geometry", "vector", "transform", "3d" ]
b63e70c392c0984922462c2b907ca8abaf734983
5,501
cpp
C++
c11httpd/http_header.cpp
toalexjin/c11httpd
6774d96c72d60ad8c371a6d846744a9ccc98d7ee
[ "MIT" ]
null
null
null
c11httpd/http_header.cpp
toalexjin/c11httpd
6774d96c72d60ad8c371a6d846744a9ccc98d7ee
[ "MIT" ]
null
null
null
c11httpd/http_header.cpp
toalexjin/c11httpd
6774d96c72d60ad8c371a6d846744a9ccc98d7ee
[ "MIT" ]
null
null
null
/** * HTTP header. * * Copyright (c) 2015 Alex Jin (toalexjin@hotmail.com) */ #include "c11httpd/http_header.h" #include <algorithm> namespace c11httpd { const fast_str_t http_header_t::Accept = "Accept"; const fast_str_t http_header_t::Accept_Charset = "Accept-Charset"; const fast_str_t http_header_t::Accept_Encoding = "Accept-Encoding"; const fast_str_t http_header_t::Accept_Language = "Accept-Language"; const fast_str_t http_header_t::Accept_Ranges = "Accept-Ranges"; const fast_str_t http_header_t::App_Json_UTF8 = "application/json; charset=UTF-8"; const fast_str_t http_header_t::App_Octet_Stream = "application/octet-stream"; const fast_str_t http_header_t::App_RPM = "application/x-redhat-package-manager"; const fast_str_t http_header_t::App_XML_UTF8 = "application/xml; charset=UTF-8"; const fast_str_t http_header_t::App_ZIP = "application/zip"; const fast_str_t http_header_t::Attachment = "attachment"; const fast_str_t http_header_t::Authorization = "Authorization"; const fast_str_t http_header_t::Bytes = "bytes"; const fast_str_t http_header_t::Compress = "compress"; const fast_str_t http_header_t::Connection = "Connection"; const fast_str_t http_header_t::Content_Language = "Content-Language"; const fast_str_t http_header_t::Content_Location = "Content-Location"; const fast_str_t http_header_t::Content_MD5 = "Content-MD5"; const fast_str_t http_header_t::Content_Disposition = "Content-Disposition"; const fast_str_t http_header_t::Content_Encoding = "Content-Encoding"; const fast_str_t http_header_t::Content_Length = "Content-Length"; const fast_str_t http_header_t::Content_Range = "Content-Range"; const fast_str_t http_header_t::Content_Type = "Content-Type"; const fast_str_t http_header_t::Date = "Date"; const fast_str_t http_header_t::Deflate = "deflate"; const fast_str_t http_header_t::Filename = "filename"; const fast_str_t http_header_t::GZIP = "gzip"; const fast_str_t http_header_t::Host = "Host"; const fast_str_t http_header_t::HTTP_VERSION_1_1 = "HTTP/1.1"; const fast_str_t http_header_t::Identify = "identify"; const fast_str_t http_header_t::Image_GIF = "image/gif"; const fast_str_t http_header_t::Image_JPEG = "image/jpeg"; const fast_str_t http_header_t::Image_PNG = "image/png"; const fast_str_t http_header_t::Keep_Alive = "keep-alive"; const fast_str_t http_header_t::Last_Modified = "Last-Modified"; const fast_str_t http_header_t::Location = "Location"; const fast_str_t http_header_t::Range = "Range"; const fast_str_t http_header_t::Server = "Server"; const fast_str_t http_header_t::Text_CSS_UTF8 = "text/css; charset=UTF-8"; const fast_str_t http_header_t::Text_HTML_UTF8 = "text/html; charset=UTF-8"; const fast_str_t http_header_t::Text_JavaScript = "text/javascript"; const fast_str_t http_header_t::Text_Plain_UTF8 = "text/plain; charset=UTF-8"; // Single instance. http_header_t::all http_header_t::all::st_instance; http_header_t::all::all() { // Common fields. const std::vector<fast_str_t> common = { "Cache-Control", "Connection", "Date", "Pragma", "Trailer", "Transfer-Encoding", "Upgrade", "Via", "Warning" }; // Request fields. const std::vector<fast_str_t> request = { "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Authorization", "Expect", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Max-Forwards", "Proxy-Authorization", "Range", "Referer", "TE", "User-Agent" }; // Response fields. const std::vector<fast_str_t> response = { "Accept-Ranges", "Age", "ETag", "Location", "Proxy-Authenticate", "Retry-After" "Server", "Vary", "WWW-Authenticate" }; // Entity fields. const std::vector<fast_str_t> entity = { "Allow", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified" }; // Add common, request, entity fields. this->m_request.reserve( common.size() + request.size() + entity.size()); for (const auto& item : common) { this->m_request.push_back(item); } for (const auto& item : request) { this->m_request.push_back(item); } for (const auto& item : entity) { this->m_request.push_back(item); } // Make the vector ascending sorted. std::sort(this->m_request.begin(), this->m_request.end(), m_less ); // Add common, response, entity fields. this->m_response.reserve( common.size() + response.size() + entity.size()); for (const auto& item : common) { this->m_response.push_back(item); } for (const auto& item : response) { this->m_response.push_back(item); } for (const auto& item : entity) { this->m_response.push_back(item); } // Make the vector ascending sorted. std::sort(this->m_response.begin(), this->m_response.end(), m_less ); } const fast_str_t* http_header_t::all::request_find(const fast_str_t& key) const { const auto it = std::lower_bound( this->m_request.cbegin(), this->m_request.cend(), key, m_less); if (it != this->m_request.cend() && !m_less(key, *it)) { return &(*it); } else { return 0; } } const fast_str_t* http_header_t::all::response_find(const fast_str_t& key) const { const auto it = std::lower_bound( this->m_response.cbegin(), this->m_response.cend(), key, m_less); if (it != this->m_response.cend() && !m_less(key, *it)) { return &(*it); } else { return 0; } } } // namespace c11httpd.
26.834146
82
0.719142
[ "vector" ]
b640bece53344f70340c3a3227570a6e84226d4c
7,920
cc
C++
Code/Vendor/Vulkan/Vulkan.GPUContext.cc
hannes-harnisch/Cultivator
fe6fb2fd87a566a6e690e18a25843a3a95199aa0
[ "MIT" ]
2
2021-08-05T05:47:05.000Z
2021-08-08T16:30:45.000Z
Code/Vendor/Vulkan/Vulkan.GPUContext.cc
hannes-harnisch/Cultivator
fe6fb2fd87a566a6e690e18a25843a3a95199aa0
[ "MIT" ]
null
null
null
Code/Vendor/Vulkan/Vulkan.GPUContext.cc
hannes-harnisch/Cultivator
fe6fb2fd87a566a6e690e18a25843a3a95199aa0
[ "MIT" ]
null
null
null
#include "PCH.hh" #include "Utils/Assert.hh" #include "Vulkan.GPUContext.hh" #include "Vulkan.Surface.hh" #include "Vulkan.Utils.hh" namespace ct { VKAPI_ATTR VkBool32 VKAPI_CALL logDebug(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT, VkDebugUtilsMessengerCallbackDataEXT const* pCallbackData, void*) { if(messageSeverity < VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) return false; std::string_view msg = pCallbackData->pMessage; if(msg.starts_with("loaderAddLayerProperties")) return false; std::printf("\n%s\n", pCallbackData->pMessage); return false; } GPUContext::GPUContext() { auto vkGetInstanceProcAddr = dl.getProcAddress<PFN_vkGetInstanceProcAddr>("vkGetInstanceProcAddr"); VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr); vk::DebugUtilsMessengerCreateInfoEXT loggerInfo { .messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError, .messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance, .pfnUserCallback = logDebug, }; initializeInstance(loggerInfo); VULKAN_HPP_DEFAULT_DISPATCHER.init(instanceHandle); #if CT_DEBUG auto [res, logger] = instanceHandle.createDebugUtilsMessengerEXT(loggerInfo); ctEnsureResult(res, "Failed to create Vulkan logger."); loggerHandle = logger; #endif initializeAdapter(); initializeDeviceAndQueues(); VULKAN_HPP_DEFAULT_DISPATCHER.init(deviceHandle); } GPUContext::~GPUContext() { ctEnsureResult(deviceHandle.waitIdle(), "Failed to wait for idle device."); deviceHandle.destroy(); #if CT_DEBUG instanceHandle.destroyDebugUtilsMessengerEXT(loggerHandle); #endif instanceHandle.destroy(); } void GPUContext::initializeInstance(vk::DebugUtilsMessengerCreateInfoEXT const& loggerInfo) { ensureInstanceExtensionsExist(); ensureLayersExist(); auto enabled = vk::ValidationFeatureEnableEXT::eBestPractices; vk::ValidationFeaturesEXT features { .pNext = &loggerInfo, .enabledValidationFeatureCount = 1, .pEnabledValidationFeatures = &enabled, }; vk::ApplicationInfo appInfo { .pApplicationName = CT_APP_NAME, .applicationVersion = VK_MAKE_VERSION(0, 0, 1), .pEngineName = CT_APP_NAME, .engineVersion = VK_MAKE_VERSION(0, 0, 1), .apiVersion = VK_API_VERSION_1_0, }; void* instanceNext = nullptr; #if CT_DEBUG instanceNext = &features; #endif vk::InstanceCreateInfo info { .pNext = instanceNext, .pApplicationInfo = &appInfo, .enabledLayerCount = count(RequiredLayers), .ppEnabledLayerNames = RequiredLayers.data(), .enabledExtensionCount = count(RequiredInstanceExtensions), .ppEnabledExtensionNames = RequiredInstanceExtensions.data(), }; auto [res, instance] = vk::createInstance(info); ctEnsureResult(res, "Failed to create Vulkan instance."); instanceHandle = instance; } void GPUContext::ensureInstanceExtensionsExist() { auto [res, extensions] = vk::enumerateInstanceExtensionProperties(); ctEnsureResult(res, "Failed to enumerate Vulkan instance extensions."); for(auto requiredExtension : RequiredInstanceExtensions) { bool found {}; for(auto& extension : extensions) if(std::strcmp(extension.extensionName, requiredExtension) == 0) { found = true; break; } ctEnsure(found, "Failed to find required Vulkan instance extension."); } } void GPUContext::ensureLayersExist() { auto [res, layers] = vk::enumerateInstanceLayerProperties(); ctEnsureResult(res, "Failed to enumerate Vulkan layers."); for(auto requiredLayer : RequiredLayers) { bool found {}; for(auto& layer : layers) if(std::strcmp(layer.layerName, requiredLayer) == 0) { found = true; break; } ctEnsure(found, "Failed to find required Vulkan layer."); } } void GPUContext::initializeAdapter() { auto [res, adapters] = instanceHandle.enumeratePhysicalDevices(); ctEnsureResult(res, "Failed to enumerate Vulkan adapters."); for(auto adapter : adapters) { deviceProps = adapter.getProperties(); if(deviceProps.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) adapterHandle = adapter; if(deviceProps.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) { adapterHandle = adapter; break; } } } namespace { struct QueueFamilies { uint32_t Graphics; uint32_t Present; }; QueueFamilies queryQueueFamilies(vk::PhysicalDevice adapter) { std::optional<uint32_t> graphicsFamily, presentFamily; uint32_t index {}; auto dummy = Surface::makeDummy(); for(auto& queueFamily : adapter.getQueueFamilyProperties()) { if(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) graphicsFamily = index; auto [res, supports] = adapter.getSurfaceSupportKHR(index, dummy.handle()); ctEnsureResult(res, "Failed to query for Vulkan surface support."); if(supports) presentFamily = index; ++index; } ctEnsure(graphicsFamily, "The GPU driver does not support graphics queues."); ctEnsure(presentFamily, "The GPU driver does not support present queues."); return {*graphicsFamily, *presentFamily}; } } void GPUContext::initializeDeviceAndQueues() { ensureDeviceExtensionsExist(); auto families = queryQueueFamilies(adapterHandle); std::array queuePriorities {1.0f}; vk::DeviceQueueCreateInfo graphicsQueueInfo { .queueFamilyIndex = families.Graphics, .queueCount = 1, .pQueuePriorities = queuePriorities.data(), }; vk::DeviceQueueCreateInfo presentQueueInfo { .queueFamilyIndex = families.Present, .queueCount = 1, .pQueuePriorities = queuePriorities.data(), }; std::vector queueInfos {graphicsQueueInfo}; if(families.Graphics != families.Present) queueInfos.push_back(presentQueueInfo); vk::PhysicalDeviceFeatures requiredFeatures { .samplerAnisotropy = true, .shaderImageGatherExtended = true, }; ensureFeaturesExist(requiredFeatures); vk::DeviceCreateInfo info { .queueCreateInfoCount = count(queueInfos), .pQueueCreateInfos = queueInfos.data(), .enabledLayerCount = count(RequiredLayers), .ppEnabledLayerNames = RequiredLayers.data(), .enabledExtensionCount = count(RequiredDeviceExtensions), .ppEnabledExtensionNames = RequiredDeviceExtensions.data(), .pEnabledFeatures = &requiredFeatures, }; auto [res, device] = adapterHandle.createDevice(info); ctEnsureResult(res, "Failed to create Vulkan device."); deviceHandle = device; graphicsQueueHandle = Queue(families.Graphics); presentQueueHandle = Queue(families.Present); } void GPUContext::ensureFeaturesExist(vk::PhysicalDeviceFeatures const& required) { using FeatureArray = std::array<vk::Bool32, sizeof(vk::PhysicalDeviceFeatures) / sizeof(vk::Bool32)>; auto requiredFeatures = std::bit_cast<FeatureArray>(required); auto availableFeatures = std::bit_cast<FeatureArray>(adapterHandle.getFeatures()); auto available = std::begin(availableFeatures); for(auto featureRequired : requiredFeatures) { if(featureRequired) ctEnsure(*available, "Required feature not available."); ++available; } } void GPUContext::ensureDeviceExtensionsExist() { auto [res, extensions] = adapterHandle.enumerateDeviceExtensionProperties(); ctEnsureResult(res, "Failed to enumerate Vulkan device extensions."); for(auto requiredExtension : RequiredDeviceExtensions) { bool found {}; for(auto& extension : extensions) if(std::strcmp(extension.extensionName, requiredExtension) == 0) { found = true; break; } ctEnsure(found, "Failed to find required Vulkan device extension."); } } }
29.662921
118
0.733838
[ "vector" ]
b643193bb71ca93110930abb2fc9167e8ac306e9
4,767
hpp
C++
lumino/LuminoEngine/include/LuminoEngine/Scene/World.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
null
null
null
lumino/LuminoEngine/include/LuminoEngine/Scene/World.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
null
null
null
lumino/LuminoEngine/include/LuminoEngine/Scene/World.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
null
null
null
 #pragma once #include "../Rendering/RenderingContext.hpp" #include "Common.hpp" namespace ln { class Level; class AnimationContext; class EnvironmentLight; class DirectionalLight; class WorldRenderView; class WorldObject; class Component; class PhysicsWorld; class PhysicsWorld2D; class EffectContext; namespace detail { struct CameraInfo; class EngineManager; class DrawElementList; class WorldSceneGraphRenderingContext; class SceneConductor; } /** 3D シーンを表すクラスです。 */ /* Note: Levelの構成 MasterLevel - SubLevel - UserLevel - SubLevel - UserLevel - SubLevel MasterLevel は Engine によって作成され、常に1つ存在している。 プログラム上で作成された WorldObject はここに追加される。 UserLevel は SceneConductor で遷移する単位。 SubLevel はオープンワールドなどシームレスなマップ移動や、先行ロードなどで利用する単位。 */ LN_CLASS() class World : public Object { LN_OBJECT; public: /** オブジェクトを World に追加します。 */ LN_METHOD() void add(WorldObject* obj); /** この World に含まれている全てのオブジェクトを World から除外します。 */ void removeAllObjects(); /** この World に含まれている全てのルートオブジェクトを取得します。 */ ReadOnlyList<Ref<WorldObject>>* rootObjects() const; void setTimeScale(float value) { m_timeScale = value; } float timeScale() const { return m_timeScale; } //void setMainAmbientLight(AmbientLight* value); const Ref<EnvironmentLight>& mainLight() const { return m_mainLight; } /** この World に含まれている WorldObject のうち、指定した型のコンポーネントを持っている最初の WorldObject を返します。 */ WorldObject* findObjectByComponentType(const TypeInfo* type) const; Level* masterScene() const; // 必ず存在するルート Level Level* activeLevel() const; // シーン遷移でアクティブになっているものがあればそれを返す。無ければ masterScene void addScene(Level* scene); //void gotoScene(Level* scene); //void callScene(Level* scene); //void returnScene(); //Level* activeScene() const; void traverse(detail::IWorldObjectVisitor* visitor) const; WorldObject* findObjectById(int id) const; WorldObject* findObjectByName(const StringView& name) const; protected: // update sequence virtual void onPreUpdate(float elapsedSeconds); virtual void onInternalPhysicsUpdate(float elapsedSeconds); virtual void onUpdate(float elapsedSeconds); virtual void onInternalAnimationUpdate(float elapsedSeconds); virtual void onPostUpdate(float elapsedSeconds); //LN_SERIALIZE_CLASS_VERSION(1); //virtual void serialize(Archive& ar) override; LN_CONSTRUCT_ACCESS: World(); virtual ~World(); void init(); virtual void onDispose(bool explicitDisposing) override; public: // TODO: internal const Ref<AnimationContext>& animationContext() const { return m_animationContext; } const Ref<PhysicsWorld>& physicsWorld() const { return m_physicsWorld; } const Ref<PhysicsWorld2D>& physicsWorld2D() const { return m_physicsWorld2D; } const Ref<EffectContext>& effectContext() const { return m_effectContext; } const Ref<detail::SceneConductor>& sceneConductor() const { return m_sceneConductor; } void updateObjectsWorldMatrix(); void updateFrame(float elapsedSeconds); detail::WorldSceneGraphRenderingContext* prepareRender(RenderViewPoint* viewPoint); void prepareRender(const WorldRenderView* renderView); void renderObjects(); // call by WorldRenderView void renderGizmos(RenderingContext* context); void enqueueActiveWorldObject(WorldObject* obj); void enqueueWorldRenderingElement(IWorldRenderingElement* element); void enqueueOffscreenRenderView(OffscreenWorldRenderView* element); const List<OffscreenWorldRenderView*>& collectedOffscreenRenderViews() const { return m_offscreenRenderViews; } Ref<AnimationContext> m_animationContext; Ref<PhysicsWorld> m_physicsWorld; Ref<PhysicsWorld2D> m_physicsWorld2D; Ref<EffectContext> m_effectContext; Ref<Level> m_masterScene; Ref<detail::SceneConductor> m_sceneConductor; Ref<EnvironmentLight> m_mainLight; detail::SceneGlobalRenderParams m_combinedSceneGlobalRenderParams; Ref<List<Ref<Level>>> m_sceneList; // Ref<List<Ref<WorldObject>>> m_rootWorldObjectList; //List<WorldObject*> m_destroyList; List<WorldObject*> m_activeObjects; List<IWorldRenderingElement*> m_worldRenderingElement; List<OffscreenWorldRenderView*> m_offscreenRenderViews; Ref<detail::WorldSceneGraphRenderingContext> m_renderingContext; //Ref<detail::WorldSceneGraphRenderingContext> m_debugRenderingContext; float m_timeScale; friend class WorldRenderView; friend class detail::EngineManager; }; namespace detail { class WorldSceneGraphRenderingContext : public RenderingContext { public: WorldSceneGraphRenderingContext(); void resetForBeginRendering(); private: }; } // namespace detail } // namespace ln
29.981132
115
0.752255
[ "object", "3d" ]
b64dbb905685586e28ead45aec5d542c2140460b
2,190
cpp
C++
android-31/java/time/format/TextStyle.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/time/format/TextStyle.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/time/format/TextStyle.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JArray.hpp" #include "../../../JString.hpp" #include "./TextStyle.hpp" namespace java::time::format { // Fields java::time::format::TextStyle TextStyle::FULL() { return getStaticObjectField( "java.time.format.TextStyle", "FULL", "Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::FULL_STANDALONE() { return getStaticObjectField( "java.time.format.TextStyle", "FULL_STANDALONE", "Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::NARROW() { return getStaticObjectField( "java.time.format.TextStyle", "NARROW", "Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::NARROW_STANDALONE() { return getStaticObjectField( "java.time.format.TextStyle", "NARROW_STANDALONE", "Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::SHORT() { return getStaticObjectField( "java.time.format.TextStyle", "SHORT", "Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::SHORT_STANDALONE() { return getStaticObjectField( "java.time.format.TextStyle", "SHORT_STANDALONE", "Ljava/time/format/TextStyle;" ); } // QJniObject forward TextStyle::TextStyle(QJniObject obj) : java::lang::Enum(obj) {} // Constructors // Methods java::time::format::TextStyle TextStyle::valueOf(JString arg0) { return callStaticObjectMethod( "java.time.format.TextStyle", "valueOf", "(Ljava/lang/String;)Ljava/time/format/TextStyle;", arg0.object<jstring>() ); } JArray TextStyle::values() { return callStaticObjectMethod( "java.time.format.TextStyle", "values", "()[Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::asNormal() const { return callObjectMethod( "asNormal", "()Ljava/time/format/TextStyle;" ); } java::time::format::TextStyle TextStyle::asStandalone() const { return callObjectMethod( "asStandalone", "()Ljava/time/format/TextStyle;" ); } jboolean TextStyle::isStandalone() const { return callMethod<jboolean>( "isStandalone", "()Z" ); } } // namespace java::time::format
21.262136
64
0.678082
[ "object" ]
b64eb3f0afde08c05589b6a7077979ae17924c66
5,268
cpp
C++
vis/src/vtk/eddaRandomSampleField.cpp
subhashis/MVEDDA
ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d
[ "MIT" ]
3
2016-01-15T20:17:21.000Z
2021-01-21T02:32:15.000Z
vis/src/vtk/eddaRandomSampleField.cpp
subhashis/MVEDDA
ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d
[ "MIT" ]
11
2016-07-26T01:37:46.000Z
2018-06-19T16:50:25.000Z
vis/src/vtk/eddaRandomSampleField.cpp
subhashis/MVEDDA
ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d
[ "MIT" ]
12
2016-02-09T04:31:41.000Z
2021-12-03T01:04:04.000Z
#include <iostream> #include "eddaRandomSampleField.h" #include "common.h" #include "vtk_common.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "io/gmm_vtk_data_array.h" // Compile with C++ compiler if Cuda is not used #include "thrust/device_vector.h" #if THRUST_DEVICE_SYSTEM!=THRUST_DEVICE_SYSTEM_CUDA #include "eddaRandomSampleField.cu" #endif using namespace std; using namespace edda; vtkStandardNewMacro(eddaRandomSampleField) // Copyright 2015 The Edda Authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. //---------------------------------------------------------------------------- eddaRandomSampleField::eddaRandomSampleField() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); ResultName = "RandomSample"; Prefix = ""; } //---------------------------------------------------------------------------- eddaRandomSampleField::~eddaRandomSampleField() { } void eddaRandomSampleField::InitializeData(vtkDataSet* input, vtkDataSet* output) { // First, copy the input geometry to the output as a starting point output->CopyStructure(input); } //---------------------------------------------------------------------------- int eddaRandomSampleField::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and output vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkDataSet *output = vtkDataSet::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); this->InitializeData(input, output); shared_ptr<GmmVtkDataArray> dataArray; // process point data dataArray = shared_ptr<GmmVtkDataArray>(new GmmVtkDataArray(input->GetPointData()) ); if (dataArray->getLength() > 0) { this->SampleDataArray( dataArray, output->GetPointData()); if (dataArray->getNumComponents()==1) output->GetPointData()->SetActiveScalars(ResultName.c_str()); else output->GetPointData()->SetActiveVectors(ResultName.c_str()); } // process cell data dataArray = shared_ptr<GmmVtkDataArray>(new GmmVtkDataArray(input->GetCellData()) ); if (dataArray->getLength() > 0) { this->SampleDataArray(dataArray, output->GetCellData()); if (dataArray->getNumComponents()==1) output->GetCellData()->SetActiveScalars(ResultName.c_str()); else output->GetCellData()->SetActiveVectors(ResultName.c_str()); } output->Modified(); this->Modified(); return 1; } //---------------------------------------------------------------------------- int eddaRandomSampleField::RequestInformation( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()), 6); // Generate dummy time steps to enable flickering double timeStepValues[] = {0,.1,.2,.3,.4,.5,.6,.7,.8,.9}; outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), timeStepValues, 10); double timeRange[2]; timeRange[0] = 0; timeRange[1] = 1.; outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2); //outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2); //outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS(), &myRequestedTime, 1); this->Modified(); return 1; } //---------------------------------------------------------------------------- int eddaRandomSampleField::RequestUpdateExtent( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); int usePiece = 0; // What ever happened to CopyUpdateExtent in vtkDataObject? // Copying both piece and extent could be bad. Setting the piece // of a structured data set will affect the extent. vtkDataObject* output = outInfo->Get(vtkDataObject::DATA_OBJECT()); if (output && (!strcmp(output->GetClassName(), "vtkUnstructuredGrid") || !strcmp(output->GetClassName(), "vtkPolyData"))) { usePiece = 1; } inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1); inInfo->Set( vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()), 6); this->Modified(); return 1; } //---------------------------------------------------------------------------- void eddaRandomSampleField::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
30.450867
93
0.670463
[ "geometry" ]
b6558d2d737d61690a99cf392985e359032ef207
17,761
cpp
C++
OpenSim/Moco/MocoTropterSolver.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
532
2015-03-13T18:51:10.000Z
2022-03-27T08:08:29.000Z
OpenSim/Moco/MocoTropterSolver.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
2,701
2015-01-03T21:33:34.000Z
2022-03-30T07:13:41.000Z
OpenSim/Moco/MocoTropterSolver.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
271
2015-02-16T23:25:29.000Z
2022-03-30T20:12:17.000Z
/* -------------------------------------------------------------------------- * * OpenSim Moco: MocoTropterSolver.cpp * * -------------------------------------------------------------------------- * * Copyright (c) 2017 Stanford University and the Authors * * * * Author(s): Christopher Dembia * * * * 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 "MocoTropterSolver.h" #include "MocoProblemRep.h" #include "MocoUtilities.h" #include <OpenSim/Common/Stopwatch.h> #ifdef OPENSIM_WITH_TROPTER #include "tropter/TropterProblem.h" #endif using namespace OpenSim; MocoTropterSolver::MocoTropterSolver() { constructProperties(); } void MocoTropterSolver::constructProperties() { constructProperty_optim_jacobian_approximation("exact"); constructProperty_optim_sparsity_detection("random"); constructProperty_exact_hessian_block_sparsity_mode(); } bool MocoTropterSolver::isAvailable() { #ifdef OPENSIM_WITH_TROPTER return true; #else return false; #endif } std::shared_ptr<const MocoTropterSolver::TropterProblemBase<double>> MocoTropterSolver::createTropterProblem() const { #ifdef OPENSIM_WITH_TROPTER checkPropertyValueIsInSet( getProperty_multibody_dynamics_mode(), {"explicit", "implicit"}); if (get_multibody_dynamics_mode() == "explicit") { return std::make_shared<ExplicitTropterProblem<double>>(*this); } else if (get_multibody_dynamics_mode() == "implicit") { return std::make_shared<ImplicitTropterProblem<double>>(*this); } else { OPENSIM_THROW_FRMOBJ(Exception, "Internal error."); } #else OPENSIM_THROW(MocoTropterSolverNotAvailable); #endif } std::unique_ptr<tropter::DirectCollocationSolver<double>> MocoTropterSolver::createTropterSolver( std::shared_ptr<const MocoTropterSolver::TropterProblemBase<double>> ocp) const { #ifdef OPENSIM_WITH_TROPTER // Check that a non-negative number of mesh points was provided. checkPropertyValueIsInRangeOrSet(getProperty_num_mesh_intervals(), 0, std::numeric_limits<int>::max(), {}); if (getProperty_mesh().size() > 0) { OPENSIM_THROW_IF_FRMOBJ((get_mesh(0) != 0), Exception, "Invalid custom mesh; first mesh " "point must be zero."); for (int i = 1; i < (int)this->getProperty_mesh().size(); ++i) { OPENSIM_THROW_IF_FRMOBJ((get_mesh(i) <= get_mesh(i - 1)), Exception, "Invalid custom mesh; mesh " "points must be strictly increasing."); } OPENSIM_THROW_IF_FRMOBJ((get_mesh(getProperty_mesh().size() - 1) != 1), Exception, "Invalid custom mesh; last mesh " "point must be one."); } // Check that a valid optimization solver was specified. checkPropertyValueIsInSet(getProperty_optim_solver(), {"ipopt", "snopt"}); // Check that a valid transcription scheme was specified. checkPropertyValueIsInSet(getProperty_transcription_scheme(), {"trapezoidal", "hermite-simpson"}); // Enforcing constraint derivatives is only supported when Hermite-Simpson // is set as the transcription scheme. if (getProblemRep().getNumKinematicConstraintEquations()) { OPENSIM_THROW_IF(get_transcription_scheme() != "hermite-simpson" && get_enforce_constraint_derivatives(), Exception, "If enforcing derivatives of model kinematic constraints, then " "the property 'transcription_scheme' must be set to " "'hermite-simpson'. Currently, it is set to '{}'.", get_transcription_scheme()); } OPENSIM_THROW_IF_FRMOBJ( getProblemRep().getNumImplicitAuxiliaryResiduals(), Exception, "MocoTropterSolver does not support problems " "with implicit auxiliary dynamics."); // Block sparsity detected is only in effect when using an exact Hessian // approximation. OPENSIM_THROW_IF( get_optim_hessian_approximation() == "limited-memory" && !getProperty_exact_hessian_block_sparsity_mode().empty(), Exception, "A value for solver property 'exact_hessian_block_sparsity_mode' " "was provided, but is unused when using a 'limited-memory' Hessian " "approximation. Set solver property 'optim_hessian_approximation' " "to 'exact' for Hessian block sparsity to take effect."); if (!getProperty_exact_hessian_block_sparsity_mode().empty()) { checkPropertyValueIsInSet( getProperty_exact_hessian_block_sparsity_mode(), {"dense", "sparse"}); } // Hessian information is not used in SNOPT. OPENSIM_THROW_IF(get_optim_hessian_approximation() == "exact" && get_optim_solver() == "snopt", Exception, "The property 'optim_hessian_approximation' was set to exact while " "using SNOPT as the optimization solver, but SNOPT does not " "utilize " "Hessian information."); // Check that the Lagrange multiplier weight is positive checkPropertyValueIsPositive(getProperty_lagrange_multiplier_weight()); // Create direct collocation solver. // --------------------------------- std::unique_ptr<tropter::DirectCollocationSolver<double>> dircol; if (getProperty_mesh().empty()) { dircol = OpenSim::make_unique<tropter::DirectCollocationSolver<double>>( ocp, get_transcription_scheme(), get_optim_solver(), get_num_mesh_intervals()); } else { std::vector<double> mesh; for (int i = 0; i < getProperty_mesh().size(); ++i) { mesh.push_back(get_mesh(i)); } dircol = OpenSim::make_unique<tropter::DirectCollocationSolver<double>>( ocp, get_transcription_scheme(), get_optim_solver(), mesh); } dircol->set_verbosity(get_verbosity() >= 1); if (getProperty_exact_hessian_block_sparsity_mode().empty()) { dircol->set_exact_hessian_block_sparsity_mode("dense"); } else { dircol->set_exact_hessian_block_sparsity_mode( get_exact_hessian_block_sparsity_mode()); } // Get optimization solver to check the remaining property settings. auto& optsolver = dircol->get_opt_solver(); // Check that number of max iterations is valid. checkPropertyValueIsInRangeOrSet(getProperty_optim_max_iterations(), 0, std::numeric_limits<int>::max(), {-1}); if (get_optim_max_iterations() != -1) optsolver.set_max_iterations(get_optim_max_iterations()); // Check that convergence tolerance is valid. checkPropertyValueIsInRangeOrSet(getProperty_optim_convergence_tolerance(), 0.0, SimTK::NTraits<double>::getInfinity(), {-1.0}); if (get_optim_convergence_tolerance() != -1) optsolver.set_convergence_tolerance(get_optim_convergence_tolerance()); // Check that constraint tolerance is valid. checkPropertyValueIsInRangeOrSet(getProperty_optim_constraint_tolerance(), 0.0, SimTK::NTraits<double>::getInfinity(), {-1.0}); if (get_optim_constraint_tolerance() != -1) optsolver.set_constraint_tolerance(get_optim_constraint_tolerance()); optsolver.set_jacobian_approximation(get_optim_jacobian_approximation()); optsolver.set_hessian_approximation(get_optim_hessian_approximation()); if (get_optim_solver() == "ipopt") { // Check that IPOPT print level is valid. checkPropertyValueIsInRangeOrSet( getProperty_optim_ipopt_print_level(), 0, 12, {-1}); if (get_verbosity() < 2) { optsolver.set_advanced_option_int("print_level", 0); } else { if (get_optim_ipopt_print_level() != -1) { optsolver.set_advanced_option_int( "print_level", get_optim_ipopt_print_level()); } } } // Check that sparsity detection mode is valid. checkPropertyValueIsInSet(getProperty_optim_sparsity_detection(), {"random", "initial-guess"}); optsolver.set_sparsity_detection(get_optim_sparsity_detection()); // Set advanced settings. // for (int i = 0; i < getProperty_optim_solver_options(); ++i) { // optsolver.set_advanced_option(TODO); //} // optsolver.set_advanced_option_string("print_timing_statistics", // "yes"); // TODO optsolver.set_advanced_option_string("derivative_test", // "second-order"); // TODO optsolver.set_findiff_hessian_step_size(1e-3); return dircol; #else OPENSIM_THROW(MocoTropterSolverNotAvailable); #endif } MocoTrajectory MocoTropterSolver::createGuess(const std::string& type) const { #ifdef OPENSIM_WITH_TROPTER OPENSIM_THROW_IF_FRMOBJ( type != "bounds" && type != "random" && type != "time-stepping", Exception, "Unexpected guess type '{}'; supported types are " "'bounds', 'random', and 'time-stepping'.", type); if (type == "time-stepping") { return createGuessTimeStepping(); } auto ocp = createTropterProblem(); auto dircol = createTropterSolver(ocp); tropter::Iterate tropIter; if (type == "bounds") { tropIter = dircol->make_initial_guess_from_bounds(); } else if (type == "random") { tropIter = dircol->make_random_iterate_within_bounds(); } return ocp->convertToMocoTrajectory(tropIter); #else OPENSIM_THROW(MocoTropterSolverNotAvailable); #endif } void MocoTropterSolver::setGuess(MocoTrajectory guess) { // Ensure the guess is compatible with this solver/problem. // Make sure to initialize the problem. TODO put in a better place. auto ocp = createTropterProblem(); checkGuess(guess); clearGuess(); m_guessFromAPI = std::move(guess); } void MocoTropterSolver::setGuessFile(const std::string& file) { clearGuess(); set_guess_file(file); } void MocoTropterSolver::checkGuess(const MocoTrajectory& guess) const { OPENSIM_THROW_IF(get_multibody_dynamics_mode() == "implicit" && guess.hasCoordinateStates() && guess.getDerivativeNames().empty(), Exception, "'multibody_dynamics_mode' set to 'implicit' and coordinate states " "exist in the guess, but no coordinate accelerations were found in " "the guess. Consider using " "MocoTrajectory::generateAccelerationsFromValues() or " "MocoTrajectory::generateAccelerationsFromSpeeds() to construct an " "appropriate guess."); guess.isCompatible( getProblemRep(), get_multibody_dynamics_mode() == "implicit", true); } void MocoTropterSolver::clearGuess() { m_guessFromAPI = MocoTrajectory(); m_guessFromFile = MocoTrajectory(); set_guess_file(""); m_guessToUse.reset(); } const MocoTrajectory& MocoTropterSolver::getGuess() const { if (!m_guessToUse) { if (get_guess_file() != "" && m_guessFromFile.empty()) { // The API should make it impossible for both guessFromFile and // guessFromAPI to be non-empty. assert(m_guessFromAPI.empty()); // No need to load from file again if we've already loaded it. MocoTrajectory guessFromFile(get_guess_file()); checkGuess(guessFromFile); m_guessFromFile = guessFromFile; m_guessToUse.reset(&m_guessFromFile); } else { // This will either be a guess specified via the API, or empty // to signal that tropter should use the default guess. m_guessToUse.reset(&m_guessFromAPI); } } // if (m_guessToUse) m_guessToUse->write("DEBUG_tropter_guess.sto"); return m_guessToUse.getRef(); } void MocoTropterSolver::printOptimizationSolverOptions(std::string solver) { #ifdef OPENSIM_WITH_TROPTER if (solver == "ipopt") { tropter::optimization::IPOPTSolver::print_available_options(); } else { log_info("No info available for {} options.", solver); } #else OPENSIM_THROW(MocoTropterSolverNotAvailable); #endif } MocoSolution MocoTropterSolver::solveImpl() const { #ifdef OPENSIM_WITH_TROPTER const Stopwatch stopwatch; OPENSIM_THROW_IF_FRMOBJ(getProblemRep().isPrescribedKinematics(), Exception, "MocoTropterSolver does not support prescribed kinematics. " "Try using prescribed motion constraints in the Coordinates."); auto ocp = createTropterProblem(); // Apply settings/options. // ----------------------- // Check that a valid verbosity level was provided. checkPropertyValueIsInSet(getProperty_verbosity(), {0, 1, 2}); // Problem print information is verbosity 1 or 2. if (get_verbosity()) { log_info(std::string(72, '=')); log_info("MocoTropterSolver starting."); log_info(getFormattedDateTime(false, "%c")); log_info(std::string(72, '-')); getProblemRep().printDescription(); } auto dircol = createTropterSolver(ocp); MocoTrajectory guess = getGuess(); tropter::Iterate tropIterate = ocp->convertToTropterIterate(guess); // Temporarily disable printing of negative muscle force warnings so the // output stream isn't flooded while computing finite differences. Logger::Level origLoggerLevel = Logger::getLevel(); Logger::setLevel(Logger::Level::Warn); tropter::Solution tropSolution; try { tropSolution = dircol->solve(tropIterate); } catch (...) { OpenSim::Logger::setLevel(origLoggerLevel); } OpenSim::Logger::setLevel(origLoggerLevel); if (get_verbosity()) { dircol->print_constraint_values(tropSolution); } MocoSolution mocoSolution = ocp->convertToMocoSolution(tropSolution); // If enforcing model constraints and not minimizing Lagrange // multipliers, check the rank of the constraint Jacobian and if // rank-deficient, print recommendation to the user to enable Lagrange // multiplier minimization. if (getProblemRep().getNumKinematicConstraintEquations() && !get_enforce_constraint_derivatives() && !get_minimize_lagrange_multipliers()) { const auto& model = getProblemRep().getModelBase(); const auto& matter = model.getMatterSubsystem(); TimeSeriesTable states = mocoSolution.exportToStatesTable(); // TODO update when we support multiple phases. auto statesTraj = StatesTrajectory::createFromStatesTable(model, states); SimTK::Matrix G; SimTK::FactorQTZ G_qtz; bool isJacobianFullRank = true; int rank; for (const auto& s : statesTraj) { // Jacobian is at most velocity-dependent. model.realizeVelocity(s); matter.calcG(s, G); G_qtz.factor<double>(G); if (G_qtz.getRank() < G.nrow()) { isJacobianFullRank = false; rank = G_qtz.getRank(); break; } } if (!isJacobianFullRank) { const std::string dashes(53, '-'); log_warn(dashes); log_warn("Rank-deficient constraint Jacobian detected."); log_warn(dashes); log_warn("The model constraint Jacobian has {} row(s) but is only " "rank {}. ", G.nrow(), rank); log_warn("Try removing redundant constraints from the model or " "enable"); log_warn("minimization of Lagrange multipliers by utilizing the " "solver "); log_warn("properties 'minimize_lagrange_multipliers' and"); log_warn("'lagrange_multiplier_weight'."); log_warn(dashes); } } // TODO move this to convert(): const long long elapsed = stopwatch.getElapsedTimeInNs(); MocoSolver::setSolutionStats(mocoSolution, tropSolution.success, tropSolution.objective, tropSolution.status, tropSolution.num_iterations, SimTK::nsToSec(elapsed)); if (get_verbosity()) { log_info(std::string(72, '-')); log_info("Elapsed real time: {}", stopwatch.formatNs(elapsed)); log_info(getFormattedDateTime(false, "%c")); if (mocoSolution) { log_info("MocoTropterSolver succeeded!"); } else { log_warn("MocoTropterSolver did NOT succeed:"); log_warn(" {}", mocoSolution.getStatus()); } log_info(std::string(72, '=')); } return mocoSolution; #else OPENSIM_THROW(MocoTropterSolverNotAvailable); #endif }
41.497664
80
0.634142
[ "mesh", "vector", "model" ]
b65bb43cc30a19a8b3528b40140750cb7a511c93
7,204
cc
C++
profman/profile_assistant.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
20
2021-06-24T16:38:42.000Z
2022-01-20T16:15:57.000Z
profman/profile_assistant.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
null
null
null
profman/profile_assistant.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
4
2021-11-03T06:01:12.000Z
2022-02-24T02:57:31.000Z
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "profile_assistant.h" #include "base/os.h" #include "base/unix_file/fd_file.h" namespace art { // Minimum number of new methods/classes that profiles // must contain to enable recompilation. static constexpr const uint32_t kMinNewMethodsForCompilation = 100; static constexpr const uint32_t kMinNewMethodsPercentChangeForCompilation = 2; static constexpr const uint32_t kMinNewClassesForCompilation = 50; static constexpr const uint32_t kMinNewClassesPercentChangeForCompilation = 2; ProfileAssistant::ProcessingResult ProfileAssistant::ProcessProfilesInternal( const std::vector<ScopedFlock>& profile_files, const ScopedFlock& reference_profile_file, const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn, bool store_aggregation_counters) { DCHECK(!profile_files.empty()); ProfileCompilationInfo info; // Load the reference profile. if (!info.Load(reference_profile_file->Fd(), /*merge_classes=*/ true, filter_fn)) { LOG(WARNING) << "Could not load reference profile file"; return kErrorBadProfiles; } // If we need to store aggregation counters (e.g. for the boot image profile), // prepare the reference profile now. if (store_aggregation_counters) { info.PrepareForAggregationCounters(); } // Store the current state of the reference profile before merging with the current profiles. uint32_t number_of_methods = info.GetNumberOfMethods(); uint32_t number_of_classes = info.GetNumberOfResolvedClasses(); // Merge all current profiles. for (size_t i = 0; i < profile_files.size(); i++) { ProfileCompilationInfo cur_info; if (!cur_info.Load(profile_files[i]->Fd(), /*merge_classes=*/ true, filter_fn)) { LOG(WARNING) << "Could not load profile file at index " << i; return kErrorBadProfiles; } if (!info.MergeWith(cur_info)) { LOG(WARNING) << "Could not merge profile file at index " << i; return kErrorBadProfiles; } } uint32_t min_change_in_methods_for_compilation = std::max( (kMinNewMethodsPercentChangeForCompilation * number_of_methods) / 100, kMinNewMethodsForCompilation); uint32_t min_change_in_classes_for_compilation = std::max( (kMinNewClassesPercentChangeForCompilation * number_of_classes) / 100, kMinNewClassesForCompilation); // Check if there is enough new information added by the current profiles. if (((info.GetNumberOfMethods() - number_of_methods) < min_change_in_methods_for_compilation) && ((info.GetNumberOfResolvedClasses() - number_of_classes) < min_change_in_classes_for_compilation)) { return kSkipCompilation; } // We were successful in merging all profile information. Update the reference profile. if (!reference_profile_file->ClearContent()) { PLOG(WARNING) << "Could not clear reference profile file"; return kErrorIO; } if (!info.Save(reference_profile_file->Fd())) { LOG(WARNING) << "Could not save reference profile file"; return kErrorIO; } return kCompile; } class ScopedFlockList { public: explicit ScopedFlockList(size_t size) : flocks_(size) {} // Will block until all the locks are acquired. bool Init(const std::vector<std::string>& filenames, /* out */ std::string* error) { for (size_t i = 0; i < filenames.size(); i++) { flocks_[i] = LockedFile::Open(filenames[i].c_str(), O_RDWR, /* block= */ true, error); if (flocks_[i].get() == nullptr) { *error += " (index=" + std::to_string(i) + ")"; return false; } } return true; } // Will block until all the locks are acquired. bool Init(const std::vector<int>& fds, /* out */ std::string* error) { for (size_t i = 0; i < fds.size(); i++) { DCHECK_GE(fds[i], 0); flocks_[i] = LockedFile::DupOf(fds[i], "profile-file", /* read_only_mode= */ true, error); if (flocks_[i].get() == nullptr) { *error += " (index=" + std::to_string(i) + ")"; return false; } } return true; } const std::vector<ScopedFlock>& Get() const { return flocks_; } private: std::vector<ScopedFlock> flocks_; }; ProfileAssistant::ProcessingResult ProfileAssistant::ProcessProfiles( const std::vector<int>& profile_files_fd, int reference_profile_file_fd, const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn, bool store_aggregation_counters) { DCHECK_GE(reference_profile_file_fd, 0); std::string error; ScopedFlockList profile_files(profile_files_fd.size()); if (!profile_files.Init(profile_files_fd, &error)) { LOG(WARNING) << "Could not lock profile files: " << error; return kErrorCannotLock; } // The reference_profile_file is opened in read/write mode because it's // cleared after processing. ScopedFlock reference_profile_file = LockedFile::DupOf(reference_profile_file_fd, "reference-profile", /* read_only_mode= */ false, &error); if (reference_profile_file.get() == nullptr) { LOG(WARNING) << "Could not lock reference profiled files: " << error; return kErrorCannotLock; } return ProcessProfilesInternal(profile_files.Get(), reference_profile_file, filter_fn, store_aggregation_counters); } ProfileAssistant::ProcessingResult ProfileAssistant::ProcessProfiles( const std::vector<std::string>& profile_files, const std::string& reference_profile_file, const ProfileCompilationInfo::ProfileLoadFilterFn& filter_fn, bool store_aggregation_counters) { std::string error; ScopedFlockList profile_files_list(profile_files.size()); if (!profile_files_list.Init(profile_files, &error)) { LOG(WARNING) << "Could not lock profile files: " << error; return kErrorCannotLock; } ScopedFlock locked_reference_profile_file = LockedFile::Open( reference_profile_file.c_str(), O_RDWR, /* block= */ true, &error); if (locked_reference_profile_file.get() == nullptr) { LOG(WARNING) << "Could not lock reference profile files: " << error; return kErrorCannotLock; } return ProcessProfilesInternal(profile_files_list.Get(), locked_reference_profile_file, filter_fn, store_aggregation_counters); } } // namespace art
38.116402
98
0.676013
[ "vector" ]
b6669f70437eec0bf1d3cbec3d35fdd252d5f16c
8,894
cpp
C++
test/v13/utility/action_list_test.cpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
null
null
null
test/v13/utility/action_list_test.cpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
8
2016-07-21T11:29:13.000Z
2016-12-03T05:16:42.000Z
test/v13/utility/action_list_test.cpp
amedama41/bulb
2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb
[ "BSL-1.0" ]
null
null
null
#define BOOST_TEST_DYN_LINK #include <canard/net/ofp/v13/action_list.hpp> #include <boost/test/unit_test.hpp> #include <cstdint> #include <utility> #include <vector> #include <canard/net/ofp/v13/actions.hpp> #include "../../test_utility.hpp" namespace of = canard::net::ofp; namespace v13 = of::v13; namespace actions = v13::actions; using boost::asio::ip::address_v4; using canard::mac_address; namespace { struct action_list_fixture { v13::action_list sut{ actions::group{0x12345678} , actions::copy_ttl_in{} , actions::copy_ttl_out{} , actions::set_ipv4_src{"127.0.0.1"_ipv4} , actions::set_eth_src{"\x01\x02\x03\x04\x05\x06"_mac} , actions::output{0x87654321} }; std::vector<std::uint8_t> binary = "\x00\x16\x00\x08\x12\x34\x56\x78""\x00\x0c\x00\x08\x00\x00\x00\x00" "\x00\x0b\x00\x08\x00\x00\x00\x00""\x00\x19\x00\x10\x80\x00\x16\x04" "\x7f\x00\x00\x01\x00\x00\x00\x00""\x00\x19\x00\x10\x80\x00\x08\x06" "\x01\x02\x03\x04\x05\x06\x00\x00""\x00\x00\x00\x10\x87\x65\x43\x21" "\xff\xff\x00\x00\x00\x00\x00\x00"_bin; }; } BOOST_AUTO_TEST_SUITE(common_type_test) BOOST_AUTO_TEST_SUITE(action_list_test) BOOST_AUTO_TEST_CASE(default_construct_test) { auto const sut = v13::action_list{}; BOOST_TEST(sut.length() == 0); BOOST_TEST(sut.empty()); BOOST_TEST(sut.size() == 0); BOOST_TEST((sut.begin() == sut.end())); } BOOST_AUTO_TEST_CASE(construct_from_single_action_test) { auto const output = actions::output{1}; auto const sut = v13::action_list{output}; BOOST_TEST(sut.length() == output.length()); BOOST_TEST(!sut.empty()); BOOST_TEST(sut.size() == 1); BOOST_TEST((sut.begin() != sut.end())); BOOST_TEST((sut.at(0) == output)); BOOST_TEST((sut[0] == output)); } BOOST_AUTO_TEST_CASE(construct_from_multiple_actions_test) { auto const output = actions::output{4}; // 16 auto const set_ipv4_src = actions::set_ipv4_src{"127.0.0.1"_ipv4}; // 16 auto const copy_ttl_in = actions::copy_ttl_in{}; // 8 auto const push_vlan = actions::push_vlan{0x8100}; // 8 auto const set_tcp_dst = actions::set_tcp_dst{6653}; // 16 auto const set_queue = actions::set_queue{4}; // 8 auto const sut = v13::action_list{ output, set_ipv4_src, copy_ttl_in, push_vlan, set_tcp_dst, set_queue }; BOOST_TEST(sut.length() == 72); BOOST_TEST(!sut.empty()); BOOST_TEST(sut.size() == 6); BOOST_TEST((sut.begin() != sut.end())); BOOST_TEST((sut.at(0) == output)); BOOST_TEST((sut[0] == output)); BOOST_TEST((sut.at(1) == set_ipv4_src)); BOOST_TEST((sut[1] == set_ipv4_src)); BOOST_TEST((sut.at(2) == copy_ttl_in)); BOOST_TEST((sut[2] == copy_ttl_in)); BOOST_TEST((sut.at(3) == push_vlan)); BOOST_TEST((sut[3] == push_vlan)); BOOST_TEST((sut.at(4) == set_tcp_dst)); BOOST_TEST((sut[4] == set_tcp_dst)); BOOST_TEST((sut.at(5) == set_queue)); BOOST_TEST((sut[5] == set_queue)); } BOOST_AUTO_TEST_CASE(construct_from_same_actions_test) { auto const output1 = actions::output{4}; // 16 auto const group = actions::group{1}; // 8 auto const output2 = actions::output{5}; // 16 auto const sut = v13::action_list{output1, group, output2}; BOOST_TEST(sut.length() == 40); BOOST_TEST(!sut.empty()); BOOST_TEST(sut.size() == 3); BOOST_TEST((sut.at(0) == output1)); BOOST_TEST((sut.at(1) == group)); BOOST_TEST((sut.at(2) == output2)); } BOOST_AUTO_TEST_SUITE(equality) BOOST_AUTO_TEST_CASE(true_if_same_object) { auto const sut = v13::action_list{ actions::output{1}, actions::set_queue{2} }; BOOST_TEST((sut == sut)); } BOOST_AUTO_TEST_CASE(true_if_action_list_is_equal) { BOOST_TEST( (v13::action_list{ actions::output{1}, actions::set_queue{2} } == v13::action_list{ actions::output{1}, actions::set_queue{2} })); } BOOST_AUTO_TEST_CASE(true_if_both_action_lists_are_empty) { BOOST_TEST((v13::action_list{} == v13::action_list{})); } BOOST_AUTO_TEST_CASE(false_if_action_list_size_is_not_equal) { BOOST_TEST( (v13::action_list{ actions::output{1} } != v13::action_list{ actions::output{1}, actions::group{2} })); } BOOST_AUTO_TEST_CASE(false_if_action_list_order_is_not_equal) { BOOST_TEST( (v13::action_list{ actions::pop_pbb{}, actions::pop_vlan{} } != v13::action_list{ actions::pop_vlan{}, actions::pop_pbb{} })); } BOOST_AUTO_TEST_CASE(false_if_contained_action_value_is_not_equal) { BOOST_TEST( (v13::action_list{ actions::pop_pbb{}, actions::set_nw_ttl{2} } != v13::action_list{ actions::pop_pbb{}, actions::set_nw_ttl{3} })); } BOOST_AUTO_TEST_CASE(false_if_contained_action_type_is_not_equal) { BOOST_TEST( (v13::action_list{ actions::pop_pbb{}, actions::copy_ttl_out{} } != v13::action_list{ actions::pop_pbb{}, actions::copy_ttl_in{} })); } BOOST_AUTO_TEST_CASE(false_if_contained_actions_are_not_equal_but_equivalent) { auto const binary = "\x00\x12\x00\x08\x10\x20\x30\x40"_bin; auto it = binary.begin(); auto const nonzero_pad_pop_vlan = actions::pop_vlan::decode(it, binary.end()); BOOST_TEST( (v13::action_list{ actions::pop_vlan{} } != v13::action_list{ nonzero_pad_pop_vlan })); } BOOST_AUTO_TEST_SUITE_END() // equality BOOST_AUTO_TEST_SUITE(function_equivalent) BOOST_AUTO_TEST_CASE(true_if_same_object) { auto const sut = v13::action_list{ actions::output{1}, actions::set_queue{2} }; BOOST_TEST(equivalent(sut, sut)); } BOOST_AUTO_TEST_CASE(true_if_action_list_is_equal) { BOOST_TEST( equivalent( v13::action_list{ actions::output{1}, actions::set_queue{2} } , v13::action_list{ actions::output{1}, actions::set_queue{2} })); } BOOST_AUTO_TEST_CASE(true_if_both_action_lists_are_empty) { BOOST_TEST(equivalent(v13::action_list{}, v13::action_list{})); } BOOST_AUTO_TEST_CASE(false_if_action_list_size_is_not_equal) { BOOST_TEST( !equivalent( v13::action_list{ actions::output{1} } , v13::action_list{ actions::output{1}, actions::group{2} })); } BOOST_AUTO_TEST_CASE(false_if_action_list_order_is_not_equal) { BOOST_TEST( !equivalent( v13::action_list{ actions::pop_pbb{}, actions::pop_vlan{} } , v13::action_list{ actions::pop_vlan{}, actions::pop_pbb{} })); } BOOST_AUTO_TEST_CASE(false_if_contained_action_value_is_not_equal) { BOOST_TEST( !equivalent( v13::action_list{ actions::pop_pbb{}, actions::set_nw_ttl{2} } , v13::action_list{ actions::pop_pbb{}, actions::set_nw_ttl{3} })); } BOOST_AUTO_TEST_CASE(false_if_contained_action_type_is_not_equal) { BOOST_TEST( !equivalent( v13::action_list{ actions::pop_pbb{}, actions::copy_ttl_out{} } , v13::action_list{ actions::pop_pbb{}, actions::copy_ttl_in{} })); } BOOST_AUTO_TEST_CASE(false_if_contained_actions_are_not_equal_but_equivalent) { auto const binary = "\x00\x12\x00\x08\x10\x20\x30\x40"_bin; auto it = binary.begin(); auto const nonzero_pad_pop_vlan = actions::pop_vlan::decode(it, binary.end()); BOOST_TEST( equivalent( v13::action_list{ actions::pop_vlan{} } , v13::action_list{ nonzero_pad_pop_vlan })); } BOOST_AUTO_TEST_SUITE_END() // function_equivalent BOOST_FIXTURE_TEST_CASE(encode_test, action_list_fixture) { auto buffer = std::vector<std::uint8_t>{}; sut.encode(buffer); BOOST_TEST(buffer.size() == sut.length()); BOOST_TEST(buffer == binary, boost::test_tools::per_element{}); } BOOST_FIXTURE_TEST_CASE(decode_test, action_list_fixture) { auto it = binary.begin(); auto const it_end = binary.end(); auto const match_set = v13::action_list::decode(it, it_end); BOOST_TEST((it == it_end)); BOOST_TEST((match_set == sut)); } BOOST_AUTO_TEST_SUITE_END() // action_list_test BOOST_AUTO_TEST_SUITE_END() // common_type_test
35.015748
83
0.611986
[ "vector" ]
b67a4f71c18708ad462cbada0ed7f59d9d8a6ee1
5,306
cpp
C++
Base/Views/voHorizontalBarView.cpp
Kitware/Visomics
5a12f132d826c32dececbd2707e920f4d5525da3
[ "Apache-2.0" ]
3
2015-05-03T05:14:50.000Z
2017-03-29T14:54:49.000Z
Base/Views/voHorizontalBarView.cpp
Kitware/Visomics
5a12f132d826c32dececbd2707e920f4d5525da3
[ "Apache-2.0" ]
null
null
null
Base/Views/voHorizontalBarView.cpp
Kitware/Visomics
5a12f132d826c32dececbd2707e920f4d5525da3
[ "Apache-2.0" ]
1
2017-03-29T15:04:16.000Z
2017-03-29T15:04:16.000Z
/*========================================================================= Program: Visomics Copyright (c) Kitware, 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. =========================================================================*/ // Qt includes #include <QDebug> #include <QLayout> // Visomics includes #include "voDataObject.h" #include "voHorizontalBarView.h" #include "voUtils.h" // VTK includes #include <QVTKWidget.h> #include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkContextScene.h> #include <vtkContextView.h> #include <vtkDoubleArray.h> #include <vtkNew.h> #include <vtkPlotBar.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkSmartPointer.h> #include <vtkStringArray.h> #include <vtkTable.h> // -------------------------------------------------------------------------- class voHorizontalBarViewPrivate { public: voHorizontalBarViewPrivate(); vtkSmartPointer<vtkContextView> ChartView; vtkSmartPointer<vtkChartXY> Chart; vtkPlotBar* BarPlot; QVTKWidget* Widget; }; // -------------------------------------------------------------------------- // voHorizontalBarViewPrivate methods // -------------------------------------------------------------------------- voHorizontalBarViewPrivate::voHorizontalBarViewPrivate() { this->Widget = 0; this->BarPlot = 0; } // -------------------------------------------------------------------------- // voHorizontalBarView methods // -------------------------------------------------------------------------- voHorizontalBarView::voHorizontalBarView(QWidget * newParent): Superclass(newParent), d_ptr(new voHorizontalBarViewPrivate) { } // -------------------------------------------------------------------------- voHorizontalBarView::~voHorizontalBarView() { } // -------------------------------------------------------------------------- void voHorizontalBarView::setupUi(QLayout * layout) { Q_D(voHorizontalBarView); d->ChartView = vtkSmartPointer<vtkContextView>::New(); d->Chart = vtkSmartPointer<vtkChartXY>::New(); d->Widget = new QVTKWidget(); d->ChartView->SetInteractor(d->Widget->GetInteractor()); d->Widget->SetRenderWindow(d->ChartView->GetRenderWindow()); d->ChartView->GetRenderer()->SetBackground(1.0, 1.0, 1.0); d->ChartView->GetScene()->AddItem(d->Chart); d->BarPlot = vtkPlotBar::SafeDownCast(d->Chart->AddPlot(vtkChart::BAR)); layout->addWidget(d->Widget); } // -------------------------------------------------------------------------- void voHorizontalBarView::setDataObjectInternal(const voDataObject& dataObject) { Q_D(voHorizontalBarView); vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject()); if (!table) { qCritical() << "voHorizontalBarView - Failed to setDataObject - vtkTable data is expected !"; return; } //Need a scratch copy, so we can insert a new column for verticalLocations vtkNew<vtkTable> localTable; localTable->DeepCopy(table); // verticalLocations is used to set axis tick marks, and as a dimension of the plotted data vtkNew<vtkDoubleArray> verticalLocations; for(double i = localTable->GetNumberOfRows(); i >= 1.0; i--) { verticalLocations->InsertNextValue(i); } verticalLocations->SetName("verticalLocations"); // Will never actually be displayed, but required by vtkPlot voUtils::insertColumnIntoTable(localTable.GetPointer(), 1, verticalLocations.GetPointer()); vtkStringArray* verticalLabels = vtkStringArray::SafeDownCast(localTable->GetColumn(0)); if (!verticalLabels) { qCritical() << "voHorizontalBarView - Failed to setDataObject - first column of vtkTable data could not be converted to string !"; return; } // See http://www.colorjack.com/?swatch=A6CEE3 unsigned char color[3] = {166, 206, 227}; d->BarPlot->SetInputData(localTable.GetPointer(), 1, 2); d->BarPlot->SetOrientation(vtkPlotBar::HORIZONTAL); d->BarPlot->SetColor(color[0], color[1], color[2], 255); d->BarPlot->SetIndexedLabels(verticalLabels); d->BarPlot->SetTooltipLabelFormat("%i: %y"); d->Chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED); // Default vertical zoom shows all bars at once. If we have many bars, we may want to change this. d->Chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0, static_cast<double>(localTable->GetNumberOfRows()) + 1.0); d->Chart->GetAxis(vtkAxis::LEFT)->SetCustomTickPositions(verticalLocations.GetPointer(), verticalLabels); d->Chart->GetAxis(vtkAxis::LEFT)->SetGridVisible(false); d->Chart->GetAxis(vtkAxis::LEFT)->SetTitle(""); d->Chart->GetAxis(vtkAxis::BOTTOM)->SetTitle(localTable->GetColumnName(2)); d->Chart->SetDrawAxesAtOrigin(true); d->ChartView->GetRenderWindow()->SetMultiSamples(4); d->ChartView->Render(); }
34.907895
134
0.624764
[ "render" ]
b67c0eb1881fe3225f810a9240c2e872756d6cb1
639
cpp
C++
application/source/asmlgen/application/dataset/file_reader.cpp
0xD34DC0DE/VeilleTechnologique
cccb9f084942a9bd626fea53ead5c376218ea44b
[ "MIT" ]
null
null
null
application/source/asmlgen/application/dataset/file_reader.cpp
0xD34DC0DE/VeilleTechnologique
cccb9f084942a9bd626fea53ead5c376218ea44b
[ "MIT" ]
null
null
null
application/source/asmlgen/application/dataset/file_reader.cpp
0xD34DC0DE/VeilleTechnologique
cccb9f084942a9bd626fea53ead5c376218ea44b
[ "MIT" ]
null
null
null
#include "asmlgen/application/dataset/file_reader.h" #include <fstream> namespace dataset { std::vector<char> FileReader::ReadFile(const std::string& filepath) { std::ifstream inputStream; inputStream.open(filepath); if (inputStream.is_open()) { inputStream.seekg(0, std::ios_base::end); std::size_t charCount = inputStream.tellg(); inputStream.seekg(0, std::ios_base::beg); std::vector<char> chars((charCount + 1) / sizeof(char)); inputStream.read((char*)&chars[0], charCount); inputStream.close(); chars[chars.size() - 1] = '\0'; return chars; } return {}; } } // namespace dataset
18.794118
67
0.665102
[ "vector" ]
b688c3757822aad8ba98fe107aef129c68ba9f12
11,616
cxx
C++
test/staticmem1.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
10
2018-03-26T07:41:44.000Z
2021-11-06T08:33:24.000Z
test/staticmem1.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
null
null
null
test/staticmem1.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
1
2020-11-17T03:17:00.000Z
2020-11-17T03:17:00.000Z
/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ //*** Class Sample to perform statistics on various multi-dim. data samples //*** NVE 30-mar-1996 CERN Geneva // A data sample can be filled using the "enter" and/or "remove" functions, // whereas the "reset" function resets the complete sample to 'empty'. // The info which can be extracted from a certain data sample are the // sum, mean, variance, sigma, covariance and correlation. // The "print" function provides all statistics data for a certain sample. // The variables for which these stat. parameters have to be calculated // are indicated by the index of the variable which is passed as an // argument to the various member functions. // The index convention for a data point (x,y) is : x=1 y=2 // // Example : // --------- // For a Sample s a data point (x,y) can be entered as s.enter(x,y) and // the mean_x can be obtained as s.mean(1) whereas the mean_y is obtained // via s.mean(2). The correlation between x and y is available via s.cor(1,2). // The x-statistics are obtained via s.print(1), y-statistics via s.print(2), // and the covariance and correlation between x and y via s.print(1,2). // All statistics of a sample are obtained via s.print(). // #ifdef __hpux #include <math.h> #include <iostream.h> #else #include <cmath> #include <iostream> using namespace std; #endif class Sample { public: Sample(); void reset(); void enter(float x); void remove(float x); void enter(float x, float y); void remove(float x, float y); void enter(float x, float y, float z); void remove(float x, float y, float z); int dim(); int n(); float sum(int i); float mean(int i); float var(int i); float sigma(int i); float cov(int i, int j); float cor(int i, int j); void print(); void print(int i); void print(int i, int j); private: int the_dim; // Dimension of the sample int the_n; // Number of entries of the sample enum {maxdim=3}; // Maximum supported dimension char the_names[maxdim]; // Variable names i.e. X,Y,Z float the_sum[maxdim]; // Total sum for each variable float the_sum2[maxdim][maxdim]; // Total sum**2 for each variable void calc(); float the_mean[maxdim]; // Mean for each variable float the_var[maxdim]; // Variation for each variable float the_sigma[maxdim]; // Standard deviation for each variable float the_cov[maxdim][maxdim]; // Covariances of pairs of variables float the_cor[maxdim][maxdim]; // Correlations of pairs of variables }; Sample::Sample() { //*** Creation of a Sample object and resetting the statistics values //*** The dimension is initialised to maximum the_dim=maxdim; the_names[0]='X'; the_names[1]='Y'; the_names[2]='Z'; the_n=0; for (int i=0; i<maxdim; i++) { the_sum[i]=0.; the_mean[i]=0.; the_var[i]=0.; the_sigma[i]=0.; for (int j=0; j<the_dim; j++) { the_sum2[i][j]=0.; the_cov[i][j]=0.; the_cor[i][j]=0.; } } } void Sample::reset() { //*** Resetting the statistics values for a certain Sample object //*** Dimension is NOT changed the_n=0; for (int i=0; i<the_dim; i++) { the_sum[i]=0.; the_mean[i]=0.; the_var[i]=0.; the_sigma[i]=0.; for (int j=0; j<the_dim; j++) { the_sum2[i][j]=0.; the_cov[i][j]=0.; the_cor[i][j]=0.; } } } void Sample::enter(float x) { //*** Entering a value into a 1-dim. sample //*** In case of first entry the dimension is set to 1 if (the_n==0) { the_dim=1; the_names[0]='X'; the_names[1]='-'; the_names[2]='-'; } if (the_dim != 1) { cout << " *Sample::enter* Error : Not a 1-dim sample." << endl; } else { the_n+=1; the_sum[0]+=x; the_sum2[0][0]+=x*x; calc(); } } void Sample::remove(float x) { //*** Removing a value from a 1-dim. sample if (the_dim != 1) { cout << " *Sample::remove* Error : Not a 1-dim sample." << endl; } else { the_n-=1; the_sum[0]-=x; the_sum2[0][0]-=x*x; calc(); } } void Sample::enter(float x, float y) { //*** Entering a pair (x,y) into a 2-dim. sample //*** In case of first entry the dimension is set to 2 if (the_n==0) { the_dim=2; the_names[0]='X'; the_names[1]='Y'; the_names[2]='-'; } if (the_dim != 2) { cout << " *Sample::enter* Error : Not a 2-dim sample." << endl; } else { the_n+=1; the_sum[0]+=x; the_sum[1]+=y; the_sum2[0][0]+=x*x; the_sum2[0][1]+=x*y; the_sum2[1][0]+=y*x; the_sum2[1][1]+=y*y; calc(); } } void Sample::remove(float x, float y) { //*** Removing a pair (x,y) from a 2-dim. sample if (the_dim != 2) { cout << " *Sample::remove* Error : Not a 2-dim sample." << endl; } else { the_n-=1; the_sum[0]-=x; the_sum[1]-=y; the_sum2[0][0]-=x*x; the_sum2[0][1]-=x*y; the_sum2[1][0]-=y*x; the_sum2[1][1]-=y*y; calc(); } } void Sample::enter(float x, float y, float z) { //*** Entering a set (x,y,z) into a 3-dim. sample //*** In case of first entry the dimension is set to 3 if (the_n==0) { the_dim=3; the_names[0]='X'; the_names[1]='Y'; the_names[2]='Z'; } if (the_dim != 3) { cout << " *Sample::enter* Error : Not a 3-dim sample." << endl; } else { the_n+=1; the_sum[0]+=x; the_sum[1]+=y; the_sum[2]+=z; the_sum2[0][0]+=x*x; the_sum2[0][1]+=x*y; the_sum2[0][2]+=x*z; the_sum2[1][0]+=y*x; the_sum2[1][1]+=y*y; the_sum2[1][2]+=y*z; the_sum2[2][0]+=z*x; the_sum2[2][1]+=z*y; the_sum2[2][2]+=z*z; calc(); } } void Sample::remove(float x, float y, float z) { //*** Removing a set (x,y,z) from a 3-dim. sample if (the_dim != 3) { cout << " *Sample::remove* Error : Not a 3-dim sample." << endl; } else { the_n-=1; the_sum[0]-=x; the_sum[1]-=y; the_sum[2]-=z; the_sum2[0][0]-=x*x; the_sum2[0][1]-=x*y; the_sum2[0][2]-=x*z; the_sum2[1][0]-=y*x; the_sum2[1][1]-=y*y; the_sum2[1][2]-=y*z; the_sum2[2][0]-=z*x; the_sum2[2][1]-=z*y; the_sum2[2][2]-=z*z; calc(); } } void Sample::calc() { //*** Calculation of the various statistical values //*** after each entering or removing action on a certain sample int i; float rn=the_n; for (i=0; i<the_dim; i++) { the_mean[i]=the_sum[i]/rn; the_var[i]=(the_sum2[i][i]/rn)-(the_mean[i]*the_mean[i]); if (the_var[i] < 0.) the_var[i]=0.; the_sigma[i]=sqrt(the_var[i]); } float test; for (i=0; i<the_dim; i++) { for (int j=0; j<the_dim; j++) { the_cov[i][j]=(the_sum2[i][j]/rn)-(the_mean[i]*the_mean[j]); test=the_sigma[i]*the_sigma[j]; if (test > 0.) the_cor[i][j]=the_cov[i][j]/test; } } } int Sample::dim() { //*** Provide the dimension of a certain sample return the_dim; } int Sample::n() { //*** Provide the number of entries of a certain sample return the_n; } float Sample::sum(int i) { //*** Provide the sum of a certain variable if (the_dim < i) { cout << " *Sample::sum* Error : Dimension less than " << i << endl; return the_sum[0]; } else { return the_sum[i-1]; } } float Sample::mean(int i) { //*** Provide the mean of a certain variable if (the_dim < i) { cout << " *Sample::mean* Error : Dimension less than " << i << endl; return the_mean[0]; } else { return the_mean[i-1]; } } float Sample::var(int i) { //*** Provide the variance of a certain variable if (the_dim < i) { cout << " *Sample::var* Error : Dimension less than " << i << endl; return the_var[0]; } else { return the_var[i-1]; } } float Sample::sigma(int i) { //*** Provide the standard deviation of a certain variable if (the_dim < i) { cout << " *Sample::sigma* Error : Dimension less than " << i << endl; return the_sigma[0]; } else { return the_sigma[i-1]; } } float Sample::cov(int i, int j) { //*** Provide the covariance between variables i and j if ((the_dim < i) || (the_dim < j)) { int k=i; if (j > i) k=j; cout << " *Sample::cov* Error : Dimension less than " << k << endl; return the_cov[0][0]; } else { return the_cov[i-1][j-1]; } } float Sample::cor(int i, int j) { //*** Provide the correlation between variables i and j if ((the_dim < i) || (the_dim < j)) { int k=i; if (j > i) k=j; cout << " *Sample::cor* Error : Dimension less than " << k << endl; return the_cor[0][0]; } else { return the_cor[i-1][j-1]; } } void Sample::print() { //*** Printing of statistics of all variables for (int i=0; i<the_dim; i++) { cout << " " << the_names[i] << " : N = " << the_n; cout << " Sum = " << the_sum[i] << " Mean = " << ( fabs(the_mean[i]) < 1e-7 ? 0.0 : the_mean[i] ); cout << " Var = " << ( fabs(the_var[i]) < 1e-7 ? 0.0 : the_var[i] ) << " Sigma = " << ( fabs(the_sigma[i]) < 1e-7 ? 0.0 : the_sigma[i] ) << endl; } } void Sample::print(int i) { //*** Printing of statistics of ith variable if (the_dim < i) { cout << " *Sample::print(i)* Error : Dimension less than " << i << endl; } else { int oldprecision = cout.precision(3); cout << " " << the_names[i-1] << " : N = " << the_n; cout << " Sum = " << the_sum[i-1] << " Mean = " << ( fabs(the_mean[i-1]) < 1e-7 ? 0.0 : the_mean[i-1] ); cout << " Var = " << ( fabs(the_var[i-1]) < 1e-7 ? 0.0 : the_var[i-1] ) << " Sigma = " << ( fabs(the_sigma[i-1])<1e-7 ? 0.0 : the_sigma[i-1] ) << endl; cout.precision(oldprecision); } } void Sample::print(int i, int j) { //*** Printing of covariance and correlation between variables i and j if ((the_dim < i) || (the_dim < j)) { int k=i; if (j > i) k=j; cout << " *Sample::print(i,j)* Error : Dimension less than " << k << endl; } else { cout << " " << the_names[i-1] << "-" << the_names[j-1] << " correlation :"; cout << " Cov. = " << the_cov[i-1][j-1] << " Cor. = " << the_cor[i-1][j-1] << endl; } } //*** The main program to test the various stat. functions int main() { Sample t; t.enter(9); cout << " Sample test :" << endl; t.print(1); Sample s1; s1.enter(19.); s1.enter(18.7); s1.enter(19.3); s1.enter(19.2); s1.enter(18.9); s1.enter(19.); s1.enter(20.2); s1.enter(19.9); s1.enter(18.6); s1.enter(19.4); s1.enter(19.3); s1.enter(18.8); s1.enter(19.3); s1.enter(19.2); s1.enter(18.7); s1.enter(18.5); s1.enter(18.6); s1.enter(19.7); s1.enter(19.9); s1.enter(20.); s1.enter(19.5); s1.enter(19.4); s1.enter(19.6); s1.enter(20.); s1.enter(18.9); cout << " Sample s1 students :" << endl; s1.print(1); s1.enter(37.); cout << " Sample s1 stud.+teacher :" << endl; s1.print(1); s1.remove(37.); cout << " Sample s1 teacher rem. :" << endl; s1.print(1); s1.reset(); s1.enter(1); s1.enter(2.); int i=3; s1.enter(i); cout << " Sample s1 just some values :" << endl; s1.print(1); Sample s2; s2.enter(1,10); s2.enter(2,20); s2.enter(3,30); cout << " Sample s2 :" << endl; s2.print(1); s2.print(2); s2.reset(); s2.enter(22,63); s2.enter(48,39); s2.enter(76,61); s2.enter(10,30); s2.enter(22,51); s2.enter(4,44); s2.enter(68,74); s2.enter(44,78); s2.enter(10,55); s2.enter(76,58); s2.enter(14,41); s2.enter(56,69); cout << " Sample s2 (CM,QM) :" << endl; s2.print(1); s2.print(2); s2.print(1,2); Sample s3; s3.enter(22,63,22); s3.enter(48,39,48); s3.enter(76,61,76); s3.enter(10,30,10); s3.enter(22,51,22); s3.enter(4,44,4); s3.enter(68,74,68); s3.enter(44,78,44); s3.enter(10,55,10); s3.enter(76,58,76); s3.enter(14,41,14); s3.enter(56,69,56); cout << " Sample s3 (CM,QM,CM) :" << endl; s3.print(); s3.print(1,2); s3.print(1,3); return 0; }
22.599222
154
0.584539
[ "object" ]
b68e23bfe025cd8c6ed71a37746ed2b350ef3c8b
1,103
cpp
C++
searchlib/src/vespa/searchlib/memoryindex/push_task.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/memoryindex/push_task.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/memoryindex/push_task.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
null
null
null
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "push_task.h" #include "push_context.h" #include "field_inverter.h" #include "url_field_inverter.h" namespace search::memoryindex { namespace { template <typename Inverter> void push_inverter(Inverter& inverter) { inverter.applyRemoves(); inverter.pushDocuments(); } } PushTask::PushTask(const PushContext& context, const std::vector<std::unique_ptr<FieldInverter>>& inverters, const std::vector<std::unique_ptr<UrlFieldInverter>>& uri_inverters, OnWriteDoneType on_write_done, std::shared_ptr<vespalib::RetainGuard> retain) : _context(context), _inverters(inverters), _uri_inverters(uri_inverters), _on_write_done(on_write_done), _retain(std::move(retain)) { } PushTask::~PushTask() = default; void PushTask::run() { for (auto field_id : _context.get_fields()) { push_inverter(*_inverters[field_id]); } for (auto uri_field_id : _context.get_uri_fields()) { push_inverter(*_uri_inverters[uri_field_id]); } } }
24.511111
256
0.724388
[ "vector" ]
b6906a6dfec4cc328ddbd69749f385d2a93df221
23,306
cpp
C++
marlin-firmware/Marlin/src/lcd/extui/lib/mks_ui/draw_acceleration_settings.cpp
voicevon/gogame_bot
a1d91f4a1b2537d00b5cd5ed78d429a9c1aad3d1
[ "MIT" ]
6
2020-12-04T21:55:04.000Z
2022-02-02T20:49:45.000Z
marlin-firmware/Marlin/src/lcd/extui/lib/mks_ui/draw_acceleration_settings.cpp
voicevon/gogame_bot
a1d91f4a1b2537d00b5cd5ed78d429a9c1aad3d1
[ "MIT" ]
1
2021-06-16T09:37:24.000Z
2021-06-16T09:44:32.000Z
marlin-firmware/Marlin/src/lcd/extui/lib/mks_ui/draw_acceleration_settings.cpp
voicevon/gogame_bot
a1d91f4a1b2537d00b5cd5ed78d429a9c1aad3d1
[ "MIT" ]
3
2021-05-01T15:13:41.000Z
2022-02-11T01:15:30.000Z
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../../../../inc/MarlinConfigPre.h" #if HAS_TFT_LVGL_UI #include "lv_conf.h" #include "draw_ui.h" #include "../../../../MarlinCore.h" #include "../../../../module/planner.h" static lv_obj_t * scr; #define ID_ACCE_RETURN 1 #define ID_ACCE_PRINT 2 #define ID_ACCE_RETRA 3 #define ID_ACCE_TRAVEL 4 #define ID_ACCE_X 5 #define ID_ACCE_Y 6 #define ID_ACCE_Z 7 #define ID_ACCE_E0 8 #define ID_ACCE_E1 9 #define ID_ACCE_UP 10 #define ID_ACCE_DOWN 11 static void event_handler(lv_obj_t * obj, lv_event_t event) { switch (obj->mks_obj_id) { case ID_ACCE_RETURN: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { uiCfg.para_ui_page = 0; lv_clear_acceleration_settings(); draw_return_ui(); } break; case ID_ACCE_PRINT: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = PrintAcceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_RETRA: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = RetractAcceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_TRAVEL: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = TravelAcceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_X: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = XAcceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_Y: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = YAcceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_Z: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = ZAcceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_E0: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = E0Acceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_E1: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { value = E1Acceleration; lv_clear_acceleration_settings(); lv_draw_number_key(); } break; case ID_ACCE_UP: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { uiCfg.para_ui_page = 0; lv_clear_acceleration_settings(); lv_draw_acceleration_settings(); } break; case ID_ACCE_DOWN: if (event == LV_EVENT_CLICKED) { } else if (event == LV_EVENT_RELEASED) { uiCfg.para_ui_page = 1; lv_clear_acceleration_settings(); lv_draw_acceleration_settings(); } break; } } void lv_draw_acceleration_settings(void) { lv_obj_t *buttonBack = NULL, *label_Back = NULL, *buttonTurnPage = NULL, *labelTurnPage = NULL; lv_obj_t *buttonPrintText = NULL, *labelPrintText = NULL, *buttonPrintValue = NULL, *labelPrintValue = NULL; lv_obj_t *buttonRetraText = NULL, *labelRetraText = NULL, *buttonRetraValue = NULL, *labelRetraValue = NULL; lv_obj_t *buttonTravelText = NULL, *labelTravelText = NULL, *buttonTravelValue = NULL, *labelTravelValue = NULL; lv_obj_t *buttonXText = NULL, *labelXText = NULL, *buttonXValue = NULL, *labelXValue = NULL; lv_obj_t *buttonYText = NULL, *labelYText = NULL, *buttonYValue = NULL, *labelYValue = NULL; lv_obj_t *buttonZText = NULL, *labelZText = NULL, *buttonZValue = NULL, *labelZValue = NULL; lv_obj_t *buttonE0Text = NULL, *labelE0Text = NULL, *buttonE0Value = NULL, *labelE0Value = NULL; lv_obj_t *buttonE1Text = NULL, *labelE1Text = NULL, *buttonE1Value = NULL, *labelE1Value = NULL; lv_obj_t * line1 = NULL, * line2 = NULL, * line3 = NULL, * line4 = NULL; if (disp_state_stack._disp_state[disp_state_stack._disp_index] != ACCELERATION_UI) { disp_state_stack._disp_index++; disp_state_stack._disp_state[disp_state_stack._disp_index] = ACCELERATION_UI; } disp_state = ACCELERATION_UI; scr = lv_obj_create(NULL, NULL); lv_obj_set_style(scr, &tft_style_scr); lv_scr_load(scr); lv_obj_clean(scr); lv_obj_t * title = lv_label_create(scr, NULL); lv_obj_set_style(title, &tft_style_label_rel); lv_obj_set_pos(title, TITLE_XPOS, TITLE_YPOS); lv_label_set_text(title, machine_menu.AccelerationConfTitle); lv_refr_now(lv_refr_get_disp_refreshing()); LV_IMG_DECLARE(bmp_para_back); // LV_IMG_DECLARE(bmp_para_arrow); LV_IMG_DECLARE(bmp_para_bank); if (uiCfg.para_ui_page != 1) { buttonPrintText = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonPrintText, PARA_UI_POS_X, PARA_UI_POS_Y); /*Set its position*/ lv_obj_set_size(buttonPrintText, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonPrintText, event_handler); lv_btn_set_style(buttonPrintText, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonPrintText, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonPrintText, LV_LAYOUT_OFF); labelPrintText = lv_label_create(buttonPrintText, NULL); /*Add a label to the button*/ buttonPrintValue = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonPrintValue, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonPrintValue, event_handler, ID_ACCE_PRINT, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonPrintValue, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonPrintValue, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonPrintValue, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonPrintValue, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonPrintValue, LV_LAYOUT_OFF); labelPrintValue = lv_label_create(buttonPrintValue, NULL); line1 = lv_line_create(scr, NULL); lv_ex_line(line1, line_points[0]); buttonRetraText = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonRetraText, PARA_UI_POS_X, PARA_UI_POS_Y * 2); /*Set its position*/ lv_obj_set_size(buttonRetraText, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonRetraText, event_handler); lv_btn_set_style(buttonRetraText, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonRetraText, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonRetraText, LV_LAYOUT_OFF); labelRetraText = lv_label_create(buttonRetraText, NULL); /*Add a label to the button*/ buttonRetraValue = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonRetraValue, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y * 2 + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonRetraValue, event_handler, ID_ACCE_RETRA, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonRetraValue, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonRetraValue, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonRetraValue, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonRetraValue, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonRetraValue, LV_LAYOUT_OFF); labelRetraValue = lv_label_create(buttonRetraValue, NULL); line2 = lv_line_create(scr, NULL); lv_ex_line(line2, line_points[1]); buttonTravelText = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonTravelText, PARA_UI_POS_X, PARA_UI_POS_Y * 3); /*Set its position*/ lv_obj_set_size(buttonTravelText, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonTravelText, event_handler); lv_btn_set_style(buttonTravelText, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonTravelText, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonTravelText, LV_LAYOUT_OFF); labelTravelText = lv_label_create(buttonTravelText, NULL); /*Add a label to the button*/ buttonTravelValue = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonTravelValue, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y * 3 + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonTravelValue, event_handler, ID_ACCE_TRAVEL, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonTravelValue, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonTravelValue, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonTravelValue, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonTravelValue, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonTravelValue, LV_LAYOUT_OFF); labelTravelValue = lv_label_create(buttonTravelValue, NULL); line3 = lv_line_create(scr, NULL); lv_ex_line(line3, line_points[2]); buttonXText = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonXText, PARA_UI_POS_X, PARA_UI_POS_Y * 4); /*Set its position*/ lv_obj_set_size(buttonXText, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonXText, event_handler); lv_btn_set_style(buttonXText, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonXText, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonXText, LV_LAYOUT_OFF); labelXText = lv_label_create(buttonXText, NULL); /*Add a label to the button*/ buttonXValue = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonXValue, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y * 4 + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonXValue, event_handler, ID_ACCE_X, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonXValue, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonXValue, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonXValue, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonXValue, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonXValue, LV_LAYOUT_OFF); labelXValue = lv_label_create(buttonXValue, NULL); line4 = lv_line_create(scr, NULL); lv_ex_line(line4, line_points[3]); buttonTurnPage = lv_imgbtn_create(scr, NULL); lv_obj_set_event_cb_mks(buttonTurnPage, event_handler, ID_ACCE_DOWN, "bmp_back70x40.bin", 0); lv_imgbtn_set_src(buttonTurnPage, LV_BTN_STATE_REL, &bmp_para_back); lv_imgbtn_set_src(buttonTurnPage, LV_BTN_STATE_PR, &bmp_para_back); lv_imgbtn_set_style(buttonTurnPage, LV_BTN_STATE_PR, &tft_style_label_pre); lv_imgbtn_set_style(buttonTurnPage, LV_BTN_STATE_REL, &tft_style_label_rel); } else { buttonYText = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonYText, PARA_UI_POS_X, PARA_UI_POS_Y); /*Set its position*/ lv_obj_set_size(buttonYText, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonYText, event_handler); lv_btn_set_style(buttonYText, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonYText, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonYText, LV_LAYOUT_OFF); labelYText = lv_label_create(buttonYText, NULL); /*Add a label to the button*/ buttonYValue = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonYValue, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonYValue, event_handler, ID_ACCE_Y, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonYValue, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonYValue, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonYValue, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonYValue, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonYValue, LV_LAYOUT_OFF); labelYValue = lv_label_create(buttonYValue, NULL); line1 = lv_line_create(scr, NULL); lv_ex_line(line1, line_points[0]); buttonZText = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonZText, PARA_UI_POS_X, PARA_UI_POS_Y * 2); /*Set its position*/ lv_obj_set_size(buttonZText, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonZText, event_handler); lv_btn_set_style(buttonZText, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonZText, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonZText, LV_LAYOUT_OFF); labelZText = lv_label_create(buttonZText, NULL); /*Add a label to the button*/ buttonZValue = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonZValue, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y * 2 + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonZValue, event_handler, ID_ACCE_Z, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonZValue, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonZValue, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonZValue, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonZValue, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonZValue, LV_LAYOUT_OFF); labelZValue = lv_label_create(buttonZValue, NULL); line2 = lv_line_create(scr, NULL); lv_ex_line(line2, line_points[1]); buttonE0Text = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonE0Text, PARA_UI_POS_X, PARA_UI_POS_Y * 3); /*Set its position*/ lv_obj_set_size(buttonE0Text, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonE0Text, event_handler); lv_btn_set_style(buttonE0Text, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonE0Text, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonE0Text, LV_LAYOUT_OFF); labelE0Text = lv_label_create(buttonE0Text, NULL); /*Add a label to the button*/ buttonE0Value = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonE0Value, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y * 3 + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonE0Value, event_handler, ID_ACCE_E0, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonE0Value, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonE0Value, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonE0Value, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonE0Value, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonE0Value, LV_LAYOUT_OFF); labelE0Value = lv_label_create(buttonE0Value, NULL); line3 = lv_line_create(scr, NULL); lv_ex_line(line3, line_points[2]); buttonE1Text = lv_btn_create(scr, NULL); /*Add a button the current screen*/ lv_obj_set_pos(buttonE1Text, PARA_UI_POS_X, PARA_UI_POS_Y * 4); /*Set its position*/ lv_obj_set_size(buttonE1Text, PARA_UI_VALUE_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ lv_obj_set_event_cb(buttonE1Text, event_handler); lv_btn_set_style(buttonE1Text, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ lv_btn_set_style(buttonE1Text, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ lv_btn_set_layout(buttonE1Text, LV_LAYOUT_OFF); labelE1Text = lv_label_create(buttonE1Text, NULL); /*Add a label to the button*/ buttonE1Value = lv_imgbtn_create(scr, NULL); lv_obj_set_pos(buttonE1Value, PARA_UI_VALUE_POS_X, PARA_UI_POS_Y * 4 + PARA_UI_VALUE_V); lv_obj_set_event_cb_mks(buttonE1Value, event_handler, ID_ACCE_E1, "bmp_value_blank.bin", 0); lv_imgbtn_set_src(buttonE1Value, LV_BTN_STATE_REL, &bmp_para_bank); lv_imgbtn_set_src(buttonE1Value, LV_BTN_STATE_PR, &bmp_para_bank); lv_imgbtn_set_style(buttonE1Value, LV_BTN_STATE_PR, &style_para_value_pre); lv_imgbtn_set_style(buttonE1Value, LV_BTN_STATE_REL, &style_para_value_rel); lv_btn_set_layout(buttonE1Value, LV_LAYOUT_OFF); labelE1Value = lv_label_create(buttonE1Value, NULL); line4 = lv_line_create(scr, NULL); lv_ex_line(line4, line_points[3]); buttonTurnPage = lv_imgbtn_create(scr, NULL); lv_obj_set_event_cb_mks(buttonTurnPage, event_handler, ID_ACCE_UP, "bmp_back70x40.bin", 0); lv_imgbtn_set_src(buttonTurnPage, LV_BTN_STATE_REL, &bmp_para_back); lv_imgbtn_set_src(buttonTurnPage, LV_BTN_STATE_PR, &bmp_para_back); lv_imgbtn_set_style(buttonTurnPage, LV_BTN_STATE_PR, &tft_style_label_pre); lv_imgbtn_set_style(buttonTurnPage, LV_BTN_STATE_REL, &tft_style_label_rel); } lv_obj_set_pos(buttonTurnPage, PARA_UI_TURN_PAGE_POS_X, PARA_UI_TURN_PAGE_POS_Y); lv_btn_set_layout(buttonTurnPage, LV_LAYOUT_OFF); labelTurnPage = lv_label_create(buttonTurnPage, NULL); buttonBack = lv_imgbtn_create(scr, NULL); lv_obj_set_event_cb_mks(buttonBack, event_handler, ID_ACCE_RETURN, "bmp_back70x40.bin", 0); lv_imgbtn_set_src(buttonBack, LV_BTN_STATE_REL, &bmp_para_back); lv_imgbtn_set_src(buttonBack, LV_BTN_STATE_PR, &bmp_para_back); lv_imgbtn_set_style(buttonBack, LV_BTN_STATE_PR, &tft_style_label_pre); lv_imgbtn_set_style(buttonBack, LV_BTN_STATE_REL, &tft_style_label_rel); lv_obj_set_pos(buttonBack, PARA_UI_BACL_POS_X, PARA_UI_BACL_POS_Y); lv_btn_set_layout(buttonBack, LV_LAYOUT_OFF); label_Back = lv_label_create(buttonBack, NULL); if (gCfgItems.multiple_language != 0) { if (uiCfg.para_ui_page != 1) { lv_label_set_text(labelPrintText, machine_menu.PrintAcceleration); lv_obj_align(labelPrintText, buttonPrintText, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelRetraText, machine_menu.RetractAcceleration); lv_obj_align(labelRetraText, buttonRetraText, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelTravelText, machine_menu.TravelAcceleration); lv_obj_align(labelTravelText, buttonTravelText, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelXText, machine_menu.X_Acceleration); lv_obj_align(labelXText, buttonXText, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelTurnPage, machine_menu.next); lv_obj_align(labelTurnPage, buttonTurnPage, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%.1f"), planner.settings.acceleration); lv_label_set_text(labelPrintValue, public_buf_l); lv_obj_align(labelPrintValue, buttonPrintValue, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%.1f"), planner.settings.retract_acceleration); lv_label_set_text(labelRetraValue, public_buf_l); lv_obj_align(labelRetraValue, buttonRetraValue, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%.1f"), planner.settings.travel_acceleration); lv_label_set_text(labelTravelValue, public_buf_l); lv_obj_align(labelTravelValue, buttonTravelValue, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%d"), (int)planner.settings.max_acceleration_mm_per_s2[X_AXIS]); lv_label_set_text(labelXValue, public_buf_l); lv_obj_align(labelXValue, buttonXValue, LV_ALIGN_CENTER, 0, 0); } else { lv_label_set_text(labelYText, machine_menu.Y_Acceleration); lv_obj_align(labelYText, buttonYText, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelZText, machine_menu.Z_Acceleration); lv_obj_align(labelZText, buttonZText, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelE0Text, machine_menu.E0_Acceleration); lv_obj_align(labelE0Text, buttonE0Text, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelE1Text, machine_menu.E1_Acceleration); lv_obj_align(labelE1Text, buttonE1Text, LV_ALIGN_IN_LEFT_MID, 0, 0); lv_label_set_text(labelTurnPage, machine_menu.previous); lv_obj_align(labelTurnPage, buttonTurnPage, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%d"), (int)planner.settings.max_acceleration_mm_per_s2[Y_AXIS]); lv_label_set_text(labelYValue, public_buf_l); lv_obj_align(labelYValue, buttonYValue, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%d"), (int)planner.settings.max_acceleration_mm_per_s2[Z_AXIS]); lv_label_set_text(labelZValue, public_buf_l); lv_obj_align(labelZValue, buttonZValue, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%d"), (int)planner.settings.max_acceleration_mm_per_s2[E_AXIS]); lv_label_set_text(labelE0Value, public_buf_l); lv_obj_align(labelE0Value, buttonE0Value, LV_ALIGN_CENTER, 0, 0); ZERO(public_buf_l); sprintf_P(public_buf_l, PSTR("%d"), (int)planner.settings.max_acceleration_mm_per_s2[E_AXIS_N(1)]); lv_label_set_text(labelE1Value, public_buf_l); lv_obj_align(labelE1Value, buttonE1Value, LV_ALIGN_CENTER, 0, 0); } lv_label_set_text(label_Back, common_menu.text_back); lv_obj_align(label_Back, buttonBack, LV_ALIGN_CENTER, 0, 0); } } void lv_clear_acceleration_settings() { lv_obj_del(scr); } #endif // HAS_TFT_LVGL_UI
48.152893
115
0.732558
[ "3d" ]
b6a644e189567510f0a750a0268ec27419f1613f
12,209
cpp
C++
import/quickitems/categories/Segmentation.cpp
yanglqq/photo
68928ef09c5274e398c81be2c6ec686b2a95d033
[ "MIT" ]
null
null
null
import/quickitems/categories/Segmentation.cpp
yanglqq/photo
68928ef09c5274e398c81be2c6ec686b2a95d033
[ "MIT" ]
null
null
null
import/quickitems/categories/Segmentation.cpp
yanglqq/photo
68928ef09c5274e398c81be2c6ec686b2a95d033
[ "MIT" ]
null
null
null
#include "Segmentation.h" #include "../ImageManager.h" Segmentation::Segmentation(QQuickItem *parent) : QQuickItem(parent), ImageProccessor() {} QString Segmentation::basicGlobalThresholding(const QString &uri, double maxValue, double threshold, int type, bool absolute, bool evaluate) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); cv::Mat dst; polka::extractLuminace(*image, [&](const cv::Mat &luminance) { cv::Mat src = absolute ? abs(luminance) : luminance; if (evaluate) polka::basicGlobalThreshold(src, threshold); cv::threshold(src, dst, threshold, maxValue, type); }); return putImage(dst, uri); } QString Segmentation::optimumGlobalThresholding1(const QString &uri, double maxValue, int type, bool useHistogramImage, const QString histogramImageURI, bool partition, int m, int n) { const cv::Mat *image1 = ImageManager::get(uri); if (!image1) return QString(); const cv::Mat *histogramImage = image1; if (useHistogramImage) { const cv::Mat *image2 = ImageManager::get(histogramImageURI); if (!image2) return QString(); histogramImage = image2; } cv::Mat dst; polka::extractLuminace(*image1, [&](const cv::Mat &luminance) { if (partition) { double threshold; std::vector<std::pair<cv::Mat, cv::Mat>> subImages; polka::partitionImage(luminance, dst, m, n, subImages); for (size_t i = 0, count = subImages.size(); i < count; i++) { std::pair<cv::Mat, cv::Mat> item = subImages[i]; polka::optimumGlobalThreshold1(item.first, threshold); cv::threshold(item.first, item.second, threshold, maxValue, type); } } else { double threshold; polka::optimumGlobalThreshold1(*histogramImage, threshold); cv::threshold(luminance, dst, threshold, maxValue, type); } }); return putImage(dst, uri); } QString Segmentation::optimumGlobalThresholding2(const QString &uri, double value1, double value2, double value3, bool useHistogramImage, const QString histogramImageURI, bool partition, int m, int n) { const cv::Mat *image1 = ImageManager::get(uri); if (!image1) return QString(); const cv::Mat *histogramImage = image1; if (useHistogramImage) { const cv::Mat *image2 = ImageManager::get(histogramImageURI); if (!image2) return QString(); histogramImage = image2; } cv::Mat dst; polka::extractLuminace(*image1, [&](const cv::Mat &luminance) { if (partition) { double t1; double t2; std::vector<std::pair<cv::Mat, cv::Mat>> subImages; polka::partitionImage(luminance, dst, m, n, subImages); for (size_t i = 0, count = subImages.size(); i < count; i++) { std::pair<cv::Mat, cv::Mat> item = subImages[i]; polka::optimumGlobalThreshold2(item.first, t1, t2); polka::threshold2(item.first, item.second, t1, t2, value1, value2, value3); } } else { double t1; double t2; polka::optimumGlobalThreshold2(*histogramImage, t1, t2); polka::threshold2(luminance, dst, t1, t2, value1, value2, value3); } }); return putImage(dst, uri); } /** struct LocalThresholding : public cv::BaseFilter { int m; int n; int area; double maxValue; double weightOfLocalVariance; double weightOfMean; double globalMean; bool usingGlobalMean; std::vector<float*> pLocal; LocalThresholding(double _maxValue, double _weightOfLocalVariance, double _weightOfMean, int _m, int _n, bool _usingGlobalMean, double _globalMean) { maxValue = _maxValue; weightOfLocalVariance = _weightOfLocalVariance; weightOfMean = _weightOfMean; m = _m; n = _n; usingGlobalMean = _usingGlobalMean; globalMean = _globalMean; anchor = cv::Point(); ksize = cv::Size(m, n); area = m * n; pLocal.resize(area); } void operator()(const uchar** src, uchar* dst, int dststep, int count, int width, int cn) { width *= cn; int center = area / 2; const float** pl = (const float**)&pLocal[0]; for (; count > 0; count--, dst += dststep, src++) { uchar* d = (uchar *)dst; for (int i = 0, k = 0; i < n; i++ ) { for (int j = 0; j < m; j++, k++) { pl[k] = (const float *)src[i] + j * cn; } } for (int i = 0; i < width; i++) { float sum = 0.0; for (int k = 0; k < area; k++) sum += pl[k][i]; float value = pl[center][i]; float mean = sum / static_cast<float>(area); float variance = std::pow(value - mean, 2); d[i] = value > weightOfLocalVariance * variance && value > weightOfMean * (usingGlobalMean ? globalMean : mean) ? maxValue : 0; } } } }; QString Segmentation::localThresholding(const QString &uri, double maxValue, double weightOfLocalVariance, double weightOfMean, int m, int n, bool usingGlobalMean) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); cv::Mat dst; polka::extractLuminace(*image, [&](const cv::Mat &luminance) { cv::Mat src; luminance.convertTo(src, CV_32F); double globalMean = 0.0; if (usingGlobalMean) { float *p = (float *)src.data; for (int i = 0, k = 0; i < src.rows; i++) { for (int j = 0; j < src.cols; j++, k++) { globalMean += p[k]; } } globalMean /= src.rows * src.cols; } cv::Ptr<cv::FilterEngine> engine = cv::Ptr<cv::FilterEngine>( new cv::FilterEngine( cv::Ptr<cv::BaseFilter>(new LocalThresholding(maxValue, weightOfLocalVariance, weightOfMean, m, n, usingGlobalMean, globalMean)), cv::Ptr<cv::BaseRowFilter>(), cv::Ptr<cv::BaseColumnFilter>(), src.type(), CV_8UC1, src.type(), cv::BORDER_CONSTANT, cv::BORDER_CONSTANT, cv::Scalar(0))); dst.create(src.size(), CV_8UC1); engine->apply(src, dst); }); return putImage(dst, uri); } **/ QString Segmentation::movingAverage(const QString &uri, double maxValue, double weightOfMean, int n) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); cv::Mat dst; polka::movingAverage(*image, dst, maxValue, weightOfMean, n); return putImage(dst, uri); } #define sign(a) ((a) < 0 ? -1 : ((a) > 0 ? 1 : 0)) QString Segmentation::marrHildreth(const QString &uri, double sigma, const QVariantList &laplacian, double threshold) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); int n = std::ceil(6.0 * sigma); if (n % 2 == 0) n++; cv::Mat gussianKernel(n, n, CV_32FC1); int offset = n / 2; float *pGussianKernel = (float *)gussianKernel.data; for (int i = -offset, k = 0; i <= offset; i++) { for (int j = -offset; j <= offset; j++, k++) { pGussianKernel[k] = std::exp(-0.5 * static_cast<float>(i * i + j * j) / static_cast<float>(sigma * sigma)); } } n = std::sqrt(laplacian.size()); cv::Mat laplacianKernel(n, n, CV_32FC1); float *pLaplacian = (float *)laplacianKernel.data; for (int i = 0, k = 0; i < n; i++) { for (int j = 0; j < n; j++, k++) { pLaplacian[k] = laplacian[k].toFloat(); } } cv::Mat dst(image->size(), CV_8UC1, cv::Scalar(0)); polka::extractLuminace(*image, [&](const cv::Mat &luminance) { cv::Mat smooth; cv::Mat deviative; cv::filter2D(luminance, smooth, CV_32F, gussianKernel, cv::Point(-1, -1), 0, cv::BORDER_DEFAULT); cv::filter2D(smooth, deviative, CV_32F, laplacianKernel, cv::Point(-1, -1), 0, cv::BORDER_DEFAULT); uchar *pdst = dst.data; float *pDeviative = (float *)deviative.data; for (int i = 0, k = 0; i < dst.rows; i++) { for (int j = 0; j < dst.cols; j++, k++) { int condition = 0; // left/right if (j > 0 && j < dst.cols - 1) { condition++; float left = pDeviative[k - 1]; float right = pDeviative[k + 1]; if (sign(left) != sign(right) && std::abs(std::abs(left) - std::abs(right)) > threshold) { pdst[k] = 255; continue; } } // up/down if (i > 0 && i < dst.rows - 1) { condition++; float up = pDeviative[k - dst.cols]; float down = pDeviative[k + dst.cols]; if (sign(up) != sign(down) && std::abs(std::abs(up) - std::abs(down)) > threshold) { pdst[k] = 255; continue; } } if (condition == 2) { // +45 diagonal float v1 = pDeviative[k - dst.cols + 1]; float v2 = pDeviative[k + dst.cols - 1]; if (sign(v1) != sign(v2) && std::abs(std::abs(v1) - std::abs(v2)) > threshold) { pdst[k] = 255; continue; } // -45 diagonal v1 = pDeviative[k - dst.cols - 1]; v2 = pDeviative[k + dst.cols + 1]; if (sign(v1) != sign(v2) && std::abs(std::abs(v1) - std::abs(v2)) > threshold) { pdst[k] = 255; continue; } } } } }); return putImage(dst, uri); } QString Segmentation::canny(const QString &uri, double lowerThreshold, double higherThreshold) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); cv::Mat dst; polka::extractLuminace(*image, [&](const cv::Mat &luminance) { cv::Canny(luminance, dst, lowerThreshold, higherThreshold); }); return putImage(dst, uri); } QString Segmentation::houghLines(const QString &uri, double rho, double theta, int threshold, double minLineLength, double maxLineGap, double minAngle, double maxAngle) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); cv::Mat dst(image->size(), CV_8UC1, cv::Scalar(0)); polka::extractLuminace(*image, [&](const cv::Mat &luminance) { std::vector<cv::Vec4i> lines; HoughLinesP(luminance, lines, rho, theta, threshold, minLineLength, maxLineGap); for(size_t i = 0; i < lines.size(); i++) { cv::Vec4i l = lines[i]; cv::line(dst, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar(255), 1, cv::LINE_AA); } }); return putImage(dst, uri); } QString Segmentation::houghCircles(const QString &uri, double dp, double minDist, double threshold1, double threshold2, int minRadiusf, int maxRadius) { const cv::Mat *image = ImageManager::get(uri); if (!image) return QString(); cv::Mat dst(image->size(), CV_8UC1, cv::Scalar(0)); polka::extractLuminace(*image, [&](const cv::Mat &luminance) { std::vector<cv::Vec3f> circles; cv::HoughCircles(luminance, circles, cv::HOUGH_GRADIENT, dp, minDist, threshold1, threshold2, minRadiusf, maxRadius); for(size_t i = 0; i < circles.size(); i++) { cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // draw the circle center cv::circle(dst, center, 3, cv::Scalar(255), -1, 8, 0); // draw the circle outline cv::circle(dst, center, radius, cv::Scalar(255), 1, 8, 0); } }); return putImage(dst, uri); }
42.245675
202
0.547219
[ "vector" ]
b6aaa5f97ba87a4ea2c13f3a7ac9a8392baf53f8
1,395
cc
C++
CommBasicObjects/toolify/src-gen/CommBasicObjectsJSON/CommTimeStampJSON.cc
Servicerobotics-Ulm/DomainModelsRepositories
7cc2bd5d4f9a11275721e77b6bd5164b9ff2bb7b
[ "BSD-3-Clause" ]
null
null
null
CommBasicObjects/toolify/src-gen/CommBasicObjectsJSON/CommTimeStampJSON.cc
Servicerobotics-Ulm/DomainModelsRepositories
7cc2bd5d4f9a11275721e77b6bd5164b9ff2bb7b
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommBasicObjects/toolify/src-gen/CommBasicObjectsJSON/CommTimeStampJSON.cc
Servicerobotics-Ulm/DomainModelsRepositories
7cc2bd5d4f9a11275721e77b6bd5164b9ff2bb7b
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//----------------------------------------------------------------------------------- // Code generated by the Toolify Robotics GmbH extension for the SmartMDSD Toolchain // // Toolify Robotics GmbH // Weinbergweg 216 // 89075 Ulm // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //----------------------------------------------------------------------------------- #include "CommTimeStampJSON.hh" namespace CommBasicObjectsIDL { void to_json(const CommBasicObjectsIDL::CommTimeStamp& obj, nlohmann::json& j) { // sec: UInt32 j["sec"] = obj.sec; // usec: UInt32 j["usec"] = obj.usec; } /** * this transformation handles missing values and checks for correct types: * - missing primitive type values (including simple arrays) are set to zero values * - missing object type values are skipped entirely * - types are checked before performing the type-cast operation */ void from_json(const nlohmann::json& j, CommBasicObjectsIDL::CommTimeStamp& obj) { // sec: UInt32 if(j.contains("sec") && j["sec"].is_number_unsigned()) { obj.sec = j["sec"].get<unsigned int>(); } // usec: UInt32 if(j.contains("usec") && j["usec"].is_number_unsigned()) { obj.usec = j["usec"].get<unsigned int>(); } } } // end namespace CommBasicObjectsIDL
29.680851
85
0.62509
[ "object" ]
b6ae945aceeab7d9b8daa6475b5215de9ec812f6
24,220
cpp
C++
bitcode/examples/avtrailer/avtrailer.cpp
eluv-io/content-bitcode
d73da79593dcf1d16065096d31ab4f1ca3d2b306
[ "MIT" ]
1
2020-09-30T18:11:32.000Z
2020-09-30T18:11:32.000Z
bitcode/examples/avtrailer/avtrailer.cpp
eluv-io/content-bitcode
d73da79593dcf1d16065096d31ab4f1ca3d2b306
[ "MIT" ]
1
2021-01-21T00:48:00.000Z
2021-01-21T01:07:50.000Z
bitcode/examples/avtrailer/avtrailer.cpp
eluv-io/content-bitcode
d73da79593dcf1d16065096d31ab4f1ca3d2b306
[ "MIT" ]
null
null
null
/* * The same as avmaster, but the video function creates a much shorter clip instead */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <pthread.h> #include <fcntl.h> #include <fstream> #include <iostream> #include <string> #include <unordered_map> #include <vector> #include <sstream> #include <nlohmann/json.hpp> #include "eluvio/dasher.h" #include "eluvio/cmdlngen.h" #include "eluvio/argutils.h" #include "eluvio/fixup-cpp.h" #include "eluvio/dashmanifest.h" #include "eluvio/dashsegment.h" #include "eluvio/utils.h" #include "eluvio/el_cgo_interface.h" #include "eluvio/bitcode_context.h" #include "eluvio/media.h" using namespace elv_context; using nlohmann::json; template<char delimiter> class WordDelimitedBy : public std::string {}; /* * Renders an html page with a dash player. */ elv_return_type dashHtml(BitCodeCallContext* ctx, char *url) { size_t szUrl = strlen(url) + 1; char mpdUrl[szUrl]; strcpy(mpdUrl,url); char *ext = strrchr(mpdUrl, '.'); if(strcmp(ext,".html") != 0){ const char* msg = "make html requested with url not containing .html"; return ctx->make_error(msg, E(msg)); } /* replace html with mpd */ if (ext != NULL) strcpy(ext, ".mpd"); /*TODO: this embedded html should be a template resource, part of the content */ const std::string body_format(R"( <!doctype html> <html> <head> <title>Eluvio Fabric Dash Player</title> <style> video{ display: block; margin-left: auto; margin-right: auto; height: 100vh; width: auto; } body { background-color:black; } </style> </head> <body> <div> <video data-dashjs-player autoplay src='%s' controls> </video> </div> <script src='https://cdn.dashjs.org/latest/dash.all.min.js'></script> </body> </html>)"); const char* headers = R"("text/html")"; std::string str_body = string_format(body_format, mpdUrl); ctx->Callback(200,headers,str_body.length()); std::vector<unsigned char> htmlData(str_body.c_str(), str_body.c_str() + str_body.length()); auto ret = ctx->WriteOutput(htmlData); if (ret.second.IsError()){ const char* msg = "WriteOutput"; return ctx->make_error(msg, ret.second); } return ctx->make_success(); } /* * Outputs the data from key "image" */ elv_return_type make_image(BitCodeCallContext* ctx) { return elv_media_fns::make_image(ctx); } /* * Outputs a single video file based on the start and end times in the request * pStart - string rep of a floating point start time * pEnd - string rep of a floating point end time * * Video Segment: http://localhost:4567/dash/rep/video?start=22&end=33 * Video Segment: http://localhost:4567/dash/rep/video?end=52&start=33 * All temp files are removed on success */ elv_return_type make_video(BitCodeCallContext* ctx, const char* pStart, const char* pEnd, nlohmann::json* output=NULL, const char* filename=NULL) { char* inputsSegment[] = { (char*)"-hide_banner", (char*)"-nostats", (char*)"-y", (char*)"-loglevel", (char*)"debug", (char*)"-i", (char*)"%INPUTFILE%", (char*)"-ss", (char*)"MISSED", (char*)"-to", (char*)"MISSED", (char*)"-c:v", (char*)"copy", (char*)"-c:a", (char*)"copy", (char*)"%MEDIA%"}; char* inputsFullVideo[] = { (char*)"-hide_banner", (char*)"-nostats", (char*)"-y", (char*)"-loglevel", (char*)"debug", (char*)"-i", (char*)"%INPUTFILE%", (char*)"-vf", (char*)R"(select='lt(mod(t\,10)\,0.5)',setpts=N/FRAME_RATE/TB)", (char*)"-af", (char*)R"(aselect='lt(mod(t\,10)\,0.5)',asetpts=N/SR/TB)", (char*)"%MEDIA%"}; int szFullParams = sizeof(inputsFullVideo)/sizeof(char*); int szSegmentParams = sizeof(inputsSegment)/sizeof(char*); char** inputs; int cEls; bool isFullVideo = false; if(pEnd == NULL || pStart == NULL){ pStart = "0.0"; inputs = inputsFullVideo; cEls = sizeof(inputsFullVideo)/sizeof(const char*); isFullVideo = true; }else{ inputs = inputsSegment; cEls = sizeof(inputsSegment)/sizeof(const char*); } auto kvPkg = ctx->SQMDGetJSON((char*)"pkg"); if (kvPkg.second.IsError()){ const char* msg = "SQMD find pkg"; return ctx->make_error(msg, kvPkg.second); } auto jsonPkg = kvPkg.first; std::string partHash = *(jsonPkg.begin()); LOG_DEBUG(ctx, "make_video", "PARTHASH", partHash, "JSON", jsonPkg); if (!isFullVideo){ inputs[8] = (char*)pStart; inputs[10] = (char*)pEnd; } nlohmann::json j; auto inputStream = ctx->NewStream(); std::string outputStream; if (output){ outputStream = (*output)["stream_id"].get<string>(); }else{ outputStream = ctx->NewStream(); } j["input_hash"] = partHash; j["output_stream_id"] = outputStream; j["output_media_segment"] = ""; std::string in_files = j.dump(); auto ffmpegRet = ctx->FFMPEGRunVideo(inputs, isFullVideo ? szFullParams : szSegmentParams, in_files); if (ffmpegRet.second.IsError()){ // ERROR return ffmpegRet; } std::vector<unsigned char> segData; auto loadRet = elv_media_fns::load_all_data_from_stream(ctx, outputStream.c_str(), segData); if (loadRet.second.IsError()){ return ctx->make_error("make_video LoadFromStream", loadRet.second); } if (output == nullptr){ if (filename == NULL) ctx->Callback(200, "video/mp4", segData.size()); else ctx->CallbackDisposition(200, "video/mp4", segData.size(), filename); auto ret = ctx->WriteOutput(segData); ctx->CloseStream(outputStream); ctx->CloseStream(inputStream); }else{ // called by tagger ctx->CloseStream(inputStream); } // NOTE IF YOU USE THE PASSED IN FILENAME YOU MUST UNLINK IT YOURSELF return ctx->make_success(); } std::string FormatTimecode ( int time ){ if ( time < 0 ) return std::string("ERROR"); int hour = time / 3600;; int min = time % 3600 / 60;; int sec = time % 60; std::string strRet; if ( hour > 0 ){ if (hour < 10){ strRet += '0'; } strRet += std::to_string(hour); strRet += ':'; } else{ strRet += "00:"; } if ( min < 60 && min > 0 ){ if ( min < 10 ){ strRet += '0'; } strRet += std::to_string(min); strRet += ':'; }else{ strRet += "00:"; } if ( sec < 60 && sec >= 0 ){ if ( sec < 10){ strRet += '0'; } strRet += std::to_string(sec); } return strRet + ".000"; } /* * Outputs the data from key "image" */ elv_return_type taggit(BitCodeCallContext* ctx, double durationInSecs) { //run --rm --mount src=/home/jan/boatramp,target=/data,type=bind video_tagging:latest boatramp_180s.mov char* inputs[] = { (char*)"run", (char*)"--rm", (char*)"--mount", (char*)"%INPUTSTREAM%", (char*)"video_tagging:latest", (char*)"%OUTPUTSTREAM%" }; double roundedUp = ceil(durationInSecs); int iRoundedUp = (int)roundedUp; int segmentSize = 30; auto ret = ctx->SQMDSetJSON((char*)"video_tags", (char*)"{}"); if (ret.second.IsError()){ const char* msg = "set video_tags on meta"; return ctx->make_error(msg, E(msg).Kind(E::Permission)); } for (int segment=0; segment<iRoundedUp; segment+=segmentSize){ using defer = shared_ptr<void>; auto inStream = ctx->NewFileStream(); auto outStream = ctx->NewFileStream(); defer _(nullptr, [ctx, inStream, outStream](...){ LOG_DEBUG(ctx, "Lambda Firing:"); ctx->CloseStream(inStream["stream_id"]); ctx->CloseStream(outStream["stream_id"]); }); nlohmann::json j; j["input_stream_id"] = inStream["stream_id"]; j["output_stream_id"] = outStream["stream_id"]; char start[64]; char end[64]; sprintf(start, "%i", segment); int iEnd = (segment + segmentSize) > iRoundedUp ? iRoundedUp : (segment + segmentSize); sprintf(end, "%i", iEnd); LOG_DEBUG(ctx, "New File", "stream_id", inStream["stream_id"], "begin_seg", start); auto res = make_video(ctx,start,end, &inStream); if (res.second.IsError()){ LOG_ERROR(ctx, "make_video failed", "segment", start); continue; } auto inFiles = j.dump(); auto tagRet = ctx->TaggerRun(inputs, sizeof(inputs)/sizeof(char*), inFiles); if (tagRet.second.IsError()){ // ERROR return tagRet; } std::vector<unsigned char> segData; auto loadRet = elv_media_fns::load_all_data_from_stream(ctx, outStream["stream_id"].get<std::string>().c_str(), segData); if (loadRet.second.IsError()){ return ctx->make_error("make_video LoadFromStream", loadRet.second); } if (strcmp((const char*)segData.data(),(char*)"") != 0){ LOG_DEBUG(ctx, "Stream segment info", "data", (const char*)segData.data()); auto jsonRep = json::parse(segData.data()); auto video_tags = jsonRep["videoTags"]; std::string timeIn = FormatTimecode(segment); std::string timeOut = FormatTimecode(iEnd); json jsonNew = json::array(); json jsonObj; jsonObj["time_in"] = timeIn; jsonObj["time_out"] = timeOut; jsonObj["tags"] = video_tags; jsonNew.push_back(jsonObj); auto ret = ctx->SQMDMergeJSON((char*)"video_tags", (char*)jsonNew.dump().c_str()); if (ret.second.IsError()){ LOG_ERROR(ctx, "SQMDMergeJSON", "video_tags", jsonNew.dump().c_str(), "inner_error", ret.second.getJSON()); return ret; } }else{ LOG_ERROR(ctx, "Empty JSON returned"); } } nlohmann::json j; j["headers"] = "application/json"; j["body"] = "SUCCESS"; return std::make_pair(j,E(false)); } /* * Externally callable function to invoke the ML video tagging * * Arguments: * None (all auto) * Example URLs: * http://localhost:8008/qlibs/ilibXXX/q/hq__XXX/call/tagger */ elv_return_type tagger(BitCodeCallContext* ctx, JPCParams&) { return taggit(ctx, 100.0); } /* find_ads(BitcodeCallCtx, std::vector<std::string>& tags) tags - vector of strings with tags of interest */ elv_return_type find_ads(BitCodeCallContext* ctx, std::vector<std::string>& tags){ auto kvPkg = ctx->KVGet((char*)"assets"); if (kvPkg == ""){ const char* msg = "getting assets from content"; return ctx->make_error(msg, E(msg).Kind(E::NotExist)); } auto jsonPkg = json::parse(kvPkg); std::map<string, float> matches; std::map<string, float>::iterator itProbs; float max = 0.0; std::string maxTag; for(auto& tag : tags){ for (json::iterator it = jsonPkg.begin(); it != jsonPkg.end(); ++it) { auto data = (*it)[tag]; if (data != NULL){ if (data > max){ max = data; maxTag = tag; } } } } char returnString[16384]; auto returnFormat = R"({"price":%.2f,"tag":"%s"})"; sprintf(returnString, returnFormat, max, maxTag.c_str()); /* Prepare output */ nlohmann::json j; j["headers"] = "application/json"; j["body"] = returnString; return std::make_pair(j,0); } /* * Returns one ad content object as a JSON { "library" : "", "hash": "" } */ elv_return_type ad(BitCodeCallContext* ctx, JPCParams& p) { /* Extract an ad library from the list */ auto adlibid = ctx->KVGet((char *)"eluv.sponsor.qlibid"); if (adlibid == "") { const char* msg = "Failed to retrieve ad library"; return ctx->make_error(msg, E(msg).Kind(E::IO)); } auto adhash = ctx->KVGet((char *)"eluv.sponsor.qhash"); if (adhash == "") { const char* msg = "Getting eluv.sponsor.qhash"; return ctx->make_error(msg, E(msg).Kind(E::IO)); } char *headers = (char *)"text/html"; char body[1024]; snprintf(body, sizeof(body), (char *)"{\"library\":\"%s\",\"hash\":\"%s\"}", adlibid.c_str(), adhash.c_str()); /* Prepare output */ nlohmann::json j; j["headers"] = headers; j["body"] = body; return std::make_pair(j,0); } elv_return_type make_hls_playlist( BitCodeCallContext* ctx, char* req ) { // Example requests: /hls/en-master.m3u8 // hls/en-video-1080p@5120000.m3u8 // hls/en-master.m3u8 // keys: ["en", "master.m3u8"], ["en", "video-1080p@5120000.m3u8"] int req_len = strlen(req); if (req_len == 0){ std::string msg = "make_hls_playlist bad request len = 0"; return ctx->make_error(msg, E(msg).Cause(eluvio_errors::ErrorKinds::BadHttpParams)); } char suffix[5]; char* preamble = (char*)alloca(req_len); char language[10]; char format[20]; char bandwidth[10]; char filename[10]; json j; language[0] = 0; for (int i=0; i < req_len; i++){ char curCh = req[i]; if (curCh == '-' || curCh == '/' || curCh == '.' || curCh == '@') // Not found lang yet req[i] = ' '; } if ( strstr(req, "master") !=NULL ) { auto ret = sscanf(req, "%s%s%s%s", preamble, language, filename, suffix); if (ret != 4){ std::string msg = "make_hls_playlist sscanf incorrect params"; return ctx->make_error(msg, E(msg, std::string("count"), ret)); } LOG_DEBUG( ctx, "request", "pre", preamble, "lang", language, "file", filename, "sfx", suffix ); } else { auto ret = sscanf(req, "%s%s%s%s%s%s", preamble, language, filename, format, bandwidth, suffix); if (ret != 6){ std::string msg = "make_hls_playlist sscanf incorrect params"; return ctx->make_error(msg, E(msg, std::string("count"), ret)); } LOG_DEBUG( ctx, "request", "pre", preamble, "lang", language, "file", filename, "fmt", format, "bw", bandwidth, "sfx", suffix ); } char offering_keybuf[128]; sprintf(offering_keybuf, "legOffering.%s", language); auto offering_b64_res = ctx->SQMDGetJSON((char*)offering_keybuf); if (offering_b64_res.second.IsError()){ return ctx->make_error("make_hls_playlist", offering_b64_res.second); } std::string offering_b64 = offering_b64_res.first; const char* msg = "make_hls_playlist extract offering"; if (offering_b64 == ""){ return ctx->make_error(msg, E(msg, "op","SQMDGetJSON", "offering", (const char*)offering_keybuf)); } LOG_DEBUG(ctx, msg, "key", offering_keybuf, "b64", offering_b64); std::string offering_json = base64_decode(offering_b64); LOG_DEBUG(ctx, msg, "key", offering_keybuf, "json", offering_json); json j2 = json::parse(offering_json); char playlist_keybuf[128]; if (strcmp(filename, "master")==0) { sprintf(playlist_keybuf, "%s.%s", filename, suffix); } else { sprintf(playlist_keybuf, "%s-%s@%s.%s", filename, format, bandwidth, suffix); } char buf[128]; sprintf(buf, "offering.%s.hls", language); LOG_DEBUG(ctx, "get playlist", "key", buf); std::string playlist_b64 = j2["offering"]["hls"][playlist_keybuf]; LOG_DEBUG(ctx, "encoded playlist", "b64", playlist_b64); std::string playlist = base64_decode(playlist_b64); LOG_DEBUG(ctx, "decoded playlist", "playlist", playlist); ctx->Callback(200, "application/x-mpegURL", playlist.length()); std::vector<unsigned char> playlistData(playlist.c_str(), playlist.c_str() + playlist.length()); auto ret = ctx->WriteOutput(playlistData); return ctx->make_success(); } /* * Dispatch content requests * * For DASH there are several types of requests: * - manifest (.mpd) * - video segment (.m4v) (initializer segment) * - audio segment (.m4a) (initializer segment has no segno) * * Arguments: * None all automatic * Example URLs: Manifest: http://localhost:4567/dash/EN.mpd Video Init Segment: http://localhost:4567/dash/EN-1280x544-1300000-init.m4v Video Segment: http://localhost:4567/dash/EN-1280x544-1300000-1.m4v Audio Init Segment: http://localhost:4567/dash/EN-STERO-3200-init.m4a Audio Segment: http://localhost:4567/dash/EN-STEREO-3200-1.m4a */ elv_return_type content(BitCodeCallContext* ctx, JPCParams& p) { auto path = ctx->HttpParam(p, "path"); if (path.second.IsError()){ return ctx->make_error("getting path from JSON", path.second); } auto params = ctx->QueryParams(p); if (params.second.IsError()){ return ctx->make_error("Query Parameters from JSON", params.second); } typedef enum eMKTypes { VIDEO , AUDIO, MANIFEST, HTML, AD } MKTypes; const char* startTag = "start"; const char* endTag = "end"; char* pContentRequest = (char*)path.first.c_str(); LOG_INFO(ctx, "content", "request", pContentRequest); char szMK[5]; int cbContentRequest = strlen(pContentRequest); MKTypes mk; strcpy(szMK, (pContentRequest+cbContentRequest-3)); /* Fist check for matching URL paths */ if (strcmp(pContentRequest, "/image") == 0) { LOG_DEBUG(ctx, "Performing REP /image"); return make_image(ctx); } if (strncmp(pContentRequest, "/checksum", strlen("/checksum")) == 0){ return elv_media_fns::make_sum(ctx, p); } auto isDownload = strncmp(pContentRequest, "/download", strlen("/download")) == 0; auto isVideo = strncmp(pContentRequest, "/video", strlen("/video")) == 0; if (isDownload || isVideo) { auto it_start = params.first.find(startTag); auto it_end = params.first.find(endTag); if (it_end == params.first.end() || it_start == params.first.end()){ return (isDownload) ? make_video(ctx, NULL,NULL,0, base_download_file) : make_video(ctx, NULL,NULL); } std::map<std::string, std::string> timeframe; timeframe[it_start->first] = it_start->second; timeframe[it_end->first] = it_end->second; auto startTime = std::stod(timeframe[startTag]); auto endTime = std::stod(timeframe[endTag]); if (startTime > endTime){ const char* msg = "Invalid range specified, end must be greater than start"; LOG_ERROR(ctx, msg, "start," ,startTime, "end", endTime); return ctx->make_error(msg, E(msg).Kind(E::Invalid)); } return (isDownload) ? make_video(ctx, timeframe[startTag].c_str(), timeframe[endTag].c_str(), 0, base_download_file): make_video(ctx, timeframe[startTag].c_str(), timeframe[endTag].c_str()); } if (strcmp(pContentRequest, "/ads") == 0) { auto it_tags = params.first.find("tags"); if (it_tags == params.first.end()){ const char* msg = "Avmaster no tags provided"; return ctx->make_error(msg, E(msg).Kind(E::IO)); } std::istringstream iss(it_tags->second); std::vector<std::string> tags((std::istream_iterator<WordDelimitedBy<','>>(iss)), std::istream_iterator<WordDelimitedBy<','>>()); return find_ads(ctx, tags); } if (strstr(pContentRequest, "/hls/")) { if (strstr(pContentRequest, ".m3u8")) { LOG_DEBUG(ctx, "REP /hls playlist", "request url", pContentRequest); try { return make_hls_playlist(ctx, pContentRequest); } catch (std::exception e) { return ctx->make_error("make_hls_playlist exception", E(e.what()).Kind(E::Other)); } } /* Fall through to serve segments - HLS and DASH segments are the same */ } /* Check for DASH extensions */ char *dot = strrchr(pContentRequest, '.'); if (!dot){ const char* msg = "dash request made but not '.' can be found in URL to parse"; return ctx->make_error(msg , E(msg).Kind(E::Invalid)); } if (strcmp(szMK, "mpd") == 0) // really need to return error if not matching any mk = MANIFEST; else if (strcmp(szMK, "m4v") == 0) mk = VIDEO; else if (strcmp(szMK, "m4a") == 0) mk = AUDIO; else if (strcmp(dot, ".html") == 0) mk = HTML; else if (strcmp(dot, ".ad") == 0) mk = AD; else{ const char* msg = "Unknown parse type detected"; return ctx->make_error(msg, E(msg).Kind(E::Other)); } // URL path (e.g.: "/dash/EN-320p@1300000-init.m4v") char* szPreamble = (char*)alloca(cbContentRequest); char szLanguage[10]; char szFormat[20]; char bandwidth[10]; char track[10]; json j; szLanguage[0] = 0; for (int i=0; i < cbContentRequest;i++){ char curCh = pContentRequest[i]; if (curCh == '-' || curCh == '/' || curCh == '.' || curCh == '@') // Not found lang yet pContentRequest[i] = ' '; } sscanf(pContentRequest, "%s%s%s%s%s%s", szPreamble, szLanguage, szFormat, bandwidth, track, szMK); LOG_DEBUG(ctx, "content", "request", pContentRequest, "preamble", szPreamble, "lang", szLanguage, "format", szFormat, "bw", bandwidth, "track", track, "mk", szMK); char buf[128]; sprintf(buf, "legOffering.%s", szLanguage); auto kvGotten = ctx->SQMDGetJSON((char*)buf); auto kvWatermark = ctx->SQMDGetJSON((char*)"watermark"); if (kvGotten.second.IsError()){ const char* msg = "json not found"; return ctx->make_error(msg, kvGotten.second); } std::string watermark_json = kvWatermark.second.IsError() ? std::string("{}") : kvWatermark.first.dump(); std::string decoded_json = base64_decode(kvGotten.first.dump().substr(1)); switch(mk){ case AUDIO: case VIDEO: { std::string rep_name = std::string(szFormat) + "@" + std::string(bandwidth); Dasher dasher((mk==AUDIO)? 'a' : 'v', std::string(szLanguage), rep_name, std::string(track), decoded_json, ctx, watermark_json); dasher.initialize(); DashSegmentGenerator<Dasher> gen(dasher); return gen.dashSegment(ctx); } break; case MANIFEST: { std::string strAuth; j = json::parse(decoded_json); DashManifest dashManifest(j); if (params.first.find("authorization") != params.first.end()){ strAuth = params.first["authorization"]; LOG_DEBUG(ctx, "Found authorization info"); } std::string manifestString = dashManifest.Create(strAuth); ctx->Callback(200, "application/dash+xml", manifestString.length()); std::vector<unsigned char> manifestData(manifestString.c_str(), manifestString.c_str()+manifestString.length()); auto ret = ctx->WriteOutput(manifestData); return ctx->make_success(); } break; case HTML: { //return dashHtml(ctx, url); const char* msg ="Feature not currently working"; return ctx->make_error(msg, E(msg).Kind(E::NotImplemented)); } case AD: return ad(ctx, p); default: { const char* msg = "unknown url file extension requested"; return ctx->make_error(msg, E(msg).Kind(E::NotExist)); } }; return ctx->make_error("unknown type requested", E("unknown type requested").Kind(E::NotExist)); } BEGIN_MODULE_MAP() MODULE_MAP_ENTRY(content) MODULE_MAP_ENTRY(ad) MODULE_MAP_ENTRY(tagger) END_MODULE_MAP()
32.379679
198
0.587655
[ "object", "vector" ]
b6b67f53b7ed8865da55b8090cd1307936b8aae1
1,145
cpp
C++
GameEngine/Sources/TextureDataStorage.cpp
GPUWorks/OpenGL-Mini-CAD-2D
fedb903302f82a1d1ff0ca6776687a60a237008a
[ "MIT" ]
1
2021-08-10T02:48:57.000Z
2021-08-10T02:48:57.000Z
GameEngine/Sources/TextureDataStorage.cpp
GPUWorks/OpenGL-Mini-CAD-2D
fedb903302f82a1d1ff0ca6776687a60a237008a
[ "MIT" ]
null
null
null
GameEngine/Sources/TextureDataStorage.cpp
GPUWorks/OpenGL-Mini-CAD-2D
fedb903302f82a1d1ff0ca6776687a60a237008a
[ "MIT" ]
null
null
null
#include "TextureDataStorage.h" //------------------------------ Constructors storage::TextureDataStorage::TextureDataStorage() { } storage::TextureDataStorage::TextureDataStorage(GLuint mip_level, GLenum sized_internal_format, GLenum base_internal_format, GLuint width, GLuint height, GLuint min_texture_size, GLuint layers) { if (width == height) this->array_2d_square_texture_buffer = storage::Array2DSquareTextureBuffer(mip_level, sized_internal_format, base_internal_format, width, min_texture_size, layers); } storage::Array2DSquareTextureBuffer storage::TextureDataStorage::getArray2DSquareTextureBuffer() { return this->array_2d_square_texture_buffer; } void storage::TextureDataStorage::addModelTexture(model::ModelFormat* model) { this->array_2d_square_texture_buffer.bindTexture(); for (mesh::MeshFormat* mesh : model->meshes) { //mesh->model_property.texture_array_index = this->array_2d_square_texture_buffer.insertData(mesh->textures[texture::TEXTURE_DIFFUSE]->width, //mesh->textures[texture::TEXTURE_DIFFUSE]->height, &(mesh->textures[texture::TEXTURE_DIFFUSE]->data[0])); } }
35.78125
194
0.763319
[ "mesh", "model" ]
b6b9e03965a33c1e4296d7fb5ebe7b0e1b24816d
9,382
cpp
C++
tlua.cpp
crazybie/tlua
fee427098af4a4fc115b619fc0d77ea4c9be549f
[ "MIT" ]
2
2018-12-11T02:46:10.000Z
2019-04-03T10:02:18.000Z
tlua.cpp
crazybie/tlua
fee427098af4a4fc115b619fc0d77ea4c9be549f
[ "MIT" ]
null
null
null
tlua.cpp
crazybie/tlua
fee427098af4a4fc115b619fc0d77ea4c9be549f
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "tlua.h" namespace tlua { LuaMgr* LuaMgr::instance = nullptr; lua_State* LuaObj::L = nullptr; LuaMgr::LuaMgr() { instance = this; L = luaL_newstate(); luaL_openlibs(L); #ifndef TLUA_NO_SOCKET luaopen_socket_core(L); #endif LuaRef loaders = getGlobal("package")["loaders"]; if (loaders.type() != LUA_TTABLE) { loaders = (LuaRef)getGlobal("package")["searchers"]; } loaders.append(&luaLoader); setGlobal("__traceback", &traceback); //lua_gc(L, LUA_GCSETSTEPMUL, 1); logError = [](const string& err) { fprintf(stderr, "LUA ERROR: %s\n", err.c_str()); }; fileLoader = loadFile; auto setupType = doString(R"( function string.split(s, p) local r = {} string.gsub(s, p, function(c) r[#r+1] = c end) return r end local function setupOverloads(class) local o = {} for k,v in pairs(class) do if type(v)=='function' then local p = string.split(k, '([^#]+)') if #p > 1 then local name, argcnt = p[1], tonumber(p[2]) o[name] = o[name] or {} table.insert(o[name], argcnt) end end end for k,v in pairs(o) do class[k] = function(...) local nargs = select('#',...) for _, needArgs in ipairs(v) do if nargs == needArgs then return class[k..'#'..nargs](...) end end error('invalid arguments count') end end end local function setupType(typeName) local class = _G[typeName] local pget = class['__prop_get'] local pset = class['__prop_set'] class._name = typeName if class._lifetime ~= 'cpp' then class.__gc = class.Delete end if class.base then local baseName = class.base class.base = _G[baseName] assert(class.base, 'base class not exported:'..baseName) end class.__index = function(t, k) local f = pget[k] if f then return f(t) end local base = class.base return class[k] or (base and base.__index(t, k)) end class.__newindex = function(t,k,v) local f = pset[k] local c = class while not f and c.base do c = c.base f = c.__prop_set[k] end if f then return f(t,v) end end setupOverloads(class) local classMt = {} if class.New then classMt.__call = function(class, ...) return class.New(...) end end setmetatable(class, classMt) end return setupType )"); for (auto i : getRegisters()) { i.second(); } for (auto i : getRegisters()) { setupType.call(i.first); } } void LuaMgr::setSourceRoot(string luaRoot /*= ""*/) { srcDir = luaRoot; } LuaMgr::~LuaMgr() { lua_close(L); L = nullptr; } std::vector<std::pair<std::string, tlua::LuaMgr::Register>>& LuaMgr::getRegisters() { static std::vector<std::pair<std::string, tlua::LuaMgr::Register>> registers; return registers; } tlua::LuaRef LuaMgr::doFile(const char *name) { auto cmd = string("return require('") + name + "')"; if (luaL_loadstring(L, cmd.c_str())) { logError(lua_tostring(L, -1)); return LuaRef(); } return FuncHelper::callLua<LuaRef>(); } tlua::LuaRef LuaMgr::doString(const char* name) { if (luaL_loadstring(L, name)) { logError(lua_tostring(L, -1)); return LuaRef(); } return FuncHelper::callLua<LuaRef>(); } tlua::LuaRef LuaMgr::newTable() { lua_newtable(L); return LuaRef::fromStack(); } tlua::LuaRef LuaMgr::getGlobal(const char* name) { lua_getglobal(L, name); return LuaRef::fromStack(); } std::string LuaMgr::loadFile(const char* name) { string ret; if (FILE* f = fopen(name, "rb")) { fseek(f, 0, SEEK_END); ret.resize(ftell(f)); fseek(f, 0, SEEK_SET); fread((void*)ret.data(), ret.size(), 1, f); fclose(f); } return ret; } void LuaMgr::traceback(const char* msg) { auto ignoreFuncStackCnt = 2;// debug.traceback + __traceback instance->logError(instance->getCallStack(msg, ignoreFuncStackCnt)); } const char* LuaMgr::getCallStack(const char* msg, int ignoreFuncStackCnt) { auto stack = instance->getGlobal("debug")["traceback"].call<const char*>(msg, ignoreFuncStackCnt); return stack; } int LuaMgr::luaLoader(lua_State* L) { string requireFile = lua_tostring(L, -1); while (auto c = strchr(&requireFile[0], '.')) *c = '/'; requireFile += ".lua"; auto filePath = instance->srcDir + "/" + requireFile; auto chunk = instance->loadFile(filePath.c_str()); if (chunk.size() == 0) { instance->logError(Sprintf("can not get file data of %s", filePath.c_str()).c_str()); return 0; } auto err = luaL_loadbuffer(L, chunk.data(), chunk.size(), requireFile.c_str()); if (err == LUA_ERRSYNTAX) { instance->logError(Sprintf("syntax error in %s", filePath.c_str()).c_str()); return 0; } return 1; } void LuaRefBase::iniFromStack() { m_ref = luaL_ref(L, LUA_REGISTRYINDEX); } LuaRefBase::~LuaRefBase() { if (m_ref != LUA_REFNIL && L) luaL_unref(L, LUA_REGISTRYINDEX, m_ref); } void LuaRefBase::push() const { lua_rawgeti(L, LUA_REGISTRYINDEX, m_ref); } int LuaRefBase::type() const { if (m_ref == LUA_REFNIL) return LUA_TNIL; PopOnExit p; push(); return lua_type(L, -1); } int LuaRefBase::createRef() const { if (m_ref == LUA_REFNIL) return LUA_REFNIL; push(); return luaL_ref(L, LUA_REGISTRYINDEX); } void LuaRefBase::pop() { luaL_unref(L, LUA_REGISTRYINDEX, m_ref); m_ref = luaL_ref(L, LUA_REGISTRYINDEX); } bool LuaRefBase::isNil() const { return type() == LUA_TNIL; } LuaRefBase::operator bool() const { return !isNil(); } int LuaRefBase::length() const { PopOnExit p{}; push(); return (int)lua_objlen(L, -1); } TableProxy::TableProxy(int tableRef) : m_tableRef(tableRef) { iniFromStack(); } TableProxy::TableProxy(TableProxy&& other) { m_tableRef = other.m_tableRef; m_ref = other.m_ref; other.m_ref = LUA_REFNIL; } void TableProxy::push() const { lua_rawgeti(L, LUA_REGISTRYINDEX, m_tableRef); lua_rawgeti(L, LUA_REGISTRYINDEX, m_ref); lua_gettable(L, -2); lua_remove(L, -2); // remove the table } LuaRef::LuaRef(LuaRef&& other) { m_ref = other.m_ref; other.m_ref = LUA_REFNIL; } LuaRef::LuaRef(TableProxy const& other) { m_ref = other.createRef(); } LuaRef::LuaRef(LuaRef const& other) { m_ref = other.createRef(); } tlua::LuaRef LuaRef::fromIndex(int index) { lua_pushvalue(L, index); return fromStack(); } tlua::LuaRef LuaRef::fromStack() { LuaRef r; r.iniFromStack(); return r; } tlua::LuaRef& LuaRef::operator=(LuaRef&& other) { luaL_unref(L, LUA_REGISTRYINDEX, m_ref); m_ref = other.m_ref; other.m_ref = LUA_REFNIL; return *this; } tlua::Iterator LuaRef::begin() const { return Iterator(*this); } tlua::Iterator LuaRef::end() const { return Iterator(); } Iterator::Iterator(const LuaRef& table) : m_table(table) { next(); } tlua::Iterator& Iterator::operator++() { if (valid) next(); return *this; } bool Iterator::operator!=(const Iterator& r) const { return !(*this == r); } bool Iterator::operator==(const Iterator& r) const { if (!valid && !r.valid) return true; return false; } std::pair<tlua::LuaRef, tlua::LuaRef> Iterator::operator*() { return std::pair<LuaRef, LuaRef>(m_key, m_value); } void Iterator::next() { m_table.push(); m_key.push(); valid = false; if (lua_next(L, -2)) { valid = true; m_value.pop(); m_key.pop(); } lua_pop(L, 1); } }
25.152815
106
0.502238
[ "vector" ]
b6c0974aeeea4069f3f67c201298557c70bc78a9
8,822
hpp
C++
Common/Interpreter/Numeric.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Common/Interpreter/Numeric.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Common/Interpreter/Numeric.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
#ifndef _NUMERIC_HPP_ #define _NUMERIC_HPP_ #include "config.hpp" #include "Macros.hpp" #include "Base.hpp" #include <boost/shared_ptr.hpp> #include <variant> #include <type_traits> using namespace boost; using namespace log4cpp; NAMESPACE_BEGIN(interp) template <class EncodingT> class Numeric : public Base<EncodingT> { private: typedef std::variant<long long,double> numeric_variant_t; numeric_variant_t m_value; public: // Constructor Numeric(); Numeric(const numeric_variant_t& value); template <class T, class = typename std::enable_if<std::is_integral<T>::value||std::is_enum<T>::value,T>::type> Numeric(T value); template <class T, class = void, class = typename std::enable_if<std::is_floating_point<T>::value,T>::type> Numeric(T value); FACTORY_PROTOTYPE1(Numeric, In< boost::shared_ptr< Base<EncodingT> > >) Numeric(boost::shared_ptr< Base<EncodingT> > const& value); // Accessors double Dvalue() const; void Dvalue(double value); long long LLvalue() const; void LLvalue(long long value); const numeric_variant_t& value() const; void value(const numeric_variant_t& value); // Virtual methods virtual typename EncodingT::string_t toString() const; virtual boost::shared_ptr< Base<EncodingT> > clone() const; virtual typename EncodingT::string_t getClassName() const; virtual boost::shared_ptr< Base<EncodingT> > invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params); // Dynamic methods boost::shared_ptr< Base<EncodingT> > minus() const; FACTORY_PROTOTYPE1(plus, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > plus(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(minus, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > minus(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(multiply, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > multiply(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(divide, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > divide(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(equals, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > equals(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(notEquals, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > notEquals(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(inferior, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > inferior(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(inferiorOrEqual, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > inferiorOrEqual(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(superior, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > superior(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(superiorOrEqual, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > superiorOrEqual(boost::shared_ptr< Base<EncodingT> > const& val) const; void increment(); void decrement(); boost::shared_ptr< Base<EncodingT> > round() const; FACTORY_PROTOTYPE1(parse, In< boost::shared_ptr< Base<EncodingT> > >) void parse(boost::shared_ptr< Base<EncodingT> > const& str); FACTORY_PROTOTYPE1(parseHex, In< boost::shared_ptr< Base<EncodingT> > >) void parseHex(boost::shared_ptr< Base<EncodingT> > const& str); FACTORY_PROTOTYPE3(parseBase64, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void parseBase64(boost::shared_ptr< Base<EncodingT> > const& str, boost::shared_ptr< Base<EncodingT> > const& pos, boost::shared_ptr< Base<EncodingT> > const& size); boost::shared_ptr< Base<EncodingT> > convertHex() const; // Methods registration FACTORY_BEGIN_REGISTER CLASS_REGISTER (Numeric) CLASS_REGISTER1 (Numeric) METHOD_REGISTER (Numeric, boost::shared_ptr< Base<EncodingT> >, minus, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, plus, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, minus, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, multiply, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, divide, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, inferior, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, inferiorOrEqual, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, superior, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, superiorOrEqual, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, equals, const_t) METHOD_REGISTER1 (Numeric, boost::shared_ptr< Base<EncodingT> >, notEquals, const_t) METHOD_KEY_REGISTER (Numeric, void, increment, no_const_t, UCS("Numeric::Increment")) METHOD_KEY_REGISTER (Numeric, void, decrement, no_const_t, UCS("Numeric::Decrement")) METHOD_KEY_REGISTER (Numeric, boost::shared_ptr< Base<EncodingT> >, round, const_t, UCS("Numeric::Round")) METHOD_KEY_REGISTER1 (Numeric, void, parse, no_const_t, UCS("Numeric::Parse")) METHOD_KEY_REGISTER1 (Numeric, void, parseHex, no_const_t, UCS("Numeric::ParseHex")) METHOD_KEY_REGISTER3 (Numeric, void, parseBase64, no_const_t, UCS("Numeric::ParseBase64")) METHOD_KEY_REGISTER (Numeric, boost::shared_ptr< Base<EncodingT> >, convertHex, const_t, UCS("Numeric::ConvertHex")) FACTORY_END_REGISTER // Methods unregistration FACTORY_BEGIN_UNREGISTER CLASS_UNREGISTER (Numeric) CLASS_UNREGISTER1 (Numeric) METHOD_UNREGISTER (Numeric, minus) METHOD_UNREGISTER1(Numeric, plus) METHOD_UNREGISTER1(Numeric, minus) METHOD_UNREGISTER1(Numeric, multiply) METHOD_UNREGISTER1(Numeric, divide) METHOD_UNREGISTER1(Numeric, inferior) METHOD_UNREGISTER1(Numeric, inferiorOrEqual) METHOD_UNREGISTER1(Numeric, superior) METHOD_UNREGISTER1(Numeric, superiorOrEqual) METHOD_UNREGISTER1(Numeric, equals) METHOD_UNREGISTER1(Numeric, notEquals) METHOD_KEY_UNREGISTER (UCS("Numeric::Increment")) METHOD_KEY_UNREGISTER (UCS("Numeric::Decrement")) METHOD_KEY_UNREGISTER (UCS("Numeric::Round")) METHOD_KEY_UNREGISTER1(UCS("Numeric::Parse")) METHOD_KEY_UNREGISTER1(UCS("Numeric::ParseHex")) METHOD_KEY_UNREGISTER3(UCS("Numeric::ParseBase64")) METHOD_KEY_UNREGISTER (UCS("Numeric::ConvertHex")) FACTORY_END_UNREGISTER }; template <class EncodingT> bool check_numeric(boost::shared_ptr< Base<EncodingT> > const& val, std::variant<long long,double>& n); template <class EncodingT> bool reset_numeric(boost::shared_ptr< Base<EncodingT> >& val, std::variant<long long,double> const& n); template <class EncodingT, class T, class = typename std::enable_if<std::is_integral<T>::value||std::is_enum<T>::value>::type> bool check_numeric_i(boost::shared_ptr< Base<EncodingT> > const& val, T& n); template <class EncodingT, class T, class = typename std::enable_if<std::is_integral<T>::value||std::is_enum<T>::value>::type> bool reset_numeric_i(boost::shared_ptr< Base<EncodingT> >& val, T n); template <class EncodingT, class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type> bool check_numeric_d(boost::shared_ptr< Base<EncodingT> > const& val, T& n); template <class EncodingT, class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type> bool reset_numeric_d(boost::shared_ptr< Base<EncodingT> >& val, T n); NAMESPACE_END #include "Numeric_impl.hpp" #endif
50.701149
173
0.674904
[ "vector" ]
b6c1bfc8e041d0577787b00c31844e20b3b391b9
32,421
cpp
C++
dev/RemotePC.QT/Server/ServerContext.cpp
androidNdk/iremote_copy
a0b263bed4d3664da7ce1a4e8adc93ea831e7fbf
[ "MIT" ]
9
2016-04-11T14:58:52.000Z
2021-10-08T21:58:24.000Z
dev/RemotePC.QT/Server/ServerContext.cpp
androidNdk/iremote_copy
a0b263bed4d3664da7ce1a4e8adc93ea831e7fbf
[ "MIT" ]
1
2018-02-14T23:38:01.000Z
2018-03-16T21:21:01.000Z
dev/RemotePC.QT/Server/ServerContext.cpp
androidNdk/iremote_copy
a0b263bed4d3664da7ce1a4e8adc93ea831e7fbf
[ "MIT" ]
5
2015-07-06T09:17:01.000Z
2020-02-10T06:30:23.000Z
/** * Copyright (c) 2013 Egor Pushkin. All rights reserved. * * 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 "Common/Common.h" #include "ServerContext.h" #include "Config.h" // Core messaging #include "Messages/MoveMessage.h" #include "Messages/MoveToMessage.h" #include "Messages/MouseClickMessage.h" #include "Messages/ScrollMessage.h" #include "Messages/ScrollMessage2.h" #include "Messages/KeyboardMessage.h" #include "Messages/AuthMessage.h" #include "Messages/AuthResponse.h" #include "Messages/AuthResponse2.h" #include "Messages/Messages.h" #include "Messages/VolumeMessage.h" #include "Messages/CookieMessage.h" #include "Messages/PasswordRequest.h" #include "Messages/PasswordMessage.h" #include "Messages/ZoomLevelMessage.h" #include "Messages/ScreenshotMessage.h" #include "Messages/ServiceRequest.h" #include "Messages/StreamRequest.h" #include "Versions/Features.h" // Hardware subsystem #include "Hardware/Hardware.h" // Users manager support #include "Server/UsersManager/User.h" #include "Server/UsersManager/DUsersManager.h" #include "Server/UsersManager/UsersManager.h" // Services manager support #include "Server/Services/ServiceDescriptor.h" #include "Server/Services/IDevice.h" #include "Server/Services/ServicesManager.h" // Shell support #include "Shell/ShellSupport.h" // Modal notifications support. #include "AuthContext.h" #include "OldiRemoteContext.h" namespace MinCOM { // {4F8320D1-752E-4525-A90D-38FB97C082A3} template<> const Guid TypeInfo< RemotePC::IServerControl >::iid_ = { 0x4f8320d1, 0x752e, 0x4525, { 0xa9, 0xd, 0x38, 0xfb, 0x97, 0xc0, 0x82, 0xa3 } }; // {D6DBC5E8-B8C7-4e07-BD46-485E704EC78F} template<> const Guid TypeInfo< RemotePC::IClientHandler >::iid_ = { 0xd6dbc5e8, 0xb8c7, 0x4e07, { 0xbd, 0x46, 0x48, 0x5e, 0x70, 0x4e, 0xc7, 0x8f } }; } namespace RemotePC { ServerContext::ServerContext( IUIEventsRef events ) : mc::CommonImpl< mc::IRunnable >() , mc::CommonImpl< IServerControl >() , mc::CommonImpl< mc::DServer >() , mc::CommonImpl< mc::DProtocol >() , service_( mc::Library::Service() ) , clients_() , authJobs_( mc::Library::JobsQueue() ) , listOfCookies_() , events_( events ) , servicesManager_( mc::Class< RemotePC::ServicesManager >::Create() ) { MC_LOG_ROUTINE; // Check whether input data is correct. if ( !events_ ) throw std::exception(); // Run authentication jobs queue if everything is fine. authJobs_->Run(); } ServerContext::~ServerContext() { // Detach itself from shell service. IShellControlPtr shellControl = ShellHost::Instance().GetShellControl(); if ( shellControl ) shellControl->AttachServer( NULL ); } // ICommon section mc::result ServerContext::PostInit() { return mc::_S_OK; } // IRunnable section mc::result ServerContext::Run() { MC_LOG_ROUTINE; // Initialize services manager. std::string service = Config::Instance().GetService(); servicesManager_->SetPort(service); // Start server. mc::IServerPtr server = mc::Library::TCPServer( service_ ); if ( mc::Error::IsError( server->AsyncAccept(service) ) ) { events_->FailedToStartService(); return mc::_S_FALSE; } // Attach itself to shell service. IShellControlPtr shellControl = ShellHost::Instance().GetShellControl(); if ( shellControl ) shellControl->AttachServer( ClassRoot_::GetSelf() ); // Subscribe on network server events to handle inbound connections. mc::Events::Advise( server, mc::CommonImpl< IRunnable >::GetSelf(), mc::TypeInfo< DServer >::GetGuid()); // Notify UI on successful service startup. events_->ServiceStarted(); // Just another safety measure. try { service_->Run(); } catch ( ... ) { } return mc::_S_OK; } // IServerControl section mc::result ServerContext::Stop() { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // Stop service from accepting connections. service_->Stop(); // Unregister current clients correctly. while ( clients_.size() > 0 ) { // Retrieve next client. mc::IProtocolPtr client = (*clients_.begin()).first; // Disconnect client forcibly. UnregisterClient(client); } return mc::_S_OK; } mc::result ServerContext::HandleClient(size_t cookie, bool auth) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // Find client. mc::IProtocolPtr client = ClientByCookie( cookie ); if ( !client ) return mc::_E_FAIL; return HandleClient(client, auth); } mc::result ServerContext::HandleClient(mc::IProtocolRef client, bool auth) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); if ( auth ) { // Find client record. Client& clientRecord = clients_[client]; // Remember authentication flag. clientRecord.SetAuthenticated(auth); // Notify UI on new client. events_->OnNewClient(client->GetCookie()); // Notify client on successful authentication. client->Send( PrepareAuthMessage( clientRecord.GetMajorVersion(), clientRecord.GetMinorVersion() ) ); // Notify client on current volume value. SendVolumeLevel(client); // Ensure that client supports zooming. if ( clientRecord.IsZoomingSupported() ) { // Notify client on zoom parameters. client->Send( HardwareProvider::Instance().PrepareZoomParams() ); } // Notify services manager on new client. servicesManager_->DeviceConnected(client, clientRecord.GetAuthMessage()); } else { UnregisterClient(client); } return mc::_S_OK; } bool ServerContext::HasClients() { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // TODO: This should be improved to return value depending on a number // of authenticated clients. return ( clients_.size() > 0 ); } bool ServerContext::HasClient(size_t cookie) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); return ( NULL != ClientByCookie(cookie) ); } Client ServerContext::GetClient(size_t cookie) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); for ( Clients_::iterator iter = clients_.begin() ; iter != clients_.end() ; ++iter ) { // Acquire next client. mc::IProtocolRef client( (*iter).first ); if ( !client ) continue; // Check whether this is the one we are looking for. if ( !client->TestCookie( cookie ) ) continue; return (*iter).second; } throw std::exception(); } bool ServerContext::TestClient(const Client& client) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); try { // Check for limit of free connections. ////////////////////////////////////////////////////////////////////////// if ( client.IsFree() ) { // Enumerate all connected clients. for ( Clients_::iterator iter = clients_.begin() ; iter != clients_.end() ; ++iter ) { // Attempt to find at least someone free and authenticated. if ( (*iter).second.IsAuthenticated() && (*iter).second.IsFree() ) { // Acquire protocol associated with client to deliver // limit message. mc::IProtocolPtr clientProtocol = ClientByCookie( client.GetCookie() ); if ( !clientProtocol ) return false; // Send message to notify client on the reason of // disconnection. mc::IMessagePtr limitMessage( mc::Class< mc::MessageImpl >::Create( Messages::limitReached_ ) ); clientProtocol->Send( limitMessage ); // Disconnection should not be performed here because it // leads to dead lock. Honest client should disconnect // itself. // Notify caller on result of the operation. return false; } } } #if defined(__MACH__) // Check for iRemove version. ////////////////////////////////////////////////////////////////////////// if ( !Features::iRemoteMac(client.GetMajorVersion(), client.GetMinorVersion()) ) { // Notify user locally on version incompatibility. mc::IRunnablePtr warnContext( mc::Class< OldiRemoteContext >::Create( client.GetCookie(), events_ ) ); authJobs_->Push(warnContext); // Disconnection should not be performed here. return false; } #endif // Platform // Another checks may follow here. } catch ( ... ) { return false; } return true; } mc::result ServerContext::SpreadMessage(mc::IMessageRef message) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // Enumerate all connected clients. for ( Clients_::iterator iter = clients_.begin() ; iter != clients_.end() ; ++iter ) { // Acquire next client. mc::IProtocolRef client( (*iter).first ); // Check whether client is alive and is authenticated. if ( !client || !(*iter).second.IsAuthenticated() ) continue; // Send message to next client. client->Send( message ); } return mc::_S_OK; } mc::result ServerContext::RequestPassword(size_t cookie, bool requestAuth) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // Find client. mc::IProtocolPtr client = ClientByCookie( cookie ); if ( !client ) return mc::_E_FAIL; // Submit password request. RequestPassword(client, requestAuth); return mc::_S_OK; } mc::result ServerContext::DisconnectClient(size_t cookie) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // Find client. mc::IProtocolPtr client = ClientByCookie( cookie ); if ( !client ) return mc::_E_FAIL; // Target connection has been found. Use internal tool to disconnect. UnregisterClient( client ); return mc::_S_OK; } void ServerContext::HandleAuthorized(IClientHandlerRef handler) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); if ( !handler ) return; // Enumerate all connected clients. Clients_::iterator iter = clients_.begin(); Clients_::iterator end = clients_.end(); for ( ; iter != end ; ++iter ) { // Acquire next client. mc::IProtocolRef clientProtocol( (*iter).first ); Client clientRecord( (*iter).second ); // Check whether client is alive and is authenticated. if ( !clientProtocol || !clientRecord.IsAuthenticated() ) continue; // Handle client. handler->Handle(clientRecord, clientProtocol, ClassRoot_::GetSelf()); } } IServicesManagerPtr ServerContext::ServicesManager() { return servicesManager_; } // DServer section mc::result ServerContext::ConnectionAccepted(mc::IConnectionRef connection) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // Handle connection. mc::IProtocolPtr client( mc::Library::Protocol(connection, mc::IProtocol::ASYNC) ); // Configure messages registry. client->GetMessagesMap()->Register(MoveMessage::messageId_, mc::Class< MoveMessage >::Create ); client->GetMessagesMap()->Register(MoveToMessage::messageId_, mc::Class< MoveToMessage >::Create ); client->GetMessagesMap()->Register(MouseClickMessage::messageId_, mc::Class< MouseClickMessage >::Create ); client->GetMessagesMap()->Register(ScrollMessage::messageId_, mc::Class< ScrollMessage >::Create ); client->GetMessagesMap()->Register(ScrollMessage2::messageId_, mc::Class< ScrollMessage2 >::Create ); client->GetMessagesMap()->Register(AuthMessage::messageId_, mc::Class< AuthMessage >::Create ); client->GetMessagesMap()->Register(KeyboardMessage::messageId_, mc::Class< KeyboardMessage >::Create ); client->GetMessagesMap()->Register(Messages::leftButtonDown_, mc::Class< mc::MessageImpl >::Create ); client->GetMessagesMap()->Register(Messages::leftButtonUp_, mc::Class< mc::MessageImpl >::Create ); client->GetMessagesMap()->Register(Messages::middleButtonDown_, mc::Class< mc::MessageImpl >::Create ); client->GetMessagesMap()->Register(Messages::middleButtonUp_, mc::Class< mc::MessageImpl >::Create ); client->GetMessagesMap()->Register(Messages::rightButtonDown_, mc::Class< mc::MessageImpl >::Create ); client->GetMessagesMap()->Register(Messages::rightButtonUp_, mc::Class< mc::MessageImpl >::Create ); client->GetMessagesMap()->Register(VolumeMessage::messageId_, mc::Class< VolumeMessage >::Create ); client->GetMessagesMap()->Register(CookieMessage::messageId_, mc::Class< CookieMessage >::Create ); client->GetMessagesMap()->Register(PasswordMessage::messageId_, mc::Class< PasswordMessage >::Create ); client->GetMessagesMap()->Register(ShellRequest::messageId_, mc::Class< ShellRequest >::Create ); client->GetMessagesMap()->Register(ZoomLevelMessage::messageId_, mc::Class< ZoomLevelMessage >::Create ); client->GetMessagesMap()->Register(ServiceRequest::messageId_, mc::Class< ServiceRequest >::Create ); client->GetMessagesMap()->Register(StreamRequest::messageId_, mc::Class< StreamRequest >::Create ); // Subscribe on message notifications. mc::Events::Advise(client, mc::CommonImpl< mc::IRunnable >::GetSelf(), mc::TypeInfo< mc::DProtocol >::GetGuid()); // Register client and set it's state to unregistered. clients_[client] = Client( connection->GetIpAddress(), client->GetCookie() ); return mc::_S_OK; } // DProtocol section mc::result ServerContext::MessageArrived(mc::IProtocolRef protocol, mc::IMessageRef message) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // TODO: Check ban list. // Check for service initialization message. if ( StreamRequest::messageId_ == message->GetCode() ) { HandleStream(protocol, message); return mc::_S_OK; } // First of all we should check whether authentication message // is arrived or no. if ( AuthMessage::messageId_ == message->GetCode() ) { HandleAuthMessage(protocol, message); return mc::_S_OK; } // Check whether auth message has been already received. if ( !clients_[protocol].HasAuthMessage() ) { // Auth message has not been received yet. UnregisterClient(protocol); return mc::_S_OK; } // Then we should proceed to password check. if ( PasswordMessage::messageId_ == message->GetCode() ) { HandlePassword(protocol, message); return mc::_S_OK; } if ( false == clients_[protocol].IsAuthenticated() ) { // Connection has not been authorized yet. Client should be // disconnected in this case. UnregisterClient(protocol); return mc::_S_OK; } if ( MoveMessage::messageId_ == message->GetCode() ) { HandleMoveByMessage(protocol, message); } else if ( MoveToMessage::messageId_ == message->GetCode() ) { HandleMoveToMessage(protocol, message); } else if ( MouseClickMessage::messageId_ == message->GetCode() ) { HandleMouseClickMessage(message); } else if ( ScrollMessage::messageId_ == message->GetCode() ) { HandleScrollMessage(message); } else if ( ScrollMessage2::messageId_ == message->GetCode() ) { HandleScrollMessage2(message); } else if ( Messages::leftButtonDown_ == message->GetCode() ) { HardwareProvider::Instance().GetMouseControl()->LeftButtonDown(); } else if ( Messages::leftButtonUp_ == message->GetCode() ) { HardwareProvider::Instance().GetMouseControl()->LeftButtonUp(); } else if ( Messages::middleButtonDown_ == message->GetCode() ) { HardwareProvider::Instance().GetMouseControl()->MiddleButtonDown(); } else if ( Messages::middleButtonUp_ == message->GetCode() ) { HardwareProvider::Instance().GetMouseControl()->MiddleButtonUp(); } else if ( Messages::rightButtonDown_ == message->GetCode() ) { HardwareProvider::Instance().GetMouseControl()->RightButtonDown(); } else if ( Messages::rightButtonUp_ == message->GetCode() ) { HardwareProvider::Instance().GetMouseControl()->RightButtonUp(); } else if ( KeyboardMessage::messageId_ == message->GetCode() ) { HandleKeyboardMessage(message); } else if ( VolumeMessage::messageId_ == message->GetCode() ) { HandleVolumeMessage(message); } else if ( CookieMessage::messageId_ == message->GetCode() ) { HandleCookieMessage(message); } else if ( ShellRequest::messageId_ == message->GetCode() ) { HandleShellRequest(message); } else if ( ZoomLevelMessage::messageId_ == message->GetCode() ) { HandleZoomLevel(protocol, message); } // Propogate message to services manager. This is required in order to deliver // compatibility information and general commands to service handlers. servicesManager_->ControlMessage(protocol, message); return mc::_S_OK; } mc::result ServerContext::DataErrorOccured(mc::IProtocolRef protocol) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // What we need to do is to unregister client correctly. UnregisterClient(protocol); return mc::_S_OK; } mc::result ServerContext::Disconnected(mc::IProtocolRef protocol) { MC_LOG_ROUTINE; mc::CoreMutexLock locker( mc::CommonImpl< IServerControl >::GetLock() ); // What we need to do is to unregister client correctly. UnregisterClient(protocol); return mc::_S_OK; } // Internal tools ////////////////////////////////////////////////////////////////////////// void ServerContext::SendVolumeLevel(mc::IProtocolRef client) { // Acquire current volume value. unsigned long value = 0; HardwareProvider::Instance().GetVolumeControl()->GetNormalizedVolume(value); // Construct message do spread new value. mc::IMessagePtr message( mc::Class< VolumeMessage >::Create( VolumeMessage::DEVICE_MASTER, value ) ); // Send message. client->Send(message); } mc::IProtocolPtr ServerContext::ClientByCookie(size_t cookie) { MC_LOG_ROUTINE; for ( Clients_::iterator iter = clients_.begin() ; iter != clients_.end() ; ++iter ) { // Acquire next client. mc::IProtocolRef client( (*iter).first ); if ( !client ) continue; // Check whether this is the one we are looking for. if ( !client->TestCookie( cookie ) ) continue; return client; } return NULL; } void ServerContext::UnregisterClient(mc::IProtocolRef protocol) { MC_LOG_ROUTINE; // Save cookie for later use. size_t cookie = protocol->GetCookie(); // 1. Notify services on disconnection. servicesManager_->DeviceDisconnected(protocol); // 2. Unsubscribe from protocol events. mc::Events::Unadvise(protocol, mc::CommonImpl< mc::IRunnable >::GetSelf(), mc::TypeInfo< mc::DProtocol >::GetGuid()); // 3. It is not enough just to erase protocol from the map to // shutdown connection properly. // 3.1. Acquire connection. mc::IConnectionPtr connection = protocol->GetConnection(); // 3.2. Close connection explicitly. connection->Close(); // 3.3. Remove protocol object from cache finally. clients_.erase( protocol ); // 4. Notify UI on disconnection. events_->OnDisconnection( cookie ); } mc::result ServerContext::HandleStream(mc::IProtocolRef protocol, mc::IMessageRef message) { MC_LOG_ROUTINE; // 1. Unsubscribe from protocol events. mc::Events::Unadvise(protocol, mc::CommonImpl< mc::IRunnable >::GetSelf(), mc::TypeInfo< mc::DProtocol >::GetGuid()); // 2. Remove protocol object from cache. clients_.erase( protocol ); // 3. Notify services manager on stream. servicesManager_->StreamConnected(protocol, message); return mc::_S_OK; } mc::result ServerContext::HandleAuthMessage(mc::IProtocolRef protocol, mc::IMessageRef message) { MC_LOG_ROUTINE; // TODO: Message contains information on client device and version. // This should be checked in future. Host software should work properly // with clients of all generations. // Attach auth message to client. clients_[protocol].AttachMessage(message); // Check whether limit of free connected devices is reached. if ( !TestClient(clients_[protocol]) ) // This routine takes care about client disconnection itself. return mc::_S_FALSE; // Check whether client has valid authentication code. bool hasCode = message->GetProperty(AuthMessage::PROP_HAS_CODE).toBool(); if ( hasCode ) { // Check whether client's code is valid. mc::Guid code = message->GetProperty(AuthMessage::PROP_CODE).toGuid(); if ( listOfCookies_.end() != listOfCookies_.find(code) ) { // Remove cookie. listOfCookies_.erase(code); // Authorize client. HandleClient( protocol, true ); // As new client has appeared we should check whether another on // which may be potentially free is waiting for approval. events_->CheckAuth(); // Finish authentication scenario after this point. return mc::_S_OK; } } // Check current security policy. if ( std::string("allow_all") == Config::Instance().GetPolicy() ) { // This policy allows for all external devices to be automatically // connected without confirmation dialog. // Authorize client. HandleClient( protocol, true ); // Finish authentication scenario after this point. return mc::_S_OK; } // Check whether client is registered in local users database. try { // Lock users manager for reading. mc::IReadWriteLock::Reader_ locker(UsersManager::Instance().GetLock()); // Find corresponding user in the database. std::string deviceId = message->GetProperty(AuthMessage::PROP_ID).toString(); User& user = UsersManager::Instance().GetUser(deviceId); // Update user settings. std::string deviceName = message->GetProperty(AuthMessage::PROP_NAME).toString(); user.SetDeviceName(deviceName); // Acquire ip address of current connection. std::string currentIp = protocol->GetConnection()->GetIpAddress(); // Check whether ip security option enabled. if ( user.IsIpRequired() ) { // Check whether user is connected with another ip address. if ( user.GetIp() != currentIp ) { // Notify device on wrong ip. mc::IMessagePtr wrongIp = mc::Class< mc::MessageImpl >::Create( Messages::wrongDeviceIp_ ); protocol->Send( wrongIp ); // Break connection with the device. UnregisterClient(protocol); return mc::_S_FALSE; } } else { // This is right place to update last user ip address. // This makes sense only when user is not associated woth any // particular ip. user.SetIp( currentIp ); } // Request password if user is found. RequestPassword(protocol, user.IsAuthRequested()); return mc::_S_OK; } catch ( ... ) { // User has not been found in the database. // Proceed to regular authentication. } // Initiate authentication (display authentication dialog). mc::IRunnablePtr authContext( mc::Class< AuthContext >::Create( protocol->GetCookie(), events_ ) ); authJobs_->Push(authContext); return mc::_S_OK; } mc::result ServerContext::HandleMoveByMessage(mc::IProtocolRef protocol, mc::IMessageRef message) { // Acquire message params. float dx = message->GetProperty(MoveMessage::PROP_DX).toFloat(); float dy = message->GetProperty(MoveMessage::PROP_DY).toFloat(); // Adjust cursor position. HardwareProvider::Instance().GetMouseControl()->MoveCursorBy(dx, dy); // Notify client on cursor position change. if ( clients_[protocol].AreServicesSupported() ) { ScreenPoint position = HardwareProvider::Instance().GetMouseControl()->GetPosition(); mc::IMessagePtr positionMessage( mc::Class< MoveToMessage >::Create(position.x_, position.y_) ); protocol->Send(positionMessage); } return mc::_S_OK; } mc::result ServerContext::HandleMoveToMessage(mc::IProtocolRef protocol, mc::IMessageRef message) { // Acquire message params. float x = message->GetProperty(MoveMessage::PROP_DX).toFloat(); float y = message->GetProperty(MoveMessage::PROP_DY).toFloat(); // Adjust cursor position. HardwareProvider::Instance().GetMouseControl()->MoveCursorTo(x, y); // Notify client on cursor position change. if ( clients_[protocol].AreServicesSupported() ) { ScreenPoint position = HardwareProvider::Instance().GetMouseControl()->GetPosition(); mc::IMessagePtr positionMessage( mc::Class< MoveToMessage >::Create(position.x_, position.y_) ); protocol->Send(positionMessage); } return mc::_S_OK; } mc::result ServerContext::HandleMouseClickMessage(mc::IMessageRef message) { MC_LOG_ROUTINE; // Acquire message params. float x = message->GetProperty(MouseClickMessage::PROP_X).toFloat(); float y = message->GetProperty(MouseClickMessage::PROP_Y).toFloat(); // Perform corresponding action. HardwareProvider::Instance().GetMouseControl()->MouseClick(x, y); return mc::_S_OK; } mc::result ServerContext::HandleScrollMessage(mc::IMessageRef message) { MC_LOG_ROUTINE; // Acquire message params. bool vertical = message->GetProperty(ScrollMessage::PROP_ORIENTATION).toBool(); int value = message->GetProperty(ScrollMessage::PROP_VALUE).toInt(); // Perform corresponding action. HardwareProvider::Instance().GetMouseControl()->Scroll(vertical, value); return mc::_S_OK; } mc::result ServerContext::HandleScrollMessage2(mc::IMessageRef message) { MC_LOG_ROUTINE; // Acquire message params. bool vertical = message->GetProperty(ScrollMessage::PROP_ORIENTATION).toBool(); int value = message->GetProperty(ScrollMessage::PROP_VALUE).toInt(); // Perform corresponding action. HardwareProvider::Instance().GetMouseControl()->Scroll2(vertical, value); return mc::_S_OK; } mc::result ServerContext::HandleKeyboardMessage(mc::IMessageRef message) { MC_LOG_ROUTINE; int type = message->GetProperty(KeyboardMessage::PROP_TYPE).toInt(); if ( KeyboardMessage::TYPE_UNICODE == type ) { unsigned short code = message->GetProperty(KeyboardMessage::PROP_SCAN).toUShort(); HardwareProvider::Instance().GetKeyboardControl()->KeyboardEventUnicode(code); } else if ( KeyboardMessage::TYPE_VIRTUAL == type ) { unsigned char vk = message->GetProperty(KeyboardMessage::PROP_VK).toUChar(); bool event = message->GetProperty(KeyboardMessage::PROP_EVENT).toBool(); HardwareProvider::Instance().GetKeyboardControl()->KeyboardEventVirtual(vk, event); } return mc::_S_OK; } mc::result ServerContext::HandleVolumeMessage(mc::IMessageRef message) { MC_LOG_ROUTINE; unsigned long value = message->GetProperty(VolumeMessage::PROP_VALUE).toULong(); HardwareProvider::Instance().GetVolumeControl()->SetNormalizedVolume(value); return mc::_S_OK; } mc::result ServerContext::HandleCookieMessage(mc::IMessageRef message) { MC_LOG_ROUTINE; mc::Guid code = message->GetProperty(CookieMessage::PROP_CODE).toGuid(); listOfCookies_.insert(code); return mc::_S_OK; } mc::result ServerContext::HandleShellRequest(mc::IMessageRef message) { IShellControlPtr shellControl = ShellHost::Instance().GetShellControl(); if ( shellControl ) { std::string command = message->GetProperty(ShellRequest::PROP_COMMAND).toString(); shellControl->Write(command, true); } else { // TODO: Client should be notified when shell service is not started // on host side. } return mc::_S_OK; } mc::result ServerContext::HandlePassword(mc::IProtocolRef protocol, mc::IMessageRef message) { MC_LOG_ROUTINE; try { if ( clients_.end() == clients_.find(protocol) ) throw std::exception(); // Acquire device id from client record. std::string deviceId = clients_[protocol].GetId(); // Acquire password from message. std::string passsword = message->GetProperty(PasswordMessage::PROP_PASSWORD).toString(); // Lock users manager for reading. mc::IReadWriteLock::Reader_ locker(UsersManager::Instance().GetLock()); // Extract user from the database. User& user = UsersManager::Instance().GetUser(deviceId); // Check whether password is correct. if ( user.TestPassword(passsword) ) { // Check whether client satisfies all criteria and current // situation. if ( !TestClient(clients_[protocol]) ) return mc::_S_FALSE; // Forced authentication on the device is not required any more. user.RequestAuth(false); // Authorize client. HandleClient(protocol, true); } else { // Check whether user still exists in the database. if ( !UsersManager::Instance().IsValidUser(deviceId) ) // This will cause user disconnection. throw std::exception(); // TODO: Authentication should be requested here. This will // initiate authentication procedure. // Notify client on password error. // Typically this should lead to the same password prompt (may be // with additional prompt on error during previous attempt). // Server side should take care about limited number of attempts. WrongPassword(protocol); } } catch ( ... ) { // It may occur in the following cases: // - authentication message has not been received from client yet; // - user has not been found in the database. // Connection should be broken in this case. UnregisterClient(protocol); return mc::_E_FAIL; } return mc::_S_OK; } mc::result ServerContext::HandleZoomLevel(mc::IProtocolRef protocol, mc::IMessageRef message) { MC_LOG_ROUTINE; // Client record should exists to handle zoom message correctly. if ( clients_.end() == clients_.find(protocol) ) { UnregisterClient(protocol); return mc::_E_FAIL; } // Remember new zoom level. It will be used to capture next screenshot. float level = message->GetProperty(ZoomLevelMessage::PROP_ZOOM_LEVEL).toFloat(); clients_[protocol].SetZoomLevel(level); return mc::_S_OK; } mc::IMessagePtr ServerContext::PrepareAuthMessage(int clientMajor, int clientMinor) { // Note: Auth response message determines host platform automatically. if ( Features::iRemoteExtendedAuthentication(clientMajor, clientMinor) ) return mc::IMessagePtr( mc::Class< AuthResponse2 >::Create( Config::Instance().GetHostId() ) ); else return mc::IMessagePtr( mc::Class< AuthResponse >::Create() ); } mc::result ServerContext::RequestPassword(mc::IProtocolRef protocol, bool requestAuth) { mc::IMessagePtr passwordRequest = mc::Class< PasswordRequest >::Create( Config::Instance().GetHostId(), requestAuth ); protocol->Send( passwordRequest ); return mc::_S_OK; } mc::result ServerContext::WrongPassword(mc::IProtocolRef protocol) { protocol->Send( mc::Class< mc::MessageImpl >::Create( Messages::wrongPassword_ ) ); return mc::_S_OK; } }
32.649547
115
0.68616
[ "object" ]
b6c2d9a0e3f5a5f96235a311b68215321dde29d6
4,711
cpp
C++
examples/wav_export/unit_tests/wav_writer_test.cpp
HpLightcorner/OXYGEN-SDK
4ede0ea07b513032605b32fc86539f081589e58c
[ "MIT" ]
4
2019-12-20T18:21:03.000Z
2020-09-08T05:16:53.000Z
examples/wav_export/unit_tests/wav_writer_test.cpp
HpLightcorner/OXYGEN-SDK
4ede0ea07b513032605b32fc86539f081589e58c
[ "MIT" ]
13
2020-07-01T19:35:08.000Z
2022-03-18T13:58:06.000Z
examples/wav_export/unit_tests/wav_writer_test.cpp
HpLightcorner/OXYGEN-SDK
4ede0ea07b513032605b32fc86539f081589e58c
[ "MIT" ]
3
2020-07-28T06:50:56.000Z
2022-02-24T10:32:52.000Z
// Copyright DEWETRON GmbH 2020 #include "wav_writer.h" //#include "uni_math_constants.h" #include <cmath> #include <boost/test/unit_test.hpp> #if _MSC_VER > 1920 #pragma warning(disable:4996) #endif BOOST_AUTO_TEST_SUITE(uni_wav_writer_test_suite) namespace { const int CHUNK_SIZE = 8; const int RIFFWAVE_SIZE = CHUNK_SIZE + 4; const int FORMAT_SIZE = CHUNK_SIZE + 16; } BOOST_AUTO_TEST_CASE(WriteHeaderTest) { FILE* tmp = std::tmpfile(); WavWriter writer(tmp); writer.writeHeader(WavFormatTag::WAV_FORMAT_PCM, 16, 44100, 2, 0); struct header { char riff[4]; uint32_t length; char wave[4]; }; BOOST_CHECK_EQUAL(sizeof(header), RIFFWAVE_SIZE); BOOST_REQUIRE_EQUAL(0, fseek(tmp, 0, SEEK_SET)); header buffer; BOOST_REQUIRE_EQUAL(1, fread(&buffer, sizeof(header), 1, tmp)); BOOST_CHECK(!std::strncmp(buffer.riff, "RIFF", 4)); BOOST_CHECK_EQUAL(buffer.length, 4 + FORMAT_SIZE + CHUNK_SIZE); BOOST_CHECK(!std::strncmp(buffer.wave, "WAVE", 4)); struct fmtheader { char fmt[4]; uint32_t length; uint16_t format_tag; uint16_t channels; uint32_t sample_rate; uint32_t bytes_per_second; uint16_t block_align; uint16_t bits_per_sample; } fmt; BOOST_REQUIRE_EQUAL(1, fread(&fmt, sizeof(fmt), 1, tmp)); BOOST_CHECK(!std::strncmp(fmt.fmt, "fmt ", 4)); BOOST_CHECK_EQUAL(fmt.length, 16); BOOST_CHECK_EQUAL(fmt.format_tag, 1); BOOST_CHECK_EQUAL(fmt.channels, 2); BOOST_CHECK_EQUAL(fmt.sample_rate, 44100); BOOST_CHECK_EQUAL(fmt.bytes_per_second, 2 * 2 * 44100); BOOST_CHECK_EQUAL(fmt.block_align, 2 * 2); BOOST_CHECK_EQUAL(fmt.bits_per_sample, 16); struct dataheader { char data[4]; uint32_t length; } dataheader; BOOST_REQUIRE_EQUAL(1, fread(&dataheader, sizeof(dataheader), 1, tmp)); BOOST_CHECK(!std::strncmp(dataheader.data, "data ", 4)); BOOST_CHECK_EQUAL(dataheader.length, 0); } BOOST_AUTO_TEST_CASE(WriteSamplesTest) { FILE* tmp = std::tmpfile(); WavWriter writer(tmp); writer.writeHeader(WavFormatTag::WAV_FORMAT_PCM, 16, 44100, 2, 10); for (int16_t n = 0; n < 10; ++n) { writer.appendSamples(&n, sizeof(int16_t)); } BOOST_CHECK_EQUAL(writer.samplesWritten(), 10); // batch add samples std::vector<int16_t> data(10, 0); writer.appendSamples(data.data(), data.size() * sizeof(int16_t)); BOOST_CHECK_EQUAL(writer.samplesWritten(), 20); BOOST_REQUIRE_EQUAL(0, fseek(tmp, RIFFWAVE_SIZE + FORMAT_SIZE + CHUNK_SIZE, SEEK_SET)); std::vector<uint16_t> samples(2 * 10); BOOST_REQUIRE_EQUAL(samples.size(), fread(samples.data(), sizeof(uint16_t), samples.size(), tmp)); for (uint16_t n = 0; n < 10; ++n) { BOOST_CHECK_EQUAL(samples[n], n); } } #if 0 BOOST_AUTO_TEST_CASE(ExternalUsabiliyTest) { // This test is used to generate a WAV file with various settings to test the import into a 3rd party audio program WavWriter writer("C:\\Temp\\export.wav"); const uint32_t Fs = 44100; const double f0 = 440; const std::size_t num_samples = Fs * 2; const std::size_t bit_depth = 24; writer.writeHeader(WavFormatTag::WAV_FORMAT_PCM, bit_depth, Fs, 1, num_samples); const double w = uni::math::constants::two_pi * f0 / Fs; const double lambda = -2.0 / Fs; const double conversion_factor = (1 << (bit_depth - 1)) - 1; for (std::size_t n = 0; n < num_samples; ++n) { double scale = std::exp(lambda * n); const double a = scale * std::sin(w * n); sint64 sample = static_cast<sint64>(a * conversion_factor); writer.appendSamples(&sample, bit_depth / 8); } writer.close(); } BOOST_AUTO_TEST_CASE(ExternalUsabiliyFloatTest) { // This test is used to generate a WAV file with various settings to test the import into a 3rd party audio program WavWriter writer("C:\\Temp\\export_float.wav"); const uint32_t Fs = 44100; const double f0 = 440; const std::size_t num_samples = Fs * 2; using sample_format = float; const std::size_t bit_depth = sizeof(sample_format) * 8; writer.writeHeader(WavFormatTag::WAV_FORMAT_FLOAT, bit_depth, Fs, 1, num_samples); const double w = uni::math::constants::two_pi * f0 / Fs; const double lambda = -2.0 / Fs; for (std::size_t n = 0; n < num_samples; ++n) { double scale = std::exp(lambda * n); const double a = scale * std::sin(w * n); sample_format sample = static_cast<sample_format>(a); writer.appendSamples(&sample, sizeof(sample)); } writer.close(); } #endif BOOST_AUTO_TEST_SUITE_END()
31.61745
119
0.663341
[ "vector" ]
b6c69f193a2f343f52e43ce6580f5874c042b687
1,840
cpp
C++
halide/linear-algebra/atax.cpp
arnablegend/polybench-dsl
21f072a7209839ac1ba85eb5cb4883e34aebaac8
[ "MIT" ]
null
null
null
halide/linear-algebra/atax.cpp
arnablegend/polybench-dsl
21f072a7209839ac1ba85eb5cb4883e34aebaac8
[ "MIT" ]
null
null
null
halide/linear-algebra/atax.cpp
arnablegend/polybench-dsl
21f072a7209839ac1ba85eb5cb4883e34aebaac8
[ "MIT" ]
null
null
null
#include "Halide.h" #include <cstdio> #include "iostream" #include <cstdlib> #include <ctime> using namespace std; using namespace Halide; // choose your data type #define DTYPE float // using the mini-dataset, other datasets are commented, use whichever desired #define M 38 // 116 390 1900 1800 #define N 42 // 124 410 2100 2200 void print_buffer(Buffer<DTYPE> buf, int num_dims){ if(num_dims == 1){ for(int i = buf.min(0); i < buf.extent(0); i++) cout << buf(i) << " "; }else if(num_dims == 2){ for(int j = buf.min(1); j < buf.extent(1); j++){ for(int i = buf.min(0); i < buf.extent(0); i++) cout << buf(i, j) << " "; cout << endl; } } } void init_buffer(Buffer<DTYPE> buf, int num_dims){ if(num_dims == 1){ for(int i = buf.min(0); i < buf.extent(0); i++) buf(i) = (DTYPE)((rand() % 100) / 10.0 + 1); }else if(num_dims = 2){ for(int j = buf.min(1); j < buf.extent(1); j++) for(int i = buf.min(0); i < buf.extent(0); i++) buf(i, j) = (DTYPE)((rand() % 100) / 10.0 + 1); } } int main(int argc, char** argv){ int n=N, m=M; Buffer<DTYPE> A(m, n, "matrix A"); Buffer<DTYPE> B(n, "vector B"); Buffer<DTYPE> out(n, "output"); srand(time(NULL)); init_buffer(A, 2); init_buffer(B, 1); // Define Halide Vars Func atax("atax"), tmp("tmp"); Var m("m"), k ("k"); RDom r(0, n, "r"); // Algorithm // out = (A * B) * (C * D) tmp(k) += A(k, r.x) * B(r.x); atax(k) += A(r.x, k) * tmp(r.x); // Using basic schedule...Can be optimized tmp.compute_root(); atax.print_loop_nest(); // Compile atax.compile_jit(); // Execute or generate binary atax.realize(out); print_buffer(out, 1); return 0; }
25.205479
78
0.527717
[ "vector" ]
b6cee38c01fd244687620f9662061583beb33187
9,923
cpp
C++
source/Lib/TLib360/TFBPSNRMetricCalc.cpp
oyhngithub/FB-PSNR
9da6beae117a21340bf25345d2e3d34f6d25ec34
[ "BSD-3-Clause" ]
null
null
null
source/Lib/TLib360/TFBPSNRMetricCalc.cpp
oyhngithub/FB-PSNR
9da6beae117a21340bf25345d2e3d34f6d25ec34
[ "BSD-3-Clause" ]
null
null
null
source/Lib/TLib360/TFBPSNRMetricCalc.cpp
oyhngithub/FB-PSNR
9da6beae117a21340bf25345d2e3d34f6d25ec34
[ "BSD-3-Clause" ]
null
null
null
#include "TFBPSNRMetricCalc.h" //#include "TLibEncoder/TEncRateCtrl.cpp" #include "TAppEncHelper360/TExt360AppEncCfg.h" // ==================================================================================================================== // DIY #include <sstream> #include <fstream> #include <iostream> TFBPSNRMetric::TFBPSNRMetric() : m_bSPSNREnabled(false) , m_pCart2D(NULL) , m_fpTable(NULL) { m_dFBPSNR[0] = m_dFBPSNR[1] = m_dFBPSNR[2] = 0; } TFBPSNRMetric::~TFBPSNRMetric() { if (m_pCart2D) { free(m_pCart2D); m_pCart2D = NULL; } if (m_fpTable) { free(m_fpTable); m_fpTable = NULL; } } Void TFBPSNRMetric::setOutputBitDepth(Int iOutputBitDepth[MAX_NUM_CHANNEL_TYPE]) { for (Int i = 0; i < MAX_NUM_CHANNEL_TYPE; i++) { m_outputBitDepth[i] = iOutputBitDepth[i]; } } Void TFBPSNRMetric::setReferenceBitDepth(Int iReferenceBitDepth[MAX_NUM_CHANNEL_TYPE]) { for (Int i = 0; i < MAX_NUM_CHANNEL_TYPE; i++) { m_referenceBitDepth[i] = iReferenceBitDepth[i]; } } Void TFBPSNRMetric::sphSampoints(const std::string &cSphDataFile) { FILE* fp = fopen(TExt360AppEncCfg::m_featureFileName.c_str(), "r"); int x, y; x = y = 0; int edgeNumbers, featureNumbers; // read longtitude, latitude if (fscanf(fp, "%d %d", &edgeNumbers, &featureNumbers) != 2) { printf("SphData file does not exist.\n"); exit(EXIT_FAILURE); fclose(fp); } m_iSphNumPoints = edgeNumbers + featureNumbers; m_pCart2D = (CPos2D*)malloc(sizeof(CPos2D)*(m_iSphNumPoints)); memset(m_pCart2D, 0, (sizeof(CPos2D) * m_iSphNumPoints)); for (Int z = 0; z < m_iSphNumPoints; z++) { if (fscanf(fp, "%lf %lf", &m_pCart2D[z].y, &m_pCart2D[z].x) != 2) { printf("Format error SphData in sphSampoints().\n"); exit(EXIT_FAILURE); } } fclose(fp); } void TFBPSNRMetric::sphToCart(CPos2D* sph, CPos3D* out) { POSType fLat = (POSType)(sph->x*S_PI / 180.0); POSType fLon = (POSType)(sph->y*S_PI / 180.0); out->x = ssin(fLon) * scos(fLat); out->y = ssin(fLat); out->z = -scos(fLon) * scos(fLat); } void TFBPSNRMetric::createTable(TGeometry *pcCodingGeomtry) { Int iNumPoints = m_iSphNumPoints; CPos2D In2d; CPos3D Out3d; SPos posIn, posOut; m_fpTable = (IPos2D*)malloc(iNumPoints * sizeof(IPos2D)); for (Int np = 0; np < iNumPoints; np++) { In2d.x = m_pCart2D[np].x; In2d.y = m_pCart2D[np].y; //get cartesian coordinates sphToCart(&In2d, &Out3d); posIn.x = Out3d.x; posIn.y = Out3d.y; posIn.z = Out3d.z; assert(posIn.x < 1 && posIn.x > -1 && posIn.y > -1 && posIn.y < 1 && posIn.z < 1 && posIn.z > -1); pcCodingGeomtry->map3DTo2D(&posIn, &posOut); posOut.x = (POSType)TGeometry::round(posOut.x); posOut.y = (POSType)TGeometry::round(posOut.y); IPos tmpPos; tmpPos.faceIdx = posOut.faceIdx; tmpPos.u = (Int)(posOut.x); tmpPos.v = (Int)(posOut.y); pcCodingGeomtry->clamp(&tmpPos); pcCodingGeomtry->geoToFramePack(&tmpPos, &m_fpTable[np]); } // ==================================================================================================================== // DIY //std::ofstream outfile("CountData.txt", std::ios::out | std::ios::binary); //if (!outfile.is_open()) //{ // std::cout << " the file open fail" << std::endl; // exit(1); //} //point2DCount countVector = pcCodingGeomtry->getPoint2DCount(); //for (int i = 0; i < countVector.size(); ++i) //{ // for (int j = 0; j < countVector[i].size(); ++j) // { // outfile << countVector[i][j] << " "; // } // outfile << "\r\n"; //} //outfile.close(); // ==================================================================================================================== } // pass the pics before and after the encode // m_fpTable stores all the data that already transform into different projections Void TFBPSNRMetric::xCalculateFBPSNR(TComPicYuv* pcOrgPicYuv, TComPicYuv* pcPicD) { Int iNumPoints = m_iSphNumPoints; Int iBitDepthForPSNRCalc[MAX_NUM_CHANNEL_TYPE]; Int iReferenceBitShift[MAX_NUM_CHANNEL_TYPE]; Int iOutputBitShift[MAX_NUM_CHANNEL_TYPE]; iBitDepthForPSNRCalc[CHANNEL_TYPE_LUMA] = std::max(m_outputBitDepth[CHANNEL_TYPE_LUMA], m_referenceBitDepth[CHANNEL_TYPE_LUMA]); iBitDepthForPSNRCalc[CHANNEL_TYPE_CHROMA] = std::max(m_outputBitDepth[CHANNEL_TYPE_CHROMA], m_referenceBitDepth[CHANNEL_TYPE_CHROMA]); iReferenceBitShift[CHANNEL_TYPE_LUMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_LUMA] - m_referenceBitDepth[CHANNEL_TYPE_LUMA]; iReferenceBitShift[CHANNEL_TYPE_CHROMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_CHROMA] - m_referenceBitDepth[CHANNEL_TYPE_CHROMA]; iOutputBitShift[CHANNEL_TYPE_LUMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_LUMA] - m_outputBitDepth[CHANNEL_TYPE_LUMA]; iOutputBitShift[CHANNEL_TYPE_CHROMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_CHROMA] - m_outputBitDepth[CHANNEL_TYPE_CHROMA]; memset(m_dFBPSNR, 0, sizeof(Double) * 3); TComPicYuv &picd = *pcPicD; Double SSDspsnr[3] = { 0, 0 ,0 }; for (Int chan = 0; chan < pcPicD->getNumberValidComponents(); chan++) { const ComponentID ch = ComponentID(chan); const Pel* pOrg = pcOrgPicYuv->getAddr(ch); const Int iOrgStride = pcOrgPicYuv->getStride(ch); const Pel* pRec = picd.getAddr(ch); const Int iRecStride = picd.getStride(ch); for (Int np = 0; np < iNumPoints; np++) { if (!chan) { Int x_loc = (Int)(m_fpTable[np].x); Int y_loc = (Int)(m_fpTable[np].y); Intermediate_Int iDifflp = (pOrg[x_loc + (y_loc*iOrgStride)] << iReferenceBitShift[toChannelType(ch)]) - (pRec[x_loc + (y_loc*iRecStride)] << iOutputBitShift[toChannelType(ch)]); SSDspsnr[chan] += iDifflp * iDifflp; } else { Int x_loc = Int(m_fpTable[np].x >> pcPicD->getComponentScaleX(COMPONENT_Cb)); Int y_loc = Int(m_fpTable[np].y >> pcPicD->getComponentScaleY(COMPONENT_Cb)); Intermediate_Int iDifflp = (pOrg[x_loc + (y_loc*iOrgStride)] << iReferenceBitShift[toChannelType(ch)]) - (pRec[x_loc + (y_loc*iRecStride)] << iOutputBitShift[toChannelType(ch)]); SSDspsnr[chan] += iDifflp * iDifflp; } } } for (Int ch_indx = 0; ch_indx < pcPicD->getNumberValidComponents(); ch_indx++) { const ComponentID ch = ComponentID(ch_indx); const Int maxval = 255 << (iBitDepthForPSNRCalc[toChannelType(ch)] - 8); Double fReflpsnr = Double(iNumPoints)*maxval*maxval; m_dFBPSNR[ch_indx] = (SSDspsnr[ch_indx] ? 10.0 * log10(fReflpsnr / (Double)SSDspsnr[ch_indx]) : 999.99); } } // create 2D table //void TEncGOP::createTable(TGeometry *pcCodingGeomtry) //{ // //-- Added by Ma Guilong // // // // 3D - cartesian - faceID, x, y // // CPos2D In2d; // CPos3D Out3d; // SPos posIn, posOut; // m_fpTable = (IPos2D*)malloc(iNumPoints * sizeof(IPos2D)); // // for (Int np = 0; np < iNumPoints; np++) // { // In2d.x = m_pCart2D[np].x; // In2d.y = m_pCart2D[np].y; // // //get cartesian coordinates // sphToCart(&In2d, &Out3d); // posIn.x = Out3d.x; posIn.y = Out3d.y; posIn.z = Out3d.z; // TGeometry *pcCodingGeomtry; // // pcCodingGeomtry->map3DTo2D(&posIn, &posOut); // // posOut.x = (POSType)TGeometry::round(posOut.x); // posOut.y = (POSType)TGeometry::round(posOut.y); // IPos tmpPos; // tmpPos.faceIdx = posOut.faceIdx; // tmpPos.u = (Int)(posOut.x); // tmpPos.v = (Int)(posOut.y); // pcCodingGeomtry->clamp(&tmpPos); // pcCodingGeomtry->geoToFramePack(&tmpPos, &m_fpTable[np]); // } //} // //Void TEncGOP::xCalculateFBPSNR(TComPicYuv* pcOrgPicYuv, TComPicYuv* pcPicD) //{ // Int iBitDepthForPSNRCalc[MAX_NUM_CHANNEL_TYPE]; // Int iReferenceBitShift[MAX_NUM_CHANNEL_TYPE]; // Int iOutputBitShift[MAX_NUM_CHANNEL_TYPE]; // iBitDepthForPSNRCalc[CHANNEL_TYPE_LUMA] = std::max(m_outputBitDepth[CHANNEL_TYPE_LUMA], m_referenceBitDepth[CHANNEL_TYPE_LUMA]); // iBitDepthForPSNRCalc[CHANNEL_TYPE_CHROMA] = std::max(m_outputBitDepth[CHANNEL_TYPE_CHROMA], m_referenceBitDepth[CHANNEL_TYPE_CHROMA]); // iReferenceBitShift[CHANNEL_TYPE_LUMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_LUMA] - m_referenceBitDepth[CHANNEL_TYPE_LUMA]; // iReferenceBitShift[CHANNEL_TYPE_CHROMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_CHROMA] - m_referenceBitDepth[CHANNEL_TYPE_CHROMA]; // iOutputBitShift[CHANNEL_TYPE_LUMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_LUMA] - m_outputBitDepth[CHANNEL_TYPE_LUMA]; // iOutputBitShift[CHANNEL_TYPE_CHROMA] = iBitDepthForPSNRCalc[CHANNEL_TYPE_CHROMA] - m_outputBitDepth[CHANNEL_TYPE_CHROMA]; // // memset(m_dSPSNR, 0, sizeof(Double) * 3); // TComPicYuv &picd = *pcPicD; // Double SSDspsnr[3] = { 0, 0 ,0 }; // // for (Int chan = 0; chan < pcPicD->getNumberValidComponents(); chan++) // { // const ComponentID ch = ComponentID(chan); // const Pel* pOrg = pcOrgPicYuv->getAddr(ch); // const Int iOrgStride = pcOrgPicYuv->getStride(ch); // const Pel* pRec = picd.getAddr(ch); // const Int iRecStride = picd.getStride(ch); // // for (Int np = 0; np < iNumPoints; np++) // { // if (!chan) // { // Int x_loc = (Int)(m_fpTable[np].x); // Int y_loc = (Int)(m_fpTable[np].y); // Intermediate_Int iDifflp = (pOrg[x_loc + (y_loc*iOrgStride)] << iReferenceBitShift[toChannelType(ch)]) - (pRec[x_loc + (y_loc*iRecStride)] << iOutputBitShift[toChannelType(ch)]); // SSDspsnr[chan] += iDifflp * iDifflp; // } // else // { // Int x_loc = Int(m_fpTable[np].x >> pcPicD->getComponentScaleX(COMPONENT_Cb)); // Int y_loc = Int(m_fpTable[np].y >> pcPicD->getComponentScaleY(COMPONENT_Cb)); // Intermediate_Int iDifflp = (pOrg[x_loc + (y_loc*iOrgStride)] << iReferenceBitShift[toChannelType(ch)]) - (pRec[x_loc + (y_loc*iRecStride)] << iOutputBitShift[toChannelType(ch)]); // SSDspsnr[chan] += iDifflp * iDifflp; // } // } // } // // for (Int ch_indx = 0; ch_indx < pcPicD->getNumberValidComponents(); ch_indx++) // { // const ComponentID ch = ComponentID(ch_indx); // const Int maxval = 255 << (iBitDepthForPSNRCalc[toChannelType(ch)] - 8); // // Double fReflpsnr = Double(iNumPoints)*maxval*maxval; // m_dSPSNR[ch_indx] = (SSDspsnr[ch_indx] ? 10.0 * log10(fReflpsnr / (Double)SSDspsnr[ch_indx]) : 999.99); // } //}
35.439286
184
0.67137
[ "transform", "3d" ]