hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
94c8af32110bf8d1516cfcda59fdbd3a8a4dbde1 | 1,572 | cpp | C++ | 63.Search-in-Rotated-Sorted-Array.cpp | DeepDuke/Lintcode-Solution | 7c92d03f1267ed84e26180fdeb8abdfc67708019 | [
"MIT"
] | null | null | null | 63.Search-in-Rotated-Sorted-Array.cpp | DeepDuke/Lintcode-Solution | 7c92d03f1267ed84e26180fdeb8abdfc67708019 | [
"MIT"
] | null | null | null | 63.Search-in-Rotated-Sorted-Array.cpp | DeepDuke/Lintcode-Solution | 7c92d03f1267ed84e26180fdeb8abdfc67708019 | [
"MIT"
] | null | null | null | /*
当数组元素有重复时,修改findPivot函数里>改成>=即可,其余与62题基本一样
*/
class Solution {
public:
/**
* @param A: an integer ratated sorted array and duplicates are allowed
* @param target: An integer
* @return: a boolean
*/
int findPivot(vector<int> A){
int L = 0, R = A.size()-1;
while(L < R-1){
int mid = L + (R-L)/2;
if(A[mid] >= A[L]){
L = mid;
}else{
R = mid;
}
}
if(A[L] > A[R]) return R;
else return 0;
}
int binarySearch(vector<int> A, int L, int R, int target){
while(L < R){
int mid = L + (R-L)/2;
if(A[mid] > target){
R = mid-1;
}else if(A[mid] < target){
L = mid+1;
}else{
return mid;
}
}
if(A[L] == target) return L;
else return -1;
}
bool search(vector<int> &A, int target) {
// write your code here
if(A.size() == 0) return false;
if(A.size() == 1) return A[0]==target?true:false;
if(A.size() == 2) return (A[0]==target || A[1]==target)?true:false;
int pivot = findPivot(A);
int index = -1;
if(pivot == 0){
// no rotation
index = binarySearch(A, 0, A.size()-1, target);
}else if(target >= A[0]){
index = binarySearch(A, 0, pivot-1, target);
}else{
index = binarySearch(A, pivot, A.size()-1, target);
}
return index==-1?false:true;
}
}; | 28.581818 | 75 | 0.442748 | DeepDuke |
94d287c82bff7c330ca856577cc0f244f8041636 | 1,411 | cxx | C++ | src/Internal/FontManager.cxx | EXio4/framefun | f055ba82e6c24609dc88b1ea2b03412748809bde | [
"MIT"
] | 1 | 2017-09-30T06:28:57.000Z | 2017-09-30T06:28:57.000Z | src/Internal/FontManager.cxx | EXio4/framefun | f055ba82e6c24609dc88b1ea2b03412748809bde | [
"MIT"
] | null | null | null | src/Internal/FontManager.cxx | EXio4/framefun | f055ba82e6c24609dc88b1ea2b03412748809bde | [
"MIT"
] | null | null | null | #include "Internal/FontManager.h"
namespace Internal {
FontManager::FontManager(Drawer& backend) : backend(backend) {
#include "font.h"
}
bool FontManager::check_bit(int c, int x, int y) {
if (bits[c].size() == 0) return false;
if (x < 0 || x >= FONT_WIDTH) return false;
if (y < 0 || y >= FONT_HEIGHT) return false;
return bits[c][y] & (1 << x);
}
void FontManager::write(Pos pos, char c, int scale, Color col, double blend) {
if (bits[c].size() == 0) return;
for (int ox = 0; ox < FONT_WIDTH; ox++) {
for (int oy = 0; oy < FONT_HEIGHT; oy++) {
if (check_bit(c, ox, oy)) {
int count = 0;
for (int Ax = -1; Ax <= 1; Ax++) {
for (int Ay = -1; Ay <= 1; Ay++) {
count += check_bit(c, ox + Ax, oy + Ay);
}
}
for (int i = 0; i < scale; i++) {
for (int j = 0; j < scale; j++) {
backend.putPixel(Pos(pos.x + ox * scale + i, pos.y + oy * scale + j), col, blend);
}
}
}
}
}
}
void FontManager::write(Pos pos, const std::string& string, int scale, int sep, Color col, double blend) {
for (int i = 0; i < string.size(); i++) {
write(Pos(pos.x + i * (16 * scale + sep), pos.y), string[i], scale, col, blend);
}
}
}
| 30.673913 | 106 | 0.464918 | EXio4 |
94d2fed44993131ce2714cef730071ddf5ba1edf | 604 | cpp | C++ | sample02.cpp | tomoaki0705/sampleMsa | b97b4697cb633e290f643bdb368a235afbde6b95 | [
"MIT"
] | 2 | 2017-08-16T07:03:32.000Z | 2018-07-02T08:22:35.000Z | sample02.cpp | tomoaki0705/sampleMsa | b97b4697cb633e290f643bdb368a235afbde6b95 | [
"MIT"
] | null | null | null | sample02.cpp | tomoaki0705/sampleMsa | b97b4697cb633e290f643bdb368a235afbde6b95 | [
"MIT"
] | null | null | null | #include <msa.h>
#include <iostream>
const char src1[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, };
const char src2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, };
char dst[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
int main(int argc, char**argv)
{
v16i8 v_src1, v_src2, v_dst;
v_src1 = __builtin_msa_ld_b((void*)src1, 0);
v_src2 = __builtin_msa_ld_b((void*)src2, 0);
v_dst = __builtin_msa_addv_b(v_src1, v_src2);
__builtin_msa_st_b(v_dst, (void*)dst, 0);
for( auto i = 0;i < 16;i++)
{
std::cout << i << ": " << (int)dst[i] << std::endl;
}
return 0;
}
| 25.166667 | 77 | 0.551325 | tomoaki0705 |
94dbeda51791685f326d833076c7d11f2b415bd9 | 1,164 | hh | C++ | system-test/maxtest/include/maxtest/execute_cmd.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | system-test/maxtest/include/maxtest/execute_cmd.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | system-test/maxtest/include/maxtest/execute_cmd.hh | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <maxtest/ccdefs.hh>
/**
* @brief execute_cmd Execute shell command
* @param cmd Command line
* @param res Pointer to variable that will contain command console output (stdout)
* @return Process exit code
*/
int execute_cmd(char * cmd, char ** res);
namespace maxtest
{
class VMNode;
}
namespace jdbc
{
enum class ConnectorVersion
{
MARIADB_250, MARIADB_270, MYSQL606
};
std::string to_string(ConnectorVersion vrs);
struct Result
{
bool success {false};
std::string output;
};
Result test_connection(ConnectorVersion vrs, const std::string& host, int port,
const std::string& user, const std::string& pass1, const std::string& pass2,
const std::string& query);
Result test_connection(ConnectorVersion vrs, const std::string& host, int port,
const std::string& user, const std::string& passwd,
const std::string& query);
}
namespace pam
{
void copy_user_map_lib(mxt::VMNode& source, mxt::VMNode& dst);
void delete_user_map_lib(mxt::VMNode& dst);
void copy_map_config(mxt::VMNode& vm);
void delete_map_config(mxt::VMNode& vm);
}
| 24.765957 | 99 | 0.68299 | sdrik |
94e32da4e7dcb55dd209aa18b620c521dbab2b7d | 31,963 | cpp | C++ | tau/TauEngine/src/model/SimpleOBJLoader.cpp | hyfloac/TauEngine | 1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c | [
"MIT"
] | 1 | 2020-04-22T04:07:01.000Z | 2020-04-22T04:07:01.000Z | tau/TauEngine/src/model/SimpleOBJLoader.cpp | hyfloac/TauEngine | 1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c | [
"MIT"
] | null | null | null | tau/TauEngine/src/model/SimpleOBJLoader.cpp | hyfloac/TauEngine | 1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c | [
"MIT"
] | null | null | null | #pragma warning(push, 0)
#include <cstdio>
#include <cstring>
#pragma warning(pop)
#include <maths/Maths.hpp>
#include <model/OBJLoader.hpp>
#include <memory>
#include "VFS.hpp"
#include "Timings.hpp"
namespace objl
{
float Vector3::magnitude() const noexcept
{
return sqrtf(this->magnitudeSquared());
}
float Vector3::midAngleCos(const Vector3& other) const noexcept
{
return this->dot(other) * rSqrt(this->magnitudeSquared() * other.magnitudeSquared());
}
Vector3 Vector3::projection(const Vector3& other) const noexcept
{
const Vector3 bn = other * rSqrt(this->magnitudeSquared());
return bn * this->dot(other);
}
Vector3 Vector3::normalize() const noexcept
{
const float recip = rSqrt(this->magnitudeSquared());
return *this * recip;
}
namespace algorithm
{
bool strEmpty(const char* str) noexcept { return !(str && strlen(str)); }
bool strEmpty(const char* str, const size_t len) noexcept { return !(str && len); }
size_t strFindLastNotOf(const char* str, const char* chars) noexcept
{
if(!str || !chars) { return 0; }
size_t ret = 0;
while(*chars != '\0')
{
const char* fnd = strrchr(str, *chars);
if(!fnd) { return strlen(str) - 1; }
const size_t offset = fnd - str;
if(offset > ret) { ret = offset; }
++chars;
}
return ret;
}
const char* subString(const char* str, const size_t count) noexcept
{
char* retStr = new(std::nothrow) char[count + 1];
if(!retStr) { return nullptr; }
retStr[count] = '\0';
strncpy_s(retStr, count + 1, str, count);
return retStr;
}
const char* subString(const char* str, const size_t start, const size_t count) noexcept
{
char* retStr = new(std::nothrow) char[count + 1];
if(!retStr) { return nullptr; }
retStr[count] = '\0';
strncpy_s(retStr, count + 1, str + start, count);
return retStr;
}
bool sameSide(const Vector3& RESTRICT p1, const Vector3& RESTRICT p2, const Vector3& RESTRICT a, const Vector3& RESTRICT b) noexcept
{
const Vector3 ba = b - a;
const Vector3 p1a = p1 - a;
const Vector3 p2a = p2 - a;
const Vector3 cp1 = ba.cross(p1a);
const Vector3 cp2 = ba.cross(p2a);
return cp1.dot(cp2) >= 0;
}
Vector3 genTriNormal(const Vector3& RESTRICT t1, const Vector3& RESTRICT t2, const Vector3& RESTRICT t3) noexcept
{
const Vector3 u = t2 - t1;
const Vector3 v = t3 - t1;
return u.cross(v);
}
bool inTriangle(const Vector3& RESTRICT point, const Vector3& RESTRICT tri1, const Vector3& RESTRICT tri2, const Vector3& RESTRICT tri3) noexcept
{
// Test to see if it is within an infinite prism that the triangle outlines.
const bool withinTriPrism = sameSide(point, tri1, tri2, tri3) &&
sameSide(point, tri2, tri1, tri3) &&
sameSide(point, tri3, tri1, tri2);
// If it isn't it will never be on the triangle
if(!withinTriPrism) { return false; }
const Vector3 n = genTriNormal(tri1, tri2, tri3);
// If the distance from the triangle to the point is 0
// it lies on the triangle
return point.projection(n).magnitudeSquared() <= 0.0001f;
}
void split(const std::string& RESTRICT in, std::vector<std::string>& RESTRICT out, const std::string& RESTRICT token) noexcept
{
out.clear();
std::string temp;
const size_t inSize = in.size();
const size_t tokenSize = token.size();
const size_t tokenSize1 = tokenSize + 1;
for(size_t i = 0; i < inSize; ++i)
{
std::string test = in.substr(i, tokenSize);
if(test == token)
{
if(!temp.empty())
{
out.push_back(temp);
temp.clear();
i += tokenSize1;
}
else { out.emplace_back(""); }
}
else if(i + tokenSize >= inSize)
{
temp += in.substr(i, tokenSize);
out.push_back(temp);
break;
}
else { temp += in[i]; }
}
}
void split(const char* RESTRICT in, std::vector<std::string>& RESTRICT out, const char token) noexcept
{
out.clear();
const size_t len = strlen(in);
char* temp = new(std::nothrow) char[len + 1];
if(!temp) { return; }
char* tempIndex = temp;
while(*in != '\0')
{
const char test = *in;
if(test == token)
{
if(tempIndex != temp)
{
*tempIndex = '\0';
out.emplace_back(temp);
tempIndex = temp;
}
else { out.emplace_back(""); }
}
else
{
*tempIndex = test;
++tempIndex;
}
++in;
}
*tempIndex = '\0';
out.emplace_back(temp);
delete[] temp;
}
const char* tail(const char* in) noexcept
{
const size_t inLen = strlen(in);
if(!strEmpty(in, inLen))
{
const size_t cTokenStart = strspn(in, " \t");
const size_t cSpaceStart = strcspn(in + cTokenStart, " \t") + cTokenStart;
const size_t cTailStart = strspn(in + cSpaceStart, " \t") + cSpaceStart;
const size_t cTailEnd = strFindLastNotOf(in, " \t");
if(cTailStart != inLen)
{
if(cTailEnd != inLen)
{
return subString(in, cTailStart, cTailEnd - cTailStart + 1);
}
return subString(in, cTailStart);
}
}
return nullptr;
}
const char* firstToken(const char* in) noexcept
{
const size_t inLen = strlen(in);
if(!strEmpty(in, inLen))
{
const size_t cTokenStart = strspn(in, " \t");
const size_t cTokenEnd = strcspn(in + cTokenStart, " \t") + cTokenStart;
if(cTokenStart != inLen)
{
if(cTokenEnd != inLen)
{
return subString(in, cTokenStart, cTokenEnd - cTokenStart);
}
return subString(in, cTokenStart);
}
}
return nullptr;
}
template<typename _T>
inline const _T& getElement(const std::vector<_T>& RESTRICT elements, const std::string& RESTRICT index)
{
i32 idx = std::stoi(index);
if(idx < 0) { idx = static_cast<i32>(elements.size() + idx); }
else { --idx; }
return elements[idx];
}
}
void Loader::genVerticesFromRawOBJ(std::vector<Vertex>& RESTRICT vertices, const std::vector<Vector3>& RESTRICT positions, const std::vector<Vector2>& RESTRICT textureCoords, const std::vector<Vector3>& RESTRICT normals, const char* currentLine) noexcept
{
std::vector<std::string> faceSplit, vertexSplit;
Vertex vertex;
const char* cTail = algorithm::tail(currentLine);
algorithm::split(cTail, faceSplit, ' ');
delete[] cTail;
bool noNormal = false;
bool noTexture = false;
enum VerticeTypes : u8
{
Pos = 0,
PosTex,
PosTexNorm,
PosNorm
};
// For every given vertex do this
for(const std::string& faceElm : faceSplit)
{
// See What type the vertex is.
VerticeTypes verticeType = static_cast<VerticeTypes>(-1);
algorithm::split(faceElm.c_str(), vertexSplit, '/');
switch(vertexSplit.size())
{
case 1:
verticeType = Pos;
break;
case 2:
verticeType = PosTex;
break;
case 3:
if(!vertexSplit[1].empty()) { verticeType = PosTexNorm; }
else { verticeType = PosNorm; }
break;
default: break;
}
// Calculate and store the vertex
switch(verticeType)
{
case Pos: // P
vertex.position = algorithm::getElement(positions, vertexSplit[0]);
vertex.textureCoordinate = Vector2();
noNormal = true;
noTexture = true;
vertices.push_back(vertex);
break;
case PosTex: // P/T
vertex.position = algorithm::getElement(positions, vertexSplit[0]);
vertex.textureCoordinate = algorithm::getElement(textureCoords, vertexSplit[1]);
noNormal = true;
vertices.push_back(vertex);
break;
case PosNorm: // P//N
vertex.position = algorithm::getElement(positions, vertexSplit[0]);
vertex.textureCoordinate = Vector2();
vertex.normal = algorithm::getElement(normals, vertexSplit[2]);
noTexture = true;
vertices.push_back(vertex);
break;
case PosTexNorm: // P/T/N
vertex.position = algorithm::getElement(positions, vertexSplit[0]);
vertex.textureCoordinate = algorithm::getElement(textureCoords, vertexSplit[1]);
vertex.normal = algorithm::getElement(normals, vertexSplit[2]);
vertices.push_back(vertex);
break;
default: break;
}
}
// take care of missing normals
// these may not be truly accurate but it is the
// best they get for not compiling a mesh with normals
if(noNormal)
{
const Vector3 a = vertices[0].position - vertices[1].position;
const Vector3 b = vertices[2].position - vertices[1].position;
const Vector3 normal = a.cross(b);
for(Vertex& vertice : vertices)
{
vertice.normal = normal;
}
}
if(!noTexture)
{
Vector3 v0 = vertices[0].position;
Vector3 v1 = vertices[1].position;
Vector3 v2 = vertices[2].position;
Vector2 t0 = vertices[0].textureCoordinate;
Vector2 t1 = vertices[1].textureCoordinate;
Vector2 t2 = vertices[2].textureCoordinate;
Vector3 dPos1 = v1 - v0;
Vector3 dPos2 = v2 - v0;
Vector2 dTex1 = t1 - t0;
Vector2 dTex2 = t2 - t0;
const float r = 1.0f / (dTex1.x() * dTex2.y() - dTex1.y() * dTex2.x());
Vector3 tangent = (dPos1 * dTex2.y() - dPos2 * dTex1.y()) * r;
Vector3 bitangent = (dPos2 * dTex1.x() - dPos1 * dTex2.x()) * r;
tangent = tangent.normalize();
bitangent = bitangent.normalize();
if(vertices[0].normal.cross(tangent).dot(bitangent) < 0.0f ||
vertices[1].normal.cross(tangent).dot(bitangent) < 0.0f ||
vertices[2].normal.cross(tangent).dot(bitangent) < 0.0f)
{
tangent = tangent * -1.0f;
}
vertices[0].tangent = tangent;
vertices[1].tangent = tangent;
vertices[2].tangent = tangent;
// vertices[0].bitangent = bitangent;
// vertices[1].bitangent = bitangent;
// vertices[2].bitangent = bitangent;
}
}
void Loader::vertexTriangulation(std::vector<u32>& RESTRICT indices, const std::vector<Vertex>& RESTRICT vertices) noexcept
{
// If there are 2 or less verts,
// no triangle can be created,
// so exit
if(vertices.size() < 3) { return; }
// If it is a triangle no need to calculate it
if(vertices.size() == 3)
{
indices.push_back(0);
indices.push_back(1);
indices.push_back(2);
return;
}
// Create a list of vertices
std::vector<Vertex> tVerts = vertices;
while(true)
{
// For every vertex
for(u32 i = 0; i < tVerts.size(); ++i)
{
// pPrev = the previous vertex in the list
Vertex pPrev;
if(i == 0) { pPrev = tVerts[tVerts.size() - 1]; }
else { pPrev = tVerts[i - 1]; }
// pCur = the current vertex;
Vertex pCur = tVerts[i];
// pNext = the next vertex in the list
Vertex pNext;
if(i == tVerts.size() - 1) { pNext = tVerts[0]; }
else { pNext = tVerts[i + 1]; }
// Check to see if there are only 3 verts left
// if so this is the last triangle
if(tVerts.size() == 3)
{
// Create a triangle from pCur, pPrev, pNext
for(u32 j = 0; j < tVerts.size(); ++j)
{
if(vertices[j].position == pCur.position) { indices.push_back(j); }
if(vertices[j].position == pPrev.position) { indices.push_back(j); }
if(vertices[j].position == pNext.position) { indices.push_back(j); }
}
tVerts.clear();
break;
}
if(tVerts.size() == 4)
{
// Create a triangle from pCur, pPrev, pNext
for(u32 j = 0; j < vertices.size(); ++j)
{
if(vertices[j].position == pCur.position) { indices.push_back(j); }
if(vertices[j].position == pPrev.position) { indices.push_back(j); }
if(vertices[j].position == pNext.position) { indices.push_back(j); }
}
Vector3 tempVec;
for(auto& vertex : tVerts)
{
if(vertex.position != pCur.position &&
vertex.position != pPrev.position &&
vertex.position != pNext.position)
{
tempVec = vertex.position;
break;
}
}
// Create a triangle from pCur, pPrev, pNext
for(u32 j = 0; j < vertices.size(); ++j)
{
if(vertices[j].position == pPrev.position) { indices.push_back(j); }
if(vertices[j].position == pNext.position) { indices.push_back(j); }
if(vertices[j].position == tempVec) { indices.push_back(j); }
}
tVerts.clear();
break;
}
// If Vertex is not an interior vertex
const Vector3 prevCur = pPrev.position - pCur.position;
const Vector3 nextCur = pNext.position - pCur.position;
const float angleCos = prevCur.midAngleCos(nextCur);
if(angleCos <= -1.0f || angleCos >= 1.0f) { continue; }
// If any vertices are within this triangle
bool inTri = false;
for(const auto& vertice : vertices)
{
if(algorithm::inTriangle(vertice.position, pPrev.position, pCur.position, pNext.position) &&
vertice.position != pPrev.position &&
vertice.position != pCur.position &&
vertice.position != pNext.position)
{
inTri = true;
break;
}
}
if(inTri) { continue; }
// Create a triangle from pCur, pPrev, pNext
for(u32 j = 0; j < vertices.size(); ++j)
{
if(vertices[j].position == pCur.position) { indices.push_back(j); }
if(vertices[j].position == pPrev.position) { indices.push_back(j); }
if(vertices[j].position == pNext.position) { indices.push_back(j); }
}
// Delete pCur from the list
for(u32 j = 0; j < tVerts.size(); ++j)
{
if(tVerts[j].position == pCur.position)
{
tVerts.erase(tVerts.begin() + j);
break;
}
}
// reset i to the start
// -1 since loop will add 1 to it
i = static_cast<u32>(-1);
}
// if no triangles were created
if(indices.empty() || tVerts.empty()) { break; }
}
}
bool Loader::loadMaterials(const char* path) noexcept
{
PERF();
const size_t pathLen = strlen(path);
if(!(pathLen > 4 && path[pathLen - 4] == '.' && path[pathLen - 3] == 'm' && path[pathLen - 2] == 't' && path[pathLen - 1] == 'l')) { return false; }
FILE* cFile;
if (fopen_s(&cFile, path, "r")) { return false; }
Material tempMaterial;
bool listening = false;
{ // Block used to destruct the line buffer.
char cCurrentLine[256];
while(fgets(cCurrentLine, sizeof(cCurrentLine), cFile))
{
if(cCurrentLine[0] == '\0' ||
cCurrentLine[0] == '\r' ||
cCurrentLine[0] == '\n' ||
cCurrentLine[0] == '#') { continue; }
const size_t lineLen = strlen(cCurrentLine);
if(cCurrentLine[lineLen - 1] == '\n') { cCurrentLine[lineLen - 1] = '\0'; }
const std::string currentLine = cCurrentLine;
// std::string sFirstToken = algorithm::firstToken(currentLine);
const char* sFirstToken = algorithm::firstToken(cCurrentLine);
if(algorithm::strEmpty(sFirstToken, lineLen)) { continue; }
const char* clTail = algorithm::tail(cCurrentLine);
// std::string tokenTail = clTail;
// delete[] clTail;
// new material and material name
if(strcmp(sFirstToken, "newmtl") == 0)
{
if(!listening) { listening = true; }
else
{
// Generate the material
// Push Back loaded Material
_materials.push_back(tempMaterial);
// Clear Loaded Material
tempMaterial = Material();
}
if(currentLine.size() > 7) { tempMaterial.name = clTail; }
else { tempMaterial.name = "none"; }
}
else if(sFirstToken[0] == 'K' && strlen(sFirstToken) == 2)
{
std::vector<std::string> temp;
algorithm::split(clTail, temp, ' ');
if(temp.size() != 3) { continue; }
Vector3* vp = nullptr;
if(sFirstToken[1] == 'a') { vp = &tempMaterial.Ka; } // Ambient Color
else if(sFirstToken[1] == 'd') { vp = &tempMaterial.Kd; } // Diffuse Color
else if(sFirstToken[1] == 's') { vp = &tempMaterial.Ks; } // Specular Color
if(vp)
{
vp->x() = std::stof(temp[0]);
vp->y() = std::stof(temp[1]);
vp->z() = std::stof(temp[2]);
}
}
// Specular Exponent
else if(strcmp(sFirstToken, "Ns") == 0) { tempMaterial.Ns = std::stof(clTail); }
// Optical Density
else if(strcmp(sFirstToken, "Ni") == 0) { tempMaterial.Ni = std::stof(clTail); }
// Dissolve
else if(strcmp(sFirstToken, "d") == 0) { tempMaterial.d = std::stof(clTail); }
// Illumination
else if(strcmp(sFirstToken, "illum") == 0) { tempMaterial.illum = std::stoi(clTail); }
// Ambient Texture Map
else if(strcmp(sFirstToken, "map_Ka") == 0) { tempMaterial.map_Ka = clTail; }
// Diffuse Texture Map
else if(strcmp(sFirstToken, "map_Kd") == 0) { tempMaterial.map_Kd = clTail; }
// Specular Texture Map
else if(strcmp(sFirstToken, "map_Ks") == 0) { tempMaterial.map_Ks = clTail; }
// Specular Highlight Map
else if(strcmp(sFirstToken, "map_Ns") == 0) { tempMaterial.map_Ns = clTail; }
// Alpha Texture Map
else if(strcmp(sFirstToken, "map_d") == 0) { tempMaterial.map_d = clTail; }
// Bump Map
else if(strcmp(sFirstToken, "map_Bump") == 0 ||
strcmp(sFirstToken, "map_bump") == 0 ||
strcmp(sFirstToken, "bump") == 0)
{ tempMaterial.map_bump = clTail; }
delete[] clTail;
delete[] sFirstToken;
}
}
// Deal with last material
_materials.push_back(tempMaterial);
// Test to see if anything was loaded
// If not return false
return !_materials.empty();
}
bool Loader::loadFile(const char* path) noexcept
{
PERF();
const size_t pathLen = strlen(path);
if(!(pathLen > 4 && path[pathLen - 4] == '.' && path[pathLen - 3] == 'o' && path[pathLen - 2] == 'b' && path[pathLen - 1] == 'j')) { return false; }
VFS::Container physPath = VFS::Instance().resolvePath(path);
if(physPath.path.length() == 0)
{
return false;
}
path = physPath.path.c_str();
FILE* cFile;
if(fopen_s(&cFile, path, "r")) { return false; }
_meshes.clear();
_vertices.clear();
_indices.clear();
std::vector<Vector3> Positions;
std::vector<Vector2> TCoords;
std::vector<Vector3> Normals;
std::vector<Vertex> Vertices;
std::vector<u32> Indices;
std::vector<std::string> MeshMatNames;
std::string meshName;
Mesh tempMesh;
{ // Block used to destruct the line buffer.
char currentLine[256];
while(fgets(currentLine, sizeof(currentLine), cFile))
{
if(currentLine[0] == '\0' ||
currentLine[0] == '\r' ||
currentLine[0] == '\n' ||
currentLine[0] == '#') { continue; }
const size_t lastChar = strlen(currentLine) - 1;
if(currentLine[lastChar] == '\n') { currentLine[lastChar] = '\0'; }
const char* sFirstToken = algorithm::firstToken(currentLine);
const size_t sFTLen = strlen(sFirstToken);
if(algorithm::strEmpty(sFirstToken, sFTLen)) { continue; }
const char cFirstToken = sFirstToken[0];
// Generate a Mesh Object or Prepare for an object to be created
if(cFirstToken == 'o' ||
cFirstToken == 'g')
{
const char* cTmpMeshName = algorithm::tail(currentLine);
// Generate the mesh to put into the array
if(!Indices.empty() && !Vertices.empty())
{
// Create Mesh
tempMesh = Mesh(Vertices, Indices);
tempMesh.name = meshName;
// Insert Mesh
_meshes.push_back(tempMesh);
// Cleanup
Vertices.clear();
Indices.clear();
meshName.clear();
}
if(!algorithm::strEmpty(cTmpMeshName)) { meshName = cTmpMeshName; }
else { meshName = "unnamed"; }
delete[] cTmpMeshName;
} // Generate a Vertex Position
else if(cFirstToken == 'v')
{
const char* clTail = algorithm::tail(currentLine);
if(sFTLen > 1)
{
const char cSecondToken = sFirstToken[1];
// Generate a Vertex Texture Coordinate
if(cSecondToken == 't')
{
std::vector<std::string> stex;
Vector2 vtex;
algorithm::split(clTail, stex, ' ');
vtex.x() = std::stof(stex[0]);
vtex.y() = std::stof(stex[1]);
TCoords.push_back(vtex);
} // Generate a Vertex Normal;
else if(cSecondToken == 'n')
{
std::vector<std::string> snor;
Vector3 vnor;
algorithm::split(clTail, snor, ' ');
vnor.x() = std::stof(snor[0]);
vnor.y() = std::stof(snor[1]);
vnor.z() = std::stof(snor[2]);
Normals.push_back(vnor);
}
}
else
{
std::vector<std::string> spos;
Vector3 vpos;
algorithm::split(clTail, spos, ' ');
vpos.x() = std::stof(spos[0]);
vpos.y() = std::stof(spos[1]);
vpos.z() = std::stof(spos[2]);
Positions.push_back(vpos);
}
delete[] clTail;
} // Generate a Face (vertices & indices)
else if(cFirstToken == 'f')
{
// Generate the vertices
std::vector<Vertex> vVerts;
genVerticesFromRawOBJ(vVerts, Positions, TCoords, Normals, currentLine);
// Subtract Vertices
for(const Vertex& vVert : vVerts)
{
Vertices.push_back(vVert);
_vertices.push_back(vVert);
}
std::vector<u32> iIndices;
vertexTriangulation(iIndices, vVerts);
// Subtract Indices
for(u32 iIndice : iIndices)
{
u32 indNum = static_cast<u32>(Vertices.size() - vVerts.size()) + iIndice;
Indices.push_back(indNum);
indNum = static_cast<u32>(_vertices.size() - vVerts.size()) + iIndice;
_indices.push_back(indNum);
}
} // Get Mesh Material Name
else if(strcmp(sFirstToken, "usemtl") == 0)
{
const char* clTail = algorithm::tail(currentLine);
MeshMatNames.emplace_back(clTail);
delete[] clTail;
// Create new Mesh, if Material changes within a group
if(!Indices.empty() && !Vertices.empty())
{
// Create Mesh
tempMesh = Mesh(Vertices, Indices);
tempMesh.name = meshName + "_2";
// Insert Mesh
_meshes.push_back(tempMesh);
// Cleanup
Vertices.clear();
Indices.clear();
}
} // Load Materials
else if(strcmp(sFirstToken, "mtllib") == 0)
{
// Generate LoadedMaterial
// Generate a path to the material file
std::vector<std::string> temp;
algorithm::split(path, temp, '/');
std::string pathToMat;
const size_t tSize = temp.size() - 1;
if(tSize >= 0)
{
for(size_t i = 0; i < tSize; ++i)
{
pathToMat += temp[i] + "/";
}
}
const char* clTail = algorithm::tail(currentLine);
pathToMat += clTail;
delete[] clTail;
// Load Materials
loadMaterials(pathToMat.c_str());
}
delete[] sFirstToken;
}
}
fclose(cFile);
// Deal with last mesh
if(!Indices.empty() && !Vertices.empty())
{
// Create Mesh
tempMesh = Mesh(Vertices, Indices);
tempMesh.name = meshName;
// Insert Mesh
_meshes.push_back(tempMesh);
}
// Set Materials for each Mesh
for(u32 i = 0; i < MeshMatNames.size(); ++i)
{
std::string matName = MeshMatNames[i];
// Find corresponding material name in loaded materials
// when found copy material variables into mesh material
for(auto& _material : _materials)
{
if(_material.name == matName)
{
_meshes[i].material = _material;
break;
}
}
}
return !(_meshes.empty() && _vertices.empty() && _indices.empty());
}
}
| 36.6969 | 259 | 0.439633 | hyfloac |
94e6b825a689255aad87f7906de452f9ac29aae3 | 1,070 | cpp | C++ | Online Judges/LightOJ/1025 - The Specials Menu.cpp | akazad13/competitive-programming | 5cbb67d43ad8d5817459043bcccac3f68d9bc688 | [
"MIT"
] | null | null | null | Online Judges/LightOJ/1025 - The Specials Menu.cpp | akazad13/competitive-programming | 5cbb67d43ad8d5817459043bcccac3f68d9bc688 | [
"MIT"
] | null | null | null | Online Judges/LightOJ/1025 - The Specials Menu.cpp | akazad13/competitive-programming | 5cbb67d43ad8d5817459043bcccac3f68d9bc688 | [
"MIT"
] | null | null | null | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define rep(i,p,n) for( i = p; i<n;i++)
#define lld long long int
#define Clear(a,b) memset(a,b,sizeof(a))
template<class T>inline bool read(T &x) {
int c=getchar();
int sgn=1;
while(~c&&c<'0'||c>'9') {
if(c=='-')sgn=-1;
c=getchar();
}
for(x=0; ~c&&'0'<=c&&c<='9'; c=getchar())x=x*10+c-'0';
x*=sgn;
return ~c;
}
/***************************************/
char str[70];
lld dp[70][70];
lld solve(int i, int j)
{
if(i>j)
return 0;
if(i==j)
return 1;
lld &ret = dp[i][j];
if(ret!=-1) return ret;
if(str[i]==str[j])
{
ret=1+solve(i,j-1)+solve(i+1,j);
}
else
{
ret=solve(i+1,j)+solve(i,j-1)-solve(i+1,j-1);
}
return ret;
}
int main()
{
int test,i,j,Case,n,m;
read(test);
rep(Case,1,test+1)
{
gets(str);
Clear(dp,-1);
int len = strlen(str);
lld ret = solve(0,len-1);
printf("Case %d: %lld\n",Case,ret);
}
return 0;
}
| 16.461538 | 58 | 0.461682 | akazad13 |
94e7b9fa7f1886713e2364dd7780f6b612101828 | 6,481 | cpp | C++ | src/textGUI.cpp | gbl08ma/imageviewer | 8c7d24af0a5bc6bfa90d00fe58aca3b24df90d71 | [
"BSD-2-Clause"
] | 9 | 2016-01-17T21:24:17.000Z | 2021-11-23T17:39:38.000Z | src/textGUI.cpp | gbl08ma/imageviewer | 8c7d24af0a5bc6bfa90d00fe58aca3b24df90d71 | [
"BSD-2-Clause"
] | null | null | null | src/textGUI.cpp | gbl08ma/imageviewer | 8c7d24af0a5bc6bfa90d00fe58aca3b24df90d71 | [
"BSD-2-Clause"
] | null | null | null | /*----------------------------------------------------------------------------/
/ JPEG and PNG Image Viewer for the Casio Prizm
/ Copyright 2014 tny. internet media
/ http://i.tny.im / admin@tny.im
/-----------------------------------------------------------------------------/
/ Copyright (c) 2014, Gabriel Maia and the tny. internet media group
/ All rights reserved.
/
/ Redistribution and use in source and binary forms, with or without
/ modification, are permitted provided that the following conditions are met:
/
/ 1. Redistributions of source code must retain the above copyright notice,
/ this list of conditions and the following disclaimer.
/
/ 2. Redistributions in binary form must reproduce the above copyright notice,
/ this list of conditions and the following disclaimer in the documentation
/ and/or other materials provided with the distribution.
/
/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/ POSSIBILITY OF SUCH DAMAGE.
/
/----------------------------------------------------------------------------*/
#include <fxcg/display.h>
#include <fxcg/file.h>
#include <fxcg/keyboard.h>
#include <fxcg/system.h>
#include <fxcg/misc.h>
#include <fxcg/app.h>
#include <fxcg/serial.h>
#include <fxcg/rtc.h>
#include <fxcg/heap.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "textGUI.hpp"
#include "stringsProvider.hpp"
#include "graphicsProvider.hpp"
typedef scrollbar TScrollbar;
int doTextArea(textArea* text) {
int scroll = 0;
int isFirstDraw = 1;
int totalTextY = 0;
int key;
int showtitle = text->title != NULL;
while(1) {
drawRectangle(text->x, text->y+24, text->width, LCD_HEIGHT_PX-24, COLOR_WHITE);
int cur = 0;
int textX = text->x;
int textY = scroll+(showtitle ? 24 : 0)+text->y; // 24 pixels for title (or not)
int temptextY = 0;
int temptextX = 0;
while(cur < text->numelements) {
if(text->elements[cur].newLine) {
textX=text->x;
textY=textY+text->lineHeight+text->elements[cur].lineSpacing;
}
int tlen = strlen(text->elements[cur].text);
char* singleword = (char*)malloc(tlen); // because of this, a single text element can't have more bytes than malloc can provide
char* src = text->elements[cur].text;
while(*src)
{
temptextX = 0;
src = (char*)toksplit((unsigned char*)src, ' ', (unsigned char*)singleword, tlen); //break into words; next word
//check if printing this word would go off the screen, with fake PrintMini drawing:
if(text->elements[cur].minimini) {
PrintMiniMini( &temptextX, &temptextY, singleword, 0, text->elements[cur].color, 1 );
} else {
PrintMini(&temptextX, &temptextY, singleword, 0, 0xFFFFFFFF, 0, 0, text->elements[cur].color, COLOR_WHITE, 0, 0);
}
if(temptextX + textX > text->width-6) {
//time for a new line
textX=text->x;
textY=textY+text->lineHeight;
} //else still fits, print new word normally (or just increment textX, if we are not "on stage" yet)
if(textY >= -24 && textY < LCD_HEIGHT_PX) {
if(text->elements[cur].minimini) {
PrintMiniMini( &textX, &textY, singleword, 0, text->elements[cur].color, 0 );
} else {
PrintMini(&textX, &textY, singleword, 0, 0xFFFFFFFF, 0, 0, text->elements[cur].color, COLOR_WHITE, 1, 0);
}
//add a space, since it was removed from token
if(*src || text->elements[cur].spaceAtEnd) PrintMini(&textX, &textY, (char*)" ", 0, 0xFFFFFFFF, 0, 0, COLOR_BLACK, COLOR_WHITE, 1, 0);
} else {
textX += temptextX;
if(*src || text->elements[cur].spaceAtEnd) textX += 7; // size of a PrintMini space
}
}
free(singleword);
if(isFirstDraw) {
totalTextY = textY+(showtitle ? 0 : 24);
} else if(textY>LCD_HEIGHT_PX) {
break;
}
cur++;
}
isFirstDraw=0;
if(showtitle) {
clearLine(1,1);
drawScreenTitle((char*)text->title);
}
int scrollableHeight = LCD_HEIGHT_PX-24*(showtitle ? 2 : 1)-text->y;
//draw a scrollbar:
if(text->scrollbar) {
TScrollbar sb;
sb.I1 = 0;
sb.I5 = 0;
sb.indicatormaximum = totalTextY;
sb.indicatorheight = scrollableHeight;
sb.indicatorpos = -scroll;
sb.barheight = scrollableHeight;
sb.bartop = (showtitle ? 24 : 0)+text->y;
sb.barleft = text->width - 6;
sb.barwidth = 6;
Scrollbar(&sb);
}
if(text->type == TEXTAREATYPE_INSTANT_RETURN) return 0;
GetKey(&key);
switch(key)
{
case KEY_CTRL_UP:
if (scroll < 0) {
scroll = scroll + 17;
if(scroll > 0) scroll = 0;
}
break;
case KEY_CTRL_DOWN:
if (textY > scrollableHeight-(showtitle ? 0 : 17)) {
scroll = scroll - 17;
if(scroll < -totalTextY+scrollableHeight-(showtitle ? 0 : 17)) scroll = -totalTextY+scrollableHeight-(showtitle ? 0 : 17);
}
break;
case KEY_CTRL_PAGEDOWN:
if (textY > scrollableHeight-(showtitle ? 0 : 17)) {
scroll = scroll - scrollableHeight;
if(scroll < -totalTextY+scrollableHeight-(showtitle ? 0 : 17)) scroll = -totalTextY+scrollableHeight-(showtitle ? 0 : 17);
}
break;
case KEY_CTRL_PAGEUP:
if (scroll < 0) {
scroll = scroll + scrollableHeight;
if(scroll > 0) scroll = 0;
}
break;
case KEY_CTRL_EXE:
if(text->allowEXE) return TEXTAREA_RETURN_EXE;
break;
case KEY_CTRL_F1:
if(text->allowF1) return TEXTAREA_RETURN_F1;
break;
case KEY_CTRL_EXIT: return TEXTAREA_RETURN_EXIT; break;
}
}
} | 38.577381 | 144 | 0.61472 | gbl08ma |
94ec18963741edd2f2b908aa71c7ce514cef5e85 | 125 | cpp | C++ | System/RocketState.cpp | MatthewGotte/214_project_Derived | 48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd | [
"MIT"
] | null | null | null | System/RocketState.cpp | MatthewGotte/214_project_Derived | 48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd | [
"MIT"
] | null | null | null | System/RocketState.cpp | MatthewGotte/214_project_Derived | 48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd | [
"MIT"
] | null | null | null | #include "RocketState.h"
RocketState::RocketState() {
}
RocketState::~RocketState() {
}
//this was updated | 11.363636 | 30 | 0.616 | MatthewGotte |
94fa2db144ba53ea10218b9e1f20d235fbac0519 | 604 | cpp | C++ | cpp/23716.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 9 | 2021-01-15T13:36:39.000Z | 2022-02-23T03:44:46.000Z | cpp/23716.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 1 | 2021-07-31T17:11:26.000Z | 2021-08-02T01:01:03.000Z | cpp/23716.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
int main() {
fastio;
int N; cin >> N;
for (int c = 1; c <= N; c++) {
string a, b; cin >> a >> b;
auto Sol = [&]() -> int {
int ret = 0;
for (const char& c : a) {
int mn = 1e9;
for (int i = 0; i < 26; i++) if (b.find('a' + i) != -1)
if (c < 'a' + i) mn = min(mn, min('a' + i - c, 26 + c - 'a' - i));
else mn = min(mn, min(c - 'a' - i, 26 + 'a' + i - c));
ret += mn;
}
return ret;
};
cout << "Case #" << c << ": " << Sol() << '\n';
}
} | 24.16 | 86 | 0.407285 | jinhan814 |
94fc43200d02999ede0b5b79a1b7abbea456baff | 171 | cpp | C++ | src/PerTypeStorage.cpp | deadmorous/factory | be42a869739deaa615a45070d0747ce4460c0250 | [
"MIT"
] | null | null | null | src/PerTypeStorage.cpp | deadmorous/factory | be42a869739deaa615a45070d0747ce4460c0250 | [
"MIT"
] | null | null | null | src/PerTypeStorage.cpp | deadmorous/factory | be42a869739deaa615a45070d0747ce4460c0250 | [
"MIT"
] | 1 | 2021-01-23T03:14:19.000Z | 2021-01-23T03:14:19.000Z | // PerTypeStorage.cpp
#include "factory/PerTypeStorage.hpp"
namespace ctm {
FACTORY_API PerTypeStorage::Data *PerTypeStorage::m_data = nullptr;
} // end namespace ctm
| 17.1 | 67 | 0.766082 | deadmorous |
94feb374137d200d9037b7f72eff91565a44c0c2 | 699 | cpp | C++ | Chapter5/Example/L5.11.cpp | flics04/XXXASYBT_CppBase | 0086df68497197f40286889b18f2d8c28eb833bb | [
"MIT"
] | 1 | 2022-02-13T02:22:39.000Z | 2022-02-13T02:22:39.000Z | Chapter5/Example/L5.11.cpp | flics04/XXXASYBT_CppBase | 0086df68497197f40286889b18f2d8c28eb833bb | [
"MIT"
] | null | null | null | Chapter5/Example/L5.11.cpp | flics04/XXXASYBT_CppBase | 0086df68497197f40286889b18f2d8c28eb833bb | [
"MIT"
] | null | null | null | /* 原书例5.11 */
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a[11][11];
a[1][1] = 1; // 设定第一行的值
for (int i = 2; i <= 10; ++i) { // 从第二行开始推
a[i][1] = 1;
a[i][i] = 1; // 设定每一行的首尾值为1
for (int j = 2; j <= i - 1; ++j) // 当前行非首尾的数
a[i][j] = a[i - 1][j - 1] + a[i - 1][j]; // 每个数等于上一行的两个数之和
}
for (int i = 1; i <= 10; ++i) {
if (i != 10)
cout << setw(30 - 3 * 1) << " "; // 控制每行的起始位置,即空格数量
for (int j = 1; j <= i; ++j)
cout << setw(6) << a[i][j];
cout << endl;
}
return 0;
}
| 27.96 | 77 | 0.347639 | flics04 |
a206f99c83620519cf0febe925ed158d343b62d3 | 310 | cpp | C++ | 14. Binary Tree/02 Recursive Traversals/02 Tree Traversals.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 190 | 2021-02-10T17:01:01.000Z | 2022-03-20T00:21:43.000Z | 14. Binary Tree/02 Recursive Traversals/02 Tree Traversals.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | null | null | null | 14. Binary Tree/02 Recursive Traversals/02 Tree Traversals.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 27 | 2021-03-26T11:35:15.000Z | 2022-03-06T07:34:54.000Z | #include<bits/stdc++.h>
using namespace std;
int main()
{
/*
Tree Traversal :
a. Breadth First Traversal (level order traversal)
b. Depth First Traversal
b.1 Inorder Traversal (Left Root Right)
b.2 Preorder Traversal (Root Left Right)
b.3 Postorder Traversal (Left Right Root)
*/
return 0;
} | 14.761905 | 51 | 0.7 | VivekYadav105 |
a2087fb11d50919ec2044a9fcbca451ae028eb5a | 15,473 | cpp | C++ | SOURCES/acmi/src/acmiview.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/acmi/src/acmiview.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/acmi/src/acmiview.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #pragma optimize( "", off )
#include <windows.h>
#include "resource.h"
#include "Graphics/include/renderwire.h"
#include "Graphics/include/terrtex.h"
#include "Graphics/include/rViewPnt.h"
#include "Graphics/include/loader.h"
#include "Graphics/include/drawbsp.h"
#include "Graphics/include/drawpole.h"
#include "Graphics/include/drawpnt.h"
#include "ui95/chandler.h"
#include "ui95/cthook.h"
#include "ClassTbl.h"
#include "Entity.h"
#include "fsound.h"
#include "f4vu.h"
#include "camp2sim.h"
#include "f4error.h"
#include "falclib/include/f4find.h"
#include "dispcfg.h"
#include "acmiUI.h"
#include "playerop.h"
#include "sim/include/simbase.h"
#include "codelib/tools/lists/lists.h"
#include "acmitape.h"
#include "AcmiView.h"
#include "FalcLib/include/dispopts.h"
#include "TimeMgr.h"
extern DeviceManager devmgr;
extern ACMIView *acmiView;
extern int DisplayFullScreen;
extern int DeviceNumber;
#include "Graphics\DXEngine\DXVBManager.h"
extern bool g_bUse_DX_Engine;
extern C_Handler *gMainHandler;
extern int TESTBUTTONPUSH;
extern LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK ACMIWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
void CalcTransformMatrix(SimBaseClass* theObject);
void CreateObject(SimBaseClass*);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ACMIView::ACMIView()
{
_platform = NULL;
_win = NULL;
_tape = NULL;
_entityUIMappings = NULL;
_isReady = FALSE;
_tapeHasLoaded = FALSE;
_pannerX = 0.0f;
_pannerY = 0.0f;
_pannerZ = 0.0f;
_pannerAz = 0.0f;
_pannerEl = 0.0f;
_chaseX = 0.0f;
_chaseY = 0.0f;
_chaseZ = 0.0f;
_tracking = FALSE;
_doWireFrame = 0;
_doLockLine = 0;
_camYaw = 0.0f;
_camPitch = 0.0f;
_camRoll = 0.0f;
Init();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ACMIView::~ACMIView()
{
Init();
//acmiView = NULL;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::Init()
{
StopGraphicsLoop();
UnloadTape( FALSE );
_drawing = FALSE;
_drawingFinished = TRUE;
_viewPoint = NULL;
_renderer = NULL;
_objectScale = 1.0F;
//LRKLUDGE
_doWeather = FALSE;
memset(_fileName, 0, 40);
InitUIVector();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::ToggleLabel(int doIDTags)
{
DrawableBSP::drawLabels = doIDTags ? TRUE : FALSE;
}
void ACMIView::ToggleHeading(int val)
{
DrawablePoled::drawHeading = val ? TRUE : FALSE;
}
void ACMIView::ToggleAltitude(int val)
{
DrawablePoled::drawAlt = val ? TRUE : FALSE;
}
void ACMIView::ToggleAirSpeed(int val)
{
DrawablePoled::drawSpeed = val ? TRUE : FALSE;
}
void ACMIView::ToggleTurnRate(int val)
{
DrawablePoled::drawTurnRate = val ? TRUE : FALSE;
}
void ACMIView::ToggleTurnRadius(int val)
{
DrawablePoled::drawTurnRadius = val ? TRUE : FALSE;
}
void ACMIView::ToggleWireFrame(int val)
{
_doWireFrame = val;
}
void ACMIView::ToggleLockLines(int val)
{
_doLockLine = val;
}
void ACMIView::ToggleScreenShot()
{
_takeScreenShot ^= 1;
_tape->SetScreenCapturing( _takeScreenShot );
};
void ACMIView::TogglePoles(int val)
{
DrawablePoled::drawPole = val ? TRUE : FALSE;
}
void ACMIView::Togglelockrange(int val)//me123
{
DrawablePoled::drawlockrange = val ? TRUE : FALSE;
}
// BING - TRYING TO SET THE OBJECTS NAME LABEL - FOR UNIQUE NAMES.
void ACMIView::SetObjectName(SimBaseClass* theObject, char *tmpStr)
{
Falcon4EntityClassType
*classPtr = (Falcon4EntityClassType*)theObject->EntityType();
if(classPtr->dataType == DTYPE_VEHICLE)
{
//sprintf(tmpStr, "%s",((VehicleClassDataType*)(classPtr->dataPtr))->Name);
sprintf(((VehicleClassDataType*)(classPtr->dataPtr))->Name,"%s",tmpStr);
}
else if(classPtr->dataType == DTYPE_WEAPON)
{
//sprintf(tmpStr, "%s",((WeaponClassDataType*)(classPtr->dataPtr))->Name);
sprintf(((WeaponClassDataType*)(classPtr->dataPtr))->Name,"%s",tmpStr);
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::SetupEntityUIMappings()
{
int
i,
numEntities;
// BING 3-21-98
TCHAR tmpStr[60];
SimTapeEntity *ep;
ACMIEntityData *e;
// _tape->_simTapeEntities[i].name;
F4Assert(_entityUIMappings == NULL);
F4Assert(_tape != NULL && _tape->IsLoaded());
numEntities = _tape->NumEntities();
_entityUIMappings = new ACMIEntityUIMap[numEntities];
F4Assert(_entityUIMappings != NULL);
for(i = 0; i < numEntities; i++)
{
_entityUIMappings[i].listboxId = -1;
_entityUIMappings[i].menuId = -1;
_entityUIMappings[i].name[0] = 0;
ep = Tape()->GetSimTapeEntity(i);
// we don't want to put chaff and flares into the list boxes
if ( ep->flags & ( ENTITY_FLAG_CHAFF | ENTITY_FLAG_FLARE ) )
continue;
GetObjectName(ep->objBase, _entityUIMappings[i].name);
if ( _entityUIMappings[i].name[0] == 0 )
continue;
e = Tape()->EntityData( i );
sprintf (tmpStr, "%d %s",e->count, _entityUIMappings[i].name);
// Update the entityUIMappings...
sprintf(_entityUIMappings[i].name,tmpStr);
((DrawableBSP*)(ep->objBase->drawPointer))->SetLabel (_entityUIMappings[i].name, ((DrawableBSP*)(ep->objBase->drawPointer))->LabelColor());
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
BOOL ACMIView::LoadTape(char *fname, BOOL reload )
{
_tapeHasLoaded = FALSE;
F4Assert(_tape == NULL);
if ( fname[0] )
memcpy(_fileName, fname, 40);
// do we have a file name?
if(_fileName[0] == 0)
return FALSE;
// create the tape from the file
_tape = new ACMITape(_fileName, _renderer, _viewPoint);
F4Assert(_tape != NULL);
// do something go wrong?
if(!_tape->IsLoaded())
{
delete _tape;
_tape = NULL;
MonoPrint
(
"InitACMIFile() --> Could not load ACMI Tape: %s.\n",
_fileName
);
return FALSE;
}
if ( reload == FALSE )
{
// Setup our entity UI mappings.
SetupEntityUIMappings();
// Set our camera objects.
SetCameraObject(0);
SetTrackingObject(0);
ResetPanner();
}
else
{
// SetupEntityUIMappings(); // JPO fixup.
}
_tapeHasLoaded = TRUE;
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::UnloadTape( BOOL reload )
{
_tapeHasLoaded = FALSE;
if ( reload == FALSE )
{
if(_entityUIMappings)
{
delete [] _entityUIMappings;
_entityUIMappings = NULL;
}
}
if(_tape)
{
delete _tape;
_tape = NULL;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
char *ACMIView::SetListBoxID(int objectNum, long listID)
{
_entityUIMappings[objectNum].listboxId = listID;
return(_entityUIMappings[objectNum].name);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
long ACMIView::ListBoxID(int objectNum, long filter)
{
long
menuID = -1;
switch(filter)
{
case INTERNAL_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case EXTERNAL_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case CHASE_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case WING_CAM:
/*
if(_tape->EntityGroup(objectNum) == 0)
{
menuID = _entityUIMappings[objectNum].listboxId;
}
break;
*/
case BANDIT_CAM:
/*
if(_tape->EntityGroup(objectNum) == 1)
{
menuID = _entityUIMappings[objectNum].listboxId;
}
break;
*/
case FRIEND_CAM:
/*
if(_tape->EntityGroup(objectNum) == 0)
{
menuID = _entityUIMappings[objectNum].listboxId;
}
break;
*/
case GVEHICLE_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case THREAT_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case WEAPON_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case TARGET_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case SAT_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case REPLAY_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case DIRECTOR_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
case FREE_CAM:
menuID = _entityUIMappings[objectNum].listboxId;
break;
// default:
};
return(menuID);
}
////////////////////////////////////////////////////////////////////////////////////
void ACMIView::GetObjectName(SimBaseClass* theObject, char *tmpStr)
{
Falcon4EntityClassType
*classPtr = (Falcon4EntityClassType*)theObject->EntityType();
memset(tmpStr, 0, 40);
if(classPtr->dataType == DTYPE_VEHICLE || classPtr->dataType == DTYPE_WEAPON) {
strcpy(tmpStr, ((DrawableBSP*)theObject->drawPointer)->Label());
if(strlen(tmpStr) == 0) {
if(classPtr->dataType == DTYPE_VEHICLE)
{
sprintf(tmpStr, "%s",((VehicleClassDataType*)(classPtr->dataPtr))->Name);
}
else if(classPtr->dataType == DTYPE_WEAPON)
{
sprintf(tmpStr, "%s",((WeaponClassDataType*)(classPtr->dataPtr))->Name);
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::InitGraphics(C_Window *win)
{
Tpoint
viewPos;
Trotation
viewRotation;
float l, t, r, b, sw, sh;
// Preload objects which will need to be instant access
// DrawableBSP::LockAndLoad(2);
//BING 3-20-98
// SET UP FOR TOGGELING OF LABELS.
// int doIDTags;
// doIDTags = 1;
DrawableBSP::drawLabels = TRUE;
DrawablePoint::drawLabels = FALSE;
// Load the terrain texture override image
// edg: need to put in switch for wireframe terrain
if ( _doWireFrame )
{
wireTexture.LoadAndCreate( "WireTile.GIF", MPR_TI_PALETTE );
wireTexture.FreeImage();
TheTerrTextures.SetOverrideTexture( wireTexture.TexHandle() );
// _renderer = new RenderWire;
_renderer = new RenderOTW;
}
else
{
_renderer = new RenderOTW;
}
_viewPoint = new RViewPoint;
if ( _doWireFrame == FALSE )
{
_viewPoint->Setup( 0.75f * PlayerOptions.TerrainDistance() * FEET_PER_KM,
PlayerOptions.MaxTerrainLevel(),
4,
DisplayOptions.bZBuffering); //JAM 30Dec03
_renderer->Setup(gMainHandler->GetFront(), _viewPoint);
// _renderer->SetTerrainTextureLevel( PlayerOptions.TextureLevel() );
// _renderer->SetSmoothShadingMode( TRUE );//PlayerOptions.GouraudOn() );
_renderer->SetHazeMode(PlayerOptions.HazingOn());
_renderer->SetDitheringMode( PlayerOptions.HazingOn() );
_renderer->SetFilteringMode( PlayerOptions.FilteringOn() );
_renderer->SetObjectDetail(PlayerOptions.ObjectDetailLevel() );
// _renderer->SetAlphaMode(PlayerOptions.AlphaOn());
_renderer->SetObjectTextureState(TRUE);//PlayerOptions.ObjectTexturesOn());
}
else
{
_viewPoint->Setup( 20.0f * FEET_PER_KM,
0,
2,
0.0f );
_renderer->Setup(gMainHandler->GetFront(), _viewPoint);
// _renderer->SetTerrainTextureLevel(2);
_renderer->SetHazeMode(FALSE);
// _renderer->SetSmoothShadingMode(FALSE);
}
TheVbManager.Setup(gMainHandler->GetFront()->GetDisplayDevice()->GetDefaultRC()->m_pD3D);
sw = (float)gMainHandler->GetFront()->targetXres();
sh = (float)gMainHandler->GetFront()->targetYres();
l = -1.0f +((float) win->GetX() /(sw * 0.5F));
t = 1.0f -((float) win->GetY() /(sh * 0.5F));
r = 1.0f -((float)(sw-(win->GetX() + win->GetW())) /(sw * 0.5F));
b = -1.0f +((float)(sh -(win->GetY() + win->GetH())) /(sh * 0.5F));
_renderer->SetViewport(l, t, r, b);
_isReady = TRUE;
_drawing = TRUE;
_drawingFinished = FALSE;
_takeScreenShot = FALSE;
_objectScale = 1.0F;
viewRotation = IMatrix;
// Update object position
viewPos.x = 110000.0F;
viewPos.y = 137000.0F;
viewPos.z = -15000.0F;
_drawingFinished = FALSE;
_initialGraphicsLoad = TRUE;
_drawing = TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::StopGraphicsLoop()
{
if(_isReady)
{
_drawing = FALSE;
_drawingFinished = TRUE;
// This really scares me. What is this here? Are we asking for a race condition???
Sleep(100);
// Remove all references to the display device
if(_renderer)
{
_renderer->Cleanup();
delete _renderer;
_renderer = NULL;
}
if(_viewPoint)
{
_viewPoint->Cleanup();
delete _viewPoint;
_viewPoint = NULL;
}
// Get rid of our texture override
if ( _doWireFrame )
{
TheTerrTextures.SetOverrideTexture( NULL );
wireTexture.FreeAll();
}
_drawingFinished = TRUE;
_isReady = FALSE;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
int ACMIView::ExitGraphics()
{
StopGraphicsLoop();
return(1);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::DrawIDTags()
{
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMIView::SetPannerXYZ( float x, float y, float z)
{
_pannerX += x;
_pannerY += y;
_pannerZ += z;
}
void ACMIView::SetPannerAzEl( float az, float el )
{
_pannerAz += az;
_pannerEl += el;
}
void ACMIView::ResetPanner( void )
{
_pannerAz = 0.0f;
_pannerEl = 0.0f;
_pannerX = 0.0f;
_pannerY = 0.0f;
_pannerZ = 0.0f;
}
| 23.443939 | 141 | 0.530925 | IsraelyFlightSimulator |
a2095ce13b8222a929e704828f6060b4d074900a | 1,920 | hpp | C++ | example/content/meta/skeleton.hpp | Seng3694/TXPK | 76a5441dc70b4a5d5d2596525de950a2d2e65aab | [
"MIT"
] | 6 | 2019-01-05T08:14:02.000Z | 2021-12-02T18:29:35.000Z | example/content/meta/skeleton.hpp | lineCode/TXPK | 20d4cd75611a44babf2bf41d5359141020dc6684 | [
"MIT"
] | 1 | 2018-03-28T06:33:08.000Z | 2018-03-29T08:22:43.000Z | example/content/meta/skeleton.hpp | Seng3694/TexturePacker | 76a5441dc70b4a5d5d2596525de950a2d2e65aab | [
"MIT"
] | 2 | 2018-12-11T01:11:20.000Z | 2020-10-30T08:14:04.000Z | #pragma once
#define SKELETON_ATTACK_1 0
#define SKELETON_ATTACK_2 1
#define SKELETON_ATTACK_3 2
#define SKELETON_ATTACK_4 3
#define SKELETON_ATTACK_5 4
#define SKELETON_ATTACK_6 5
#define SKELETON_ATTACK_7 6
#define SKELETON_ATTACK_8 7
#define SKELETON_ATTACK_9 8
#define SKELETON_ATTACK_10 9
#define SKELETON_ATTACK_11 10
#define SKELETON_ATTACK_12 11
#define SKELETON_ATTACK_13 12
#define SKELETON_ATTACK_14 13
#define SKELETON_ATTACK_15 14
#define SKELETON_ATTACK_16 15
#define SKELETON_ATTACK_17 16
#define SKELETON_ATTACK_18 17
#define SKELETON_DEAD_1 18
#define SKELETON_DEAD_2 19
#define SKELETON_DEAD_3 20
#define SKELETON_DEAD_4 21
#define SKELETON_DEAD_5 22
#define SKELETON_DEAD_6 23
#define SKELETON_DEAD_7 24
#define SKELETON_DEAD_8 25
#define SKELETON_DEAD_9 26
#define SKELETON_DEAD_10 27
#define SKELETON_DEAD_11 28
#define SKELETON_DEAD_12 29
#define SKELETON_DEAD_13 30
#define SKELETON_DEAD_14 31
#define SKELETON_DEAD_15 32
#define SKELETON_HIT_1 33
#define SKELETON_HIT_2 34
#define SKELETON_HIT_3 35
#define SKELETON_HIT_4 36
#define SKELETON_HIT_5 37
#define SKELETON_HIT_6 38
#define SKELETON_HIT_7 39
#define SKELETON_HIT_8 40
#define SKELETON_IDLE_1 41
#define SKELETON_IDLE_2 42
#define SKELETON_IDLE_3 43
#define SKELETON_IDLE_4 44
#define SKELETON_IDLE_5 45
#define SKELETON_IDLE_6 46
#define SKELETON_IDLE_7 47
#define SKELETON_IDLE_8 48
#define SKELETON_IDLE_9 49
#define SKELETON_IDLE_10 50
#define SKELETON_IDLE_11 51
#define SKELETON_REACT_1 52
#define SKELETON_REACT_2 53
#define SKELETON_REACT_3 54
#define SKELETON_REACT_4 55
#define SKELETON_WALK_1 56
#define SKELETON_WALK_2 57
#define SKELETON_WALK_3 58
#define SKELETON_WALK_4 59
#define SKELETON_WALK_5 60
#define SKELETON_WALK_6 61
#define SKELETON_WALK_7 62
#define SKELETON_WALK_8 63
#define SKELETON_WALK_9 64
#define SKELETON_WALK_10 65
#define SKELETON_WALK_11 66
#define SKELETON_WALK_12 67
#define SKELETON_WALK_13 68
| 26.666667 | 29 | 0.854167 | Seng3694 |
a20f733ceab85e87e666cc6b0b24dc1a0d8aee7a | 3,274 | hpp | C++ | framework/frontend/parser/ll/ll_algorithm.hpp | aamshukov/frontend | 6be5fea43b7776691034f3b4f56d318d7cdf18f8 | [
"MIT"
] | 2 | 2018-12-21T17:08:55.000Z | 2018-12-21T17:08:57.000Z | framework/frontend/parser/ll/ll_algorithm.hpp | aamshukov/frontend | 6be5fea43b7776691034f3b4f56d318d7cdf18f8 | [
"MIT"
] | null | null | null | framework/frontend/parser/ll/ll_algorithm.hpp | aamshukov/frontend | 6be5fea43b7776691034f3b4f56d318d7cdf18f8 | [
"MIT"
] | null | null | null | //..............................
// UI Lab Inc. Arthur Amshukov .
//..............................
#ifndef __LL_ALGORITHM_H__
#define __LL_ALGORITHM_H__
#pragma once
BEGIN_NAMESPACE(frontend)
USINGNAMESPACE(core)
class ll_algorithm : private noncopyable
{
public:
using symbol_type = grammar::symbol_type;
using symbols_type = grammar::symbols_type;
using pool_type = grammar::pool_type;
using rule_type = grammar::rule_type;
using rules_type = grammar::rules_type;
using set_type = grammar::set_type;
using sets_type = grammar::sets_type;
public:
// strong-LL(k)
using strong_ll_table_row_type = std::vector<std::optional<rule_type>>;
using strong_ll_table_type = std::vector<strong_ll_table_row_type>;
// LL(k)
// http://www.fit.vutbr.cz/~ikocman/llkptg/
// %token a b c
// %% /* LL(2) */
// S : B a A a a
// | b A b a ;
// A : /*eps*/
// | b ;
// B : b ;
// Table T0(T(S,{ε})
// .................
//
// u production follow
// ---------------------------------------------
// b a S -> B a A a a B:{a a, a b}, A:{a a}
// b b S -> b A b a A:{b a}
//
using ll_tal_table_key_type = std::tuple<std::size_t, symbol_type, sets_type>; // T[A, L] and number of the table
using ll_tal_table_follow_type = std::vector<std::pair<symbol_type, sets_type>>;
struct ll_tal_table_row
{
using follow_type = ll_tal_table_follow_type; // for brevity
set_type lookahead; // u aka L, FIRSTk(α) (+)k L, { ba } or { bb }
rule_type production; // production, S -> B a A a a or S -> b A b a
follow_type follow; // local FOLLOWk sets, B:{a a, a b}, A:{a a} or A:{b a}
};
using ll_tal_table_row_type = ll_tal_table_row;
using ll_tal_table_type = std::pair<ll_tal_table_key_type, std::vector<ll_tal_table_row_type>>;
using ll_tal_tables_type = std::vector<ll_tal_table_type>;
using ll_table_entry_symbol_type = std::variant<symbol_type, ll_tal_table_type>;
using ll_table_entry_type = std::vector<ll_table_entry_symbol_type>;
using ll_table_row_type = std::vector<std::optional<ll_table_entry_type>>;
using ll_table_type = std::vector<ll_table_row_type>;
static void infix_operator(const sets_type& sets1, const sets_type& sets2, std::size_t k, sets_type& result);
static void infix_operator(const std::vector<sets_type>& sets, std::size_t k, sets_type& result);
public:
static bool is_strong_ll_grammar(const grammar& gr, uint8_t k);
static void build_strong_ll_table(const grammar& gr, uint8_t k, strong_ll_table_type& result);
static bool is_ll_grammar(const grammar& gr, uint8_t k);
static void build_ll_tal_tables(const grammar& gr, uint8_t k, ll_tal_tables_type& result);
static void build_ll_table(const grammar& gr, uint8_t k, ll_table_type& result);
};
END_NAMESPACE
#endif // __LL_ALGORITHM_H__
| 38.517647 | 122 | 0.580024 | aamshukov |
a20fc9ecd2dd2cd79c6fa3aecd87c583a6da3247 | 6,025 | hpp | C++ | include/pfp/parse.hpp | AaronHong1024/pfp-cst | 0390fce9915e789595f1fd699d7c5fd5ea61fd25 | [
"MIT"
] | 6 | 2020-06-23T11:46:27.000Z | 2021-06-01T09:59:01.000Z | include/pfp/parse.hpp | maxrossi91/pfp-data-structures | 6c5c1b801573d1c5116297e3cca20d1517c41e7b | [
"MIT"
] | null | null | null | include/pfp/parse.hpp | maxrossi91/pfp-data-structures | 6c5c1b801573d1c5116297e3cca20d1517c41e7b | [
"MIT"
] | 1 | 2021-11-25T05:30:53.000Z | 2021-11-25T05:30:53.000Z | /* pfp-parse - prefix free parsing parse
Copyright (C) 2020 Massimiliano Rossi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ .
*/
/*!
\file parse.hpp
\brief parse.hpp define and build the prefix-free parse data structure.
\author Massimiliano Rossi
\date 03/04/2020
*/
#ifndef _PFP_PARSE_HH
#define _PFP_PARSE_HH
#include <common.hpp>
#include <sdsl/rmq_support.hpp>
#include <sdsl/int_vector.hpp>
extern "C" {
#include<gsacak.h>
}
// TODO: Extend it to non-integer alphabets
class parse{
public:
std::vector<uint32_t> p;
std::vector<uint_t> saP;
std::vector<uint_t> isaP;
std::vector<int_t> lcpP;
sdsl::rmq_succinct_sct<> rmq_lcp_P;
// sdsl::bit_vector b_p; // Starting position of each phrase in D
// sdsl::bit_vector::rank_1_type rank_b_p;
// sdsl::bit_vector::select_1_type select_b_p;
bool saP_flag = false;
bool isaP_flag = false;
bool lcpP_flag = false;
bool rmq_lcp_P_flag = false;
size_t alphabet_size;
typedef size_t size_type;
// Default constructor for load
parse() {}
parse( std::vector<uint32_t>& p_,
size_t alphabet_size_,
bool saP_flag_ = true,
bool isaP_flag_ = true,
bool lcpP_flag_ = true,
bool rmq_lcp_P_flag_ = true ):
p(p_),
alphabet_size(alphabet_size_)
{
assert(p.back() == 0);
build(saP_flag_, isaP_flag_, lcpP_flag_, rmq_lcp_P_flag_);
}
parse( std::string filename,
size_t alphabet_size_,
bool saP_flag_ = true,
bool isaP_flag_ = true,
bool lcpP_flag_ = true,
bool rmq_lcp_P_flag_ = true ):
alphabet_size(alphabet_size_)
{
// Building dictionary from file
std::string tmp_filename = filename + std::string(".parse");
read_file(tmp_filename.c_str(), p);
p.push_back(0); // this is the terminator for the sacak algorithm
build(saP_flag_, isaP_flag_, lcpP_flag_, rmq_lcp_P_flag_);
}
void build(bool saP_flag_, bool isaP_flag_, bool lcpP_flag_, bool rmq_lcp_P_flag_){
// TODO: check if it has been already computed
if(saP_flag_){
saP.resize(p.size());
// suffix array of the parsing.
verbose("Computing SA of the parsing");
_elapsed_time(
sacak_int(&p[0],&saP[0],p.size(),alphabet_size);
);
}
assert(!isaP_flag_ || (saP_flag || saP_flag_) );
if(isaP_flag_ && !isaP_flag){
// inverse suffix array of the parsing.
verbose("Computing ISA of the parsing");
_elapsed_time(
{
isaP.resize(p.size());
for(int i = 0; i < saP.size(); ++i){
isaP[saP[i]] = i;
}
}
);
}
if(lcpP_flag_){
lcpP.resize(p.size());
// LCP array of the parsing.
verbose("Computing LCP of the parsing");
_elapsed_time(
LCP_array(&p[0], isaP, saP, p.size(), lcpP);
);
}
assert(!rmq_lcp_P_flag_ || (lcpP_flag || lcpP_flag_));
if(rmq_lcp_P_flag_ && ! rmq_lcp_P_flag){
rmq_lcp_P_flag = true;
verbose("Computing RMQ over LCP of the parsing");
// Compute the LCP rank of P
_elapsed_time(
rmq_lcp_P = sdsl::rmq_succinct_sct<>(&lcpP);
);
}
}
// Serialize to a stream.
size_type serialize(std::ostream &out, sdsl::structure_tree_node *v = nullptr, std::string name = "") const
{
sdsl::structure_tree_node *child = sdsl::structure_tree::add_child(v, name, sdsl::util::class_name(*this));
size_type written_bytes = 0;
written_bytes += my_serialize(p, out, child, "parse");
written_bytes += my_serialize(saP, out, child, "saP");
written_bytes += my_serialize(isaP, out, child, "isaP");
written_bytes += my_serialize(lcpP, out, child, "lcpP");
written_bytes += rmq_lcp_P.serialize(out, child, "rmq_lcp_P");
// written_bytes += b_p.serialize(out, child, "b_p");
// written_bytes += rank_b_p.serialize(out, child, "rank_b_p");
// written_bytes += select_b_p.serialize(out, child, "select_b_p");
written_bytes += sdsl::write_member(alphabet_size, out, child, "alphabet_size");
// written_bytes += sdsl::serialize(p, out, child, "parse");
// written_bytes += sdsl::serialize(saP, out, child, "saP");
// written_bytes += sdsl::serialize(isaP, out, child, "isaP");
// written_bytes += sdsl::serialize(lcpP, out, child, "lcpP");
// written_bytes += rmq_lcp_P.serialize(out, child, "rmq_lcp_P");
// // written_bytes += b_p.serialize(out, child, "b_p");
// // written_bytes += rank_b_p.serialize(out, child, "rank_b_p");
// // written_bytes += select_b_p.serialize(out, child, "select_b_p");
// written_bytes += sdsl::write_member(alphabet_size, out, child, "alphabet_size");
sdsl::structure_tree::add_size(child, written_bytes);
return written_bytes;
}
//! Load from a stream.
void load(std::istream &in)
{
my_load(p, in);
my_load(saP, in);
my_load(isaP, in);
my_load(lcpP, in);
rmq_lcp_P.load(in);
// b_p.load(in);
// rank_b_p.load(in);
// select_b_p.load(in);
sdsl::read_member(alphabet_size, in);
// sdsl::load(p, in);
// sdsl::load(saP, in);
// sdsl::load(isaP, in);
// sdsl::load(lcpP, in);
// rmq_lcp_P.load(in);
// // b_p.load(in);
// // rank_b_p.load(in);
// // select_b_p.load(in);
// sdsl::read_member(alphabet_size, in);
}
};
#endif /* end of include guard: _PFP_PARSE_HH */
| 30.897436 | 111 | 0.641494 | AaronHong1024 |
a2120217dc2454cf7dffc794c1f67bfdcdbb8d74 | 302 | hpp | C++ | CoreLib/exception.hpp | NuLL3rr0r/footpal-native-server | f28cad64c9e098cdeb63296c4733e0ad1a912139 | [
"Unlicense",
"MIT"
] | 1 | 2022-01-22T09:49:42.000Z | 2022-01-22T09:49:42.000Z | CoreLib/exception.hpp | NuLL3rr0r/footpal-native-server | f28cad64c9e098cdeb63296c4733e0ad1a912139 | [
"Unlicense",
"MIT"
] | null | null | null | CoreLib/exception.hpp | NuLL3rr0r/footpal-native-server | f28cad64c9e098cdeb63296c4733e0ad1a912139 | [
"Unlicense",
"MIT"
] | null | null | null | #ifndef CORELIB_EXCEPTION_HPP
#define CORELIB_EXCEPTION_HPP
#include <stdexcept>
#include <string>
namespace CoreLib {
class Exception;
}
class CoreLib::Exception : public std::runtime_error
{
public:
explicit Exception(const std::string &message);
};
#endif /* CORELIB_EXCEPTION_HPP */
| 14.380952 | 52 | 0.748344 | NuLL3rr0r |
b8c703dfa4b754cdadd071c944984223795bb4dd | 2,787 | hpp | C++ | include/asioext/socks/error.hpp | zweistein-frm2/asio-extensions | bafea77c48d674930405cb7f93bdfe65539abc39 | [
"BSL-1.0"
] | 17 | 2018-04-13T00:38:55.000Z | 2022-01-21T08:38:36.000Z | include/asioext/socks/error.hpp | zweistein-frm2/asio-extensions | bafea77c48d674930405cb7f93bdfe65539abc39 | [
"BSL-1.0"
] | 4 | 2017-03-16T03:34:38.000Z | 2020-05-08T00:05:51.000Z | include/asioext/socks/error.hpp | zweistein-frm2/asio-extensions | bafea77c48d674930405cb7f93bdfe65539abc39 | [
"BSL-1.0"
] | 5 | 2017-09-06T15:56:04.000Z | 2021-09-14T07:38:02.000Z | /// @file
/// Defines SOCKS error codes.
///
/// @copyright Copyright (c) 2018 Tim Niederhausen (tim@rnc-ag.de)
/// Distributed under the Boost Software License, Version 1.0.
/// (See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt)
#ifndef ASIOEXT_SOCKS_ERROR_HPP
#define ASIOEXT_SOCKS_ERROR_HPP
#include "asioext/detail/config.hpp"
#if ASIOEXT_HAS_PRAGMA_ONCE
# pragma once
#endif
#include "asioext/error_code.hpp"
ASIOEXT_NS_BEGIN
namespace socks {
/// @ingroup net_socks
/// @defgroup net_socks_error Error handling
/// @{
/// @brief SOCKS-specific error codes
enum class error
{
/// @brief No error.
none = 0,
/// @brief SOCKS version mismatch between server and client.
///
/// Used in case the client receives a packet with a different
// server major version.
invalid_version,
/// @brief Server supports none of our authentication methods.
///
/// Used in case the server rejects all of our proposed authentication
/// methods
///
/// @see async_greet
no_acceptable_auth_method,
/// @brief Authentication type version mismatch between client and server.
///
/// The version of the agreed-on authentication scheme is different on
/// the server.
invalid_auth_version,
/// @brief The server rejected our login attempt.
login_failed,
/// @brief The SOCKS @c command we sent was rejected.
///
/// The server doesn't understand the @c command we sent.
command_not_supported,
/// @brief The client's identd is not reachable from the server.
identd_not_reachable,
/// @brief A generic error occurred.
///
/// This value is used when the SOCKS server gives us no additional
/// information.
generic,
};
#if defined(ASIOEXT_ERRORCATEGORY_IN_HEADER)
class error_category_impl : public error_category
{
public:
#if defined(ASIOEXT_ERRORCATEGORY_CONSTEXPR_CTOR)
constexpr error_category_impl() = default;
#endif
ASIOEXT_DECL const char* name() const ASIOEXT_NOEXCEPT;
ASIOEXT_DECL std::string message(int value) const;
};
#endif
/// @brief Get the @c error_category for @c error
ASIOEXT_DECLARE_ERRORCATEGORY(error_category_impl, get_error_category)
inline error_code make_error_code(error e) ASIOEXT_NOEXCEPT
{
return error_code(static_cast<int>(e), get_error_category());
}
/// @}
}
ASIOEXT_NS_END
#if defined(ASIOEXT_USE_BOOST_ASIO)
namespace boost {
namespace system {
template <>
struct is_error_code_enum<asioext::socks::error>
{
static const bool value = true;
};
}
}
#else
namespace std {
template <>
struct is_error_code_enum<asioext::socks::error>
{
static const bool value = true;
};
}
#endif
#if defined(ASIOEXT_HEADER_ONLY) || defined(ASIOEXT_HAS_CONSTEXPR_ERRORCATEGORY)
# include "asioext/socks/impl/socks_error.cpp"
#endif
#endif
| 21.438462 | 80 | 0.736634 | zweistein-frm2 |
b8cb35dad706ff2045f5839502444072a4f5826a | 253 | cpp | C++ | Console Test Alpha/Node Chap.cpp | StoutGames/Afford | 73f016fa873c228f9aa320552749d39c245fdb15 | [
"MIT"
] | 1 | 2016-05-11T02:01:20.000Z | 2016-05-11T02:01:20.000Z | Console Test Alpha/Node Chap.cpp | StoutGames/Afford | 73f016fa873c228f9aa320552749d39c245fdb15 | [
"MIT"
] | null | null | null | Console Test Alpha/Node Chap.cpp | StoutGames/Afford | 73f016fa873c228f9aa320552749d39c245fdb15 | [
"MIT"
] | null | null | null | #include "Afford\Node.h"
#include "Afford Chap.h"
namespace Stout {
namespace TAlpha {
namespace Node {
class Chap : public Stout::Afford::Base::Node,
public Stout::TAlpha::Afford::Chap {
ST_AF_DECLARE_NODE(Chap)
};
}
}
} | 14.055556 | 48 | 0.636364 | StoutGames |
b8cf4d5dcda348618fe59d0be1faaa247dcbfb2f | 1,399 | cpp | C++ | src/Triangle.cpp | MickAlmighty/StudyOpenGL | aebebc9e89cca5a00569e7c5876045e36eed0c3b | [
"MIT"
] | null | null | null | src/Triangle.cpp | MickAlmighty/StudyOpenGL | aebebc9e89cca5a00569e7c5876045e36eed0c3b | [
"MIT"
] | null | null | null | src/Triangle.cpp | MickAlmighty/StudyOpenGL | aebebc9e89cca5a00569e7c5876045e36eed0c3b | [
"MIT"
] | null | null | null | #include "Triangle.h"
#include <iostream>
Triangle::Triangle(std::vector<Vertex> vector3): vec3(vector3)
{
mids = std::vector<Vertex>();
calculateMids();
}
Triangle::Triangle()
{
}
Triangle::Triangle(float vertices[])
{
this->vec3 = std::vector<Vertex>();
this->mids = std::vector<Vertex>();
for(int i = 0; i < 9; i += 3)
{
float x = 0;
float y = 0;
float z = 0;
for(int j = 0; j < 3; j++)
{
if( (i + j) % 3 == 0)
{
x = vertices[i + j];
}
if ((i + j) % 3 == 1)
{
y = vertices[i + j];
}
if ((i + j) % 3 == 2)
{
z = vertices[i + j];
}
}
//std::cout <<"Wyswietl: "<< x << " " << y << " " << z << std::endl;
//std::shared_ptr<Vertex> shared_ptr(new Vertex(x, y, z));
vec3.push_back(Vertex(x,y,z));
}
calculateMids();
}
Triangle::~Triangle() { }
void Triangle::calculateMids()
{
for(unsigned int i = 0; i < (vec3.size() - 1); i++)
{
for (unsigned int j = 1; j < vec3.size(); j++)
{
if(vec3.at(i) != vec3.at(j))
{
mids.push_back(createMidVertex(vec3.at(i), vec3.at(j)));
}
}
}
}
Vertex Triangle::createMidVertex(Vertex &x1, Vertex &x2)
{
float a1 = (x1.getX() + x2.getX()) / 2;
float y1 = (x1.getY() + x2.getY()) / 2;
float z1 = (x1.getZ() + x2.getZ()) / 2;
return Vertex(a1, y1, z1);
}
std::vector<Vertex> Triangle::getVec3()
{
return vec3;
}
std::vector<Vertex> Triangle::getMids()
{
return mids;
}
| 17.4875 | 70 | 0.538956 | MickAlmighty |
b8e0aed1db1e71752196e93dd51589ea878dd6d3 | 4,206 | cpp | C++ | Sail/src/API/DX12/resources/DescriptorHeap.cpp | BTH-StoraSpel-DXR/SPLASH | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 12 | 2019-09-11T15:52:31.000Z | 2021-11-14T20:33:35.000Z | Sail/src/API/DX12/resources/DescriptorHeap.cpp | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 227 | 2019-09-11T08:40:24.000Z | 2020-06-26T14:12:07.000Z | Sail/src/API/DX12/resources/DescriptorHeap.cpp | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 2 | 2020-10-26T02:35:18.000Z | 2020-10-26T02:36:01.000Z | #include "pch.h"
#include "DescriptorHeap.h"
#include "Sail/Application.h"
DescriptorHeap::DescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE type, unsigned int numDescriptors, bool shaderVisible, bool frameDependant)
: m_numDescriptors(numDescriptors)
, m_index(0)
, m_frameDependant(frameDependant)
{
m_context = Application::getInstance()->getAPI<DX12API>();
D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
heapDesc.NumDescriptors = numDescriptors;
heapDesc.Flags = (type != D3D12_DESCRIPTOR_HEAP_TYPE_RTV && type != D3D12_DESCRIPTOR_HEAP_TYPE_DSV && shaderVisible) ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
heapDesc.Type = type;
ThrowIfFailed(m_context->getDevice()->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&m_descHeap)));
m_incrementSize = m_context->getDevice()->GetDescriptorHandleIncrementSize(type);
// Store start positions that will be used for the second swap buffer if frameDependant is set to true
if (frameDependant) {
m_secondHalfCPUHandleStart = m_descHeap->GetCPUDescriptorHandleForHeapStart();
m_secondHalfCPUHandleStart.ptr += m_incrementSize * numDescriptors / 2;
m_secondHalfGPUHandleStart = m_descHeap->GetGPUDescriptorHandleForHeapStart();
m_secondHalfGPUHandleStart.ptr += m_incrementSize * numDescriptors / 2;
// Set num descriptors available for each swap buffer
m_numDescriptors /= 2;
}
}
DescriptorHeap::~DescriptorHeap() {
}
ID3D12DescriptorHeap* DescriptorHeap::get() const {
return m_descHeap.Get();
}
D3D12_CPU_DESCRIPTOR_HANDLE DescriptorHeap::getNextCPUDescriptorHandle(int nSteps) {
return getCPUDescriptorHandleForIndex(getAndStepIndex(nSteps));
}
D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::getNextGPUDescriptorHandle() {
return getGPUDescriptorHandleForIndex(getAndStepIndex());
}
D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::getCurentGPUDescriptorHandle() const {
return getGPUDescriptorHandleForIndex(m_index);
}
D3D12_CPU_DESCRIPTOR_HANDLE DescriptorHeap::getCurentCPUDescriptorHandle() const {
return getCPUDescriptorHandleForIndex(m_index);
}
unsigned int DescriptorHeap::getDescriptorIncrementSize() const {
return m_incrementSize;
}
void DescriptorHeap::setIndex(unsigned int index) {
if (index >= m_numDescriptors) {
SAIL_LOG_ERROR("Tried to set descriptor heap index to a value larger than max (" + std::to_string(m_numDescriptors) + ")!");
}
m_index = index;
}
void DescriptorHeap::bind(ID3D12GraphicsCommandList4* cmdList) const {
ID3D12DescriptorHeap* descriptorHeaps[] = { m_descHeap.Get() };
cmdList->SetDescriptorHeaps(ARRAYSIZE(descriptorHeaps), descriptorHeaps);
}
unsigned int DescriptorHeap::getAndStepIndex(int nSteps) {
std::lock_guard<std::mutex> lock(m_getAndStepIndex_mutex);
unsigned int i = m_index;
m_index = (m_index + nSteps) % m_numDescriptors;
// The index should never loop by this method since this means that it has looped mid-frame and will cause the GPU to read out of bounds
if (m_index < i) {
SAIL_LOG_ERROR("Descriptor heap index has looped mid-frame - this may cause missing textures or GPU crashes! This can be caused by having too many textured objects being rendered simulateously. In that case, consider reducing the amount of textured objects or increase the descriptor heap size (which is currently " + std::to_string(m_numDescriptors) + ")");
}
return i;
}
D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::getGPUDescriptorHandleForIndex(unsigned int index) const {
if (index >= m_numDescriptors) {
SAIL_LOG_ERROR("Tried to get out of bounds descriptor heap gpu handle!");
}
auto heapHandle = (m_frameDependant && m_context->getSwapIndex() == 1) ? m_secondHalfGPUHandleStart : m_descHeap->GetGPUDescriptorHandleForHeapStart();
heapHandle.ptr += index * m_incrementSize;
return heapHandle;
}
D3D12_CPU_DESCRIPTOR_HANDLE DescriptorHeap::getCPUDescriptorHandleForIndex(unsigned int index) const {
if (index >= m_numDescriptors) {
SAIL_LOG_ERROR("Tried to get out of bounds descriptor heap cpu handle!");
}
auto heapHandle = (m_frameDependant && m_context->getSwapIndex() == 1) ? m_secondHalfCPUHandleStart : m_descHeap->GetCPUDescriptorHandleForHeapStart();
heapHandle.ptr += index * m_incrementSize;
return heapHandle;
}
| 41.643564 | 360 | 0.795768 | BTH-StoraSpel-DXR |
b8e1b4dbfa69461a54aeba01cc4c641953e96d1c | 6,121 | hpp | C++ | src/graphics/effects/FXAA.hpp | Sam-Belliveau/MKS66-Graphics-Library | 4ccf04f977a15007e32bdb5a238704eaaff0c895 | [
"MIT"
] | null | null | null | src/graphics/effects/FXAA.hpp | Sam-Belliveau/MKS66-Graphics-Library | 4ccf04f977a15007e32bdb5a238704eaaff0c895 | [
"MIT"
] | null | null | null | src/graphics/effects/FXAA.hpp | Sam-Belliveau/MKS66-Graphics-Library | 4ccf04f977a15007e32bdb5a238704eaaff0c895 | [
"MIT"
] | null | null | null | #pragma once
/**
* Copyright (c) 2022 Sam Belliveau
*
* 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.
*/
#include <cmath>
#include "../math/Math.hpp"
#include "../math/Vector2D.hpp"
#include "../Image.hpp"
namespace SPGL
{
namespace FXAA
{
constexpr Float EDGE_THRESHOLD_MIN = 0.0312;
constexpr Float EDGE_THRESHOLD_MAX = 0.125;
constexpr Float SUBPIXEL_QUALITY = 0.75;
constexpr int ITERATIONS = 48;
Color get_pixel(const Image& image, const Vec2i& pos)
{
const Float lumaC = image(pos).luma();
const Float lumaU = image(pos + Vec2i(+0,+1)).luma();
const Float lumaD = image(pos + Vec2i(+0,-1)).luma();
const Float lumaL = image(pos + Vec2i(-1,+0)).luma();
const Float lumaR = image(pos + Vec2i(+1,+0)).luma();
const Float luma_max = std::max({lumaC, lumaU, lumaD, lumaL, lumaR});
const Float luma_min = std::min({lumaC, lumaU, lumaD, lumaL, lumaR});
const Float luma_range = luma_max - luma_min;
if (luma_range < std::max(EDGE_THRESHOLD_MIN, luma_max * EDGE_THRESHOLD_MAX))
{ return image(pos); }
const Float lumaUR = image(pos + Vec2i(+1,+1)).luma();
const Float lumaUL = image(pos + Vec2i(-1,+1)).luma();
const Float lumaDR = image(pos + Vec2i(+1,-1)).luma();
const Float lumaDL = image(pos + Vec2i(-1,-1)).luma();
const Float lumaDU = lumaD + lumaU;
const Float lumaLR = lumaL + lumaR;
const Float lumaUC = lumaUL + lumaUR;
const Float lumaDC = lumaDL + lumaDR;
const Float lumaLC = lumaDL + lumaUL;
const Float lumaRC = lumaDR + lumaUR;
const Float edge_horizontal =
1.0 * std::abs(lumaLC - 2.0 * lumaL) +
2.0 * std::abs(lumaDU - 2.0 * lumaC) +
1.0 * std::abs(lumaRC - 2.0 * lumaR);
const Float edge_vertical =
1.0 * std::abs(lumaUC - 2.0 * lumaU) +
2.0 * std::abs(lumaLR - 2.0 * lumaC) +
1.0 * std::abs(lumaDC - 2.0 * lumaD);
const bool horizontal = edge_horizontal >= edge_vertical;
const Float luma1 = horizontal ? lumaD : lumaL;
const Float luma2 = horizontal ? lumaU : lumaR;
const Float gradient1 = luma1 - lumaC;
const Float gradient2 = luma2 - lumaC;
const bool steepest = std::abs(gradient1) > std::abs(gradient2);
const Float gradient = 0.25 * std::max(std::abs(gradient1), std::abs(gradient2));
const Float step_length = steepest ? -1.0 : 1.0;
const Float luma_avg = 0.5 * ((steepest ? luma1 : luma2) + lumaC);
Vec2d current_pos = pos;
if(horizontal) current_pos.y += step_length * 0.5;
else current_pos.x += step_length * 0.5;
const Vec2d offset = horizontal
? Vec2d(1.0, 0.0)
: Vec2d(0.0, 1.0);
Vec2d pos1 = current_pos - offset;
Vec2d pos2 = current_pos + offset;
bool reached1 = false;
bool reached2 = false;
bool reached_both = false;
Float lumaE1 = 0.0, lumaE2 = 0.0;
for(int i = 0; i < ITERATIONS; ++i)
{
if(!reached1) lumaE1 = image.interpolate(pos1).luma() - luma_avg;
if(!reached2) lumaE2 = image.interpolate(pos2).luma() - luma_avg;
reached1 = std::abs(lumaE1) >= gradient;
reached2 = std::abs(lumaE2) >= gradient;
reached_both = reached1 && reached2;
if(!reached1) pos1 -= offset;
if(!reached2) pos2 += offset;
if(reached_both) break;
}
const Float luma_final_avg = (1.0 / 12.0) * (2.0 * (lumaDU + lumaLR) + lumaLC + lumaRC);
const Float subpixel_offset1 = Math::limit(std::abs(luma_final_avg - lumaC) / luma_range);
const Float subpixel_offset2 = (-2.0 * subpixel_offset1 + 3.0) * subpixel_offset1 * subpixel_offset1;
const Float subpixel_offset = subpixel_offset2 * subpixel_offset2 * SUBPIXEL_QUALITY;
const Float distance1 = horizontal ? (pos.x - pos1.x) : (pos.y - pos1.y);
const Float distance2 = horizontal ? (pos2.x - pos.x) : (pos2.y - pos.y);
const bool direction = distance1 < distance2;
const Float distance = std::min(distance1, distance2);
const Float edge_thickness = distance1 + distance2;
const Float pixel_offset = -distance / edge_thickness + 0.5;
const bool correct_variation = ((direction ? lumaE1 : lumaE2) < 0.0) != (lumaC < luma_avg);
const Float final_offset = std::max(correct_variation ? pixel_offset : 0.0, subpixel_offset);
Vec2d final_pos = pos;
if(horizontal) final_pos.y += final_offset * step_length;
else final_pos.x += final_offset * step_length;
return image.interpolate(final_pos);
}
Image apply(const Image& image)
{
Image result(image);
for(int x = 0; x < image.width(); ++x)
for(int y = 0; y < image.height(); ++y)
{
Vec2i pos(x, y);
result(pos) = get_pixel(image, pos);
}
return result;
}
}
} | 37.323171 | 113 | 0.556935 | Sam-Belliveau |
b8ea187a70b3a4fbc2365e1cba954ae14def70bf | 2,908 | hxx | C++ | main/DelayRebootHelper.hxx | atanisoft/esp32olcbhub | 81dcf84c65fd28fd2ad86c3cf2ade7ef3f4ce0a4 | [
"BSD-2-Clause"
] | 2 | 2020-11-06T18:46:32.000Z | 2021-04-09T18:30:01.000Z | main/DelayRebootHelper.hxx | atanisoft/esp32olcbhub | 81dcf84c65fd28fd2ad86c3cf2ade7ef3f4ce0a4 | [
"BSD-2-Clause"
] | 29 | 2020-11-06T18:46:03.000Z | 2021-05-30T12:53:58.000Z | main/DelayRebootHelper.hxx | atanisoft/esp32olcbhub | 81dcf84c65fd28fd2ad86c3cf2ade7ef3f4ce0a4 | [
"BSD-2-Clause"
] | null | null | null | /** \copyright
* Copyright (c) 2020, Mike Dunston
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file DelayReboot.hxx
*
* Implementation of a countdown to reboot
*
* @author Mike Dunston
* @date 14 July 2020
*/
#ifndef DELAY_REBOOT_HXX_
#define DELAY_REBOOT_HXX_
#include <executor/Service.hxx>
#include <executor/StateFlow.hxx>
#include <utils/logging.h>
#include <utils/Singleton.hxx>
extern "C" void reboot();
namespace esp32olcbhub
{
/// Utility class that will reboot the node after a pre-defined time has
/// elapsed.
class DelayRebootHelper : public StateFlowBase
, public Singleton<DelayRebootHelper>
{
public:
/// Constructor.
///
/// @param service is the @ref Service that will execute this flow.
DelayRebootHelper(Service *service) : StateFlowBase(service)
{
}
/// Starts the countdown timer.
void start()
{
start_flow(STATE(delay));
}
private:
StateFlowTimer timer_{this};
const uint16_t DELAY_INTERVAL_MSEC{250};
const uint64_t DELAY_INTERVAL_NSEC{
(uint64_t)MSEC_TO_NSEC(DELAY_INTERVAL_MSEC)};
uint16_t delayCountdown_{2000};
/// Counts down the time until reboot should occur.
Action delay()
{
delayCountdown_ -= DELAY_INTERVAL_MSEC;
if (delayCountdown_)
{
LOG(WARNING
, "[Reboot] %u ms remaining until reboot", delayCountdown_);
return sleep_and_call(&timer_, DELAY_INTERVAL_NSEC, STATE(delay));
}
reboot();
return exit();
}
};
} // namespace esp32olcbhub
#endif // DELAY_REBOOT_HXX_ | 31.956044 | 79 | 0.709422 | atanisoft |
b8ea85780745b7feb45657a4dc6d929fac6744e7 | 426 | hpp | C++ | cho/inc/cho/generated/riot_api_platform.hpp | Querijn/ChoPlusPlus | 9ff68c7ae6594ca9bdb6928489c7ac01b15d0aee | [
"MIT"
] | 2 | 2017-05-22T10:45:27.000Z | 2020-06-15T13:49:50.000Z | cho/inc/cho/generated/riot_api_platform.hpp | Querijn/ChoPlusPlus | 9ff68c7ae6594ca9bdb6928489c7ac01b15d0aee | [
"MIT"
] | 5 | 2017-05-23T06:35:24.000Z | 2019-02-02T11:47:06.000Z | cho/inc/cho/generated/riot_api_platform.hpp | Querijn/ChoPlusPlus | 9ff68c7ae6594ca9bdb6928489c7ac01b15d0aee | [
"MIT"
] | null | null | null | #pragma once
// This file is automatically generated!
// To edit this, edit template/platform_header.mst and run cho_generator.
namespace cho
{
enum class platform_id
{
br1 = 0,
eun1 = 1,
euw1 = 2,
jp1 = 3,
kr = 4,
la1 = 5,
la2 = 6,
na1 = 7,
oc1 = 8,
tr1 = 9,
ru = 10,
pbe1 = 11,
americas = 12,
europe = 13,
asia = 14,
};
platform_id get_platform_by_string(const char* a_platform_string);
} | 15.777778 | 73 | 0.626761 | Querijn |
b8ed1379e1795e54597a71b4c4623421ca77fc2d | 403 | cpp | C++ | src/simple/client.cpp | AndreyMokryj/unix-ipc-lab | 6a11b71b3215f9e7d8d3a9f192ab202c1882864f | [
"MIT"
] | 1 | 2020-11-20T19:42:43.000Z | 2020-11-20T19:42:43.000Z | src/simple/client.cpp | Nlioxa/unix-ipc-lab | 1f052aadf933fe39bf7a80414b0e35c49ac7c140 | [
"MIT"
] | null | null | null | src/simple/client.cpp | Nlioxa/unix-ipc-lab | 1f052aadf933fe39bf7a80414b0e35c49ac7c140 | [
"MIT"
] | null | null | null | #include "../message.hpp"
#include "../channel.hpp"
int main()
{
auto channel = ipc::Channel::Client(8000);
{
auto msg = data::Message();
channel.Read((char *)&msg, sizeof(msg));
std::cout << "server: " << msg << '\n';
}
{
auto msg = data::Message::Notice("Hi, All!");
channel.Write((char *)&msg, sizeof(msg));
}
return EXIT_SUCCESS;
} | 20.15 | 53 | 0.51861 | AndreyMokryj |
b8ed1454ccc8e9d69e2a70774a9d41871f1d28dd | 1,754 | hh | C++ | dune/xt/la/solver/istl/preconditioners.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 2 | 2020-02-08T04:08:52.000Z | 2020-08-01T18:54:14.000Z | dune/xt/la/solver/istl/preconditioners.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 35 | 2019-08-19T12:06:35.000Z | 2020-03-27T08:20:39.000Z | dune/xt/la/solver/istl/preconditioners.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:34.000Z | 2020-02-08T04:09:34.000Z | // This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2019)
// René Fritze (2019)
// Tobias Leibner (2019 - 2020)
#ifndef DUNE_XT_LA_SOLVER_ISTL_PRECONDITIONERS_HH
#define DUNE_XT_LA_SOLVER_ISTL_PRECONDITIONERS_HH
#include <type_traits>
#include <cmath>
#include <dune/istl/preconditioners.hh>
namespace Dune::XT::LA {
template <class O>
class IdentityPreconditioner : public Dune::Preconditioner<typename O::domain_type, typename O::range_type>
{
public:
//! \brief The domain type of the preconditioner.
using domain_type = typename O::domain_type;
//! \brief The range type of the preconditioner.
using range_type = typename O::range_type;
//! \brief The field type of the preconditioner.
using field_type = typename range_type::field_type;
using InverseOperator = O;
IdentityPreconditioner(const SolverCategory::Category cat)
: category_(cat)
{}
//! Category of the preconditioner (see SolverCategory::Category)
SolverCategory::Category category() const final
{
return category_;
}
void pre(domain_type&, range_type&) final {}
void apply(domain_type& v, const range_type& d) final
{
v = d;
}
void post(domain_type&) final {}
private:
SolverCategory::Category category_;
};
} // namespace Dune::XT::LA
#endif // DUNE_XT_LA_SOLVER_ISTL_PRECONDITIONERS_HH
| 28.290323 | 107 | 0.729761 | dune-community |
b8f0b20d21c6af78b09716b18b0fdc53cde18d26 | 1,056 | cpp | C++ | shared/memory/object_hook.cpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | shared/memory/object_hook.cpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | shared/memory/object_hook.cpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | #include "shared/memory/object_hook.hpp"
namespace shared::memory
{
ObjectHook::ObjectHook( void* procedure, void* replace )
{
if( !Create( procedure, replace ) )
{
// throw exception
}
}
ObjectHook::~ObjectHook()
{
Destroy();
}
bool ObjectHook::Create( void* procedure, void* replace )
{
m_procedure = reinterpret_cast< std::uint8_t* >( procedure );
if( !m_procedure )
return false;
m_replace = replace;
if( !m_replace )
return false;
m_restore = new std::uint8_t[ 7 ];
memcpy( m_restore, m_procedure, 7 );
VirtualProtect( m_procedure, 16, PAGE_EXECUTE_READWRITE, &m_protect );
Replace();
return true;
}
void ObjectHook::Destroy()
{
Restore();
}
void ObjectHook::Replace()
{
if( !m_procedure )
return;
*reinterpret_cast<std::uint16_t*>( m_procedure ) = 0x50B8;
*reinterpret_cast<void**>( m_procedure + 1 ) = m_replace;
*reinterpret_cast<std::uint16_t*>( m_procedure + 5 ) = 0xE0FF;
}
void ObjectHook::Restore()
{
if( !m_procedure )
return;
if( !m_restore )
return;
memcpy( m_procedure, m_restore, 7 );
}
} | 16 | 71 | 0.683712 | jrnh |
b8f2f9f8e7d01089771601f40f0d32177ba7b6b6 | 7,492 | cpp | C++ | sdk/src/pixie/error.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 2 | 2021-04-14T13:58:50.000Z | 2021-08-09T19:42:25.000Z | sdk/src/pixie/error.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 1 | 2021-08-31T10:32:07.000Z | 2021-09-03T15:03:00.000Z | sdk/src/pixie/error.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 1 | 2022-03-25T12:32:52.000Z | 2022-03-25T12:32:52.000Z | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright 2021 XIA LLC, 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.
*/
/** @file error.cpp
* @brief Implements custom error codes used throughout the SDK.
*/
#include <iomanip>
#include <iostream>
#include <map>
#include <pixie/error.hpp>
#include <pixie/log.hpp>
#include <pixie/util.hpp>
namespace xia {
namespace pixie {
namespace error {
struct result_code {
const int result;
const char* text;
result_code() : result(99), text("error code not set") {}
result_code(const int result_, const char* text_) : result(result_), text(text_) {}
};
static const std::map<code, result_code> result_codes = {
{code::success, {0, "success"}},
/*
* Crate
*/
{code::crate_already_open, {100, "crate already open"}},
{code::crate_not_ready, {101, "crate not ready"}},
{code::crate_invalid_param, {102, "invalid system parameter"}},
/*
* Module
*/
{code::module_number_invalid, {200, "invalid module number"}},
{code::module_total_invalid, {201, "invalid module count"}},
{code::module_already_open, {202, "module already open"}},
{code::module_close_failure, {203, "module failed to close"}},
{code::module_offline, {204, "module offline"}},
{code::module_info_failure, {205, "module information failure"}},
{code::module_invalid_operation, {206, "invalid module operation"}},
{code::module_invalid_firmware, {207, "invalid module firmware"}},
{code::module_initialize_failure, {208, "module initialization failure"}},
{code::module_invalid_param, {209, "invalid module parameter"}},
{code::module_invalid_var, {210, "invalid module variable"}},
{code::module_param_disabled, {211, "module parameter disabled"}},
{code::module_param_readonly, {212, "module parameter is readonly"}},
{code::module_param_writeonly, {213, "module parameter is writeonly"}},
{code::module_task_timeout, {214, "module task timeout"}},
{code::module_invalid_slot, {215, "invalid module slot number"}},
{code::module_not_found, {216, "module not found"}},
{code::module_test_invalid, {217, "module test invalid"}},
/*
* Channel
*/
{code::channel_number_invalid, {300, "invalid channel number"}},
{code::channel_invalid_param, {301, "invalid channel parameter"}},
{code::channel_invalid_var, {302, "invalid channel variable"}},
{code::channel_invalid_index, {303, "invalid channel variable"}},
{code::channel_param_disabled, {304, "invalid channel index"}},
{code::channel_param_readonly, {305, "channel parameter is readonly"}},
{code::channel_param_writeonly, {306, "channel parameter is writeonly"}},
/*
* Device
*/
{code::device_load_failure, {500, "device failed to load"}},
{code::device_boot_failure, {501, "device failed to boot"}},
{code::device_initialize_failure, {502, "device failed to initialize"}},
{code::device_copy_failure, {503, "device variable copy failed"}},
{code::device_image_failure, {504, "device image failure"}},
{code::device_hw_failure, {505, "device hardware failure"}},
{code::device_dma_failure, {506, "device dma failure"}},
{code::device_dma_busy, {507, "device dma busy"}},
{code::device_fifo_failure, {508, "device fifo failure"}},
{code::device_eeprom_failure, {509, "device eeprom failure"}},
{code::device_eeprom_bad_type, {510, "device eeprom bad type"}},
{code::device_eeprom_not_found, {511, "device eeprom tag not found"}},
/*
* Configuration
*/
{code::config_invalid_param, {600, "invalid config parameter"}},
{code::config_param_not_found, {601, "config parameter not found"}},
{code::config_json_error, {602, "config json error"}},
/*
* File handling
*/
{code::file_not_found, {700, "file not found"}},
{code::file_open_failure, {701, "file open failure"}},
{code::file_read_failure, {702, "file read failure"}},
{code::file_size_invalid, {703, "invalid file size"}},
{code::file_create_failure, {704, "file create failure"}},
/*
* System
*/
{code::no_memory, {800, "no memory"}},
{code::slot_map_invalid, {801, "invalid slot map"}},
{code::invalid_value, {802, "invalid number"}},
{code::not_supported, {803, "not supported"}},
{code::buffer_pool_empty, {804, "buffer pool empty"}},
{code::buffer_pool_not_empty, {805, "buffer pool not empty"}},
{code::buffer_pool_busy, {806, "buffer pool bust"}},
{code::buffer_pool_not_enough, {807, "buffer pool not enough"}},
/*
* Catch all
*/
{code::unknown_error, {900, "unknown error"}},
{code::internal_failure, {901, "internal failure"}},
{code::bad_allocation, {902, "bad allocation"}},
{code::bad_error_code, {990, "bad error code"}},
};
bool check_code_match() {
return result_codes.size() == size_t(code::last);
}
error::error(const code type_, const std::ostringstream& what)
: runtime_error(what.str()), type(type_) {
log(log::error) << "error(except): " << what.str();
}
error::error(const code type_, const std::string& what) : runtime_error(what), type(type_) {
log(log::error) << "error(except): " << what;
}
error::error(const code type_, const char* what) : runtime_error(what), type(type_) {
log(log::error) << "error(except): " << what;
}
void error::output(std::ostream& out) {
util::ostream_guard flags(out);
out << std::setfill(' ') << "error: code:" << std::setw(3) << result() << " : " << what();
}
int error::result() const {
return api_result(type);
}
std::string error::result_text() const {
return api_result_text(type);
}
int error::return_code() const {
return 0 - result();
}
int api_result(enum code type) {
auto search = result_codes.find(type);
int result;
if (search == result_codes.end()) {
result = result_codes.at(code::bad_error_code).result;
} else {
result = search->second.result;
}
return result;
}
std::string api_result_text(enum code type) {
auto search = result_codes.find(type);
std::string text;
if (search == result_codes.end()) {
text = result_codes.at(code::bad_error_code).text;
} else {
text = search->second.text;
}
return text;
}
int return_code(int result) {
return 0 - result;
}
int api_result_bad_alloc_error() {
return api_result(code::bad_allocation);
}
int api_result_unknown_error() {
return api_result(code::unknown_error);
}
int api_result_not_supported() {
return api_result(code::not_supported);
}
} // namespace error
} // namespace pixie
} // namespace xia
std::ostringstream& operator<<(std::ostringstream& out, xia::pixie::error::error& error) {
out << "result=" << error.result() << ", " << error.what();
return out;
}
std::ostream& operator<<(std::ostream& out, xia::pixie::error::error& error) {
error.output(out);
return out;
}
| 34.846512 | 94 | 0.66204 | xiallc |
b8f4da58cdcea145f36de4a07347a2722cec931e | 4,927 | cpp | C++ | src/nexmark_hot_items_ws/BidFilter.cpp | DonTassettitos/AIR | 92c93f05d6f15095d403dcbbe7ebe16563198697 | [
"BSD-3-Clause"
] | null | null | null | src/nexmark_hot_items_ws/BidFilter.cpp | DonTassettitos/AIR | 92c93f05d6f15095d403dcbbe7ebe16563198697 | [
"BSD-3-Clause"
] | null | null | null | src/nexmark_hot_items_ws/BidFilter.cpp | DonTassettitos/AIR | 92c93f05d6f15095d403dcbbe7ebe16563198697 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2020 University of Luxembourg. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF LUXEMBOURG 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 UNIVERSITY OF LUXEMBOURG 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.
**/
/*
* BidFilter.cpp
*
* Created on: April 16, 2020
* Author: damien.tassetti
*/
#include "BidFilter.hpp"
#include "../nexmark_gen/PODTypes.hpp"
#include "../serialization/Serialization.hpp"
#include <string.h>
#include <mpi.h>
using nexmark_hot_items_ws::BidFilter;
using nexmark_gen::Bid;
using nexmark_gen::Event;
using nexmark_gen::EventType;
BidFilter::BidFilter(int tag, int rank, int worldSize) :
Vertex(tag, rank, worldSize) {
}
BidFilter::~BidFilter() {
}
void BidFilter::batchProcess() {
}
void BidFilter::streamProcess(int channel) {
Message* inMessage;
list<Message*>* tmpMessages = new list<Message*>();
while (ALIVE) {
pthread_mutex_lock(&listenerMutexes[channel]);
while (inMessages[channel].empty())
pthread_cond_wait(&listenerCondVars[channel],
&listenerMutexes[channel]);
while (!inMessages[channel].empty()) {
inMessage = inMessages[channel].front();
inMessages[channel].pop_front();
tmpMessages->push_back(inMessage);
}
pthread_mutex_unlock(&listenerMutexes[channel]);
while (!tmpMessages->empty()) {
inMessage = tmpMessages->front();
tmpMessages->pop_front();
int message_id = Serialization::unwrap<int>(inMessage);
Message* outMessage;
vector<Bid> bids = filterBids(inMessage);
getNextMessage(outMessage, bids);
Serialization::wrap<int>(message_id, outMessage); // id doesn't change
send(outMessage);
delete inMessage; // delete message from incoming queue
}
tmpMessages->clear();
}
delete tmpMessages;
}
Message* BidFilter::initMessage(size_t capacity) {
return new Message(capacity);
}
void BidFilter::getNextMessage(Message*& outMessage, vector<Bid> & bids) {
outMessage = initMessage(sizeof(Bid) * bids.size() + sizeof(int));
for(size_t i = 0; i < bids.size(); i++){
Serialization::wrap<Bid>(bids[i], outMessage);
}
}
// we wish to modify where outMessage points to, but just read inMessage
vector<Bid> BidFilter::filterBids(Message*const inMessage){
// do not delete the input message here
unsigned int nof_events = inMessage->size / sizeof(Event);
vector<Bid> bids;
for(size_t i = 0; i < nof_events ; i++){
const Event& e = Serialization::read_front<Event>(inMessage, sizeof(Event) * i);
switch (e.event_type)
{
case EventType::BidType:
bids.push_back(e.bid);
break;
default:
// do nothing, try the next event
break;
}
}
return bids;
}
// we just pass the address of the message we wish to send, no modification intended
void BidFilter::send(Message*const message){
for (size_t operatorIndex = 0; operatorIndex < next.size(); operatorIndex++) {
// messages are not sent to another dataflow (no sharding)
int idx = operatorIndex * worldSize + rank;
pthread_mutex_lock(&senderMutexes[idx]);
outMessages[idx].push_back(message);
pthread_cond_signal(&senderCondVars[idx]);
pthread_mutex_unlock(&senderMutexes[idx]);
}
}
| 32.846667 | 96 | 0.669373 | DonTassettitos |
7700edddfcf6f467fd7181d3a8c7e5cb6628a2ed | 9,639 | cpp | C++ | src/coherence/net/internal/ScopedReferenceStore.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/net/internal/ScopedReferenceStore.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/net/internal/ScopedReferenceStore.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "private/coherence/net/internal/ScopedReferenceStore.hpp"
#include "coherence/net/CacheService.hpp"
#include "coherence/net/ServiceInfo.hpp"
#include "coherence/security/auth/Subject.hpp"
#include "coherence/util/Collections.hpp"
#include "coherence/util/HashSet.hpp"
#include "coherence/util/Iterator.hpp"
#include "coherence/util/SafeHashMap.hpp"
#include "coherence/util/Set.hpp"
#include "private/coherence/security/SecurityHelper.hpp"
COH_OPEN_NAMESPACE3(coherence,net,internal)
using coherence::net::CacheService;
using coherence::net::ServiceInfo;
using coherence::security::auth::Subject;
using coherence::security::SecurityHelper;
using coherence::util::Collections;
using coherence::util::HashSet;
using coherence::util::Iterator;
using coherence::util::SafeHashMap;
using coherence::util::Set;
// ----- constructors -------------------------------------------------------
ScopedReferenceStore::ScopedReferenceStore(OperationalContext::View vContext)
: f_hMapByName(self(), SafeHashMap::create()),
f_vContext(self(), vContext)
{
}
// ----- ScopedReferenceStore methods ---------------------------------------
void ScopedReferenceStore::clear()
{
f_hMapByName->clear();
}
NamedCache::Handle
ScopedReferenceStore::getCache(String::View vsCacheName) const
{
Object::Holder ohHolder = f_hMapByName->get(vsCacheName);
if (ohHolder == NULL || instanceof<NamedCache::Handle>(ohHolder))
{
return cast<NamedCache::Handle>(ohHolder);
}
else if (instanceof<SubjectScopedReference::Handle>(ohHolder))
{
SubjectScopedReference::Handle hScopedRef =
cast<SubjectScopedReference::Handle>(ohHolder);
return cast<NamedCache::Handle>(hScopedRef->get());
}
else
{
COH_THROW (UnsupportedOperationException::create("invalid type"));
}
}
Service::Handle
ScopedReferenceStore::getService(String::View vsServiceName) const
{
Object::Holder ohHolder = f_hMapByName->get(vsServiceName);
if (ohHolder == NULL || instanceof<Service::Handle>(ohHolder))
{
return cast<Service::Handle>(ohHolder);
}
else if (instanceof<SubjectScopedReference::Handle>(ohHolder))
{
SubjectScopedReference::Handle hScopedRef =
cast<SubjectScopedReference::Handle>(ohHolder);
return cast<Service::Handle>(hScopedRef->get());
}
else
{
COH_THROW (UnsupportedOperationException::create("invalid type"));
}
}
Collection::View ScopedReferenceStore::getAllCaches() const
{
Set::Handle hSetRef = HashSet::create();
for (Iterator::Handle hIter = f_hMapByName->values()->iterator();
hIter->hasNext(); )
{
Object::Holder ohHolder = hIter->next();
if (instanceof<SubjectScopedReference::Handle>(ohHolder))
{
hSetRef->addAll(cast<SubjectScopedReference::Handle>(ohHolder)->values());
}
else if (instanceof<NamedCache::Handle>(ohHolder))
{
hSetRef->add(ohHolder);
}
else
{
COH_THROW (UnsupportedOperationException::create("invalid type"));
}
}
return hSetRef;
}
Collection::View
ScopedReferenceStore::getAllCaches(String::View vsCacheName) const
{
Set::Handle hSetRef = HashSet::create();
Object::Holder ohHolder = f_hMapByName->get(vsCacheName);
if (instanceof<NamedCache::Handle>(ohHolder))
{
hSetRef->add(ohHolder);
}
else if (instanceof<SubjectScopedReference::Handle>(ohHolder))
{
hSetRef->addAll(cast<SubjectScopedReference::Handle>(ohHolder)->values());
}
else
{
COH_THROW (UnsupportedOperationException::create("invalid type"));
}
return hSetRef;
}
Collection::View ScopedReferenceStore::getAllServices() const
{
Set::Handle hSetRef = HashSet::create();
for (Iterator::Handle hIter = f_hMapByName->values()->iterator();
hIter->hasNext(); )
{
Object::Holder ohHolder = hIter->next();
if (instanceof<SubjectScopedReference::Handle>(ohHolder))
{
hSetRef->addAll(cast<SubjectScopedReference::Handle>(ohHolder)->values());
}
else if (instanceof<Service::Handle>(ohHolder))
{
hSetRef->add(ohHolder);
}
else
{
COH_THROW (UnsupportedOperationException::create("invalid type"));
}
}
return hSetRef;
}
Set::View ScopedReferenceStore::getNames() const
{
return f_hMapByName->keySet();
}
void ScopedReferenceStore::putCache(NamedCache::Handle hCache)
{
String::View vsCacheName = hCache->getCacheName();
CacheService::View vCacheService = hCache->getCacheService();
if (vCacheService != NULL &&
isRemoteServiceType(vCacheService->getInfo()->getServiceType())
&& f_vContext->isSubjectScopingEnabled())
{
SubjectScopedReference::Handle hScopedRef =
cast<SubjectScopedReference::Handle>(f_hMapByName->get(vsCacheName));
if (hScopedRef == NULL)
{
hScopedRef = SubjectScopedReference::create();
f_hMapByName->put(vsCacheName, hScopedRef);
}
hScopedRef->set(hCache);
}
else
{
f_hMapByName->put(vsCacheName, hCache);
}
}
void ScopedReferenceStore::putService(Service::Handle hService,
String::View vsName, ServiceInfo::ServiceType vType)
{
if (isRemoteServiceType(vType) && f_vContext->isSubjectScopingEnabled())
{
SubjectScopedReference::Handle hScopedRef =
cast<SubjectScopedReference::Handle>(f_hMapByName->get(vsName));
if (hScopedRef == NULL)
{
hScopedRef = SubjectScopedReference::create();
f_hMapByName->put(vsName, hScopedRef);
}
hScopedRef->set(hService);
}
else
{
f_hMapByName->put(vsName, hService);
}
}
bool ScopedReferenceStore::releaseCache(NamedCache::Handle hCache)
{
String::View vsCacheName = hCache->getCacheName();
bool fFound = false;
Object::Holder ohHolder = f_hMapByName->get(vsCacheName);
if (ohHolder == hCache)
{
// remove the mapping
f_hMapByName->remove(vsCacheName);
fFound = true;
}
else if (instanceof<SubjectScopedReference::Handle>(ohHolder))
{
SubjectScopedReference::Handle hScopedRef =
cast<SubjectScopedReference::Handle>(ohHolder);
if (hScopedRef->get() == hCache)
{
hScopedRef->remove();
fFound = true;
if (hScopedRef->isEmpty())
{
f_hMapByName->remove(vsCacheName);
}
}
}
return fFound;
}
void ScopedReferenceStore::remove(String::View vsName)
{
f_hMapByName->remove(vsName);
}
bool ScopedReferenceStore::isRemoteServiceType(ServiceInfo::ServiceType nType)
{
return nType == ServiceInfo::remote_cache ||
nType == ServiceInfo::remote_invocation;
}
// ----- inner class: SubjectScopedReference --------------------------------
// ----- constructors ---------------------------------------------------
ScopedReferenceStore::SubjectScopedReference::SubjectScopedReference()
: f_hMapSubjectScope(self(), SafeHashMap::create()), m_ohRef(self())
{
}
Object::Handle ScopedReferenceStore::SubjectScopedReference::get() const
{
Subject::View vSubject = SecurityHelper::getCurrentSubject();
if (vSubject == NULL)
{
return cast<Object::Handle>(m_ohRef);
}
else
{
return cast<Object::Handle>(f_hMapSubjectScope->get(vSubject));
}
}
bool ScopedReferenceStore::SubjectScopedReference::isEmpty() const
{
Subject::View vSubject = SecurityHelper::getCurrentSubject();
return vSubject == NULL ? m_ohRef == NULL
: f_hMapSubjectScope->isEmpty();
}
void ScopedReferenceStore::SubjectScopedReference::set(Object::Handle hRef)
{
Subject::View vSubject = SecurityHelper::getCurrentSubject();
if (vSubject == NULL)
{
m_ohRef = hRef;
}
else
{
f_hMapSubjectScope->put(vSubject, hRef);
}
}
Object::Handle ScopedReferenceStore::SubjectScopedReference::remove()
{
Subject::View vSubject = SecurityHelper::getCurrentSubject();
return vSubject == NULL ? cast<Object::Handle>(m_ohRef = NULL)
: cast<Object::Handle>(f_hMapSubjectScope->remove(vSubject));
}
Collection::View ScopedReferenceStore::SubjectScopedReference::values() const
{
Object::Holder ohRef = m_ohRef;
// return any subject scoped entries
if (ohRef == NULL)
{
return f_hMapSubjectScope->values();
}
// a single non-subject scoped entry
if (f_hMapSubjectScope->isEmpty())
{
return Collections::singleton(ohRef);
}
// both one or more subject scoped entries and a non-subject scoped entry
Collection::Handle hCol = HashSet::create(f_hMapSubjectScope->values());
hCol->add(ohRef);
return hCol;
}
COH_CLOSE_NAMESPACE3
| 29.033133 | 86 | 0.618425 | chpatel3 |
7702889edaa42726c728c30d3c1a615134795250 | 3,429 | cpp | C++ | test/Interface/Component_Test.cpp | ctj12461/MultiGenerator | 15e4ef159502f5d886bbb7f03e4f8b41bf759382 | [
"MIT"
] | 2 | 2022-03-24T11:37:10.000Z | 2022-03-24T11:37:18.000Z | test/Interface/Component_Test.cpp | ctj12461/MultiGenerator | 15e4ef159502f5d886bbb7f03e4f8b41bf759382 | [
"MIT"
] | null | null | null | test/Interface/Component_Test.cpp | ctj12461/MultiGenerator | 15e4ef159502f5d886bbb7f03e4f8b41bf759382 | [
"MIT"
] | null | null | null | #include <iostream>
#include <filesystem>
#include <cassert>
#include <MultiGenerator/Interface/Component.hpp>
namespace Workflow = MultiGenerator::Workflow;
namespace Variable = MultiGenerator::Variable;
namespace Interface = MultiGenerator::Interface;
class AddGenerator : public Interface::GeneratingTask {
private:
void generate(std::ostream &data, const Variable::DataConfig &config) override {
int a = std::stoi(config.get("a").value());
int b = std::stoi(config.get("b").value());
data << a << " " << b << std::endl;
}
};
class AddSolution : public Interface::SolutionTask {
private:
void solve(std::istream &dataIn, std::ostream &dataOut,
const Variable::DataConfig &config) override {
int a, b;
dataIn >> a >> b;
dataOut << a + b << std::endl;
}
};
class IntegratedAddGenerator : public Interface::IntegratedGeneratingTask {
private:
void generate(std::ostream &dataIn, std::ostream &dataOut,
const Variable::DataConfig &config) override {
int a = std::stoi(config.get("a").value());
int b = std::stoi(config.get("b").value());
dataIn << a << " " << b << std::endl;
dataOut << a + b << std::endl;
}
};
void testGeneratingTask() {
{
AddGenerator task;
task.setProblemName("add");
task.setArgument(std::make_shared<Variable::SubtaskArgument>(
1,
1,
Variable::DataConfig::create({
{"a", "1"},
{"b", "2"}
})
));
task.initEnvironment();
task.call();
}
{
std::string str;
std::getline(std::ifstream("add1-1.in"), str);
assert(str == "1 2");
}
{
namespace filesystem = std::filesystem;
filesystem::remove(filesystem::path("add1-1.in"));
}
}
void testSolutionTask() {
{
std::ofstream("add1-1.in") << 1 << " " << 2 << std::endl;
}
{
AddSolution task;
task.setProblemName("add");
task.setArgument(std::make_shared<Variable::SubtaskArgument>(1, 1,
Variable::DataConfig::create({})));
task.initEnvironment();
task.call();
}
{
std::string str;
std::getline(std::ifstream("add1-1.out"), str);
assert(str == "3");
}
{
namespace filesystem = std::filesystem;
filesystem::remove(filesystem::path("add1-1.in"));
filesystem::remove(filesystem::path("add1-1.out"));
}
}
void testIntegratedGeneratingTask() {
{
IntegratedAddGenerator task;
task.setProblemName("add");
task.setArgument(std::make_shared<Variable::SubtaskArgument>(
1,
1,
Variable::DataConfig::create({
{"a", "1"},
{"b", "2"}
})
));
task.initEnvironment();
task.call();
}
{
std::string str;
std::getline(std::ifstream("add1-1.in"), str);
assert(str == "1 2");
std::getline(std::ifstream("add1-1.out"), str);
assert(str == "3");
}
{
namespace filesystem = std::filesystem;
filesystem::remove(filesystem::path("add1-1.in"));
filesystem::remove(filesystem::path("add1-1.out"));
}
}
int main() {
testGeneratingTask();
testSolutionTask();
testIntegratedGeneratingTask();
return 0;
} | 25.977273 | 84 | 0.551473 | ctj12461 |
7702b2745333aef83310036b29b12bb8ed2f4c03 | 818 | cpp | C++ | Programacao Orientada Objectos/MMInvaders/Project1WForms/InimigoBoss.cpp | dicamarques14/ProjectosProgramacao | fdfa52cc46fc8dcdc65d4cb471ed31546433a6ad | [
"MIT"
] | null | null | null | Programacao Orientada Objectos/MMInvaders/Project1WForms/InimigoBoss.cpp | dicamarques14/ProjectosProgramacao | fdfa52cc46fc8dcdc65d4cb471ed31546433a6ad | [
"MIT"
] | null | null | null | Programacao Orientada Objectos/MMInvaders/Project1WForms/InimigoBoss.cpp | dicamarques14/ProjectosProgramacao | fdfa52cc46fc8dcdc65d4cb471ed31546433a6ad | [
"MIT"
] | null | null | null | #include "InimigoBoss.h"
InimigoBoss::InimigoBoss(int _tipo, int _id, int _x,int _y)
:Inimigo( _tipo, _id, _x, _y)
{
TamanhoH = BossSizeInit_H;
TamanhoW = BossSizeInit_W;
EstadoBoca = Fechada;
}
InimigoBoss::~InimigoBoss(void)
{
}
bool InimigoBoss::RetiraVida(int _dano){
//se estiver com a boca aberta, pode sofrer dano, isto e aumenta em tamanho
if(EstadoBoca){
TamanhoH += BossGrowPTiro;
TamanhoW += BossGrowPTiro;
}
//se ja atingir o limite de tamanho, morre
if(TamanhoH > BossSizeFinal_H || TamanhoW > BossSizeFinal_W){
return true;
}
return false;
}
int InimigoBoss::getEstadoBoca(){
return EstadoBoca;
}
void InimigoBoss::controlaBoca(int _EstadoBoca){
EstadoBoca = _EstadoBoca;
}
void InimigoBoss::getSize(int &_w,int &_h){ //tamanho actual
_h = TamanhoH;
_w = TamanhoW;
} | 18.177778 | 76 | 0.717604 | dicamarques14 |
770c98f96afd1faac686df9c2b581be9f2d5940e | 5,472 | cpp | C++ | Source/DialogueSystemEditor/Private/DialogueGraphEditor/SDialogueGraphNode.cpp | WiseMooseGames/quest-system-plugin | 0a88f13d5e9795d8f403d44b7a2d123b279608b1 | [
"MIT"
] | null | null | null | Source/DialogueSystemEditor/Private/DialogueGraphEditor/SDialogueGraphNode.cpp | WiseMooseGames/quest-system-plugin | 0a88f13d5e9795d8f403d44b7a2d123b279608b1 | [
"MIT"
] | null | null | null | Source/DialogueSystemEditor/Private/DialogueGraphEditor/SDialogueGraphNode.cpp | WiseMooseGames/quest-system-plugin | 0a88f13d5e9795d8f403d44b7a2d123b279608b1 | [
"MIT"
] | null | null | null | #include "SDialogueGraphNode.h"
#include "SGraphPin.h"
#include "Widgets/SBoxPanel.h"
#include "DialogueEdNode.h"
#include "DialogueGraphColors.h"
#include "GraphEditorSettings.h"
#include "SlateOptMacros.h"
#include "Widgets/Text/SInlineEditableTextBlock.h"
class SDialogueGraphPin : public SGraphPin
{
public:
SLATE_BEGIN_ARGS(SDialogueGraphPin) {}
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, UEdGraphPin* InPin)
{
this->SetCursor(EMouseCursor::Default);
bShowLabel = true;
GraphPinObj = InPin;
check(GraphPinObj != nullptr);
const UEdGraphSchema* Schema = GraphPinObj->GetSchema();
check(Schema);
SBorder::Construct(SBorder::FArguments()
.BorderImage(this, &SDialogueGraphPin::GetPinBorder)
.BorderBackgroundColor(this, &SDialogueGraphPin::GetPinColor)
.OnMouseButtonDown(this, &SDialogueGraphPin::OnPinMouseDown)
.Cursor(this, &SDialogueGraphPin::GetPinCursor)
);
}
protected:
virtual FSlateColor GetPinColor() const override
{
return DialogueGraphColors::Pin::Default;
}
virtual TSharedRef<SWidget> GetDefaultValueWidget() override
{
return SNew(STextBlock);
}
const FSlateBrush* GetPinBorder() const
{
return (IsHovered())
? FEditorStyle::GetBrush(TEXT("Graph.StateNode.Pin.BackgroundHovered"))
: FEditorStyle::GetBrush(TEXT("Graph.StateNode.Pin.Background"));
}
};
/////////////////////////////////////////////////////
// SDialogueGraphNode
void SDialogueGraphNode::Construct(const FArguments& InArgs, UDialogueEdNode* InNode)
{
this->GraphNode = InNode;
this->SetCursor(EMouseCursor::CardinalCross);
this->UpdateGraphNode();
}
BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION
void SDialogueGraphNode::UpdateGraphNode()
{
InputPins.Empty();
OutputPins.Empty();
// Reset variables that are going to be exposed, in case we are refreshing an already setup node.
RightNodeBox.Reset();
LeftNodeBox.Reset();
const FSlateBrush* NodeTypeIcon = GetNameIcon();
FLinearColor TitleShadowColor(0.6f, 0.6f, 0.6f);
TSharedPtr<SErrorText> ErrorText;
TSharedPtr<SNodeTitle> NodeTitle = SNew(SNodeTitle, GraphNode);
this->ContentScale.Bind(this, &SGraphNode::GetContentScale);
this->GetOrAddSlot(ENodeZone::Center)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("Graph.StateNode.Body"))
.Padding(0)
.BorderBackgroundColor(this, &SDialogueGraphNode::GetBorderBackgroundColor)
[
SNew(SOverlay)
// PIN AREA
+ SOverlay::Slot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SAssignNew(RightNodeBox, SVerticalBox)
]
// STATE NAME AREA
+ SOverlay::Slot()
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
.Padding(10.0f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("Graph.StateNode.ColorSpill"))
.BorderBackgroundColor(this, &SDialogueGraphNode::GetBackgroundColor)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
.Visibility(EVisibility::SelfHitTestInvisible)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
// POPUP ERROR MESSAGE
SAssignNew(ErrorText, SErrorText)
.BackgroundColor(this, &SDialogueGraphNode::GetErrorColor)
.ToolTipText(this, &SDialogueGraphNode::GetErrorMsgToolTip)
]
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
[
SNew(SImage)
.Image(NodeTypeIcon)
]
+ SHorizontalBox::Slot()
.Padding(FMargin(4.0f, 0.0f, 4.0f, 0.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SAssignNew(InlineEditableText, SInlineEditableTextBlock)
.Style(FEditorStyle::Get(), "Graph.StateNode.NodeTitleInlineEditableText")
.Text(NodeTitle.Get(), &SNodeTitle::GetHeadTitle)
.OnVerifyTextChanged(this, &SDialogueGraphNode::OnVerifyNameTextChanged)
.OnTextCommitted(this, &SDialogueGraphNode::OnNameTextCommited)
.IsReadOnly(this, &SDialogueGraphNode::IsNameReadOnly)
.IsSelected(this, &SDialogueGraphNode::IsSelectedExclusively)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
NodeTitle.ToSharedRef()
]
]
]
]
]
];
ErrorReporting = ErrorText;
ErrorReporting->SetError(ErrorMsg);
CreatePinWidgets();
}
END_SLATE_FUNCTION_BUILD_OPTIMIZATION
void SDialogueGraphNode::CreatePinWidgets()
{
UDialogueEdNode* Node = CastChecked<UDialogueEdNode>(GraphNode);
UEdGraphPin* CurPin = Node->GetOutputPin();
if (!CurPin->bHidden)
{
TSharedPtr<SGraphPin> NewPin = SNew(SDialogueGraphPin, CurPin);
this->AddPin(NewPin.ToSharedRef());
}
}
void SDialogueGraphNode::AddPin(const TSharedRef<SGraphPin>& PinToAdd)
{
PinToAdd->SetOwner(SharedThis(this));
RightNodeBox->AddSlot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
.FillHeight(1.0f)
[
PinToAdd
];
OutputPins.Add(PinToAdd);
}
const FSlateBrush* SDialogueGraphNode::GetNameIcon() const
{
return FEditorStyle::GetBrush(TEXT("Graph.StateNode.Icon"));
}
FSlateColor SDialogueGraphNode::GetBorderBackgroundColor() const
{
return DialogueGraphColors::NodeBorder::Root;
}
FSlateColor SDialogueGraphNode::GetBackgroundColor() const
{
UDialogueEdNode* MyNode = CastChecked<UDialogueEdNode>(GraphNode);
return MyNode ? MyNode->GetBackgroundColor() : FLinearColor(0.08f, 0.08f, 0.08f);
}
EVisibility SDialogueGraphNode::GetDragOverMarkerVisibility() const
{
return EVisibility::Visible;
} | 25.933649 | 99 | 0.716374 | WiseMooseGames |
771216fc5562c9d774ebeae84b46310519d28a0c | 843 | cpp | C++ | ParticleSystem_FullCode/Motor2D/j1Pool.cpp | xavimarin35/Particle-System | e3728fef00add33fa42c07f1bc36348a7cab9d00 | [
"MIT"
] | 1 | 2020-07-04T11:04:54.000Z | 2020-07-04T11:04:54.000Z | ParticleSystem_FullCode/Motor2D/j1Pool.cpp | xavimarin35/Particle-System | e3728fef00add33fa42c07f1bc36348a7cab9d00 | [
"MIT"
] | null | null | null | ParticleSystem_FullCode/Motor2D/j1Pool.cpp | xavimarin35/Particle-System | e3728fef00add33fa42c07f1bc36348a7cab9d00 | [
"MIT"
] | null | null | null | #include "j1Pool.h"
#include "j1Emitter.h"
#include "j1Particle.h"
#include <assert.h>
j1Pool::j1Pool(j1Emitter* emitter)
{
size = emitter->GetSize();
vec = new j1Particle[size];
startParticle = &vec[0];
}
j1Pool::~j1Pool()
{
delete[] vec;
vec = nullptr;
}
bool j1Pool::Update(float dt)
{
for (int i = 0; i < size; i++)
{
if (vec[i].Living() == true)
{
vec[i].Update(dt);
vec[i].Draw();
}
else if(vec[i].Living() == false)
{
startParticle = &vec[i];
}
else {
return false;
}
}
return true;
}
void j1Pool::CreateParticles(fPoint pos, float speed, float angle, float size, int life, SDL_Rect tex, SDL_Color startColor, SDL_Color endColor)
{
assert(startParticle != nullptr);
j1Particle* p = startParticle;
p->LoadParticleProperties(pos, speed, angle, size, life, tex, startColor, endColor);
} | 17.5625 | 144 | 0.646501 | xavimarin35 |
7715ccb2e84ebdaf36cd03fede19adaafc650c04 | 6,197 | cpp | C++ | engine/src/channelmodifier.cpp | hawesy/qlcplus | 1702f03144fe210611881f15424a535febae0c6a | [
"ECL-2.0",
"Apache-2.0"
] | 478 | 2015-01-20T14:51:17.000Z | 2022-03-31T06:56:05.000Z | engine/src/channelmodifier.cpp | hjtappe/qlcplus | b5537fa11d419d148eca5cb1321ee98d3dc5047b | [
"ECL-2.0",
"Apache-2.0"
] | 711 | 2015-01-05T06:50:06.000Z | 2022-03-06T20:31:07.000Z | engine/src/channelmodifier.cpp | hjtappe/qlcplus | b5537fa11d419d148eca5cb1321ee98d3dc5047b | [
"ECL-2.0",
"Apache-2.0"
] | 386 | 2015-01-07T15:36:59.000Z | 2022-03-31T06:56:07.000Z | /*
Q Light Controller Plus
channelmodifier.cpp
Copyright (c) Massimo Callegari
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.txt
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 "channelmodifier.h"
#include "qlcfile.h"
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QDebug>
ChannelModifier::ChannelModifier()
{
m_values.fill(0, 256);
m_name = QString();
m_type = UserTemplate;
}
void ChannelModifier::setName(QString name)
{
m_name = name;
}
QString ChannelModifier::name() const
{
return m_name;
}
void ChannelModifier::setType(ChannelModifier::Type type)
{
m_type = type;
}
ChannelModifier::Type ChannelModifier::type() const
{
return m_type;
}
void ChannelModifier::setModifierMap(QList<QPair<uchar, uchar> > map)
{
m_map = map;
m_values.fill(0, 256);
QPair<uchar, uchar> lastDMXPair;
for (int i = 0; i < m_map.count(); i++)
{
QPair<uchar, uchar> dmxPair = m_map.at(i);
m_values[dmxPair.first] = dmxPair.second;
if (i != 0)
{
// calculate the increment to go from one pair to another
// in a linear progression
float dmxInc = 0;
if (dmxPair.first - lastDMXPair.first > 0)
dmxInc = (float)(dmxPair.second - lastDMXPair.second) / (float)(dmxPair.first - lastDMXPair.first);
// use a float variable here to be as more accurate as possible
float floatVal = lastDMXPair.second;
for (int p = lastDMXPair.first; p < dmxPair.first; p++)
{
// the float value is rounded here but it
// is what we wanted
m_values[p] = floatVal;
floatVal += dmxInc;
}
}
lastDMXPair = dmxPair;
}
// Enable the following to display the template full range of value
/*
qDebug() << "Template:" << m_name;
for (int d = 0; d < m_values.count(); d++)
qDebug() << "Pos:" << d << "val:" << QString::number((uchar)m_values.at(d));
*/
}
QList< QPair<uchar, uchar> > ChannelModifier::modifierMap() const
{
return m_map;
}
uchar ChannelModifier::getValue(uchar dmxValue)
{
return m_values.at(dmxValue);
}
QFile::FileError ChannelModifier::saveXML(const QString &fileName)
{
QFile::FileError error;
if (fileName.isEmpty() == true)
return QFile::OpenError;
QFile file(fileName);
if (file.open(QIODevice::WriteOnly) == false)
return file.error();
QXmlStreamWriter doc(&file);
doc.setAutoFormatting(true);
doc.setAutoFormattingIndent(1);
doc.setCodec("UTF-8");
QLCFile::writeXMLHeader(&doc, KXMLQLCChannelModifierDocument);
doc.writeTextElement(KXMLQLCChannelModName, m_name);
qDebug() << "Got map with" << m_map.count() << "handlers";
for(int i = 0; i < m_map.count(); i++)
{
QPair<uchar, uchar> mapElement = m_map.at(i);
doc.writeStartElement(KXMLQLCChannelModHandler);
doc.writeAttribute(KXMLQLCChannelModOriginalDMX, QString::number(mapElement.first));
doc.writeAttribute(KXMLQLCChannelModModifiedDMX, QString::number(mapElement.second));
doc.writeEndElement();
}
/* End the document and close all the open elements */
error = QFile::NoError;
doc.writeEndDocument();
file.close();
return error;
}
QFile::FileError ChannelModifier::loadXML(const QString &fileName, Type type)
{
QFile::FileError error = QFile::NoError;
if (fileName.isEmpty() == true)
return QFile::OpenError;
QXmlStreamReader *doc = QLCFile::getXMLReader(fileName);
if (doc == NULL || doc->device() == NULL || doc->hasError())
{
qWarning() << Q_FUNC_INFO << "Unable to read from" << fileName;
return QFile::ReadError;
}
while (!doc->atEnd())
{
if (doc->readNext() == QXmlStreamReader::DTD)
break;
}
if (doc->hasError())
{
QLCFile::releaseXMLReader(doc);
return QFile::ResourceError;
}
QList< QPair<uchar, uchar> > modMap;
if (doc->dtdName() == KXMLQLCChannelModifierDocument)
{
if (doc->readNextStartElement() == false)
return QFile::ResourceError;
if (doc->name() == KXMLQLCChannelModifierDocument)
{
while (doc->readNextStartElement())
{
if (doc->name() == KXMLQLCChannelModName)
{
setName(doc->readElementText());
}
else if(doc->name() == KXMLQLCChannelModHandler)
{
QPair <uchar, uchar> dmxPair(0, 0);
QXmlStreamAttributes attrs = doc->attributes();
if (attrs.hasAttribute(KXMLQLCChannelModOriginalDMX))
dmxPair.first = attrs.value(KXMLQLCChannelModOriginalDMX).toString().toUInt();
if (attrs.hasAttribute(KXMLQLCChannelModModifiedDMX))
dmxPair.second = attrs.value(KXMLQLCChannelModModifiedDMX).toString().toUInt();
modMap.append(dmxPair);
doc->skipCurrentElement();
}
else if (doc->name() == KXMLQLCCreator)
{
/* Ignore creator information */
doc->skipCurrentElement();
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown ChannelModifier tag:" << doc->name();
doc->skipCurrentElement();
}
}
}
}
if (modMap.count() > 0)
{
setType(type);
setModifierMap(modMap);
}
QLCFile::releaseXMLReader(doc);
return error;
}
| 29.231132 | 115 | 0.597224 | hawesy |
7724de68ca3d4c8b204642f4e2dd1d9c6e779d5f | 7,764 | cpp | C++ | test/network/SocketImplTest/socket_impl_test.cpp | luckysym/Taurus | d336e7bd226411f7e3d348dc701c79182e85c316 | [
"Apache-2.0"
] | null | null | null | test/network/SocketImplTest/socket_impl_test.cpp | luckysym/Taurus | d336e7bd226411f7e3d348dc701c79182e85c316 | [
"Apache-2.0"
] | null | null | null | test/network/SocketImplTest/socket_impl_test.cpp | luckysym/Taurus | d336e7bd226411f7e3d348dc701c79182e85c316 | [
"Apache-2.0"
] | null | null | null | #include "../../../src/net/socket_impl.h"
#include "../../../src/net/socket_opt_impl.h"
#include <mercury/nio/buffer.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestSuite.h>
#include <cppunit/extensions/HelperMacros.h>
#include <unistd.h>
#include <iostream>
using namespace mercury;
using namespace mercury::net;
using namespace std;
class SocketImpTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( SocketImpTest );
CPPUNIT_TEST( testServerSocket );
CPPUNIT_TEST( testClientSocketInvalid );
CPPUNIT_TEST( testClientSocketValid );
CPPUNIT_TEST_SUITE_END();
private:
SocketImpl::Ptr m_ptrSocketImpl;
RuntimeError m_err;
public:
SocketImpTest() {
cout<<"construct"<<endl;
}
void setUp () {
CreateSocket(m_ptrSocketImpl);
// CreateClientSocket();
}
void tearDown() {
// CloseClientSocket();
CloseSocket(m_ptrSocketImpl);
}
// 测试创建一个服务端socket并执行监听
void testServerSocket() {
this->BindSocket(m_ptrSocketImpl);
this->ListenSocket(m_ptrSocketImpl);
this->GetLocalAddress(m_ptrSocketImpl);
}
// 测试创建一个客户端socket并连接一个无效地址
void testClientSocketInvalid() {
this->ConnectSocketInvalid(m_ptrSocketImpl);
}
void testClientSocketValid() {
this->ConnectSocketLocal22(m_ptrSocketImpl);
this->GetRemoteAddress22(m_ptrSocketImpl);
this->GetClientLocalAddress(m_ptrSocketImpl);
this->ShutdownSocket(m_ptrSocketImpl);
}
protected:
void CreateSocket(SocketImpl::Ptr &ptrSocket) {
ptrSocket.reset(new SocketImpl());
printf("Server Socket Ptr: %p\n", ptrSocket.get());
CPPUNIT_ASSERT( ptrSocket != nullptr );
RuntimeError errinfo;
CPPUNIT_ASSERT( ptrSocket->Create(AF_INET, SOCK_STREAM, errinfo) );
CPPUNIT_ASSERT( ptrSocket->Fd() > 0 );
CPPUNIT_ASSERT( ptrSocket->State() == SocketImpl::SOCK_STATE_CREATED );
cout<<"socket created, fd: "<<ptrSocket->Fd()<<endl;
// 设置socket reuse addr
int bopt;
SocketOptReuseAddr optreuseaddr( ptrSocket->Fd() );
CPPUNIT_ASSERT( optreuseaddr.Get(&bopt, m_err) );
CPPUNIT_ASSERT( !bopt );
CPPUNIT_ASSERT( optreuseaddr.Set(true, m_err) );
CPPUNIT_ASSERT( optreuseaddr.Get(&bopt, m_err) );
CPPUNIT_ASSERT( bopt );
cout<<"socket opt reuseaddr: "<<bopt<<endl;
}
void SetSocketBuffer(SocketImpl::Ptr &ptrSocket) {
// 获取和设置收发缓存
int rcvbuf, sndbuf;
SocketOptRecvBuffer optrcvbuf(ptrSocket->Fd());
SocketOptSendBuffer optsndbuf(ptrSocket->Fd());
CPPUNIT_ASSERT( optrcvbuf.Get(&rcvbuf, m_err));
CPPUNIT_ASSERT( optsndbuf.Get(&sndbuf, m_err));
cout<<"default socket rcvbuf: "<<rcvbuf<<endl;
cout<<"default socket sndbuf: "<<sndbuf<<endl;
CPPUNIT_ASSERT( optrcvbuf.Set(4096, m_err));
CPPUNIT_ASSERT( optsndbuf.Set(16384 * 2, m_err));
CPPUNIT_ASSERT( optrcvbuf.Get(&rcvbuf, m_err));
CPPUNIT_ASSERT( optsndbuf.Get(&sndbuf, m_err));
CPPUNIT_ASSERT( rcvbuf == 4096);
CPPUNIT_ASSERT( sndbuf == 16384 * 2);
}
void CloseSocket(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
cout<<"Socket Closed: "<<ptrSocket->Fd()<<endl;
CPPUNIT_ASSERT( ptrSocket->Close(errinfo));
CPPUNIT_ASSERT( ptrSocket->Fd() == INVALID_SOCKET );
CPPUNIT_ASSERT( ptrSocket->State() == SocketImpl::SOCK_STATE_CLOSED );
}
void BindSocket (SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
CPPUNIT_ASSERT( ptrSocket->Bind("0.0.0.0", 10024, errinfo));
}
void ListenSocket(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
CPPUNIT_ASSERT( ptrSocket->Listen(SOMAXCONN, errinfo));
CPPUNIT_ASSERT( ptrSocket->State() == SocketImpl::SOCK_STATE_OPEN );
}
void GetLocalAddress(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
string addr = ptrSocket->GetLocalAddress(errinfo);
CPPUNIT_ASSERT(errinfo.code() == 0);
CPPUNIT_ASSERT(!addr.empty());
cout<<addr<<endl;
}
void ConnectSocketInvalid(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
CPPUNIT_ASSERT(!ptrSocket->Connect("127.0.0.1", 10024, errinfo));
CPPUNIT_ASSERT( ptrSocket->State() == SocketImpl::SOCK_STATE_CREATED);
}
void ConnectSocketLocal22(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
CPPUNIT_ASSERT( ptrSocket->Connect("127.0.0.1", 22, errinfo));
CPPUNIT_ASSERT( ptrSocket->State() == SocketImpl::SOCK_STATE_OPEN);
}
void GetRemoteAddress22(SocketImpl::Ptr &ptrSocket) {
RuntimeError e1;
std::string addr = ptrSocket->GetRemoteAddress(e1);
CPPUNIT_ASSERT(!addr.empty());
RuntimeError e2;
int port = ptrSocket->GetRemotePort(e2);
CPPUNIT_ASSERT(port == 22);
}
void GetClientLocalAddress(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
string addr = ptrSocket->GetLocalAddress(errinfo);
CPPUNIT_ASSERT(errinfo.code() == 0);
CPPUNIT_ASSERT(!addr.empty());
cout<<addr<<endl;
}
void ShutdownSocket(SocketImpl::Ptr &ptrSocket) {
RuntimeError errinfo;
CPPUNIT_ASSERT( ptrSocket->ShutdownInput(errinfo) );
CPPUNIT_ASSERT( ptrSocket->ShutdownOutput(errinfo) );
}
}; // end class SocketImpTest
class URL_Test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( URL_Test );
CPPUNIT_TEST( testURL );
CPPUNIT_TEST_SUITE_END();
public:
void setUp () { }
void tearDown() { }
void testURL() {
URL url;
CPPUNIT_ASSERT(url.schema()[0] == '\0');
CPPUNIT_ASSERT(url.host()[0] == '\0');
CPPUNIT_ASSERT(url.port() == -1);
URL url1("http", "192.168.1.1", 8080);
CPPUNIT_ASSERT(0 == strcmp("http", url1.schema()));
CPPUNIT_ASSERT(0 == strcmp("192.168.1.1", url1.host()));
CPPUNIT_ASSERT(url1.port() == 8080);
cout<<url1.str()<<endl;
RuntimeError e;
URL url2("http://192.168.1.2:8080", e);
CPPUNIT_ASSERT(0 == e.code());
CPPUNIT_ASSERT(0 == strcmp("http", url2.schema()));
CPPUNIT_ASSERT(0 == strcmp("192.168.1.2", url2.host()));
CPPUNIT_ASSERT(url2.port() == 8080);
cout<<url2.str()<<endl;
URL url3("http", "fe80::9069:38e5:2d7:8ed3", -1);
CPPUNIT_ASSERT(0 == strcmp("http", url3.schema()));
CPPUNIT_ASSERT(0 == strcmp("fe80::9069:38e5:2d7:8ed3", url3.host()));
CPPUNIT_ASSERT(url3.port() == -1);
cout<<url3.str()<<endl;
URL url4("http", "[fe80::9069:38e5:2d7:8ed4]", 0);
CPPUNIT_ASSERT(0 == strcmp("http", url4.schema()));
CPPUNIT_ASSERT(0 == strcmp("[fe80::9069:38e5:2d7:8ed4]", url4.host()));
CPPUNIT_ASSERT(url4.port() == 0);
cout<<url4.str()<<endl;
e.clear();
URL url5("http://[fe80::9069:38e5:2d7:8ed4]:9090", e);
CPPUNIT_ASSERT(0 == strcmp("http", url5.schema()));
CPPUNIT_ASSERT(0 == strcmp("[fe80::9069:38e5:2d7:8ed4]", url5.host()));
CPPUNIT_ASSERT(url5.port() == 9090);
cout<<url5.str()<<endl;
}
};
// CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( SocketImpTest, "alltest" );
// CPPUNIT_TEST_SUITE_REGISTRATION( SocketImpTest );
CPPUNIT_TEST_SUITE_REGISTRATION( URL_Test );
int main(int argc, char **argv)
{
CppUnit::TextUi::TestRunner runner;
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
runner.addTest(suite);
runner.run();
return 0;
}
| 33.61039 | 82 | 0.635111 | luckysym |
7725f6bf849068cd3a35a8f021547f344178a896 | 4,017 | cpp | C++ | src/XESCore/MapCreate.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 71 | 2015-12-15T19:32:27.000Z | 2022-02-25T04:46:01.000Z | src/XESCore/MapCreate.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 19 | 2016-07-09T19:08:15.000Z | 2021-07-29T10:30:20.000Z | src/XESCore/MapCreate.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 42 | 2015-12-14T19:13:02.000Z | 2022-03-01T15:15:03.000Z | /*
* Copyright (c) 2008, Laminar Research.
*
* 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 "MapCreate.h"
#include "AssertUtils.h"
#include "MapHelpers.h"
void Map_CreateWithLineData(
Pmwx& out_map,
const vector<Segment_2>& input_curves,
const vector<GIS_halfedge_data>& input_data)
{
DebugAssert(input_curves.size() == input_data.size());
out_map.clear();
int n;
vector<Curve_2> curves;
curves.resize(input_curves.size());
for(n = 0; n < input_curves.size(); ++n)
curves[n] = Curve_2(input_curves[n], n);
CGAL::insert(out_map, curves.begin(), curves.end());
for(Pmwx::Edge_iterator eit = out_map.edges_begin(); eit != out_map.edges_end(); ++eit)
{
DebugAssert(eit->curve().data().size() >= 1);
// CGAL maintains a lot of information for us that makes life easy:
// 1. The underlying curve of an edge is a sub-curve of the input curve - it is NEVER flipped. is_directed_right tells whether
// it is lex-right.*
// 2. Each half-edge's direction tells us if the half-edge is lex-right...strangely, "SMALLER" means lex-right.
// Putting these two things together, we can easily detect which of two half-edges is in the same vs. opposite direction of the input
// curve.
// * lex-right means lexicographically x-y larger...means target is to the right of source UNLESS it's vertical (then UP = true, down = false).
Halfedge_handle he = he_is_same_direction(eit) ? eit : eit->twin();
int cid = eit->curve().data().front();
DebugAssert(cid >= 0 && cid < input_data.size());
he->set_data(input_data[cid]);
// he->data().mDominant = true;
// he->twin()->data().mDominant = false;
// Do NOT leave the keys in the map...
eit->curve().data().clear();
}
}
void Map_CreateReturnEdges(
Pmwx& out_map,
const vector<Segment_2>& input_curves,
vector<vector<Pmwx::Halfedge_handle> >& halfedge_handles)
{
out_map.clear();
halfedge_handles.resize(input_curves.size());
int n;
vector<Curve_2> curves;
curves.resize(input_curves.size());
for(n = 0; n < input_curves.size(); ++n)
curves[n] = Curve_2(input_curves[n], n);
CGAL::insert(out_map, curves.begin(), curves.end());
for(Pmwx::Edge_iterator eit = out_map.edges_begin(); eit != out_map.edges_end(); ++eit)
{
DebugAssert(eit->curve().data().size() >= 1);
// We are going to go through each key and find the matching curve. Note that if we had two overlapping curves in
// opposite directions in the input data, we will pick the two TWIN half-edges, since we go with the direction
// of the source curve. This means that input data based on a wide set of source polygons that overlap will
// create correct rings.
for(EdgeKey_iterator k = eit->curve().data().begin(); k != eit->curve().data().end(); ++k)
{
Halfedge_handle he = he_get_same_direction(Halfedge_handle(eit));
halfedge_handles[*k].push_back(he);
}
// Do NOT leave the keys in the map...
eit->curve().data().clear();
}
}
| 37.194444 | 145 | 0.702514 | rromanchuk |
772cee79e402b32aa9ca343e60ad1a7e676adfae | 2,368 | cc | C++ | src/ipopt_solver.cc | huhumeng/ifopt_review | 7e29fb8dd1e75f7a229a82cbd8440cab2740f6ff | [
"BSD-3-Clause"
] | 1 | 2021-07-26T06:35:37.000Z | 2021-07-26T06:35:37.000Z | src/ipopt_solver.cc | huhumeng/ifopt_review | 7e29fb8dd1e75f7a229a82cbd8440cab2740f6ff | [
"BSD-3-Clause"
] | null | null | null | src/ipopt_solver.cc | huhumeng/ifopt_review | 7e29fb8dd1e75f7a229a82cbd8440cab2740f6ff | [
"BSD-3-Clause"
] | 1 | 2021-07-26T06:35:38.000Z | 2021-07-26T06:35:38.000Z | #include "ipopt_solver.h"
#include "ipopt_adapter.h"
namespace ifopt {
IpoptSolver::IpoptSolver()
{
ipopt_app_ = std::make_shared<Ipopt::IpoptApplication>();
/* Which linear solver to use. Mumps is default because it comes with the
* precompiled ubuntu binaries. However, the coin-hsl solvers can be
* significantly faster and are free for academic purposes. They can be
* downloaded here: http://www.hsl.rl.ac.uk/ipopt/ and must be compiled
* into your IPOPT libraries. Then you can use the additional strings:
* "ma27, ma57, ma77, ma86, ma97" here.
*/
SetOption("linear_solver", "mumps");
/* whether to use the analytical derivatives "exact" coded in ifopt, or let
* IPOPT approximate these through "finite difference-values". This is usually
* significantly slower.
*/
SetOption("jacobian_approximation", "exact");
SetOption("hessian_approximation", "limited-memory");
SetOption("max_cpu_time", 40.0);
SetOption("tol", 0.001);
SetOption("print_timing_statistics", "no");
SetOption("print_user_options", "no");
SetOption("print_level", 4);
// SetOption("max_iter", 1);
// SetOption("derivative_test", "first-order");
// SetOption("derivative_test_tol", 1e-3);
}
void IpoptSolver::Solve (Problem& nlp)
{
using namespace Ipopt;
ApplicationReturnStatus status_ = ipopt_app_->Initialize();
if(status_ != Solve_Succeeded) {
std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl;
throw std::length_error("Ipopt could not initialize correctly");
}
// convert the NLP problem to Ipopt
SmartPtr<TNLP> nlp_ptr = new IpoptAdapter(nlp);
status_ = ipopt_app_->OptimizeTNLP(nlp_ptr);
if(status_ != Solve_Succeeded) {
std::string msg = "ERROR: Ipopt failed to find a solution. Return Code: " + std::to_string(status_) + "\n";
std::cerr << msg;
}
}
void IpoptSolver::SetOption (const std::string& name, const std::string& value)
{
ipopt_app_->Options()->SetStringValue(name, value);
}
void IpoptSolver::SetOption (const std::string& name, int value)
{
ipopt_app_->Options()->SetIntegerValue(name, value);
}
void IpoptSolver::SetOption (const std::string& name, double value)
{
ipopt_app_->Options()->SetNumericValue(name, value);
}
} /* namespace ifopt */
| 32.438356 | 115 | 0.679476 | huhumeng |
772d08cb0f190ed4030f52d2fc69eb6cd9fa8b24 | 14,280 | cpp | C++ | tools/file.cpp | GregoryIstratov/external_sort | 50b3c417c0aa05eea5464e94cdfe2ad2c1b264bf | [
"MIT"
] | null | null | null | tools/file.cpp | GregoryIstratov/external_sort | 50b3c417c0aa05eea5464e94cdfe2ad2c1b264bf | [
"MIT"
] | null | null | null | tools/file.cpp | GregoryIstratov/external_sort | 50b3c417c0aa05eea5464e94cdfe2ad2c1b264bf | [
"MIT"
] | null | null | null | #include <list>
#include "file.hpp"
#include "exception.hpp"
#include "../log.hpp"
#include "raw_file.hpp"
#include "mapped_file.hpp"
#if defined(_WINDOWS)
#include <Windows.h>
class win_error_string
{
public:
~win_error_string()
{
if (err_)
{
LocalFree(err_);
err_ = nullptr;
}
}
std::string operator()(DWORD err_code)
{
LCID lcid;
GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER
| LOCALE_ILANGUAGE,
(wchar_t*)&lcid, sizeof(lcid));
if (!FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM,
nullptr,
err_code,
lcid,
(LPTSTR)&err_,
0,
nullptr)
)
{
return std::string();
}
return std::string(err_);
}
private:
char* err_ = nullptr;
};
void delete_file(const char* filename)
{
if (!DeleteFileA(filename))
{
auto s = win_error_string()(GetLastError());
throw std::runtime_error(s);
}
}
void iterate_dir(const char* path, std::function<void(const char*)>&& callback)
{
std::list<std::string> names;
std::string search_path = path;
search_path += "/*.*";
WIN32_FIND_DATA fd;
HANDLE h_find = FindFirstFileA(search_path.c_str(), &fd);
if (h_find != INVALID_HANDLE_VALUE)
{
do
{
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
callback(fd.cFileName);
}
} while (FindNextFileA(h_find, &fd));
FindClose(h_find);
}
else
{
THROW_EXCEPTION << "Failed to read directory '"
<< path
<< "': "
<< win_error_string()(GetLastError());
}
}
bool check_dir_exist(const char* path)
{
DWORD dw_attrib = GetFileAttributesA(path);
return (dw_attrib != INVALID_FILE_ATTRIBUTES &&
(dw_attrib & FILE_ATTRIBUTE_DIRECTORY));
}
void create_directory(const char* name)
{
if (!CreateDirectoryA(name, nullptr))
THROW_EXCEPTION << win_error_string()(GetLastError()));
}
#else
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void delete_file(const char* filename)
{
if (std::remove(filename) != 0)
throw std::runtime_error(strerror(errno));
}
void iterate_dir(const char* path, std::function<void(const char*)>&& callback)
{
struct dir_guard
{
explicit
dir_guard(DIR* _dir) : p_dir(_dir) {}
~dir_guard()
{
if(p_dir) closedir(p_dir);
}
DIR* p_dir;
};
DIR* dir = opendir(path);
dirent* ent;
dir_guard guard(dir);
if(!dir)
THROW_EXCEPTION << "Failed to open directory '"
<< path
<< "': "
<< put_errno;
while((ent = readdir(dir)))
{
if (std::strcmp(ent->d_name, ".") == 0
|| std::strcmp(ent->d_name, "..") == 0)
continue;
callback(ent->d_name);
}
}
bool check_dir_exist(const char* path)
{
DIR* dir = opendir(path);
if (dir)
{
closedir(dir);
return true;
}
else if (ENOENT == errno)
{
return false;
}
else
{
THROW_EXCEPTION << "Error in checking die existance: "
<< put_errno;
}
}
void create_directory(const char* path)
{
#if defined(_WIN32)
auto ret = mkdir(path);
#else
mode_t mode = 0755;
auto ret = mkdir(path, mode);
#endif
if(ret != 0)
THROW_EXCEPTION << "Failed to create directory '"
<< path << "': " << put_errno;
}
#endif // defined
void _file_write(std::string&& filename, const void* data, size_t size)
{
//raw_file_writer f(std::move(filename));
//f.write(data, size);
auto f = mapped_file::create();
f->open(filename.c_str(), size, std::ios::out | std::ios::trunc);
auto r = f->range();
r->lock();
mem_copy(r->data(), data, r->size());
}
std::vector<unsigned char> _file_read_all(std::string&& filename)
{
raw_file_reader f(std::move(filename));
uint64_t sz = f.file_size();
std::vector<unsigned char> data(sz);
f.read((char*)&data[0], sz);
return data;
}
class boost_memory_mapped_file_source;
class boost_memory_mapped_file_sink;
class system_mmap_file_source {};
class system_mmap_file_sink {};
/* Little explanation on this:
* If we want to use memory mapping we could choose between using boost maping
* and OS API maping, if CONFIG_USE_MMAP is enabled and boost is disabled or
* not available we check for the system mmap which can be not implemented for
* the host and we throw static_assert to not let it be compiled.
*/
template<typename T>
struct mmap_source_factory
{
/*
* using std::is_same<T,T> is a trick to make static assertion
* deferred until template isn't invoked
*/
static_assert(std::is_same<T, T>::value && !IS_ENABLED(CONFIG_USE_MMAP),
"Unsupported mmap type for this OS");
std::unique_ptr<memory_mapped_file_source> operator()() const
{
throw;
}
};
template<typename T>
struct mmap_sink_factory
{
static_assert(std::is_same<T, T>::value && !IS_ENABLED(CONFIG_USE_MMAP),
"Unsupported mmap type for this OS");
std::unique_ptr<memory_mapped_file_sink> operator()() const
{
throw;
}
};
#if defined(__BOOST_FOUND)
#include <boost/iostreams/device/mapped_file.hpp>
class boost_memory_mapped_file_source : public memory_mapped_file_source
{
public:
void open(const char* filename) override
{
source_.open(filename);
if (!source_)
THROW_EXCEPTION << "Cannot open file '"
<< filename << "' for mapping";
}
void close() override
{
source_.close();
}
size_t size() const override
{
return source_.size();
}
const char* data() const override
{
return source_.data();
}
private:
boost::iostreams::mapped_file_source source_;
};
class boost_memory_mapped_file_sink : public memory_mapped_file_sink
{
public:
void open(const char* filename, size_t size,
size_t offset, bool create) override
{
boost::iostreams::mapped_file_params params;
params.path = filename;
params.flags = boost::iostreams::mapped_file_base::readwrite;
params.offset = offset;
if (!create)
params.length = size;
else
params.new_file_size = size;
sink_.open(params);
if (!sink_)
THROW_EXCEPTION << "Can't open file '" << filename
<< "' for mapping";
}
void close() override
{
sink_.close();
}
char* data() const override
{
return sink_.data();
}
private:
boost::iostreams::mapped_file_sink sink_;
};
template<>
struct mmap_source_factory<boost_memory_mapped_file_source>
{
auto operator()() const
{
return std::make_unique<boost_memory_mapped_file_source>();
}
};
template<>
struct mmap_sink_factory<boost_memory_mapped_file_sink>
{
auto operator()() const
{
return std::make_unique<boost_memory_mapped_file_sink>();
}
};
#endif // __BOOST_FOUND
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
class posix_mmap_file_source : public memory_mapped_file_source
{
public:
~posix_mmap_file_source()
{
close();
}
void open(const char* filename) override
{
debug() << "[posix_mmap_file_source]: open '" << filename << "'";
auto fd = ::open(filename, O_RDONLY);
if (fd == -1)
THROW_FILE_EXCEPTION(filename) << "Cannot open the file";
struct stat sb;
if (fstat(fd, &sb) == -1)
THROW_EXCEPTION << "Cannot get file '" << filename
<< "' stat: " << put_errno;
size_ = sb.st_size;
ptr_ = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
if (ptr_ == MAP_FAILED)
THROW_FILE_EXCEPTION(filename) << "mmap failed";
}
size_t size() const override
{
return size_;
}
void close() override
{
if (ptr_ != nullptr || ptr_ != MAP_FAILED)
{
munmap(ptr_, size_);
ptr_ = nullptr;
}
if (fd_ != fd_type())
{
::close(fd_);
fd_ = fd_type();
}
}
const char* data() const override
{
return (char*)ptr_;
}
private:
using fd_type = decltype(::open("", O_RDONLY));
fd_type fd_ = fd_type();
void* ptr_ = nullptr;
size_t size_ = 0;
};
class posix_mmap_file_sink : public memory_mapped_file_sink
{
public:
~posix_mmap_file_sink()
{
close();
}
void open(const char* filename, size_t size,
size_t offset, bool create) override
{
size_ = size;
fd_ = ::open(filename, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if (fd_ == -1)
THROW_FILE_EXCEPTION(filename) << "Cannot open the file";
/* Something needs to be written at the end of the file to
* have the file actually have the new size.
* Just writing an empty string at the current file position will do.
*
* Note:
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - An empty string is actually a single '\0' character, so a zero-byte
* will be written at the last byte of the file.
*/
if (lseek(fd_, size - 1, SEEK_SET) == -1)
THROW_FILE_EXCEPTION(filename) << "Cannot seek the file";
if (write(fd_, "", 1) == -1)
THROW_FILE_EXCEPTION(filename) << "Cannot write the file";
ptr_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED,
fd_, 0);
if (ptr_ == MAP_FAILED)
THROW_FILE_EXCEPTION(filename) << "Cannot map the file";
}
void close() override
{
if (ptr_ != nullptr || ptr_ != MAP_FAILED)
{
munmap(ptr_, size_);
ptr_ = nullptr;
}
if (fd_ != fd_type())
{
::close(fd_);
fd_ = fd_type();
}
}
char* data() const override
{
return (char*)ptr_;
}
private:
using fd_type = decltype(::open("", O_RDONLY));
fd_type fd_ = fd_type();
void* ptr_ = nullptr;
size_t size_ = 0;
};
template<>
struct mmap_source_factory<system_mmap_file_source>
{
auto operator()() const
{
return std::make_unique<posix_mmap_file_source>();
}
};
template<>
struct mmap_sink_factory<system_mmap_file_sink>
{
auto operator()() const
{
return std::make_unique<posix_mmap_file_sink>();
}
};
#endif // POSIX
/*
* If boost if not enabled or not available fallback to system mmap
*/
using mmap_source_boost_type = std::conditional<IS_ENABLED(CONFIG_BOOST),
boost_memory_mapped_file_source,
system_mmap_file_source>::type;
using mmap_sink_boost_type = std::conditional<IS_ENABLED(CONFIG_BOOST),
boost_memory_mapped_file_sink,
system_mmap_file_sink>::type;
using mmap_source_type = std::conditional<IS_ENABLED(CONFIG_PREFER_BOOST_MMAP),
mmap_source_boost_type,
system_mmap_file_source>::type;
using mmap_sink_type = std::conditional<IS_ENABLED(CONFIG_PREFER_BOOST_MMAP),
mmap_sink_boost_type,
system_mmap_file_sink>::type;
std::unique_ptr<memory_mapped_file_source> memory_mapped_file_source::create()
{
return mmap_source_factory<mmap_source_type>()();
}
std::unique_ptr<memory_mapped_file_sink> memory_mapped_file_sink::create()
{
return mmap_sink_factory<mmap_sink_type>()();
}
| 26.201835 | 90 | 0.4993 | GregoryIstratov |
772da99d579715b5ed8d54c711413f99cfeab239 | 7,520 | cpp | C++ | examples/platforms/posix/ble_stub.cpp | CAJ2/openthread | 120aa72ff2268cce60f773219ebe9162d20f0b90 | [
"BSD-3-Clause"
] | null | null | null | examples/platforms/posix/ble_stub.cpp | CAJ2/openthread | 120aa72ff2268cce60f773219ebe9162d20f0b90 | [
"BSD-3-Clause"
] | null | null | null | examples/platforms/posix/ble_stub.cpp | CAJ2/openthread | 120aa72ff2268cce60f773219ebe9162d20f0b90 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements the CLI interpreter.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <openthread/error.h>
#include <openthread/instance.h>
#include <openthread/platform/ble.h>
#include <openthread/platform/toolchain.h>
#include <common/logging.hpp>
OT_TOOL_WEAK
void otPlatBleGapOnConnected(otInstance *aInstance, uint16_t aConnectionId)
{
(void)aInstance;
(void)aConnectionId;
otLogInfoBle("[API] %s id=%d", __func__, aConnectionId);
}
OT_TOOL_WEAK
void otPlatBleGapOnDisconnected(otInstance *aInstance, uint16_t aConnectionId)
{
(void)aInstance;
(void)aConnectionId;
otLogInfoBle("[API] %s id=%d", __func__, aConnectionId);
}
OT_TOOL_WEAK
void otPlatBleGapOnAdvReceived(otInstance *aInstance, otPlatBleDeviceAddr *aAddress, otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aAddress;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGapOnScanRespReceived(otInstance *aInstance, otPlatBleDeviceAddr *aAddress, otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aAddress;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnReadResponse(otInstance *aInstance, otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattServerOnReadRequest(otInstance *aInstance, uint16_t aHandle, otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aHandle;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnWriteResponse(otInstance *aInstance, uint16_t aHandle)
{
(void)aInstance;
(void)aHandle;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnSubscribeResponse(otInstance *aInstance, uint16_t aHandle)
{
(void)aInstance;
(void)aHandle;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnIndication(otInstance *aInstance, uint16_t aHandle, otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aHandle;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnServiceDiscovered(otInstance *aInstance,
uint16_t aStartHandle,
uint16_t aEndHandle,
uint16_t aServiceUuid,
otError aError)
{
(void)aInstance;
(void)aStartHandle;
(void)aEndHandle;
(void)aServiceUuid;
(void)aError;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnCharacteristicsDiscoverDone(otInstance * aInstance,
otPlatBleGattCharacteristic *aChars,
uint16_t aCount,
otError aError)
{
(void)aInstance;
(void)aChars;
(void)aCount;
(void)aError;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnDescriptorsDiscoverDone(otInstance * aInstance,
otPlatBleGattDescriptor *aDescs,
uint16_t aCount,
otError aError)
{
(void)aInstance;
(void)aDescs;
(void)aCount;
(void)aError;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattClientOnMtuExchangeResponse(otInstance *aInstance, uint16_t aMtu, otError aError)
{
(void)aInstance;
(void)aMtu;
(void)aError;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattServerOnIndicationConfirmation(otInstance *aInstance, uint16_t aHandle)
{
(void)aInstance;
(void)aHandle;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattServerOnWriteRequest(otInstance *aInstance, uint16_t aHandle, otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aHandle;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleGattServerOnSubscribeRequest(otInstance *aInstance, uint16_t aHandle, bool aSubscribing)
{
(void)aInstance;
(void)aHandle;
(void)aSubscribing;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleL2capOnSduReceived(otInstance * aInstance,
uint16_t aLocalCid,
uint16_t aPeerCid,
otBleRadioPacket *aPacket)
{
(void)aInstance;
(void)aLocalCid;
(void)aPeerCid;
(void)aPacket;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleL2capOnSduSent(otInstance *aInstance)
{
(void)aInstance;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleL2capOnConnectionRequest(otInstance *aInstance, uint16_t aPsm, uint16_t aMtu, uint16_t aPeerCid)
{
(void)aInstance;
(void)aPsm;
(void)aMtu;
(void)aPeerCid;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleL2capOnConnectionResponse(otInstance * aInstance,
otPlatBleL2capError aError,
uint16_t aMtu,
uint16_t aPeerCid)
{
(void)aInstance;
(void)aError;
(void)aMtu;
(void)aPeerCid;
otLogInfoBle("[API] %s", __func__);
}
OT_TOOL_WEAK
void otPlatBleL2capOnDisconnect(otInstance *aInstance, uint16_t aLocalCid, uint16_t aPeerCid)
{
(void)aInstance;
(void)aLocalCid;
(void)aPeerCid;
otLogInfoBle("[API] %s", __func__);
}
#ifdef __cplusplus
} // extern "C"
#endif
| 27.545788 | 116 | 0.653324 | CAJ2 |
772e8a733ed13ca3796de488e295342493c60d4c | 2,292 | cc | C++ | gcc-gcc-7_3_0-release/libvtv/testsuite/other-tests/dlopen_mt.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/libvtv/testsuite/other-tests/dlopen_mt.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/libvtv/testsuite/other-tests/dlopen_mt.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | #include <stdlib.h>
#include <dlfcn.h>
#include <stdio.h>
#include "vtv_utils.h"
#include "vtv_rts.h"
#include "pthread.h"
#define NUM_REPEATS 10
#define NUM_THREADS 10
#define NUM_SOS 100
#define NUM_SOS_PER_THREAD (NUM_SOS/NUM_THREADS)
typedef void (*voidfn)(void);
int failures = 0;
void
__vtv_verify_fail (void **data_set_ptr, const void *vtbl_pointer)
{
failures++;
return;
}
void do_dlopen(int so_num)
{
char so_name [sizeof("soxxx.so")];
sprintf(so_name, "so%d.so", so_num);
// printf("dl-opening %s\n", so_name);
void * dlhandle = dlopen(so_name, RTLD_NOW);
if (!dlhandle)
{
fprintf(stderr, "dlopen so:%s error: %s\n", so_name, dlerror());
exit(1);
}
char so_entry [sizeof("so_entry_xxx")];
sprintf(so_entry, "so_entry_%d", so_num);
voidfn so_entry_fn = (voidfn)dlsym(dlhandle, so_entry);
if (!so_entry_fn)
{
fprintf(stderr, "so:%s dlsym error: %s\n", so_name, dlerror());
exit(2);
}
so_entry_fn();
dlclose(dlhandle);
}
volatile int threads_completed_it = 0;
volatile int current_wave = -1;
void * do_dlopens(void * ptid)
{
for (int k = 0; k < NUM_REPEATS; k++)
{
for (int i = 0; i < NUM_SOS_PER_THREAD; i++)
{
while (current_wave < (k*NUM_SOS_PER_THREAD + i)) /* from 0 to 99 */
;
do_dlopen((NUM_SOS_PER_THREAD * *(int *)ptid) + i);
int old_value;
do {
old_value = threads_completed_it;
} while (!__sync_bool_compare_and_swap(&threads_completed_it, old_value, old_value + 1));
if (old_value == (NUM_THREADS - 1)) // Only one thread will do this.
{
threads_completed_it = 0;
printf("%c%d", 13, current_wave + 1);
fflush(stdout);
current_wave++;
}
}
}
return NULL;
}
int main()
{
pthread_t thread_ids[NUM_THREADS];
int thread_nids[NUM_THREADS];
for (int t = 0; t < NUM_THREADS; t++ )
{
thread_nids[t] = t;
if (pthread_create(&thread_ids[t], NULL, do_dlopens, &thread_nids[t]) != 0)
{
printf("failed pthread_create\n");
exit(1);
}
}
current_wave = 0; // start the work on the other threads
for (int t = 0; t < NUM_THREADS; t++)
if (pthread_join(thread_ids[t], NULL) != 0)
{
printf("failed pthread_join\n");
exit(2);
}
printf("\n");
return 0;
}
| 20.283186 | 92 | 0.624346 | best08618 |
772ebce74f6d6f6cf88ae89042c524213ec6c9e9 | 3,402 | cpp | C++ | sample/truss/sample_truss_totalstressdesign.cpp | PANFACTORY/PANSFEM2 | 5ca886a89ebac1df6449513149843d0721bce1b4 | [
"MIT"
] | 6 | 2021-01-28T08:51:08.000Z | 2022-01-06T23:19:27.000Z | sample/truss/sample_truss_totalstressdesign.cpp | PANFACTORY/PANSFEM2 | 5ca886a89ebac1df6449513149843d0721bce1b4 | [
"MIT"
] | 1 | 2020-08-30T10:42:54.000Z | 2020-09-01T07:28:11.000Z | sample/truss/sample_truss_totalstressdesign.cpp | PANFACTORY/PANSFEM2 | 5ca886a89ebac1df6449513149843d0721bce1b4 | [
"MIT"
] | 1 | 2021-09-22T00:31:55.000Z | 2021-09-22T00:31:55.000Z | #include <iostream>
#include <vector>
#include "../../src/LinearAlgebra/Models/Vector.h"
#include "../../src/PrePost/Mesher/GrandStructure.h"
#include "../../src/FEM/Controller/BoundaryCondition.h"
#include "../../src/FEM/Equation/Truss.h"
#include "../../src/FEM/Controller/Assembling.h"
#include "../../src/LinearAlgebra/Solvers/CG.h"
#include "../../src/PrePost/Export/ExportToVTK.h"
using namespace PANSFEM2;
int main() {
//********************Set design parameters********************
double A0 = 0.25; // Initial section [mm^2]
double E = 200000.0; // Young modulus [MPa]
double sigmat = 50.0; // Tensile strength [MPa]
double sigmac = 50.0; // Compressive strength [MPa]
//********************Set model datas********************
GrandStructure2D<double> mesh = GrandStructure2D<double>(4000.0, 2000.0, 4, 2, 1500);
std::vector<Vector<double> > x = mesh.GenerateNodes();
std::vector<std::vector<int> > elements = mesh.GenerateElements();
std::vector<std::pair<std::pair<int, int>, double> > ufixed = mesh.GenerateFixedlist({ 0, 1 }, [](Vector<double> _x){
if(abs(_x(0)) < 1.0e-5 && (abs(_x(1)) < 1.0e-5 || abs(_x(1) - 2000.0) < 1.0e-5)) {
return true;
}
return false;
});
std::vector<std::pair<std::pair<int, int>, double> > qfixed = mesh.GenerateFixedlist({ 1 }, [](Vector<double> _x){
if(abs(_x(0) - 4000.0) < 1.0e-5 && abs(_x(1) - 1000.0) < 1.0e-5) {
return true;
}
return false;
});
for(auto& qfixedi : qfixed) {
qfixedi.second = -5000.0;
}
std::vector<Vector<double> > u = std::vector<Vector<double> >(x.size(), Vector<double>(2));
std::vector<std::vector<int> > nodetoglobal = std::vector<std::vector<int> >(x.size(), std::vector<int>(2, 0));
std::vector<double> A = std::vector<double>(elements.size(), A0);
//********************Get displacement********************
SetDirichlet(u, nodetoglobal, ufixed);
int KDEGREE = Renumbering(nodetoglobal);
LILCSR<double> K = LILCSR<double>(KDEGREE, KDEGREE);
std::vector<double> F = std::vector<double>(KDEGREE, 0.0);
for(int i = 0; i < elements.size(); i++) {
std::vector<std::vector<std::pair<int, int> > > nodetoelement;
Matrix<double> Ke;
Truss2D<double>(Ke, nodetoelement, elements[i], { 0, 1 }, x, E, A[i]);
Assembling(K, F, u, Ke, nodetoglobal, nodetoelement, elements[i]);
}
Assembling(F, qfixed, nodetoglobal);
CSR<double> Kmod = CSR<double>(K);
std::vector<double> result = CG(Kmod, F, 100000, 1.0e-10);
Disassembling(u, result, nodetoglobal);
//********************Update ********************
for(int i = 0; i < elements.size(); i++) {
Vector<double> li = x[elements[i][1]] - x[elements[i][0]];
Vector<double> di = u[elements[i][1]] - u[elements[i][0]];
double fi = E*A[i]*di*li/pow(li.Norm(), 2.0);
if(fi > 0.0) {
A[i] = fi/sigmat;
} else {
A[i] = -fi/sigmac;
}
}
//********************Export datas********************
std::ofstream fout("sample/truss/result.vtk");
MakeHeadderToVTK(fout);
AddPointsToVTK(x, fout);
AddElementToVTK(elements, fout);
AddElementTypes(std::vector<int>(elements.size(), 3), fout);
AddPointVectors(u, "u", fout, true);
AddElementScalers(A, "A", fout, true);
fout.close();
return 0;
} | 37.8 | 121 | 0.566725 | PANFACTORY |
7730b84a349f6fb3551c12ac0141ca6904d56f67 | 6,493 | cc | C++ | source/LibMultiSense/details/flash.cc | DArpinoRobotics/libmultisense | d3ed760c26762eabf3d9875a2379ff435b4f4be3 | [
"Unlicense"
] | null | null | null | source/LibMultiSense/details/flash.cc | DArpinoRobotics/libmultisense | d3ed760c26762eabf3d9875a2379ff435b4f4be3 | [
"Unlicense"
] | null | null | null | source/LibMultiSense/details/flash.cc | DArpinoRobotics/libmultisense | d3ed760c26762eabf3d9875a2379ff435b4f4be3 | [
"Unlicense"
] | null | null | null | /**
* @file LibMultiSense/details/flash.cc
*
* Copyright 2013
* Carnegie Robotics, LLC
* 4501 Hatfield Street, Pittsburgh, PA 15201
* http://www.carnegierobotics.com
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Carnegie Robotics, LLC nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CARNEGIE ROBOTICS, LLC 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.
*
* Significant history (date, user, job code, action):
* 2013-05-15, ekratzer@carnegierobotics.com, PR1044, Created file.
**/
#include "details/channel.hh"
#include "details/query.hh"
#include "details/wire/AckMessage.h"
#include "details/wire/SysFlashOpMessage.h"
#include "details/wire/SysFlashResponseMessage.h"
namespace crl {
namespace multisense {
namespace details {
//
// Erase a flash region
void impl::eraseFlashRegion(uint32_t region)
{
wire::SysFlashResponse response;
//
// Start the erase operation
Status status = waitData(wire::SysFlashOp(wire::SysFlashOp::OP_ERASE, region),
response);
if (Status_Ok != status)
CRL_EXCEPTION("OP_ERASE failed: %d", status);
//
// Check for success, or flash in progress
switch(response.status) {
case wire::SysFlashResponse::STATUS_SUCCESS:
case wire::SysFlashResponse::STATUS_ERASE_IN_PROGRESS:
break; // ok, erase is happening
default:
CRL_EXCEPTION("OP_ERASE ack'd, but failed: %d\n", response.status);
}
//
// Wait for the erase to complete
const double ERASE_TIMEOUT = 210.0; // seconds
utility::TimeStamp start = utility::TimeStamp::getCurrentTime();
int prevProgress = -1;
while((utility::TimeStamp::getCurrentTime() - start) < ERASE_TIMEOUT) {
//
// Request current progress
status = waitData(wire::SysFlashOp(), response);
if (Status_Ok != status)
CRL_EXCEPTION("failed to request flash erase status");
//
// IDLE means the flash has been erased
if (wire::SysFlashResponse::STATUS_IDLE == response.status)
return; // success
//
// Prompt and delay a bit
if (response.erase_progress != prevProgress &&
0 == (response.erase_progress % 5))
CRL_DEBUG("erasing... %3d%%\n", response.erase_progress);
usleep(100000);
prevProgress = response.erase_progress;
}
CRL_EXCEPTION("erase op timed out after %.0f seconds", ERASE_TIMEOUT);
}
//
// Program or verify a flash region from a file
void impl::programOrVerifyFlashRegion(std::ifstream& file,
uint32_t operation,
uint32_t region)
{
//
// Get file size
file.seekg(0, file.end);
std::streamoff fileLength = file.tellg();
file.seekg(0, file.beg);
wire::SysFlashOp op(operation, region, 0,
wire::SysFlashOp::MAX_LENGTH);
int prevProgress = -1;
const char *opNameP;
switch(operation) {
case wire::SysFlashOp::OP_PROGRAM: opNameP = "programming"; break;
case wire::SysFlashOp::OP_VERIFY: opNameP = "verifying"; break;
default:
CRL_EXCEPTION("unknown operation type: %d", operation);
}
do {
//
// Initialize data and read next chunk
memset(op.data, 0xFF, op.length);
file.read((char *) op.data, op.length);
//
// Send command, await response
wire::SysFlashResponse rsp;
Status status = waitData(op, rsp, 0.5, 4);
if (Status_Ok != status)
CRL_EXCEPTION("SysFlashOp (%s) failed: %d", opNameP, status);
else if (wire::SysFlashResponse::STATUS_SUCCESS != rsp.status)
CRL_EXCEPTION("%s failed @ %d/%d bytes", opNameP,
file.tellg(), fileLength);
//
// Print out progress
int progress = static_cast<int> ((100 * op.start_address) / fileLength);
if (progress != prevProgress && 0 == (progress % 5))
CRL_DEBUG("%s... %3d%%\n", opNameP, progress);
//
// Update state
prevProgress = progress;
op.start_address += op.length;
} while (!file.eof());
if ((int) op.start_address < fileLength)
CRL_EXCEPTION("unexpected EOF while %s", opNameP);
CRL_DEBUG("%s complete\n", opNameP);
}
//
// Wrapper for all flash operations
Status impl::doFlashOp(const std::string& filename,
uint32_t operation,
uint32_t region)
{
try {
std::ifstream file(filename.c_str(),
std::ios::in | std::ios::binary);
if (!file.good())
CRL_EXCEPTION("unable to open file: \"%s\"",
filename.c_str());
if (wire::SysFlashOp::OP_PROGRAM == operation)
eraseFlashRegion(region);
programOrVerifyFlashRegion(file, operation, region);
} catch (const std::exception& e) {
CRL_DEBUG("exception: %s\n", e.what());
return Status_Exception;
}
return Status_Ok;
}
}}}; // namespaces
| 30.919048 | 82 | 0.630833 | DArpinoRobotics |
77355e54b6042162562346981da3997f1f648ba6 | 3,476 | hpp | C++ | libraries/plugins/activenode/include/graphene/activenode/activenode.hpp | district1/tyslin-core | 4ad5592e29e07ccc466a232f4b407c0d7ef105dd | [
"MIT"
] | 8 | 2019-05-20T00:50:41.000Z | 2019-12-17T23:50:03.000Z | libraries/plugins/activenode/include/graphene/activenode/activenode.hpp | jacekdalecki84/LocalCoin-core | 9ffa8785a305c730257690ca274533cc69c0560d | [
"MIT"
] | 3 | 2019-07-17T18:42:29.000Z | 2022-02-18T00:21:20.000Z | libraries/plugins/activenode/include/graphene/activenode/activenode.hpp | jacekdalecki84/LocalCoin-core | 9ffa8785a305c730257690ca274533cc69c0560d | [
"MIT"
] | 7 | 2019-04-11T14:20:15.000Z | 2022-01-20T15:06:57.000Z | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <fc/thread/future.hpp>
#include <fc/optional.hpp>
namespace graphene { namespace activenode_plugin {
using namespace fc;
using namespace chain;
namespace activenode_condition
{
enum activenode_condition_enum
{
performed_activity = 0,
not_synced = 1,
not_my_turn = 2,
not_time_yet = 3,
no_private_key = 4,
lag = 5,
no_scheduled_activenodes = 6,
deleted = 7,
not_sending = 8,
exception_perform_activity = 9
};
}
class activenode_plugin : public graphene::app::plugin {
public:
~activenode_plugin() {
try {
if( _activity_task.valid() )
_activity_task.cancel_and_wait(__FUNCTION__);
} catch(fc::canceled_exception&) {
//Expected exception. Move along.
} catch(fc::exception& e) {
edump((e.to_detail_string()));
}
}
std::string plugin_name()const override;
virtual void plugin_set_program_options(
boost::program_options::options_description &command_line_options,
boost::program_options::options_description &config_file_options
) override;
void set_activenode_plugin_enabled(bool allow) { _activenode_plugin_enabled = allow; }
virtual void plugin_initialize( const boost::program_options::variables_map& options ) override;
virtual void plugin_startup() override;
virtual void plugin_shutdown() override;
private:
void schedule_activity_loop();
void on_new_block_applied(const signed_block& new_block);
activenode_condition::activenode_condition_enum activity_loop();
activenode_condition::activenode_condition_enum maybe_send_activity( fc::limited_mutable_variant_object& capture );
activenode_condition::activenode_condition_enum send_activity( fc::limited_mutable_variant_object& capture );
boost::program_options::variables_map _options;
bool _activenode_plugin_enabled = true;
std::pair<chain::public_key_type, fc::ecc::private_key> _private_key;
optional<chain::activenode_id_type> _activenode = optional<chain::activenode_id_type>();
std::string _activenode_account_name;
chain::account_id_type _activenode_account_id;
fc::future<void> _activity_task;
};
} } //graphene::activenode_plugin
| 35.469388 | 118 | 0.743671 | district1 |
7740256b51351f4881c05b33d494a513ff2cf626 | 1,438 | cpp | C++ | dbms/src/DataStreams/MergingAggregatedBlockInputStream.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 85 | 2022-03-25T09:03:16.000Z | 2022-03-25T09:45:03.000Z | dbms/src/DataStreams/MergingAggregatedBlockInputStream.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 7 | 2022-03-25T08:59:10.000Z | 2022-03-25T09:40:13.000Z | dbms/src/DataStreams/MergingAggregatedBlockInputStream.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 11 | 2022-03-25T09:15:36.000Z | 2022-03-25T09:45:07.000Z | // Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Columns/ColumnsNumber.h>
#include <DataStreams/MergingAggregatedBlockInputStream.h>
namespace DB
{
Block MergingAggregatedBlockInputStream::getHeader() const
{
return aggregator.getHeader(final);
}
Block MergingAggregatedBlockInputStream::readImpl()
{
if (!executed)
{
executed = true;
AggregatedDataVariants data_variants;
Aggregator::CancellationHook hook = [&]() { return this->isCancelled(); };
aggregator.setCancellationHook(hook);
aggregator.mergeStream(children.back(), data_variants, max_threads);
blocks = aggregator.convertToBlocks(data_variants, final, max_threads);
it = blocks.begin();
}
Block res;
if (isCancelledOrThrowIfKilled() || it == blocks.end())
return res;
res = std::move(*it);
++it;
return res;
}
}
| 25.678571 | 82 | 0.700974 | solotzg |
7744ac9c2457c9e52ff425bfcc6a79a27d828f58 | 5,828 | cpp | C++ | Sources_Common/HTTP/HTTPClient/CHTTPAuthorizationDigest.cpp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Sources_Common/HTTP/HTTPClient/CHTTPAuthorizationDigest.cpp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Sources_Common/HTTP/HTTPClient/CHTTPAuthorizationDigest.cpp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007-2009 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
CHTTPAuthorizationDigest.cpp
Author:
Description: <describe the CHTTPAuthorizationDigest class here>
*/
#include "CHTTPAuthorizationDigest.h"
#include "CStringUtils.h"
#include "CHTTPDefinitions.h"
#include "CHTTPRequestResponse.h"
#include "base64.h"
#include "md5.h"
#include <memory>
#include <stdio.h>
using namespace http;
void CHTTPAuthorizationDigest::GenerateAuthorization(std::ostream& os, const CHTTPRequestResponse* request) const
{
// Generate response
const_cast<CHTTPAuthorizationDigest*>(this)->GenerateResponse(request);
// Generate header
if (mQop.empty())
{
os << cHeaderAuthorization << cHeaderDelimiter << "Digest "
<< "username=\"" << mUser << "\"," << net_endl
<< " realm=\"" << mRealm << "\"," << net_endl
<< " nonce=\"" << mNonce << "\"," << net_endl
<< " uri=\"" << request->GetRURI() << "\"," << net_endl
<< " response=\"" << mResponse << "\"";
}
else
{
os << cHeaderAuthorization << cHeaderDelimiter << "Digest "
<< "username=\"" << mUser << "\"," << net_endl
<< " realm=\"" << mRealm << "\"," << net_endl
<< " nonce=\"" << mNonce << "\"," << net_endl
<< " uri=\"" << request->GetRURI() << "\"," << net_endl
<< " qop=auth," << net_endl
<< " nc=" << mNC << "," << net_endl
<< " cnonce=\"" << mCnonce << "\"," << net_endl
<< " response=\"" << mResponse << "\"";
}
if (mAlgorithm.length() != 0)
os << "," << net_endl << " algorithm=\"" << mAlgorithm << "\"";
if (mOpaque.length() != 0)
os << "," << net_endl << " opaque=\"" << mOpaque << "\"";
os << net_endl;
}
void CHTTPAuthorizationDigest::ParseAuthenticateHeader(const cdstrvect& hdrs)
{
for(cdstrvect::const_iterator iter = hdrs.begin(); iter != hdrs.end(); iter++)
{
// Strip any space
cdstring temp(*iter);
char* p = temp.c_str_mod();
// Must have digest token
if (::stradvtokcmp(&p, "Digest") != 0)
continue;
// Get each name/value pair
while(true)
{
char* name = ::strgettokenstr(&p, SPACE_TAB "=");
if ((name == NULL) || (*p == 0))
return;
char* value = ::strgettokenstr(&p, SPACE_TAB ",");
if (value == NULL)
return;
if (::strcmpnocase(name, "realm") == 0)
{
mRealm = value;
}
else if (::strcmpnocase(name, "domain") == 0)
{
mDomain = value;
}
else if (::strcmpnocase(name, "nonce") == 0)
{
mNonce = value;
}
else if (::strcmpnocase(name, "opaque") == 0)
{
mOpaque = value;
}
else if (::strcmpnocase(name, "stale") == 0)
{
mStale = (::strcmpnocase(value, "false") != 0);
}
else if (::strcmpnocase(name, "algorithm") == 0)
{
mAlgorithm = value;
}
else if (::strcmpnocase(name, "qop") == 0)
{
mQop = value;
}
else
{
// Unknown token - ignore
}
// Punt over comma
while((*p != 0) && (*p == ','))
p++;
}
break;
}
}
void _H(unsigned char* , char*, unsigned long);
void _H(unsigned char* digest, char* s, unsigned long s_len)
{
MD5_CTX ctx;
MD5Init(&ctx);
MD5Update(&ctx, (unsigned char*) s, s_len);
MD5Final(digest, &ctx);
}
void _KD(unsigned char*, char*, char*);
void _KD(unsigned char* digest, char* k, char* s)
{
std::auto_ptr<char> p(new char[::strlen(k) + ::strlen(s) + 2]);
::strcpy(p.get(), k);
::strcat(p.get(), ":");
::strcat(p.get(), s);
_H(digest, p.get(), ::strlen(p.get()));
}
void _TOHEX(char*, unsigned char*);
void _TOHEX(char* digest_hex, unsigned char* digest)
{
for(int i = 0; i < 16; i++)
{
unsigned char lo_q = digest[i];
unsigned char hi_q = (lo_q >> 4);
lo_q = lo_q & 0xF;
digest_hex[2*i] = hi_q + ((hi_q >= 0xA) ? ('a' - 0x0A) : '0');
digest_hex[2*i + 1] = lo_q + ((lo_q >= 0xA) ? ('a' - 0x0A) : '0');
}
digest_hex[2*16] = 0;
}
void CHTTPAuthorizationDigest::GenerateResponse(const CHTTPRequestResponse* request)
{
if (mQop.empty())
{
// Clear out old values
mNC.clear();
mCnonce.clear();
}
else
{
// Generate nc-count
++mClientCount;
mNC.clear();
mNC.reserve(256);
::snprintf(mNC.c_str_mod(), 256, "%08x", mClientCount);
mCnonce = mNC;
mCnonce += mUser;
mCnonce += mPswd;
mCnonce += mRealm;
mCnonce.md5(mCnonce);
}
// Determine HA1
unsigned char digest[16];
cdstring A1;
A1 = mUser;
A1 += ":";
A1 += mRealm;
A1 += ":";
A1 += mPswd;
_H(digest, A1, A1.length());
if (mAlgorithm == "MD5-sess")
{
cdstring data = "XXXXXXXXXXXXXXXX";
data += ":";
data += mNonce;
data += ":";
data += mCnonce;
cdstring::size_type datalen = data.length();
::memcpy(data.c_str_mod(), digest, 16);
_H(digest, data, datalen);
}
cdstring HA1;
HA1.reserve(32);
_TOHEX(HA1, digest);
// Determine HA2
cdstring A2;
A2 = request->GetMethod();
A2 += ":";
A2 += request->GetRURI();
if (mQop == "auth-int")
{
// Ughh we do not do this right now
// Hash the body
}
_H(digest, A2, A2.length());
cdstring HA2;
HA2.reserve(32);
_TOHEX(HA2, digest);
// Now do KD...
cdstring sval;
sval = mNonce;
sval += ":";
if (!mQop.empty())
{
sval += mNC;
sval += ":";
sval += mCnonce;
sval += ":";
sval += mQop;
sval += ":";
}
sval += HA2;
_KD(digest, HA1, sval);
mResponse.clear();
mResponse.reserve(32);
_TOHEX(mResponse, digest);
}
| 22.765625 | 113 | 0.590597 | mulberry-mail |
7746185f4742e46753a900c16c6d6e56806cae65 | 3,408 | cpp | C++ | PebblesGameofLife/src/events.cpp | NicholasHallman/PebblesGameOfLife | d198fb46030a79b2918fcef3d62268919e89f672 | [
"MIT"
] | 2 | 2019-12-08T12:41:01.000Z | 2021-01-25T22:31:47.000Z | PebblesGameofLife/src/events.cpp | NicholasHallman/PebblesGameOfLife | d198fb46030a79b2918fcef3d62268919e89f672 | [
"MIT"
] | null | null | null | PebblesGameofLife/src/events.cpp | NicholasHallman/PebblesGameOfLife | d198fb46030a79b2918fcef3d62268919e89f672 | [
"MIT"
] | null | null | null | /*
* events.cpp
*
* Created on: Nov 23, 2017
* Author: Nicholas Hallman
* Omid Ghiyasian
*/
#include"events.hpp"
int speedX = 0;
int speedY = 0;
int runs = 0;
void mouseOver(int x, int y){
y = 768 - y;
int change = 0;
int index = buttonOver(x, y);
if(index != -1){
glutSetCursor(GLUT_CURSOR_CROSSHAIR);
change = 1;
buttons[index].hover = true;
glutPostRedisplay();
} else{
resetHover();
}
if(change == 0){
glutSetCursor(GLUT_CURSOR_INHERIT);
glutPostRedisplay();
}
}
void mouseClicked(int button, int state, int x, int y){
bool leftC = false;
bool rightC = false;
if(button == 0 && state == 1) leftC = true;
if(button == 2 && state == 1) rightC = true;
if(leftC && colorW){
glReadPixels(x,768 - y,1,1,GL_RGB,GL_FLOAT, colors);
colorW = false;
}
y = 768 - y;
int index = buttonOver(x,y);
if(index != -1 && leftC){
buttons[index].clicked();
}
if(pState == 2 && leftC && y < 730 && !colorW){
int relX = floor(x - ( floor(1366 - (CSIZE * map.size))/2) - map.x) / CSIZE;
int relY = floor(y - ( floor((768 - (CSIZE * map.size))/2) - 18) - map.y) / CSIZE;
if(relX >= 0 && relX < map.size && relY >= 0 && relY < map.size){
if(map.cells[relX][relY].newState == 1){
map.cells[relX][relY].newState = 0;
} else{
map.cells[relX][relY].newState = 1;
}
}
}
if((pState == 2 || pState == 3) && rightC){
map.x = 0;
map.y = 0;
}
}
void keyPress(unsigned char key, int x, int y){
if(pState == 2 || pState == 3 || pState == 6){
switch(key){
case 'w':
speedY = -4;
break;
case 's':
speedY = 4;
break;
case 'd':
speedX = -4;
break;
case 'a':
speedX = 4;
break;
}
}
}
void keyRelease(unsigned char key, int x, int y){
if(pState == 2 || pState == 3 || pState == 6){
switch(key){
case 's':
case 'w':
speedY = 0;
break;
case 'a':
case 'd':
speedX = -0;
break;
}
}
}
int buttonOver(int x, int y){
for(int i = 0; i < 20; i++){
if(buttons[i].active){
int posX = buttons[i].position.x;
int posY = buttons[i].position.y;
int wide = buttons[i].rWidth;
if(x > posX && x < posX + wide && y > posY && y < posY + 26){
return i;
}
}
}
return -1;
}
void timer(int x){
GLfloat rx;
GLfloat ry;
GLfloat rz;
runs ++;
if(pState == 2 || pState == 3){
map.x += speedX;
map.y += speedY;
} else if(pState == 6){
if(speedX > 0) speedX = 1;
if(speedX < 0) speedX = -1;
if(speedY > 0) speedY = 1;
if(speedY < 0) speedY = -1;
myCamera.rotate(speedY, speedX, 0.0, 0.5);
}
if(runs == 10){
runs = 0;
if(pState == 6){
simulate3D();
} else{
simulate2D();
}
}
if(pState == 5){
rx = myWorld.torus[0]->getMC().matrix[0][0];
ry = myWorld.torus[0]->getMC().matrix[1][0];
rz = myWorld.torus[0]->getMC().matrix[2][0];
myWorld.torus[0]->rotate_mc(rx,ry,rz,0.3);
rx = myWorld.torus[0]->getMC().matrix[0][1];
ry = myWorld.torus[0]->getMC().matrix[1][1];
rz = myWorld.torus[0]->getMC().matrix[2][1];
myWorld.torus[0]->rotate_mc(rx,ry,rz,0.5);
rx = myWorld.torus[0]->getMC().matrix[0][2];
ry = myWorld.torus[0]->getMC().matrix[1][2];
rz = myWorld.torus[0]->getMC().matrix[2][2];
myWorld.torus[0]->rotate_mc(rx,ry,rz,0.);
}
if (x)
glutPostRedisplay();
glutTimerFunc(16, timer, x);
}
void resetHover(){
for(int i = 0; i < 20; i++){
if(buttons[i].position.x != -1){
buttons[i].hover = false;
}
}
}
| 19.146067 | 85 | 0.561913 | NicholasHallman |
77485cf0749e102ac8fbf1a459e2682b643e644e | 1,779 | hpp | C++ | mpllibs/metamonad/v1/impl/match_boxed_impl.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 70 | 2015-01-15T09:05:15.000Z | 2021-12-08T15:49:31.000Z | mpllibs/metamonad/v1/impl/match_boxed_impl.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 4 | 2015-06-18T19:25:34.000Z | 2016-05-13T19:49:51.000Z | mpllibs/metamonad/v1/impl/match_boxed_impl.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 5 | 2015-07-10T08:18:09.000Z | 2021-12-01T07:17:57.000Z | #ifndef MPLLIBS_METAMONAD_V1_IMPL_MATCH_BOXED_IMPL_HPP
#define MPLLIBS_METAMONAD_V1_IMPL_MATCH_BOXED_IMPL_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <mpllibs/metamonad/v1/impl/lazy_match_c_impl.hpp>
#include <mpllibs/metamonad/v1/impl/merge_map.hpp>
#include <mpllibs/metamonad/v1/is_exception.hpp>
#include <mpllibs/metamonad/v1/metafunction.hpp>
#include <mpllibs/metamonad/v1/unbox.hpp>
#include <mpllibs/metamonad/v1/lambda_c.hpp>
#include <mpllibs/metamonad/v1/name.hpp>
#include <mpllibs/metamonad/v1/if_.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/zip_view.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/back.hpp>
namespace mpllibs
{
namespace metamonad
{
namespace v1
{
namespace impl
{
// Elements of Ps and Vs are boxed because Ps or Vs may contain mpl::na
// in which case Ps and Vs have different sizes and zip_view can not
// handle that.
MPLLIBS_V1_METAFUNCTION(match_boxed_impl, (Ps)(Vs))
((
boost::mpl::fold<
boost::mpl::zip_view<boost::mpl::vector<Ps, Vs> >,
boost::mpl::map<>,
lambda_c<s, p,
if_<
is_exception<s>,
s,
merge_map<
s,
impl::lazy_match_c_impl<
unbox<boost::mpl::front<p> >,
unbox<boost::mpl::back<p> >
>
>
>
>
>
));
}
}
}
}
#endif
| 28.238095 | 79 | 0.605396 | sabel83 |
774ef12ba7d744a60fdbef0a4283c54a8f1f3ae5 | 31,705 | cpp | C++ | code/cray_dx_renderer.cpp | ALEXMORF/cray | ebf61b37ccde690081648f3408c6c5963bdd43c6 | [
"MIT"
] | 36 | 2019-01-13T02:37:45.000Z | 2021-09-22T02:27:49.000Z | code/cray_dx_renderer.cpp | ALEXMORF/cray | ebf61b37ccde690081648f3408c6c5963bdd43c6 | [
"MIT"
] | null | null | null | code/cray_dx_renderer.cpp | ALEXMORF/cray | ebf61b37ccde690081648f3408c6c5963bdd43c6 | [
"MIT"
] | 5 | 2019-01-12T20:09:32.000Z | 2022-02-03T18:06:40.000Z | #include <imgui_impl_dx11.cpp>
//#include "cray_hlsl_code.h"
internal ID3DBlob *
CompileDXShaderFromFile(LPCWSTR Path, char *EntryPoint, char *Target, UINT Flags)
{
ID3DBlob *CompiledCode = 0;
ID3DBlob *ShaderError = 0;
HRESULT CompiledShader = D3DCompileFromFile(Path, 0,
0, EntryPoint,
Target, Flags,
0, &CompiledCode,
&ShaderError);
if (FAILED(CompiledShader))
{
Panic("%s Error: %s", Target, (char *)ShaderError->GetBufferPointer());
}
return CompiledCode;
}
internal ID3DBlob *
CompileDXShader(char *Name, char *SourceCode,
char *EntryPoint, char *Target, UINT Flags)
{
ID3DBlob *CompiledCode = 0;
ID3DBlob *ShaderError = 0;
HRESULT CompiledShader = D3DCompile(SourceCode,
strlen(SourceCode),
Name, 0, 0,
EntryPoint, Target,
Flags, 0, &CompiledCode,
&ShaderError);
if (FAILED(CompiledShader))
{
Panic("%s Error: %s", Target, (char *)ShaderError->GetBufferPointer());
}
return CompiledCode;
}
internal ID3D11VertexShader *
CreateDXVS(ID3D11Device1 *Device, char *Name, char *SourceCode,
char *EntryPoint, UINT CompilerFlags)
{
ID3D11VertexShader *VS = 0;
ID3DBlob *VSCode = CompileDXShader(Name, SourceCode, EntryPoint,
"vs_5_0", CompilerFlags);
HRESULT CreatedShader = Device->CreateVertexShader(VSCode->GetBufferPointer(),
VSCode->GetBufferSize(), 0, &VS);
ASSERT(SUCCEEDED(CreatedShader));
VSCode->Release();
return VS;
}
internal ID3D11PixelShader *
CreateDXPS(ID3D11Device1 *Device, char *Name, char *SourceCode,
char *EntryPoint, UINT CompilerFlags)
{
ID3D11PixelShader *PS = 0;
ID3DBlob *PSCode = CompileDXShader(Name, SourceCode, EntryPoint,
"ps_5_0", CompilerFlags);
HRESULT CreatedShader = Device->CreatePixelShader(PSCode->GetBufferPointer(),
PSCode->GetBufferSize(), 0, &PS);
ASSERT(SUCCEEDED(CreatedShader));
PSCode->Release();
return PS;
}
internal ID3D11Buffer *
CreateDynamicConstantBuffer(ID3D11Device1 *Device, void *Data, UINT DataSize)
{
ID3D11Buffer *Buffer = 0;
D3D11_BUFFER_DESC BufferDesc = {};
BufferDesc.ByteWidth = DataSize;
BufferDesc.Usage = D3D11_USAGE_DYNAMIC;
BufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA InitialData = {};
InitialData.pSysMem = Data;
HRESULT CreatedBuffer = Device->CreateBuffer(&BufferDesc, &InitialData, &Buffer);
ASSERT(SUCCEEDED(CreatedBuffer));
return Buffer;
}
internal dx_render_target
CreateDXRenderTarget(ID3D11Device1 *Device, int Width, int Height,
DXGI_FORMAT Format)
{
dx_render_target RenderTarget = {};
D3D11_TEXTURE2D_DESC TextureDesc = {};
TextureDesc.Width = Width;
TextureDesc.Height = Height;
TextureDesc.MipLevels = 1;
TextureDesc.ArraySize = 1;
TextureDesc.Format = Format;
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_DEFAULT;
TextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET|D3D11_BIND_SHADER_RESOURCE;
TextureDesc.CPUAccessFlags = 0;
TextureDesc.MiscFlags = 0;
HRESULT CreatedTexture = Device->CreateTexture2D(&TextureDesc, 0,
&RenderTarget.Tex);
ASSERT(SUCCEEDED(CreatedTexture));
HRESULT CreatedRTV = Device->CreateRenderTargetView(RenderTarget.Tex,
0, &RenderTarget.RTV);
ASSERT(SUCCEEDED(CreatedRTV));
HRESULT CreatedRV = Device->CreateShaderResourceView(RenderTarget.Tex, 0,
&RenderTarget.SRV);
ASSERT(SUCCEEDED(CreatedRV));
return RenderTarget;
}
internal void
Release(dx_render_target *RenderTarget)
{
RenderTarget->Tex->Release();
RenderTarget->RTV->Release();
RenderTarget->SRV->Release();
*RenderTarget = {};
}
internal void
Refresh(dx_renderer *Renderer)
{
Renderer->Context.SampleCountSoFar = 0;
}
internal void
CreateWindowSizeCoupledResources(dx_renderer *Renderer)
{
ID3D11Device1 *Device = Renderer->Device;
HRESULT GotBackBuffer = Renderer->SwapChain->GetBuffer(0, IID_PPV_ARGS(&Renderer->BackBuffer));
ASSERT(SUCCEEDED(GotBackBuffer));
HRESULT CreatedBackBufferRTV = Device->CreateRenderTargetView(Renderer->BackBuffer,
0, &Renderer->BackBufferView);
ASSERT(SUCCEEDED(CreatedBackBufferRTV));
D3D11_TEXTURE2D_DESC BackBufferDesc = {};
Renderer->BackBuffer->GetDesc(&BackBufferDesc);
int ClientWidth = BackBufferDesc.Width;
int ClientHeight = BackBufferDesc.Height;
for (int BufferIndex = 0; BufferIndex < 2; ++BufferIndex)
{
Renderer->SamplerBuffers[BufferIndex] = CreateDXRenderTarget(
Device, ClientWidth, ClientHeight,
DXGI_FORMAT_R32G32B32A32_FLOAT);
}
Renderer->PositionBuffer = CreateDXRenderTarget(Device,
ClientWidth, ClientHeight,
DXGI_FORMAT_R32G32B32A32_FLOAT);
Renderer->NormalBuffer = CreateDXRenderTarget(Device,
ClientWidth, ClientHeight,
DXGI_FORMAT_R32G32B32A32_FLOAT);
//TODO(chen): compress these when we have a material system in place
Renderer->AlbedoBuffer = CreateDXRenderTarget(Device,
ClientWidth, ClientHeight,
DXGI_FORMAT_B8G8R8A8_UNORM);
Renderer->EmissionBuffer = CreateDXRenderTarget(Device,
ClientWidth, ClientHeight,
DXGI_FORMAT_R32G32B32A32_FLOAT);
// depth stencil buffer
{
D3D11_TEXTURE2D_DESC DepthStencilBufferDesc = {};
DepthStencilBufferDesc.Width = ClientWidth;
DepthStencilBufferDesc.Height = ClientHeight;
DepthStencilBufferDesc.MipLevels = 1;
DepthStencilBufferDesc.ArraySize = 1;
DepthStencilBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
DepthStencilBufferDesc.SampleDesc.Count = 1;
DepthStencilBufferDesc.SampleDesc.Quality = 0;
DepthStencilBufferDesc.Usage = D3D11_USAGE_DEFAULT;
DepthStencilBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
HRESULT CreatedDepthStencil = Device->CreateTexture2D(&DepthStencilBufferDesc, 0, &Renderer->DepthStencilBuffer);
ASSERT(SUCCEEDED(CreatedDepthStencil));
D3D11_DEPTH_STENCIL_VIEW_DESC DepthStencilViewDesc = {};
DepthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
DepthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
HRESULT CreatedDepthStencilView = Device->CreateDepthStencilView(Renderer->DepthStencilBuffer, &DepthStencilViewDesc, &Renderer->DepthStencilView);
ASSERT(SUCCEEDED(CreatedDepthStencilView));
}
}
internal void
SetViewport(dx_renderer *Renderer, int Width, int Height)
{
D3D11_VIEWPORT Viewport = {};
Viewport.Width = (f32)Width;
Viewport.Height = (f32)Height;
Viewport.MinDepth = 0.0f;
Viewport.MaxDepth = 1.0f;
Renderer->DeviceContext->RSSetViewports(1, &Viewport);
}
internal void
SetPersistentStates(dx_renderer *Renderer, int Width, int Height)
{
ID3D11DeviceContext1 *DeviceContext = Renderer->DeviceContext;
ID3D11Buffer *ConstantBuffers[] = {
Renderer->SettingsBuffer,
Renderer->CameraBuffer,
Renderer->ContextBuffer,
};
DeviceContext->VSSetConstantBuffers(0, ARRAY_COUNT(ConstantBuffers),
ConstantBuffers);
DeviceContext->PSSetConstantBuffers(0, ARRAY_COUNT(ConstantBuffers),
ConstantBuffers);
DeviceContext->IASetInputLayout(0);
DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
DeviceContext->VSSetShader(Renderer->FullscreenVS, 0, 0);
DeviceContext->PSSetSamplers(0, 1, &Renderer->PointSampler);
SetViewport(Renderer, Width, Height);
DeviceContext->RSSetState(Renderer->RasterizerState);
}
internal dx_renderer
InitDXRenderer(HWND Window, camera *Camera, int Width, int Height)
{
dx_renderer Renderer = {};
Renderer.Width = Width;
Renderer.Height = Height;
clock_t BeginClock = clock();
ID3D11Device *TempDevice = 0;
ID3D11DeviceContext *TempDeviceContext = 0;
D3D_FEATURE_LEVEL FeatureLevels[] = {
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT DeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if CRAY_DEBUG
DeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
HRESULT CreatedDevice = D3D11CreateDevice(0,
D3D_DRIVER_TYPE_HARDWARE,
0, DeviceFlags,
FeatureLevels, ARRAY_COUNT(FeatureLevels),
D3D11_SDK_VERSION, &TempDevice,
0, &TempDeviceContext);
ASSERT(SUCCEEDED(CreatedDevice));
TempDevice->QueryInterface(IID_PPV_ARGS(&Renderer.Device));
TempDeviceContext->QueryInterface(IID_PPV_ARGS(&Renderer.DeviceContext));
#if CRAY_DEBUG
HRESULT GotDebug = Renderer.Device->QueryInterface(IID_PPV_ARGS(&Renderer.Debug));
ASSERT(SUCCEEDED(GotDebug));
HRESULT GotInfoQueue = Renderer.Debug->QueryInterface(IID_PPV_ARGS(&Renderer.InfoQueue));
ASSERT(SUCCEEDED(GotInfoQueue));
HRESULT TurnedOn = S_OK;
TurnedOn = Renderer.InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
ASSERT(SUCCEEDED(TurnedOn));
TurnedOn = Renderer.InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true);
ASSERT(SUCCEEDED(TurnedOn));
TurnedOn = Renderer.InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, true);
ASSERT(SUCCEEDED(TurnedOn));
TurnedOn = Renderer.InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_INFO, true);
ASSERT(SUCCEEDED(TurnedOn));
TurnedOn = Renderer.InfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_MESSAGE, true);
ASSERT(SUCCEEDED(TurnedOn));
#endif
ID3D11Device1 *Device = Renderer.Device;
ID3D11DeviceContext1 *DeviceContext = Renderer.DeviceContext;
IDXGIFactory2 *Factory = 0;
IDXGIDevice1 *DXGIDevice = 0;
IDXGIAdapter *Adapter = 0;
Device->QueryInterface(IID_PPV_ARGS(&DXGIDevice));
DXGIDevice->GetAdapter(&Adapter);
Adapter->GetParent(IID_PPV_ARGS(&Factory));
DXGI_SWAP_CHAIN_DESC1 SwapChainDesc = {};
SwapChainDesc.Width = 0; // use window width
SwapChainDesc.Height = 0; // use window height
SwapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
SwapChainDesc.Stereo = false;
SwapChainDesc.SampleDesc.Count = 1;
SwapChainDesc.SampleDesc.Quality = 0;
SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
SwapChainDesc.BufferCount = 2;
SwapChainDesc.Scaling = DXGI_SCALING_STRETCH;
SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
SwapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
SwapChainDesc.Flags = 0;
HRESULT CreatedSwapChain = Factory->CreateSwapChainForHwnd(Device,
Window, &SwapChainDesc,
0, 0, &Renderer.SwapChain);
ASSERT(SUCCEEDED(CreatedSwapChain));
CreateWindowSizeCoupledResources(&Renderer);
D3D11_DEPTH_STENCIL_DESC DepthStencilDesc = {};
DepthStencilDesc.DepthEnable = true;
DepthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
DepthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
DepthStencilDesc.StencilEnable = false;
HRESULT CreatedDepthStencilState = Device->CreateDepthStencilState(&DepthStencilDesc, &Renderer.DepthStencilState);
ASSERT(SUCCEEDED(CreatedDepthStencilState));
#if CRAY_DEBUG
UINT CompilerFlags = D3DCOMPILE_DEBUG;
#else
UINT CompilerFlags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
#endif
char *gpass = ReadFile("../code/gpass.hlsl");
char *fullscreen = ReadFile("../code/fullscreen.hlsl");
char *sample = ReadFile("../code/sample.hlsl");
char *output = ReadFile("../code/output.hlsl");
// create GPass shaders and its input layout
{
ID3DBlob *GPassVSCode = CompileDXShader("gpass.hlsl", gpass,
"vsmain", "vs_5_0", CompilerFlags);
Device->CreateVertexShader(GPassVSCode->GetBufferPointer(),
GPassVSCode->GetBufferSize(), 0, &Renderer.GPassVS);
D3D11_INPUT_ELEMENT_DESC InputLayoutDesc[] =
{
{"POS", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
D3D11_INPUT_PER_VERTEX_DATA, 0 },
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,
D3D11_APPEND_ALIGNED_ELEMENT,
D3D11_INPUT_PER_VERTEX_DATA, 0 },
{"ALBEDO", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,
D3D11_APPEND_ALIGNED_ELEMENT,
D3D11_INPUT_PER_VERTEX_DATA, 0 },
{"EMISSION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,
D3D11_APPEND_ALIGNED_ELEMENT,
D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
HRESULT CreatedInputLayout = Device->CreateInputLayout(
InputLayoutDesc,
ARRAY_COUNT(InputLayoutDesc),
GPassVSCode->GetBufferPointer(),
GPassVSCode->GetBufferSize(),
&Renderer.GPassInputLayout);
ASSERT(SUCCEEDED(CreatedInputLayout));
GPassVSCode->Release();
Renderer.GPassPS = CreateDXPS(Device, "gpass.hlsl", gpass, "psmain", CompilerFlags);
}
Renderer.FullscreenVS = CreateDXVS(Device, "fullscreen.hlsl", fullscreen, "main", CompilerFlags);
Renderer.SamplePS = CreateDXPS(Device, "sample.hlsl", sample, "main", CompilerFlags);
Renderer.OutputPS = CreateDXPS(Device, "output.hlsl", output, "main", CompilerFlags);
D3D11_SAMPLER_DESC PointSamplerDesc = {};
PointSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
PointSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
PointSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
PointSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
PointSamplerDesc.MipLODBias = 0;
PointSamplerDesc.MaxAnisotropy = 1;
PointSamplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
PointSamplerDesc.MinLOD = 0.0f;
PointSamplerDesc.MaxLOD = 0.0f;
HRESULT CreatedPointSampler = Device->CreateSamplerState(&PointSamplerDesc, &Renderer.PointSampler);
ASSERT(SUCCEEDED(CreatedPointSampler));
D3D11_RASTERIZER_DESC1 RasterizerStateDesc = {};
RasterizerStateDesc.FillMode = D3D11_FILL_SOLID;
RasterizerStateDesc.CullMode = D3D11_CULL_NONE;
RasterizerStateDesc.FrontCounterClockwise = true;
HRESULT CreatedRasterizerState = Device->CreateRasterizerState1(&RasterizerStateDesc, &Renderer.RasterizerState);
ASSERT(SUCCEEDED(CreatedRasterizerState));
D3D11_TEXTURE2D_DESC BackBufferDesc = {};
Renderer.BackBuffer->GetDesc(&BackBufferDesc);
int ClientWidth = BackBufferDesc.Width;
int ClientHeight = BackBufferDesc.Height;
Renderer.DoAutoFocus = true;
Renderer.Settings.Exposure = 0.8f;
Renderer.Settings.FOV = DegreeToRadian(45.0f);
Renderer.Settings.RasterizeFirstBounce = false;
Renderer.Settings.EnableGroundPlane = true;
Renderer.Settings.MaxBounceCount = 2;
Renderer.Settings.L = {0.5f, 0.4f, -0.5f};
Renderer.Settings.SunRadiance = V3(12.0f);
Renderer.Settings.Zenith = 2.0f * V3(0.0f, 0.44f, 2.66f);
Renderer.Settings.Azimuth = 2.0f * V3(1.0f, 1.4f, 1.6f);
Renderer.Camera.P = Camera->P;
Renderer.Camera.LookAt = Camera->LookAt;
Renderer.Camera.Aperture = 0.02f;
Renderer.Camera.FocalDistance = 2.0f;
Renderer.Context.AspectRatio = (f32)ClientWidth / (f32)ClientHeight;
Renderer.SettingsBuffer = CreateDynamicConstantBuffer(Device, &Renderer.Settings, sizeof(Renderer.Settings));
Renderer.CameraBuffer = CreateDynamicConstantBuffer(Device, &Renderer.Camera, sizeof(Renderer.Camera));
Renderer.ContextBuffer = CreateDynamicConstantBuffer(Device, &Renderer.Context, sizeof(Renderer.Context));
SetPersistentStates(&Renderer, ClientWidth, ClientHeight);
ImGui::CreateContext();
ImGui::GetIO().RenderDrawListsFn = ImGui_ImplDX11_RenderDrawData;
ImGui_ImplDX11_Init(Device, DeviceContext);
Renderer.BufferIndex = 0;
Renderer.LastBufferIndex = 1;
Renderer.InitElapsedTime = CalcSecondsPassed(BeginClock);
return Renderer;
}
inline packed_triangle
Pack(triangle Triangle)
{
packed_triangle PackedTriangle = {};
PackedTriangle.A = Triangle.A;
PackedTriangle.B = Triangle.B;
PackedTriangle.C = Triangle.C;
PackedTriangle.N = Triangle.N;
PackedTriangle.Albedo = Triangle.Albedo;
PackedTriangle.Emission = Triangle.Emission;
return PackedTriangle;
}
inline packed_bvh_entry
Pack(bvh_entry BVHEntry)
{
packed_bvh_entry PackedBVHEntry = {};
PackedBVHEntry.BoundMin = BVHEntry.BoundMin;
PackedBVHEntry.BoundMax = BVHEntry.BoundMax;
PackedBVHEntry.PrimitiveOffset = BVHEntry.PrimitiveOffset;
PackedBVHEntry.PrimitiveCount = BVHEntry.PrimitiveCount;
PackedBVHEntry.Axis = BVHEntry.Axis;
return PackedBVHEntry;
}
internal ID3D11Buffer *
CreateStructuredBuffer(ID3D11Device1 *Device, void *Data,
int ElementCount, int Stride,
ID3D11ShaderResourceView **BufferView_Out)
{
ID3D11Buffer *Buffer = 0;
//NOTE(chen): must be 16-byte aligned
ASSERT(Stride % 16 == 0);
D3D11_BUFFER_DESC BufferDesc = {};
BufferDesc.ByteWidth = ElementCount * Stride;
BufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
BufferDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
BufferDesc.CPUAccessFlags = 0;
BufferDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
BufferDesc.StructureByteStride = Stride;
D3D11_SUBRESOURCE_DATA BufferData = {};
BufferData.pSysMem = Data;
HRESULT CreatedBuffer = Device->CreateBuffer(&BufferDesc, &BufferData, &Buffer);
ASSERT(SUCCEEDED(CreatedBuffer));
D3D11_SHADER_RESOURCE_VIEW_DESC BufferViewDesc = {};
BufferViewDesc.Format = DXGI_FORMAT_UNKNOWN;
BufferViewDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
BufferViewDesc.Buffer.NumElements = ElementCount;
HRESULT CreatedBufferView = Device->CreateShaderResourceView(Buffer, &BufferViewDesc, BufferView_Out);
ASSERT(SUCCEEDED(CreatedBufferView));
return Buffer;
}
internal void
UploadModelToRenderer(dx_renderer *Renderer, loaded_model Model)
{
if (Renderer->TriangleBuffer || Renderer->BVHBuffer ||
Renderer->VertexBuffer)
{
Renderer->TriangleBufferView->Release();
Renderer->TriangleBuffer->Release();
Renderer->BVHBufferView->Release();
Renderer->BVHBuffer->Release();
Renderer->VertexBuffer->Release();
Refresh(Renderer);
}
ID3D11Device1 *Device = Renderer->Device;
ID3D11DeviceContext1 *DeviceContext = Renderer->DeviceContext;
// upload packed triangles
{
packed_triangle *PackedTriangles = BufInit(BufCount(Model.Triangles), packed_triangle);
for (int TriIndex = 0; TriIndex < BufCount(PackedTriangles); ++TriIndex)
{
PackedTriangles[TriIndex] = Pack(Model.Triangles[TriIndex]);
}
Renderer->TriangleBuffer = CreateStructuredBuffer(Device, PackedTriangles,
(int)BufCount(PackedTriangles),
sizeof(packed_triangle),
&Renderer->TriangleBufferView);
BufFree(PackedTriangles);
}
// upload packed BVH
{
packed_bvh_entry *PackedBVH = BufInit(BufCount(Model.BVH), packed_bvh_entry);
for (int EntryIndex = 0; EntryIndex < BufCount(PackedBVH); ++EntryIndex)
{
PackedBVH[EntryIndex] = Pack(Model.BVH[EntryIndex]);
}
Renderer->BVHBuffer = CreateStructuredBuffer(Device, PackedBVH,
(int)BufCount(PackedBVH),
sizeof(packed_bvh_entry),
&Renderer->BVHBufferView);
BufFree(PackedBVH);
}
ID3D11ShaderResourceView *ResourceViews[] = {
Renderer->TriangleBufferView,
Renderer->BVHBufferView,
};
DeviceContext->PSSetShaderResources(0, ARRAY_COUNT(ResourceViews), ResourceViews);
D3D11_BUFFER_DESC VertexBufferDesc = {};
VertexBufferDesc.ByteWidth = sizeof(vertex) * (int)BufCount(Model.Vertices);
VertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA VertexBufferData = {};
VertexBufferData.pSysMem = Model.Vertices;
HRESULT CreatedVertexBuffer = Device->CreateBuffer(&VertexBufferDesc, &VertexBufferData, &Renderer->VertexBuffer);
ASSERT(SUCCEEDED(CreatedVertexBuffer));
Renderer->VertexCount = (int)BufCount(Model.Vertices);
}
internal void
UpdateBuffer(ID3D11DeviceContext1 *DeviceContext, ID3D11Buffer *Buffer, void *Data, size_t DataSize)
{
D3D11_MAPPED_SUBRESOURCE MappedResource = {};
HRESULT ResourceIsMapped = DeviceContext->Map(Buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource);
ASSERT(SUCCEEDED(ResourceIsMapped));
memcpy(MappedResource.pData, Data, DataSize);
DeviceContext->Unmap(Buffer, 0);
}
//NOTE(chen): this is for determining if samples need to be refreshed
internal b32
NeedsRefresh(render_settings Old, render_settings New)
{
b32 Result = false;
Result = Result || Old.FOV != New.FOV;
Result = Result || Old.RasterizeFirstBounce != New.RasterizeFirstBounce;
Result = Result || Old.MaxBounceCount != New.MaxBounceCount;
Result = Result || Old.EnableGroundPlane != New.EnableGroundPlane;
Result = Result || Old.DoCoherentSample != New.DoCoherentSample;
Result = Result || Old.L != New.L;
Result = Result || Old.SunRadiance != New.SunRadiance;
Result = Result || Old.Zenith != New.Zenith;
Result = Result || Old.Azimuth != New.Azimuth;
return Result;
}
bool operator==(render_settings A, render_settings B)
{
return memcpy(&A, &B, sizeof(A)) == 0;
}
bool operator!=(render_settings A, render_settings B)
{
return !(A == B);
}
internal void
RefreshCamera(dx_renderer *Renderer, camera *Camera)
{
Renderer->Camera.P = Camera->P;
Renderer->Camera.LookAt = Camera->LookAt;
UpdateBuffer(Renderer->DeviceContext, Renderer->CameraBuffer,
&Renderer->Camera, sizeof(Renderer->Camera));
Refresh(Renderer);
}
internal void
ResizeResources(dx_renderer *Renderer, int NewWidth, int NewHeight)
{
ASSERT(NewWidth != Renderer->Width || NewHeight != Renderer->Height);
Renderer->Width = NewWidth;
Renderer->Height = NewHeight;
// release screen-size coupled resources
Renderer->BackBuffer->Release();
Renderer->BackBufferView->Release();
for (int I = 0; I < ARRAY_COUNT(Renderer->SamplerBuffers); ++I)
{
Release(&Renderer->SamplerBuffers[I]);
}
Release(&Renderer->PositionBuffer);
Release(&Renderer->NormalBuffer);
Release(&Renderer->AlbedoBuffer);
Release(&Renderer->EmissionBuffer);
Renderer->DepthStencilBuffer->Release();
Renderer->DepthStencilView->Release();
HRESULT ResizedBackBuffers = Renderer->SwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
if (FAILED(ResizedBackBuffers))
{
HRESULT DeviceRemovedReason = Renderer->Device->GetDeviceRemovedReason();
ASSERT(!"Failed to resize back buffers");
}
CreateWindowSizeCoupledResources(Renderer);
SetViewport(Renderer, NewWidth, NewHeight);
Renderer->Context.AspectRatio = (f32)NewWidth / (f32)NewHeight;
Refresh(Renderer);
}
internal void
Render(dx_renderer *Renderer, camera *Camera, f32 T)
{
ID3D11DeviceContext1 *DeviceContext = Renderer->DeviceContext;
context_data *Context = &Renderer->Context;
Context->Time = T;
Context->RandSeed.X = (f32)rand() / RAND_MAX;
Context->RandSeed.Y = (f32)rand() / RAND_MAX;
Context->View = Transpose(Mat4LookAt(Camera->P, Camera->LookAt));
Context->Projection = Transpose(Mat4PerspectiveDX(Renderer->Settings.FOV, Context->AspectRatio, 0.1f, 1000.0f));
UpdateBuffer(DeviceContext, Renderer->ContextBuffer,
&Renderer->Context, sizeof(Renderer->Context));
if (Renderer->OldSettings != Renderer->Settings)
{
UpdateBuffer(Renderer->DeviceContext, Renderer->SettingsBuffer,
&Renderer->Settings, sizeof(Renderer->Settings));
Renderer->OldSettings = Renderer->Settings;
}
if (Renderer->Settings.RasterizeFirstBounce || Renderer->DoAutoFocus)
{
UINT VBStride = sizeof(vertex);
UINT VBOffset = 0;
DeviceContext->IASetVertexBuffers(0, 1, &Renderer->VertexBuffer, &VBStride, &VBOffset);
DeviceContext->IASetInputLayout(Renderer->GPassInputLayout);
DeviceContext->VSSetShader(Renderer->GPassVS, 0, 0);
DeviceContext->PSSetShader(Renderer->GPassPS, 0, 0);
f32 ClearRGBA[4] = {0.0f};
DeviceContext->ClearRenderTargetView(Renderer->PositionBuffer.RTV, ClearRGBA);
DeviceContext->ClearRenderTargetView(Renderer->NormalBuffer.RTV, ClearRGBA);
DeviceContext->ClearRenderTargetView(Renderer->AlbedoBuffer.RTV, ClearRGBA);
DeviceContext->ClearRenderTargetView(Renderer->EmissionBuffer.RTV, ClearRGBA);
DeviceContext->ClearDepthStencilView(Renderer->DepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
//NOTE(chen): unbind gbuffer's SRV so they can be used as output
ID3D11ShaderResourceView *NullSRVs[] = {0, 0, 0, 0};
DeviceContext->PSSetShaderResources(3, ARRAY_COUNT(NullSRVs), NullSRVs);
ID3D11RenderTargetView *RenderTargetViews[] = {
Renderer->PositionBuffer.RTV,
Renderer->NormalBuffer.RTV,
Renderer->AlbedoBuffer.RTV,
Renderer->EmissionBuffer.RTV,
};
DeviceContext->OMSetDepthStencilState(Renderer->DepthStencilState, 0);
DeviceContext->OMSetRenderTargets(ARRAY_COUNT(RenderTargetViews), RenderTargetViews, Renderer->DepthStencilView);
ASSERT(Renderer->VertexCount != 0);
DeviceContext->Draw(Renderer->VertexCount, 0);
//NOTE(chen): unbind gbuffer's RTV so they can be used as shader resources
DeviceContext->OMSetRenderTargets(0, 0, 0);
ID3D11ShaderResourceView *GBufferViews[] = {
Renderer->PositionBuffer.SRV,
Renderer->NormalBuffer.SRV,
Renderer->AlbedoBuffer.SRV,
Renderer->EmissionBuffer.SRV,
};
DeviceContext->PSSetShaderResources(3, ARRAY_COUNT(GBufferViews), GBufferViews);
}
if (Renderer->DoAutoFocus)
{
if (!Renderer->AutoFocusStagingTex)
{
D3D11_TEXTURE2D_DESC TextureDesc = {};
TextureDesc.Width = 1;
TextureDesc.Height = 1;
TextureDesc.MipLevels = 1;
TextureDesc.ArraySize = 1;
TextureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_STAGING;
TextureDesc.BindFlags = 0;
TextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
TextureDesc.MiscFlags = 0;
HRESULT CreatedStagingTex = Renderer->Device->CreateTexture2D(&TextureDesc, 0,
&Renderer->AutoFocusStagingTex);
ASSERT(SUCCEEDED(CreatedStagingTex));
ASSERT(Renderer->AutoFocusStagingTex);
}
int CenterPixelX = Renderer->Width / 2;
int CenterPixelY = Renderer->Height / 2;
D3D11_BOX CopyBox = {};
CopyBox.left = CenterPixelX;
CopyBox.top = CenterPixelY;
CopyBox.front = 0;
CopyBox.right = CopyBox.left+1;
CopyBox.bottom = CopyBox.top+1;
CopyBox.back = CopyBox.front+1;
DeviceContext->CopySubresourceRegion(Renderer->AutoFocusStagingTex, 0,
0, 0, 0, Renderer->PositionBuffer.Tex,
0, &CopyBox);
D3D11_MAPPED_SUBRESOURCE MappedData = {};
DeviceContext->Map(Renderer->AutoFocusStagingTex, 0, D3D11_MAP_READ, 0, &MappedData);
v4 CenterRayHitP = *(v4 *)MappedData.pData;
DeviceContext->Unmap(Renderer->AutoFocusStagingTex, 0);
f32 CenterRayDepth = Len(Camera->P - V3(CenterRayHitP));
if (Abs(Renderer->Camera.FocalDistance - CenterRayDepth) > 0.01f)
{
Renderer->Camera.FocalDistance = CenterRayDepth;
RefreshCamera(Renderer, Camera);
}
}
int BufferIndex = Renderer->BufferIndex;
int LastBufferIndex = Renderer->LastBufferIndex;
DeviceContext->IASetInputLayout(0);
DeviceContext->VSSetShader(Renderer->FullscreenVS, 0, 0);
DeviceContext->PSSetShaderResources(2, 1, &Renderer->SamplerBuffers[LastBufferIndex].SRV);
DeviceContext->PSSetShader(Renderer->SamplePS, 0, 0);
DeviceContext->OMSetRenderTargets(1, &Renderer->SamplerBuffers[BufferIndex].RTV, 0);
DeviceContext->Draw(3, 0);
DeviceContext->PSSetShader(Renderer->OutputPS, 0, 0);
DeviceContext->OMSetRenderTargets(1, &Renderer->BackBufferView, 0);
DeviceContext->PSSetShaderResources(2, 1, &Renderer->SamplerBuffers[BufferIndex].SRV);
DeviceContext->Draw(3, 0);
Renderer->Context.SampleCountSoFar += 1;
Renderer->LastBufferIndex = BufferIndex;
Renderer->BufferIndex = (BufferIndex + 1) % 2;
}
internal void
Present(dx_renderer *Renderer)
{
DXGI_PRESENT_PARAMETERS PresentParameters = {};
HRESULT PresentedBackBuffer = Renderer->SwapChain->Present1(0, 0, &PresentParameters);
if (FAILED(PresentedBackBuffer))
{
HRESULT DeviceRemovedReason = Renderer->Device->GetDeviceRemovedReason();
ASSERT(!"Failed to present back buffer");
}
} | 39.830402 | 155 | 0.654849 | ALEXMORF |
77517aa35c0b1e66609f0b11a4de78cb609ca5a4 | 733 | cpp | C++ | BHRgoal/PFOO-L/pfool.cpp | dasebe/optimalwebcaching | 401da5ebd2e0fdb21798f8dcea52b6355efb7dc5 | [
"BSD-2-Clause"
] | 37 | 2018-05-21T03:04:43.000Z | 2022-02-17T11:19:03.000Z | BHRgoal/PFOO-L/pfool.cpp | dasebe/optimalwebcaching | 401da5ebd2e0fdb21798f8dcea52b6355efb7dc5 | [
"BSD-2-Clause"
] | 4 | 2018-07-14T23:57:11.000Z | 2022-02-04T01:31:12.000Z | BHRgoal/PFOO-L/pfool.cpp | dasebe/optimalwebcaching | 401da5ebd2e0fdb21798f8dcea52b6355efb7dc5 | [
"BSD-2-Clause"
] | 8 | 2019-04-26T20:13:18.000Z | 2021-11-18T13:24:37.000Z | #include <cassert>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <fstream>
#include "lib/parse_trace.h"
#include "lib/solve_mcf.h"
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << argv[0] << " traceFile cacheSize" << std::endl;
return 1;
}
std::cerr << "start up\n";
std::string path(argv[1]);
uint64_t cacheSize(std::stoull(argv[2]));
// parse trace file
std::vector<trEntry> trace;
uint64_t byteSum = 0;
parseTraceFile(trace, path,byteSum);
std::cerr << "parsed " << byteSum << " bytes\n";
cacheAlg(trace);
std::cerr << "processed\n";
printRes(trace, byteSum, cacheSize);
return 0;
}
| 20.361111 | 68 | 0.604366 | dasebe |
77523e7965d744b41208b37d8fa71878ab300e0c | 3,330 | cpp | C++ | third_party/libosmium/test/t/tags/test_tag_list.cpp | Mapotempo/osrm-backend | a62c10321c0a269e218ab4164c4ccd132048f271 | [
"BSD-2-Clause"
] | 1 | 2016-11-29T15:02:40.000Z | 2016-11-29T15:02:40.000Z | third_party/libosmium/test/t/tags/test_tag_list.cpp | aaronbenz/osrm-backend | 758d4023050d1f49971f919cea872a2276dafe14 | [
"BSD-2-Clause"
] | 1 | 2019-02-04T18:10:57.000Z | 2019-02-04T18:10:57.000Z | third_party/libosmium/test/t/tags/test_tag_list.cpp | Mapotempo/osrm-backend | a62c10321c0a269e218ab4164c4ccd132048f271 | [
"BSD-2-Clause"
] | null | null | null | #include "catch.hpp"
#include <osmium/builder/builder_helper.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/tag.hpp>
TEST_CASE("create tag list") {
osmium::memory::Buffer buffer(10240);
SECTION("with TagListBuilder from char*") {
{
osmium::builder::TagListBuilder builder(buffer);
builder.add_tag("highway", "primary");
builder.add_tag("name", "Main Street");
}
buffer.commit();
}
SECTION("with TagListBuilder from char* with length") {
{
osmium::builder::TagListBuilder builder(buffer);
builder.add_tag("highway", strlen("highway"), "primary", strlen("primary"));
builder.add_tag("nameXX", 4, "Main Street", 11);
}
buffer.commit();
}
SECTION("with TagListBuilder from std::string") {
{
osmium::builder::TagListBuilder builder(buffer);
builder.add_tag(std::string("highway"), std::string("primary"));
const std::string source = "name";
std::string gps = "Main Street";
builder.add_tag(source, gps);
}
buffer.commit();
}
SECTION("with build_tag_list from initializer list") {
osmium::builder::build_tag_list(buffer, {
{ "highway", "primary" },
{ "name", "Main Street" }
});
}
SECTION("with build_tag_list_from_map") {
osmium::builder::build_tag_list_from_map(buffer, std::map<const char*, const char*>({
{ "highway", "primary" },
{ "name", "Main Street" }
}));
}
SECTION("with build_tag_list_from_func") {
osmium::builder::build_tag_list_from_func(buffer, [](osmium::builder::TagListBuilder& tlb) {
tlb.add_tag("highway", "primary");
tlb.add_tag("name", "Main Street");
});
}
const osmium::TagList& tl = *buffer.begin<osmium::TagList>();
REQUIRE(osmium::item_type::tag_list == tl.type());
REQUIRE(2 == tl.size());
auto it = tl.begin();
REQUIRE(std::string("highway") == it->key());
REQUIRE(std::string("primary") == it->value());
++it;
REQUIRE(std::string("name") == it->key());
REQUIRE(std::string("Main Street") == it->value());
++it;
REQUIRE(it == tl.end());
REQUIRE(std::string("primary") == tl.get_value_by_key("highway"));
REQUIRE(nullptr == tl.get_value_by_key("foo"));
REQUIRE(std::string("default") == tl.get_value_by_key("foo", "default"));
REQUIRE(std::string("Main Street") == tl["name"]);
}
TEST_CASE("empty keys and values are okay") {
osmium::memory::Buffer buffer(10240);
const osmium::TagList& tl = osmium::builder::build_tag_list(buffer, {
{ "empty value", "" },
{ "", "empty key" }
});
REQUIRE(osmium::item_type::tag_list == tl.type());
REQUIRE(2 == tl.size());
auto it = tl.begin();
REQUIRE(std::string("empty value") == it->key());
REQUIRE(std::string("") == it->value());
++it;
REQUIRE(std::string("") == it->key());
REQUIRE(std::string("empty key") == it->value());
++it;
REQUIRE(it == tl.end());
REQUIRE(std::string("") == tl.get_value_by_key("empty value"));
REQUIRE(std::string("empty key") == tl.get_value_by_key(""));
}
| 32.330097 | 100 | 0.565766 | Mapotempo |
7753416567c24701ce09016caf57ca0eef8a8efd | 867 | cpp | C++ | src/main/cpp/pistis/log4cxx/Log4CxxLogMessageReceiver.cpp | tomault/pistis-log4cxx | 849e507a654d05362122582192ead7dba9798abe | [
"Apache-2.0"
] | null | null | null | src/main/cpp/pistis/log4cxx/Log4CxxLogMessageReceiver.cpp | tomault/pistis-log4cxx | 849e507a654d05362122582192ead7dba9798abe | [
"Apache-2.0"
] | null | null | null | src/main/cpp/pistis/log4cxx/Log4CxxLogMessageReceiver.cpp | tomault/pistis-log4cxx | 849e507a654d05362122582192ead7dba9798abe | [
"Apache-2.0"
] | null | null | null | #include "Log4CxxLogMessageReceiver.hpp"
using namespace pistis::logging;
using namespace pistis::log4cxx;
const Log4CxxLogLevelTranslator Log4CxxLogMessageReceiver::_LOG4CXX_LEVEL;
Log4CxxLogMessageReceiver::Log4CxxLogMessageReceiver(
LogMessageFactory* factory,
const ::log4cxx::LoggerPtr& logger
):
_factory(factory), _logger(logger) {
// Intentionally left blank
}
void Log4CxxLogMessageReceiver::receive(LogMessage* msg) {
if (msg) {
if (!msg->empty()) {
_write(msg->logLevel(), msg->begin(), msg->end());
}
_factory->release(msg);
}
}
void Log4CxxLogMessageReceiver::setLogLevel(LogLevel logLevel) {
_logger->setLevel(_LOG4CXX_LEVEL[logLevel]);
}
void Log4CxxLogMessageReceiver::_write(LogLevel level, const char* begin,
const char* end) {
_logger->log(_LOG4CXX_LEVEL[level], std::string(begin, end));
}
| 26.272727 | 74 | 0.732411 | tomault |
775d97d6727f184cce3d273681bb6ad2b0124fc8 | 2,576 | hpp | C++ | src/comment.hpp | lem0nez/instanalyzer | 0bb2353ecc6d3657245d2f8053a55172da03968e | [
"Apache-2.0"
] | null | null | null | src/comment.hpp | lem0nez/instanalyzer | 0bb2353ecc6d3657245d2f8053a55172da03968e | [
"Apache-2.0"
] | null | null | null | src/comment.hpp | lem0nez/instanalyzer | 0bb2353ecc6d3657245d2f8053a55172da03968e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2019 Nikita Dudko. All rights reserved.
* Contacts: <nikita.dudko.95@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <ctime>
#include <map>
#include <set>
#include <string>
#include "nlohmann/json.hpp"
#include "profile.hpp"
class Comment {
public:
Comment() = default;
inline bool operator<(const Comment& rhs) const {
return m_creation_time < rhs.m_creation_time;
}
inline std::string get_id() const { return m_id; }
inline std::string get_text() const { return m_text; }
inline std::string get_post_shortcode() const { return m_post_shortcode; }
inline Profile get_profile() const { return m_profile; }
inline unsigned int get_likes() const { return m_likes; }
inline std::time_t get_creation_time() const { return m_creation_time; }
inline bool is_spam() const { return m_is_spam; }
inline void set_id(const std::string& t_id) { m_id = t_id; }
inline void set_text(const std::string& t_text) { m_text = t_text; }
inline void set_post_shortcode(const std::string& t_shortcode) {
m_post_shortcode = t_shortcode;
}
inline void set_profile(const Profile& t_profile) {
m_profile = t_profile;
}
inline void set_likes(const unsigned int& t_likes) { m_likes = t_likes; }
inline void set_creation_time(const std::size_t& t_creation_time) {
m_creation_time = t_creation_time;
}
inline void set_spam(const bool& t_is_spam) { m_is_spam = t_is_spam; }
static std::set<Comment> get_comments(const std::set<nlohmann::json>&);
static void show_commentators(const Profile&);
static void show_commentator_info(
const Profile& owner, const std::string& commentator);
static void print_comments(const std::set<Comment>& comments,
const std::string& label = "");
static void show_references(const Profile& owner,
const std::string& commentator, std::set<Comment> comments = {});
private:
std::string m_id, m_text, m_post_shortcode;
Profile m_profile;
unsigned int m_likes;
std::time_t m_creation_time;
bool m_is_spam;
};
| 33.454545 | 76 | 0.726708 | lem0nez |
7764bf44fbd662d7d1ce9b42d955824374cd57d2 | 1,129 | cpp | C++ | src/visualman/abstrarenderer.cpp | cad420/VisualMan | 1ad86dec229891c4e93b86732ae98e52e44f5c8d | [
"MIT"
] | 6 | 2019-09-27T06:16:12.000Z | 2022-02-26T08:00:05.000Z | src/visualman/abstrarenderer.cpp | cad420/VisualMan | 1ad86dec229891c4e93b86732ae98e52e44f5c8d | [
"MIT"
] | null | null | null | src/visualman/abstrarenderer.cpp | cad420/VisualMan | 1ad86dec229891c4e93b86732ae98e52e44f5c8d | [
"MIT"
] | 1 | 2019-06-04T17:19:16.000Z | 2019-06-04T17:19:16.000Z |
#include "abstrarenderer.h"
#include "renderevent.h"
namespace vm
{
void AbstraRenderer::DispatchOnRenderStartedEvent()
{
//Debug("AbstraRenderer::DispatchOnRenderStartedEvent\n");
for ( auto it = startedCallbacks.begin(); it != startedCallbacks.end(); ) {
auto &item = *it;
if ( item->IsEnabled() && item->OnRendererStartedEvent( this ) && item->IsRemoveAfterCallEnabled() )
it = startedCallbacks.erase( it );
else
++it;
}
}
void AbstraRenderer::DispatchOnRenderFinishedEvent()
{
//Debug("AbstraRenderer::DispatchOnRenderFinishedEent\n");
for ( auto it = finishedCallbacks.begin(); it != finishedCallbacks.end(); ) {
auto &item = *it;
if ( item->IsEnabled() && item->OnRendererFinishedEvent( this ) && item->IsRemoveAfterCallEnabled() )
it = finishedCallbacks.erase( it );
else
++it;
}
}
void AbstraRenderer::AddRenderStartedEventCallback( VMRef<IRenderEvent> callback )
{
startedCallbacks.push_back( std::move( callback ) );
}
void AbstraRenderer::AddRenderFinishedEventCallback( VMRef<IRenderEvent> callback )
{
finishedCallbacks.push_back( std::move( callback ) );
}
} // namespace vm
| 26.255814 | 103 | 0.719221 | cad420 |
7765a1ed9a9c5b979d17ec0a327499ae3b54d25d | 11,160 | cpp | C++ | simpletest_ext.cpp | jonathanrlemos/simpletest | 0b0086279c756aa7bd14a40d907352233fc98313 | [
"MIT"
] | null | null | null | simpletest_ext.cpp | jonathanrlemos/simpletest | 0b0086279c756aa7bd14a40d907352233fc98313 | [
"MIT"
] | null | null | null | simpletest_ext.cpp | jonathanrlemos/simpletest | 0b0086279c756aa7bd14a40d907352233fc98313 | [
"MIT"
] | null | null | null | /** @file simpletest_ext.cpp
* @brief simpletest extended functions.
* @copyright Copyright (c) 2018 Jonathan Lemos
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "simpletest_ext.hpp"
#include <algorithm>
#include <cstring>
#include <cerrno>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include <unistd.h>
namespace simpletest{
/**
* @brief Do not use this function directly; instead, use the MAKE_PATH() macro.
* This function makes a path out of several components.
* Each component besides the last will have a trailing '/' appended after it.
* If a component ends with a '/' and the next also starts with a '/', only one '/' is added.
*
* @param components A vector containing the components to turn into a path.
*
* @return A string corresponding to that path.
*/
static std::string AT_CONST __makepath(std::vector<std::string> components){
std::string ret;
// needed so the following line does not throw an out_of_range error if the vector is empty
if (components.empty()){
return "";
}
ret = components[0];
// for each component after the first
for (size_t i = 1; i < components.size(); ++i){
// if the string does not end with a '/' */
if (ret[ret.size() - 1] != '/'){
// append one
ret += '/';
}
// if the string starts with a '/', append everything after the '/', otherwise append the entire string
ret += (components[i][0] == '/' ? components[i].c_str() + 1 : components[i]);
}
return ret;
}
/**
* @brief Makes a path out of several components.
* For example:<br>
* ```C++
* MAKE_PATH("/home", "equifax", "passwords.txt") == "/home/equifax/passwords.txt";
* MAKE_PATH("/home/", "/equifax/", "/passwords.txt") == "/home/equifax/passwords.txt";
* MAKE_PATH("home/", "/equifax", "/passwords.txt") == "home/equifax/passwords.txt";
* ```
*/
#define MAKE_PATH(...) __makepath({__VA_ARGS__})
struct TestEnvironment::TestEnvironmentImpl{
/**
* @brief Vector that holds the files within this test environment.
* These files are removed once the TestEnvironment's destructor is called.
*/
std::vector<std::string> files;
/**
* @brief Vector that holds the directories within this test environment.
* These directories are removed once the TestEnvrionment's destructor is called.
*/
std::vector<std::string> directories;
/**
* @brief Destructor for TestEnvironmentImpl.
* This removes all files and directories in the files/directories vector.
*/
~TestEnvironmentImpl(){
std::for_each(files.begin(), files.end(), [](const auto& elem){
chmod(elem.c_str(), 0644);
remove(elem.c_str());
});
std::for_each(directories.begin(), directories.end(), [](const auto& elem){
chmod(elem.c_str(), 0755);
rmdir(elem.c_str());
});
}
/**
* @brief Creates an empty directory within the test environment and adds it to the directory vector.
* This is a helper function for createTestDirectory(), but it can also be used standalone.
*
* @param path The path of the directory to create.
* @param mode The permissions to create the directory with.
* By default this is set to 0755, which allows read+write+execute permission for this user and only read+execute for others.
*/
void createNewDirectory(const char* path, mode_t mode = 0755){
// if we could not create the directory, and the directory does not already exist
if (mkdir(path, mode) != 0 && errno != EEXIST){
throw std::runtime_error("Failed to create directory " + std::string(path) + '(' + std::strerror(errno) + ')');
}
directories.push_back(path);
}
/**
* @brief Creates a file within the test environment and adds it to the internal file vector.
* This is a helper function for createTestDirectory(), but it can also be used standalone.
* This file will be filled with random data generated by the fillMemory() function.
*
* @param path The path of the file to create.
* @param mode The mode to create the file with.
* By default this is set to 0644, which allows read+write permission for this user and only read for others.
* @param maxLen The maximum length of the random data to fill the file with.
* By default this is set to 4096, which means that the file will be anywhere from 0 to 4096 bytes.
*/
void createTestFile(const char* path, mode_t mode = 0644, size_t maxLen = 4096){
std::vector<unsigned char> randData;
// generate a random number from 0 to maxLen
// this will be the length of the file
size_t randLen = rand::next() % (maxLen + 1);
// resize the vector so it can hold the length of data we need.
randData.resize(randLen);
// fill the vector with random data
fillMemory(&(randData[0]), randLen);
// now create the file using this data
createFile(path, &(randData[0]), randLen, mode);
// finally, add the file to our internal file vector
files.push_back(path);
}
/**
* @brief Creates a directory within the test environment and fills it with test files.
* These files will be created with the following format:
* `{path}/{filePrefix}{number}.txt`
* The number is 1-indexed.
* The files are added to the internal file vector.
* Each of these test files will be filled with random data.
*
* @param path The directory to create.
* If this directory's parent does not exist, this function will fail.
*
* @param filePrefix The prefix to append to each file.
* @param nFiles The number of files to create.
* @param maxLen The maximum length of the files to create.
*/
void createTestDirectory(const char* path, const char* filePrefix = "", int nFiles = 20, size_t maxLen = 4096){
createNewDirectory(path);
for (int i = 1; i <= nFiles; ++i){
// make a path with the following format:
// {path}/{filePrefix}{number}.txt
//
// do not use MAKE_PATH(path, filePrefix, std::to_string(i), ".txt"), because that will make a file with this format: `{path}/{filePrefix}/{number}/.txt`, which is not what we want
std::string file = MAKE_PATH(path, filePrefix + std::to_string(i) + ".txt");
createTestFile(file.c_str(), maxLen);
}
}
};
void createFile(const char* path, void* mem, size_t memLen, mode_t mode){
// open an ostream corresponding to the file
std::ofstream ofs;
ofs.open(path);
if (!ofs){
throw std::runtime_error("Failed to create file " + std::string(path) + " (" + std::strerror(errno) + ")");
}
// write the data pointed to by mem literally
// it has to be cast to a char*, because for some bizarre reason, std::ostream::write() takes a char* instead of a void*/unsigned char*/byte*
ofs.write((char*)mem, memLen);
// flush output
ofs.close();
// if there were any errors writing
if (!ofs){
throw std::runtime_error("Failed to write to file " + std::string(path));
}
// finally, chmod our file to the correct mode
if (chmod(path, mode) != 0){
std::stringstream ss_oct;
ss_oct << std::oct << mode;
throw std::runtime_error("Failed to chmod file " + std::string(path) + " to " + ss_oct.str() + ' ' + std::strerror(errno));
}
}
void createFile(const char* path, size_t maxRandLen, mode_t mode){
std::vector<unsigned char> randData;
// get a random number from 0 to maxRandLen
size_t randLen = rand::next() % (maxRandLen + 1);
// resize the vector so it can hold the amount of data we need
randData.resize(randLen);
// fill the vector by passing a pointer to its internal unsigned char*
fillMemory(&(randData[0]), randLen);
// finally, create the file with this data
createFile(path, &(randData[0]), randLen, mode);
}
int cmpFile(const char* file1, const char* file2){
char c1;
char c2;
std::ifstream if1;
std::ifstream if2;
if1.open(file1);
if (!if1){
throw std::runtime_error("Failed to open file " + std::string(file1) + " (" + std::strerror(errno) + ")");
}
if2.open(file2);
if (!if1){
throw std::runtime_error("Failed to open file " + std::string(file2) + " (" + std::strerror(errno) + ")");
}
do{
c1 = if1.get();
c2 = if2.get();
}while (c1 != EOF && c1 == c2);
return c1 - c2;
}
int cmpFile(const char* file, void* mem, size_t memLen){
char c1 = 0;
unsigned char* ucmem = (unsigned char*)mem;
size_t memPtr = 0;
std::ifstream ifs;
ifs.open(file);
if (!ifs){
throw std::runtime_error("Failed to open file " + std::string(file) + " (" + std::strerror(errno) + ")");
}
for (; memPtr < memLen && (c1 = ifs.get()) == ucmem[memPtr]; memPtr++);
return c1 - ucmem[memPtr];
}
int cmpFile(void* mem, size_t memLen, const char* file){
return -cmpFile(file, mem, memLen);
}
bool fileExists(const char* file){
struct stat st;
if (stat(file, &st) != 0){
if (errno != ENOENT && errno != ENOTDIR){
throw std::runtime_error("Failed to stat " + std::string(file) + " (" + std::strerror(errno) + ")");
}
return false;
}
return S_ISREG(st.st_mode);
}
TestEnvironment::TestEnvironment(): impl(std::make_unique<TestEnvironmentImpl>()){}
TestEnvironment::TestEnvironment(TestEnvironment&& other){
impl = std::move(other.impl);
}
TestEnvironment& TestEnvironment::operator=(TestEnvironment&& other){
impl = std::move(other.impl);
return *this;
}
TestEnvironment::~TestEnvironment(){
std::for_each(impl->files.begin(), impl->files.end(), [](const auto& elem){
chmod(elem.c_str(), 0755);
remove(elem.c_str());
});
std::for_each(impl->directories.begin(), impl->directories.end(), [](const auto& elem){
chmod(elem.c_str(), 0666);
rmdir(elem.c_str());
});
}
TestEnvironment& TestEnvironment::setupBasicEnvironment(const char* basePath){
// seed the rng so we get the same environment every time
rand::seed(0);
impl->createNewDirectory(basePath);
impl->createTestDirectory(basePath, "file");
std::sort(impl->files.begin(), impl->files.end());
return *this;
}
TestEnvironment& TestEnvironment::setupFullEnvironment(const char* basePath){
// seed the rng so we get the same environment every time
rand::seed(0);
impl->createNewDirectory(basePath);
// create 3 test directories under basePath/dir1, basePath/dir2, and basePath/excl
impl->createTestDirectory(MAKE_PATH(basePath, "dir1").c_str(), "dir1");
impl->createTestDirectory(MAKE_PATH(basePath, "dir2").c_str(), "dir2");
impl->createTestDirectory(MAKE_PATH(basePath, "excl").c_str(), "excl");
// create a file with all blocked permissions under basePath/excl/exclnoacc.txt
impl->createTestFile(MAKE_PATH(basePath, "excl", "exclnoacc.txt").c_str(), 0000);
// create a directory with all blocked permissions under basePath/noacc
impl->createNewDirectory(MAKE_PATH(basePath, "noacc").c_str(), 0000);
// sort the entries so binary search can be used on them
std::sort(impl->files.begin(), impl->files.end());
return *this;
}
const std::vector<std::string>& TestEnvironment::getFiles() const{
return impl->files;
}
void fillMemory(void* mem, size_t len){
unsigned char* ucmem = (unsigned char*)mem;
for (size_t i = 0; i < len; ++i){
ucmem[i] = rand::next() % ('Z' - 'A') + 'A';
}
}
namespace rand{
static thread_local unsigned randSeed = 0;
void seed(unsigned seed){
randSeed = seed;
}
int next(){
randSeed = 1103515245 * randSeed + 12345;
return randSeed;
}
}
}
| 32.347826 | 183 | 0.685663 | jonathanrlemos |
776821dc1eb910559898126559b27fb056207c36 | 202,797 | cpp | C++ | PochiVM/test_call_cpp_func.cpp | dghosef/taco | c5074c359af51242d76724f97bb5fe7d9b638658 | [
"MIT"
] | null | null | null | PochiVM/test_call_cpp_func.cpp | dghosef/taco | c5074c359af51242d76724f97bb5fe7d9b638658 | [
"MIT"
] | null | null | null | PochiVM/test_call_cpp_func.cpp | dghosef/taco | c5074c359af51242d76724f97bb5fe7d9b638658 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "pochivm.h"
#include "test_util_helper.h"
#include "codegen_context.hpp"
using namespace PochiVM;
TEST(SanityCallCppFn, Sanity_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)(TestClassA*, int);
{
auto [fn, c, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
c->SetY(v + Literal<int>(1)),
Return((*c).GetY() + Literal<int>(2))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
TestClassA a;
int ret = interpFn(&a, 123);
ReleaseAssert(a.m_y == 123 + 1);
ReleaseAssert(ret == 123 + 3);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
TestClassA a;
int ret = interpFn(&a, 123);
ReleaseAssert(a.m_y == 123 + 1);
ReleaseAssert(ret == 123 + 3);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
if (x_isDebugBuild)
{
jit.SetAllowResolveSymbolInHostProcess(true);
}
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
TestClassA a;
int ret = jitFn(&a, 123);
ReleaseAssert(a.m_y == 123 + 1);
ReleaseAssert(ret == 123 + 3);
}
}
TEST(SanityCallCppFn, Sanity_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int64_t(*)(TestClassA*, int);
{
auto [fn, c, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
c->PushVec(v),
Return(c->GetVectorSum())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
TestClassA a;
int expectedSum = 0;
std::vector<int> expectedVec;
for (int i = 0; i < 100; i++)
{
int k = rand() % 1000;
int64_t ret = interpFn(&a, k);
expectedVec.push_back(k);
expectedSum += k;
ReleaseAssert(ret == expectedSum);
ReleaseAssert(a.m_vec == expectedVec);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
TestClassA a;
int expectedSum = 0;
std::vector<int> expectedVec;
for (int i = 0; i < 100; i++)
{
int k = rand() % 1000;
int64_t ret = interpFn(&a, k);
expectedVec.push_back(k);
expectedSum += k;
ReleaseAssert(ret == expectedSum);
ReleaseAssert(a.m_vec == expectedVec);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "before_opt");
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
TestClassA a;
int expectedSum = 0;
std::vector<int> expectedVec;
for (int i = 0; i < 100; i++)
{
int k = rand() % 1000;
int64_t ret = jitFn(&a, k);
expectedVec.push_back(k);
expectedSum += k;
ReleaseAssert(ret == expectedSum);
ReleaseAssert(a.m_vec == expectedVec);
}
}
}
TEST(SanityCallCppFn, TypeMismatchErrorCase)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = double(*)(TestClassA*);
{
auto [fn, c] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(c->GetVectorSum())
);
}
ReleaseAssert(!thread_pochiVMContext->m_curModule->Validate());
ReleaseAssert(thread_errorContext->HasError());
AssertIsExpectedOutput(thread_errorContext->m_errorMsg);
}
TEST(SanityCallCppFn, Sanity_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)(std::string*);
{
auto [fn, c] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::FreeFnRecursive2(*c))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::string val = "10";
int result = interpFn(&val);
ReleaseAssert(result == 89);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::string val = "10";
int result = interpFn(&val);
ReleaseAssert(result == 89);
}
thread_pochiVMContext->m_curModule->EmitIR();
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "before_opt");
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::string val = "10";
int result = jitFn(&val);
ReleaseAssert(result == 89);
}
}
TEST(SanityCallCppFn, UnusedCppTypeCornerCase)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void*(*)(std::string*);
{
auto [fn, c] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(ReinterpretCast<void*>(c))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::string val = "10";
void* result = interpFn(&val);
ReleaseAssert(result == reinterpret_cast<void*>(&val));
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::string val = "10";
void* result = interpFn(&val);
ReleaseAssert(result == reinterpret_cast<void*>(&val));
}
thread_pochiVMContext->m_curModule->EmitIR();
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "before_opt");
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::string val = "10";
void* result = jitFn(&val);
ReleaseAssert(result == reinterpret_cast<void*>(&val));
}
}
TEST(SanityCallCppFn, BooleanTypeCornerCase_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = bool(*)(int, bool*, bool**);
{
auto [fn, a, b, c] = NewFunction<FnPrototype>("testfn");
auto d = fn.NewVariable<bool>();
fn.SetBody(
Declare(d, a == Literal<int>(233)),
Return(CallFreeFn::TestCornerCases::BoolParamTest1(d, b, c))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[3];
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(b, 233, 3);
x[0] = true; x[1] = false;
ReleaseAssert(interpFn(233, b, ppx) == false);
ReleaseAssert(_b[0] == 1);
ReleaseAssert(_b[1] == 1);
ReleaseAssert(_b[2] == 1);
memset(b, 233, 3);
x[0] = false; x[1] = true;
ReleaseAssert(interpFn(100, b, ppx) == true);
ReleaseAssert(_b[0] == 1);
ReleaseAssert(_b[1] == 0);
ReleaseAssert(_b[2] == 0);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[3];
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(b, 233, 3);
x[0] = true; x[1] = false;
ReleaseAssert(interpFn(233, b, ppx) == false);
ReleaseAssert(_b[0] == 1);
ReleaseAssert(_b[1] == 1);
ReleaseAssert(_b[2] == 1);
memset(b, 233, 3);
x[0] = false; x[1] = true;
ReleaseAssert(interpFn(100, b, ppx) == true);
ReleaseAssert(_b[0] == 1);
ReleaseAssert(_b[1] == 0);
ReleaseAssert(_b[2] == 0);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[3];
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(b, 233, 3);
x[0] = true; x[1] = false;
ReleaseAssert(jitFn(233, b, ppx) == false);
ReleaseAssert(_b[0] == 1);
ReleaseAssert(_b[1] == 1);
ReleaseAssert(_b[2] == 1);
memset(b, 233, 3);
x[0] = false; x[1] = true;
ReleaseAssert(jitFn(100, b, ppx) == true);
ReleaseAssert(_b[0] == 1);
ReleaseAssert(_b[1] == 0);
ReleaseAssert(_b[2] == 0);
}
}
TEST(SanityCallCppFn, BooleanTypeCornerCase_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = bool(*)(int, bool**, bool**);
{
auto [fn, a, b, c] = NewFunction<FnPrototype>("testfn");
auto d = fn.NewVariable<bool>();
fn.SetBody(
Declare(d, a == Literal<int>(233)),
CallFreeFn::TestCornerCases::BoolParamTest2(d, *b, c),
Return(d)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[4];
bool* pb = b;
bool** ppb = &pb;
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(x, 233, 1); x[1] = false;
memset(b, 233, 4);
ReleaseAssert(interpFn(233, ppx, ppb) == false);
ReleaseAssert(*reinterpret_cast<uint8_t*>(x) == 1);
ReleaseAssert(_b[2] == 1);
ReleaseAssert(_b[3] == 0);
ReleaseAssert(*ppx = pb);
}
{
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[4];
bool* pb = b;
bool** ppb = &pb;
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(x, 233, 1); x[1] = true;
memset(b, 233, 4); b[1] = false;
ReleaseAssert(interpFn(100, ppx, ppb) == true);
ReleaseAssert(*reinterpret_cast<uint8_t*>(x) == 0);
ReleaseAssert(_b[2] == 1);
ReleaseAssert(_b[3] == 0);
ReleaseAssert(*ppx = pb);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[4];
bool* pb = b;
bool** ppb = &pb;
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(x, 233, 1); x[1] = false;
memset(b, 233, 4);
ReleaseAssert(interpFn(233, ppx, ppb) == false);
ReleaseAssert(*reinterpret_cast<uint8_t*>(x) == 1);
ReleaseAssert(_b[2] == 1);
ReleaseAssert(_b[3] == 0);
ReleaseAssert(*ppx = pb);
}
{
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[4];
bool* pb = b;
bool** ppb = &pb;
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(x, 233, 1); x[1] = true;
memset(b, 233, 4); b[1] = false;
ReleaseAssert(interpFn(100, ppx, ppb) == true);
ReleaseAssert(*reinterpret_cast<uint8_t*>(x) == 0);
ReleaseAssert(_b[2] == 1);
ReleaseAssert(_b[3] == 0);
ReleaseAssert(*ppx = pb);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[4];
bool* pb = b;
bool** ppb = &pb;
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(x, 233, 1); x[1] = false;
memset(b, 233, 4);
ReleaseAssert(jitFn(233, ppx, ppb) == false);
ReleaseAssert(*reinterpret_cast<uint8_t*>(x) == 1);
ReleaseAssert(_b[2] == 1);
ReleaseAssert(_b[3] == 0);
ReleaseAssert(*ppx = pb);
}
{
bool x[2];
bool* px = x;
bool** ppx = &px;
bool b[4];
bool* pb = b;
bool** ppb = &pb;
uint8_t* _b = reinterpret_cast<uint8_t*>(b);
memset(x, 233, 1); x[1] = true;
memset(b, 233, 4); b[1] = false;
ReleaseAssert(jitFn(100, ppx, ppb) == true);
ReleaseAssert(*reinterpret_cast<uint8_t*>(x) == 0);
ReleaseAssert(_b[2] == 1);
ReleaseAssert(_b[3] == 0);
ReleaseAssert(*ppx = pb);
}
}
}
TEST(SanityCallCppFn, VoidStarCornerCase_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void*(*)(void*, void**);
{
auto [fn, a, b] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::TestCornerCases::VoidStarParamTest1(a, b))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
void* a = reinterpret_cast<void*>(233);
void* c;
void** b = &c;
ReleaseAssert(interpFn(a, b) == reinterpret_cast<void*>(233 + 8));
ReleaseAssert(c == reinterpret_cast<void*>(233));
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
void* a = reinterpret_cast<void*>(233);
void* c;
void** b = &c;
ReleaseAssert(interpFn(a, b) == reinterpret_cast<void*>(233 + 8));
ReleaseAssert(c == reinterpret_cast<void*>(233));
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
void* a = reinterpret_cast<void*>(233);
void* c;
void** b = &c;
ReleaseAssert(jitFn(a, b) == reinterpret_cast<void*>(233 + 8));
ReleaseAssert(c == reinterpret_cast<void*>(233));
}
}
TEST(SanityCallCppFn, VoidStarCornerCase_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void*(*)(void*, void**);
{
auto [fn, a, b] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
CallFreeFn::TestCornerCases::VoidStarParamTest2(a, b),
Return(a)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
void* a = reinterpret_cast<void*>(233);
void* b[2];
b[0] = nullptr; b[1] = reinterpret_cast<void*>(345);
ReleaseAssert(interpFn(a, b) == reinterpret_cast<void*>(345));
ReleaseAssert(b[0] == reinterpret_cast<void*>(233));
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
void* a = reinterpret_cast<void*>(233);
void* b[2];
b[0] = nullptr; b[1] = reinterpret_cast<void*>(345);
ReleaseAssert(interpFn(a, b) == reinterpret_cast<void*>(345));
ReleaseAssert(b[0] == reinterpret_cast<void*>(233));
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
void* a = reinterpret_cast<void*>(233);
void* b[2];
b[0] = nullptr; b[1] = reinterpret_cast<void*>(345);
ReleaseAssert(jitFn(a, b) == reinterpret_cast<void*>(345));
ReleaseAssert(b[0] == reinterpret_cast<void*>(233));
}
}
TEST(SanityCallCppFn, ReturnsNonPrimitiveType)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = bool(*)(int);
{
auto [fn, param] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<TestNonTrivialConstructor>();
fn.SetBody(
Declare(v, Variable<TestNonTrivialConstructor>::Create(param)),
Return(v.GetValue() == Literal<int>(233))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
ReleaseAssert(interpFn(233) == true);
ReleaseAssert(interpFn(234) == false);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
ReleaseAssert(interpFn(233) == true);
ReleaseAssert(interpFn(234) == false);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
// in non-debug build, the whole thing should have been inlined and optimized out
//
jit.SetAllowResolveSymbolInHostProcess(x_isDebugBuild);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
ReleaseAssert(jitFn(233) == true);
ReleaseAssert(jitFn(234) == false);
}
}
TEST(SanityCallCppFn, NonTrivialCopyConstructor)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)(TestNonTrivialCopyConstructor*);
{
auto [fn, param] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(Variable<TestNonTrivialCopyConstructor>::Fn(*param))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
TestNonTrivialCopyConstructor::counter = 0;
TestNonTrivialCopyConstructor x(5);
ReleaseAssert(interpFn(&x) == 5);
ReleaseAssert(TestNonTrivialCopyConstructor::counter == 1);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
TestNonTrivialCopyConstructor::counter = 0;
TestNonTrivialCopyConstructor x(5);
ReleaseAssert(interpFn(&x) == 5);
ReleaseAssert(TestNonTrivialCopyConstructor::counter == 1);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
TestNonTrivialCopyConstructor::counter = 0;
TestNonTrivialCopyConstructor x(5);
ReleaseAssert(jitFn(&x) == 5);
ReleaseAssert(TestNonTrivialCopyConstructor::counter == 1);
}
}
TEST(SanityCallCppFn, Constructor_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(std::vector<int>*);
{
auto [fn, param] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<std::vector<int>>();
fn.SetBody(
Declare(v),
CallFreeFn::CopyVectorInt(param, v.Addr())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
interpFn(&a);
ReleaseAssert(a.size() == 0);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
interpFn(&a);
ReleaseAssert(a.size() == 0);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
jitFn(&a);
ReleaseAssert(a.size() == 0);
}
}
TEST(SanityCallCppFn, Constructor_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(std::vector<int>*, size_t);
{
auto [fn, param, num] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<std::vector<int>>();
fn.SetBody(
Declare(v, Constructor<std::vector<int>>(num)),
CallFreeFn::CopyVectorInt(param, v.Addr())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
interpFn(&a, 100);
ReleaseAssert(a.size() == 100);
for (size_t i = 0; i < 100; i++) { ReleaseAssert(a[i] == 0); }
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
interpFn(&a, 100);
ReleaseAssert(a.size() == 100);
for (size_t i = 0; i < 100; i++) { ReleaseAssert(a[i] == 0); }
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
jitFn(&a, 100);
ReleaseAssert(a.size() == 100);
for (size_t i = 0; i < 100; i++) { ReleaseAssert(a[i] == 0); }
}
}
TEST(SanityCallCppFn, Constructor_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(std::vector<int>*, size_t, int);
{
auto [fn, param, num, val] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<std::vector<int>>();
fn.SetBody(
Declare(v, Constructor<std::vector<int>>(num, val)),
CallFreeFn::CopyVectorInt(param, v.Addr())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
interpFn(&a, 100, 34567);
ReleaseAssert(a.size() == 100);
for (size_t i = 0; i < 100; i++) { ReleaseAssert(a[i] == 34567); }
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
interpFn(&a, 100, 34567);
ReleaseAssert(a.size() == 100);
for (size_t i = 0; i < 100; i++) { ReleaseAssert(a[i] == 34567); }
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::vector<int> a;
a.push_back(233);
jitFn(&a, 100, 45678);
ReleaseAssert(a.size() == 100);
for (size_t i = 0; i < 100; i++) { ReleaseAssert(a[i] == 45678); }
}
}
TEST(SanityCallCppFn, Constructor_4)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(std::vector<int>*, std::vector<int>*);
{
auto [fn, param, param2] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<std::vector<int>>();
fn.SetBody(
Declare(v, Constructor<std::vector<int>>(*param2)),
CallFreeFn::CopyVectorInt(param, v.Addr())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a, b;
a.push_back(233);
b.push_back(456); b.push_back(567);
interpFn(&a, &b);
ReleaseAssert(a.size() == 2);
ReleaseAssert(a[0] == 456 && a[1] == 567);
ReleaseAssert(b.size() == 2);
ReleaseAssert(b[0] == 456 && b[1] == 567);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::vector<int> a, b;
a.push_back(233);
b.push_back(456); b.push_back(567);
interpFn(&a, &b);
ReleaseAssert(a.size() == 2);
ReleaseAssert(a[0] == 456 && a[1] == 567);
ReleaseAssert(b.size() == 2);
ReleaseAssert(b[0] == 456 && b[1] == 567);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::vector<int> a, b;
a.push_back(233);
b.push_back(456); b.push_back(567);
jitFn(&a, &b);
ReleaseAssert(a.size() == 2);
ReleaseAssert(a[0] == 456 && a[1] == 567);
ReleaseAssert(b.size() == 2);
ReleaseAssert(b[0] == 456 && b[1] == 567);
}
}
TEST(SanityCallCppFn, Constructor_5)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)();
{
auto [fn] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<TestConstructor1>();
fn.SetBody(
Declare(v),
Return(v.GetValue())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
ReleaseAssert(interpFn() == 233);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
ReleaseAssert(interpFn() == 233);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
ReleaseAssert(jitFn() == 233);
}
}
TEST(SanityCallCppFn, ManuallyCallDestructor)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(TestDestructor1*);
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
CallDestructor(v)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
int out = 0;
TestDestructor1* obj = reinterpret_cast<TestDestructor1*>(alloca(sizeof(TestDestructor1)));
new (obj) TestDestructor1(233, &out);
ReleaseAssert(out == 0);
interpFn(obj);
ReleaseAssert(out == 233);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
int out = 0;
TestDestructor1* obj = reinterpret_cast<TestDestructor1*>(alloca(sizeof(TestDestructor1)));
new (obj) TestDestructor1(233, &out);
ReleaseAssert(out == 0);
interpFn(obj);
ReleaseAssert(out == 233);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(x_isDebugBuild);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
int out = 0;
TestDestructor1* obj = reinterpret_cast<TestDestructor1*>(alloca(sizeof(TestDestructor1)));
new (obj) TestDestructor1(233, &out);
ReleaseAssert(out == 0);
jitFn(obj);
ReleaseAssert(out == 233);
}
}
TEST(SanityCallCppFn, DestructorSanity_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(int, int*);
{
auto [fn, v, addr] = NewFunction<FnPrototype>("testfn");
auto x = fn.NewVariable<TestDestructor1>();
fn.SetBody(
Declare(x, Constructor<TestDestructor1>(v, addr))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
int out = 0;
interpFn(233, &out);
ReleaseAssert(out == 233);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
int out = 0;
interpFn(233, &out);
ReleaseAssert(out == 233);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(x_isDebugBuild);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
int out = 0;
jitFn(233, &out);
ReleaseAssert(out == 233);
}
}
TEST(SanityCallCppFn, DestructorSanity_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
auto x = fn.NewVariable<TestDestructor2>();
fn.SetBody(
Declare(x, Constructor<TestDestructor2>(r, Literal<int>(123)))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert((r.order == std::vector<int>{123, -123}));
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert((r.order == std::vector<int>{123, -123}));
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
jitFn(&r);
ReleaseAssert((r.order == std::vector<int>{123, -123}));
}
}
TEST(SanityCallCppFn, DestructorCalledInReverseOrder_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1002)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1003)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1004))
);
}
std::vector<int> expectedAns {
1000, 1, 1001, 2, 1002, 3, 1003, 4, 1004, -4, -3, -2, -1
};
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
jitFn(&r);
ReleaseAssert(r.order == expectedAns);
}
}
TEST(SanityCallCppFn, DestructorCalledInReverseOrder_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Scope(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004))
),
(*r).Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Scope(
r->Push(Literal<int>(1007)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009))
),
r->Push(Literal<int>(1010)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1011))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns {
1000, 1, 1001, 1002, 2, 1003, 3, 1004, -3, -2, 1005, 4, 1006,
1007, 5, 1008, 6, 1009, -6, -5, 1010, 7, 1011, -7, -4, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
jitFn(&r);
ReleaseAssert(r.order == expectedAns);
}
}
TEST(SanityCallCppFn, BlockDoesNotConstituteVariableScope)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Block(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004))
),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Block(
r->Push(Literal<int>(1007)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009))
),
r->Push(Literal<int>(1010)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1011))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns {
1000, 1, 1001, 1002, 2, 1003, 3, 1004, 1005, 4, 1006, 1007, 5, 1008, 6, 1009,
1010, 7, 1011, -7, -6, -5, -4, -3, -2, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
jitFn(&r);
ReleaseAssert(r.order == expectedAns);
}
}
TEST(SanityCallCppFn, DestructorCalledUponReturnStmt)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1002)),
Scope(
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1005)),
Scope(
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1008))
),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Scope(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013)),
Return()
)
)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns {
1000, 1, 1001, 2, 1002, 1003, 3, 1004, 4, 1005, 1006, 5, 1007, 6, 1008,
-6, -5, 1009, 7, 1010, 1011, 8, 1012, 9, 1013, -9, -8, -7, -4, -3, -2, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
interpFn(&r);
ReleaseAssert(r.order == expectedAns);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
CtorDtorOrderRecorder r;
jitFn(&r);
ReleaseAssert(r.order == expectedAns);
}
}
TEST(SanityCallCppFn, DestructorInteractionWithIfStatement_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, bool, bool);
{
auto [fn, r, b1, b2] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
auto v13 = fn.NewVariable<TestDestructor2>();
auto v14 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
If(b1).Then(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
If(b2).Then(
r->Push(Literal<int>(1004)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006))
).Else(
r->Push(Literal<int>(1007)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009))
),
r->Push(Literal<int>(1010)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1011))
).Else(
r->Push(Literal<int>(1012)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1013)),
If(b2).Then(
r->Push(Literal<int>(1014)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1015)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1016))
).Else(
r->Push(Literal<int>(1017)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1018)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1019))
),
r->Push(Literal<int>(1020)),
Declare(v13, Constructor<TestDestructor2>(r, Literal<int>(13))),
r->Push(Literal<int>(1021))
),
r->Push(Literal<int>(1022)),
Declare(v14, Constructor<TestDestructor2>(r, Literal<int>(14))),
r->Push(Literal<int>(1023))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 1004, 3, 1005, 4, 1006, -4, -3,
1010, 7, 1011, -7, -2, 1022, 14, 1023, -14, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 1007, 5, 1008, 6, 1009, -6, -5,
1010, 7, 1011, -7, -2, 1022, 14, 1023, -14, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 1012, 8, 1013, 1014, 9, 1015, 10, 1016, -10, -9,
1020, 13, 1021, -13, -8, 1022, 14, 1023, -14, -1
};
std::vector<int> expectedAns4 {
1000, 1, 1001, 1012, 8, 1013, 1017, 11, 1018, 12, 1019, -12, -11,
1020, 13, 1021, -13, -8, 1022, 14, 1023, -14, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithIfStatement_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, bool, bool);
{
auto [fn, r, b1, b2] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
auto v13 = fn.NewVariable<TestDestructor2>();
auto v14 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
If(b1).Then(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
If(b2).Then(
r->Push(Literal<int>(1004)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Return()
).Else(
r->Push(Literal<int>(1007)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009))
),
r->Push(Literal<int>(1010)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1011)),
Return()
).Else(
r->Push(Literal<int>(1012)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1013)),
If(b2).Then(
r->Push(Literal<int>(1014)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1015)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1016)),
Return()
).Else(
r->Push(Literal<int>(1017)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1018)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1019))
),
r->Push(Literal<int>(1020)),
Declare(v13, Constructor<TestDestructor2>(r, Literal<int>(13))),
r->Push(Literal<int>(1021))
),
r->Push(Literal<int>(1022)),
Declare(v14, Constructor<TestDestructor2>(r, Literal<int>(14))),
r->Push(Literal<int>(1023))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 1004, 3, 1005, 4, 1006, -4, -3, -2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 1007, 5, 1008, 6, 1009, -6, -5,
1010, 7, 1011, -7, -2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 1012, 8, 1013, 1014, 9, 1015, 10, 1016, -10, -9, -8, -1
};
std::vector<int> expectedAns4 {
1000, 1, 1001, 1012, 8, 1013, 1017, 11, 1018, 12, 1019, -12, -11,
1020, 13, 1021, -13, -8, 1022, 14, 1023, -14, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithIfStatement_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, bool, bool);
{
auto [fn, r, b1, b2] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
auto v13 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
If(b1).Then(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
If(b2).Then(
r->Push(Literal<int>(1004)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Return()
).Else(
r->Push(Literal<int>(1007)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Return()
)
).Else(
r->Push(Literal<int>(1012)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1013)),
If(b2).Then(
r->Push(Literal<int>(1014)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1015)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1016)),
Return()
).Else(
r->Push(Literal<int>(1017)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1018)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1019))
),
r->Push(Literal<int>(1020)),
Declare(v13, Constructor<TestDestructor2>(r, Literal<int>(13))),
r->Push(Literal<int>(1021)),
Return()
)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 1004, 3, 1005, 4, 1006, -4, -3, -2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 1007, 5, 1008, 6, 1009, -6, -5, -2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 1012, 8, 1013, 1014, 9, 1015, 10, 1016, -10, -9, -8, -1
};
std::vector<int> expectedAns4 {
1000, 1, 1001, 1012, 8, 1013, 1017, 11, 1018, 12, 1019, -12, -11,
1020, 13, 1021, -13, -8, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, true, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, true, false);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false, true);
ReleaseAssert(r.order == expectedAns3);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false, false);
ReleaseAssert(r.order == expectedAns4);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithForLoop_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, int);
{
auto [fn, r, x] = NewFunction<FnPrototype>("testfn");
auto i = fn.NewVariable<int>();
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
For(Block(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004)),
Declare(i, Literal<int>(0))
), i < Literal<int>(3), Assign(i, i + Literal<int>(1))).Do(
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
If(i == x).Then(
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Break()
).Else(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013))
),
r->Push(Literal<int>(1014)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1015)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1016))
),
r->Push(Literal<int>(1017)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1018))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns0 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithForLoop_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, int);
{
auto [fn, r, x] = NewFunction<FnPrototype>("testfn");
auto i = fn.NewVariable<int>();
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
For(Block(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004)),
Declare(i, Literal<int>(0))
), i < Literal<int>(3), Assign(i, i + Literal<int>(1))).Do(
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
If(i == x).Then(
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Continue()
).Else(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013))
),
r->Push(Literal<int>(1014)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1015)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1016))
),
r->Push(Literal<int>(1017)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1018))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns0 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithForLoop_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, int);
{
auto [fn, r, x] = NewFunction<FnPrototype>("testfn");
auto i = fn.NewVariable<int>();
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
For(Block(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004)),
Declare(i, Literal<int>(0))
), i < Literal<int>(3), Assign(i, i + Literal<int>(1))).Do(
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
If(i == x).Then(
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Return()
).Else(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013))
),
r->Push(Literal<int>(1014)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1015)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1016))
),
r->Push(Literal<int>(1017)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1018))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns0 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, -1
};
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-3, -2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
-3, -2, 1017, 12, 1018, -12, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithForLoop_4)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, bool);
{
auto [fn, r, b] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
For(Block(
r->Push(Literal<int>(1002)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1003)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
r->Push(Literal<int>(1004))
), b, Block()).Do(
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
Break()
),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns1 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
1005, 4, 1006, 5, 1007, -5, -4, -3, -2, 1008, 6, 1009, -6, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 1002, 2, 1003, 3, 1004,
-3, -2, 1008, 6, 1009, -6, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false);
ReleaseAssert(r.order == expectedAns2);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false);
ReleaseAssert(r.order == expectedAns2);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false);
ReleaseAssert(r.order == expectedAns2);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithWhileLoop_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, int);
{
auto [fn, r, x] = NewFunction<FnPrototype>("testfn");
auto i = fn.NewVariable<int>();
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1002)),
Declare(i, Literal<int>(0)),
While(i < Literal<int>(3)).Do(
Assign(i, i + Literal<int>(1)),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
If(i - Literal<int>(1) == x).Then(
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Return()
).Else(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013))
),
r->Push(Literal<int>(1014)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1015)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1016))
),
r->Push(Literal<int>(1017)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1018))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns0 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-2, -1
};
std::vector<int> expectedAns1 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
-2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1017, 12, 1018, -12, -2, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithWhileLoop_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, int);
{
auto [fn, r, x] = NewFunction<FnPrototype>("testfn");
auto i = fn.NewVariable<int>();
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1002)),
Declare(i, Literal<int>(0)),
While(i < Literal<int>(3)).Do(
Assign(i, i + Literal<int>(1)),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
If(i - Literal<int>(1) == x).Then(
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Break()
).Else(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013))
),
r->Push(Literal<int>(1014)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1015)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1016))
),
r->Push(Literal<int>(1017)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1018))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns0 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1017, 12, 1018, -12, -2, -1
};
std::vector<int> expectedAns1 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1017, 12, 1018, -12, -2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1017, 12, 1018, -12, -2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1017, 12, 1018, -12, -2, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithWhileLoop_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, int);
{
auto [fn, r, x] = NewFunction<FnPrototype>("testfn");
auto i = fn.NewVariable<int>();
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1002)),
Declare(i, Literal<int>(0)),
While(i < Literal<int>(3)).Do(
Assign(i, i + Literal<int>(1)),
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
If(i - Literal<int>(1) == x).Then(
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
r->Push(Literal<int>(1010)),
Continue()
).Else(
r->Push(Literal<int>(1011)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
r->Push(Literal<int>(1012)),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
r->Push(Literal<int>(1013))
),
r->Push(Literal<int>(1014)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
r->Push(Literal<int>(1015)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->Push(Literal<int>(1016))
),
r->Push(Literal<int>(1017)),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->Push(Literal<int>(1018))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns0 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1017, 12, 1018, -12, -2, -1
};
std::vector<int> expectedAns1 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1017, 12, 1018, -12, -2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1008, 6, 1009, 7, 1010, -7, -6, -5, -4,
1017, 12, 1018, -12, -2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1005, 4, 1006, 5, 1007, 1011, 8, 1012, 9, 1013, -9, -8, 1014, 10, 1015, 11, 1016, -11, -10, -5, -4,
1017, 12, 1018, -12, -2, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, 0);
ReleaseAssert(r.order == expectedAns0);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 1);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 2);
ReleaseAssert(r.order == expectedAns2);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, 3);
ReleaseAssert(r.order == expectedAns3);
}
}
}
TEST(SanityCallCppFn, DestructorInteractionWithWhileLoop_4)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*, bool);
{
auto [fn, r, b] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->Push(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
r->Push(Literal<int>(1001)),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->Push(Literal<int>(1002)),
While(b).Do(
r->Push(Literal<int>(1005)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->Push(Literal<int>(1006)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
r->Push(Literal<int>(1007)),
Break()
),
r->Push(Literal<int>(1008)),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->Push(Literal<int>(1009))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
std::vector<int> expectedAns1 {
1000, 1, 1001, 2, 1002,
1005, 4, 1006, 5, 1007, -5, -4, 1008, 6, 1009, -6, -2, -1
};
std::vector<int> expectedAns2 {
1000, 1, 1001, 2, 1002, 1008, 6, 1009, -6, -2, -1
};
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false);
ReleaseAssert(r.order == expectedAns2);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
interpFn(&r, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
interpFn(&r, false);
ReleaseAssert(r.order == expectedAns2);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
{
CtorDtorOrderRecorder r;
jitFn(&r, true);
ReleaseAssert(r.order == expectedAns1);
}
{
CtorDtorOrderRecorder r;
jitFn(&r, false);
ReleaseAssert(r.order == expectedAns2);
}
}
}
TEST(SanityCallCppFn, StaticVarInFunction)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)();
{
auto [fn] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::TestStaticVarInFunction(Literal<bool>(false)))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
TestStaticVarInFunction(true /*reset*/);
int expected = 123;
for (int i = 0; i < 10; i++)
{
expected += 12;
ReleaseAssert(TestStaticVarInFunction(false /*reset*/) == expected);
expected += 12;
ReleaseAssert(interpFn() == expected);
}
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
TestStaticVarInFunction(true /*reset*/);
int expected = 123;
for (int i = 0; i < 10; i++)
{
expected += 12;
ReleaseAssert(TestStaticVarInFunction(false /*reset*/) == expected);
expected += 12;
ReleaseAssert(interpFn() == expected);
}
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
TestStaticVarInFunction(true /*reset*/);
int expected = 123;
for (int i = 0; i < 10; i++)
{
expected += 12;
ReleaseAssert(TestStaticVarInFunction(false /*reset*/) == expected);
expected += 12;
ReleaseAssert(jitFn() == expected);
}
}
}
TEST(SanityCallCppFn, ConstantWithSignificantAddress)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = TestConstantClass*(*)();
{
auto [fn] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::TestConstantWithSignificantAddress())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
const TestConstantClass* expectedAddr = TestConstantWithSignificantAddress();
const TestConstantClass* actualAddr = interpFn();
ReleaseAssert(expectedAddr == actualAddr);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
const TestConstantClass* expectedAddr = TestConstantWithSignificantAddress();
const TestConstantClass* actualAddr = interpFn();
ReleaseAssert(expectedAddr == actualAddr);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
const TestConstantClass* expectedAddr = TestConstantWithSignificantAddress();
const TestConstantClass* actualAddr = jitFn();
ReleaseAssert(expectedAddr == actualAddr);
}
}
TEST(SanityCallCppFn, ConstantWithInsignificantAddress)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = bool(*)(uint8_t*);
{
auto [fn, x] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::TestConstantWithInsignificantAddress(x))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
ReleaseAssert(interpFn(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>("123"))) == false);
ReleaseAssert(interpFn(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>("12345678"))) == true);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
ReleaseAssert(interpFn(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>("123"))) == false);
ReleaseAssert(interpFn(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>("12345678"))) == true);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
ReleaseAssert(jitFn(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>("123"))) == false);
ReleaseAssert(jitFn(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>("12345678"))) == true);
}
}
TEST(SanityCallCppFn, StringInternQuirkyBehavior)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = uint8_t*(*)();
{
auto [fn] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::StringInterningQuirkyBehavior())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
const uint8_t* v1 = StringInterningQuirkyBehavior();
const uint8_t* v2 = interpFn();
ReleaseAssert(v1 == v2);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
const uint8_t* v1 = StringInterningQuirkyBehavior();
const uint8_t* v2 = interpFn();
ReleaseAssert(v1 == v2);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
const uint8_t* v1 = StringInterningQuirkyBehavior();
const uint8_t* v2 = jitFn();
if (!x_isDebugBuild)
{
// in release build, the function should have been optimized out,
// resulting in two different symbols
//
ReleaseAssert(v1 != v2);
ReleaseAssert(strcmp(reinterpret_cast<const char*>(v1), reinterpret_cast<const char*>(v2)) == 0);
}
else
{
// in debug build, no inlining happens, we should still be calling the host process's function
//
ReleaseAssert(v1 == v2);
}
}
}
TEST(SanityCallCppFn, UnexpectedException_Interp)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(int);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
CallFreeFn::TestNoExceptButThrows(r)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
interpFn(345); // nothing should happen
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(interpFn(123), "");
#pragma clang diagnostic pop
}
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
interpFn(345); // nothing should happen
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(interpFn(123), "");
#pragma clang diagnostic pop
}
}
TEST(SanityCallCppFn, UnexpectedException_LLVM)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(int);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
CallFreeFn::TestNoExceptButThrows(r)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
jitFn(345); // nothing should happen
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(jitFn(123), "");
#pragma clang diagnostic pop
}
}
TEST(SanityCallCppFn, Exception_PropagateThrough_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(CtorDtorOrderRecorder*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
auto v1 = fn.NewVariable<TestDestructor2>();
auto v2 = fn.NewVariable<TestDestructor2>();
auto v3 = fn.NewVariable<TestDestructor2>();
auto v4 = fn.NewVariable<TestDestructor2>();
auto v5 = fn.NewVariable<TestDestructor2>();
auto v6 = fn.NewVariable<TestDestructor2>();
auto v7 = fn.NewVariable<TestDestructor2>();
auto v8 = fn.NewVariable<TestDestructor2>();
auto v9 = fn.NewVariable<TestDestructor2>();
auto v10 = fn.NewVariable<TestDestructor2>();
auto v11 = fn.NewVariable<TestDestructor2>();
auto v12 = fn.NewVariable<TestDestructor2>();
auto v13 = fn.NewVariable<TestDestructor2>();
auto v14 = fn.NewVariable<TestDestructor2>();
fn.SetBody(
r->PushMaybeThrow(Literal<int>(1000)),
Declare(v1, Constructor<TestDestructor2>(r, Literal<int>(1))),
Declare(v2, Constructor<TestDestructor2>(r, Literal<int>(2))),
r->PushMaybeThrow(Literal<int>(1001)),
Declare(v3, Constructor<TestDestructor2>(r, Literal<int>(3))),
Scope(
r->PushMaybeThrow(Literal<int>(1002)),
Declare(v4, Constructor<TestDestructor2>(r, Literal<int>(4))),
r->PushMaybeThrow(Literal<int>(1003)),
Declare(v5, Constructor<TestDestructor2>(r, Literal<int>(5))),
Declare(v6, Constructor<TestDestructor2>(r, Literal<int>(6))),
r->PushMaybeThrow(Literal<int>(1004))
),
r->PushMaybeThrow(Literal<int>(1005)),
Declare(v7, Constructor<TestDestructor2>(r, Literal<int>(7))),
Scope(
r->PushMaybeThrow(Literal<int>(1006)),
Declare(v8, Constructor<TestDestructor2>(r, Literal<int>(8))),
Declare(v9, Constructor<TestDestructor2>(r, Literal<int>(9))),
Scope(
r->PushMaybeThrow(Literal<int>(1007)),
Declare(v10, Constructor<TestDestructor2>(r, Literal<int>(10))),
Scope(
r->PushMaybeThrow(Literal<int>(1008)),
Declare(v11, Constructor<TestDestructor2>(r, Literal<int>(11))),
r->PushMaybeThrow(Literal<int>(1009))
),
Declare(v12, Constructor<TestDestructor2>(r, Literal<int>(12))),
r->PushMaybeThrow(Literal<int>(1010))
),
r->PushMaybeThrow(Literal<int>(1011)),
Declare(v13, Constructor<TestDestructor2>(r, Literal<int>(13))),
r->PushMaybeThrow(Literal<int>(1012)),
r->PushMaybeThrow(Literal<int>(1013))
),
r->PushMaybeThrow(Literal<int>(1014)),
Declare(v14, Constructor<TestDestructor2>(r, Literal<int>(14))),
r->PushMaybeThrow(Literal<int>(1015))
);
}
auto testFn = [](std::function<std::remove_pointer_t<FnPrototype>> f, int value, const std::vector<int>& expectedAns, bool expectThrow) {
CtorDtorOrderRecorder r;
r.throwValue = value;
try {
f(&r);
ReleaseAssert(!expectThrow);
} catch(int v) {
if (expectThrow) {
ReleaseAssert(v == value);
} else {
ReleaseAssert(false);
}
} catch(...) {
ReleaseAssert(false);
}
ReleaseAssert(r.order == expectedAns);
};
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
std::vector<int> expectedAns1000 {
1000
};
std::vector<int> expectedAns1 {
1000, 1
};
std::vector<int> expectedAns2 {
1000, 1, 2, -1
};
std::vector<int> expectedAns1001 {
1000, 1, 2, 1001, -2, -1
};
std::vector<int> expectedAns3 {
1000, 1, 2, 1001, 3, -2, -1
};
std::vector<int> expectedAns1002 {
1000, 1, 2, 1001, 3, 1002, -3, -2, -1
};
std::vector<int> expectedAns4 {
1000, 1, 2, 1001, 3, 1002, 4, -3, -2, -1
};
std::vector<int> expectedAns1003 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, -4, -3, -2, -1
};
std::vector<int> expectedAns5 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, -4, -3, -2, -1
};
std::vector<int> expectedAns6 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, -5, -4, -3, -2, -1
};
std::vector<int> expectedAns1004 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, -3, -2, -1
};
std::vector<int> expectedAns1005 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, -3, -2, -1
};
std::vector<int> expectedAns7 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, -3, -2, -1
};
std::vector<int> expectedAns1006 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, -7, -3, -2, -1
};
std::vector<int> expectedAns8 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, -7, -3, -2, -1
};
std::vector<int> expectedAns9 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1007 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
-9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns10 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1008 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, -10, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns11 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, -10, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1009 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, -10, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns12 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, -10, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1010 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1011 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns13 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1012 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, 1012, -13, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1013 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, 1012, 1013, -13, -9, -8, -7, -3, -2, -1
};
std::vector<int> expectedAns1014 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, 1012, 1013, -13, -9, -8, 1014, -7, -3, -2, -1
};
std::vector<int> expectedAns14 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, 1012, 1013, -13, -9, -8, 1014, 14, -7, -3, -2, -1
};
std::vector<int> expectedAns1015 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, 1012, 1013, -13, -9, -8, 1014, 14, 1015,
-14, -7, -3, -2, -1
};
std::vector<int> expectedAns1016 {
1000, 1, 2, 1001, 3, 1002, 4, 1003, 5, 6, 1004, -6, -5, -4, 1005, 7, 1006, 8, 9, 1007,
10, 1008, 11, 1009, -11, 12, 1010, -12, -10, 1011, 13, 1012, 1013, -13, -9, -8, 1014, 14, 1015,
-14, -7, -3, -2, -1
};
{
auto _interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::function<std::remove_pointer_t<FnPrototype>> interpFn = [_interpFn](CtorDtorOrderRecorder* param) {
return _interpFn(param);
};
testFn(interpFn, 1000, expectedAns1000, true);
testFn(interpFn, 1001, expectedAns1001, true);
testFn(interpFn, 1002, expectedAns1002, true);
testFn(interpFn, 1003, expectedAns1003, true);
testFn(interpFn, 1004, expectedAns1004, true);
testFn(interpFn, 1005, expectedAns1005, true);
testFn(interpFn, 1006, expectedAns1006, true);
testFn(interpFn, 1007, expectedAns1007, true);
testFn(interpFn, 1008, expectedAns1008, true);
testFn(interpFn, 1009, expectedAns1009, true);
testFn(interpFn, 1010, expectedAns1010, true);
testFn(interpFn, 1011, expectedAns1011, true);
testFn(interpFn, 1012, expectedAns1012, true);
testFn(interpFn, 1013, expectedAns1013, true);
testFn(interpFn, 1014, expectedAns1014, true);
testFn(interpFn, 1015, expectedAns1015, true);
testFn(interpFn, 1016, expectedAns1016, false);
testFn(interpFn, 1, expectedAns1, true);
testFn(interpFn, 2, expectedAns2, true);
testFn(interpFn, 3, expectedAns3, true);
testFn(interpFn, 4, expectedAns4, true);
testFn(interpFn, 5, expectedAns5, true);
testFn(interpFn, 6, expectedAns6, true);
testFn(interpFn, 7, expectedAns7, true);
testFn(interpFn, 8, expectedAns8, true);
testFn(interpFn, 9, expectedAns9, true);
testFn(interpFn, 10, expectedAns10, true);
testFn(interpFn, 11, expectedAns11, true);
testFn(interpFn, 12, expectedAns12, true);
testFn(interpFn, 13, expectedAns13, true);
testFn(interpFn, 14, expectedAns14, true);
}
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
testFn(interpFn, 1000, expectedAns1000, true);
testFn(interpFn, 1001, expectedAns1001, true);
testFn(interpFn, 1002, expectedAns1002, true);
testFn(interpFn, 1003, expectedAns1003, true);
testFn(interpFn, 1004, expectedAns1004, true);
testFn(interpFn, 1005, expectedAns1005, true);
testFn(interpFn, 1006, expectedAns1006, true);
testFn(interpFn, 1007, expectedAns1007, true);
testFn(interpFn, 1008, expectedAns1008, true);
testFn(interpFn, 1009, expectedAns1009, true);
testFn(interpFn, 1010, expectedAns1010, true);
testFn(interpFn, 1011, expectedAns1011, true);
testFn(interpFn, 1012, expectedAns1012, true);
testFn(interpFn, 1013, expectedAns1013, true);
testFn(interpFn, 1014, expectedAns1014, true);
testFn(interpFn, 1015, expectedAns1015, true);
testFn(interpFn, 1016, expectedAns1016, false);
testFn(interpFn, 1, expectedAns1, true);
testFn(interpFn, 2, expectedAns2, true);
testFn(interpFn, 3, expectedAns3, true);
testFn(interpFn, 4, expectedAns4, true);
testFn(interpFn, 5, expectedAns5, true);
testFn(interpFn, 6, expectedAns6, true);
testFn(interpFn, 7, expectedAns7, true);
testFn(interpFn, 8, expectedAns8, true);
testFn(interpFn, 9, expectedAns9, true);
testFn(interpFn, 10, expectedAns10, true);
testFn(interpFn, 11, expectedAns11, true);
testFn(interpFn, 12, expectedAns12, true);
testFn(interpFn, 13, expectedAns13, true);
testFn(interpFn, 14, expectedAns14, true);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
testFn(jitFn, 1000, expectedAns1000, true);
testFn(jitFn, 1001, expectedAns1001, true);
testFn(jitFn, 1002, expectedAns1002, true);
testFn(jitFn, 1003, expectedAns1003, true);
testFn(jitFn, 1004, expectedAns1004, true);
testFn(jitFn, 1005, expectedAns1005, true);
testFn(jitFn, 1006, expectedAns1006, true);
testFn(jitFn, 1007, expectedAns1007, true);
testFn(jitFn, 1008, expectedAns1008, true);
testFn(jitFn, 1009, expectedAns1009, true);
testFn(jitFn, 1010, expectedAns1010, true);
testFn(jitFn, 1011, expectedAns1011, true);
testFn(jitFn, 1012, expectedAns1012, true);
testFn(jitFn, 1013, expectedAns1013, true);
testFn(jitFn, 1014, expectedAns1014, true);
testFn(jitFn, 1015, expectedAns1015, true);
testFn(jitFn, 1016, expectedAns1016, false);
testFn(jitFn, 1, expectedAns1, true);
testFn(jitFn, 2, expectedAns2, true);
testFn(jitFn, 3, expectedAns3, true);
testFn(jitFn, 4, expectedAns4, true);
testFn(jitFn, 5, expectedAns5, true);
testFn(jitFn, 6, expectedAns6, true);
testFn(jitFn, 7, expectedAns7, true);
testFn(jitFn, 8, expectedAns8, true);
testFn(jitFn, 9, expectedAns9, true);
testFn(jitFn, 10, expectedAns10, true);
testFn(jitFn, 11, expectedAns11, true);
testFn(jitFn, 12, expectedAns12, true);
testFn(jitFn, 13, expectedAns13, true);
testFn(jitFn, 14, expectedAns14, true);
}
}
TEST(SanityCallCppFn, MemberObjectAccessor_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)(std::pair<int, double>*);
{
auto [fn, r] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(r->first())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::pair<int, double> v = std::make_pair(123, 456.789);
ReleaseAssert(interpFn(&v) == 123);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::pair<int, double> v = std::make_pair(123, 456.789);
ReleaseAssert(interpFn(&v) == 123);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::pair<int, double> v = std::make_pair(123, 456.789);
ReleaseAssert(jitFn(&v) == 123);
}
}
TEST(SanityCallCppFn, MemberObjectAccessor_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = void(*)(std::pair<int, double>*, double);
{
auto [fn, r, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Assign(r->second(), v)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::pair<int, double> v = std::make_pair(123, 456.789);
interpFn(&v, 543.21);
ReleaseAssert(fabs(v.second - 543.21) < 1e-12);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::pair<int, double> v = std::make_pair(123, 456.789);
interpFn(&v, 543.21);
ReleaseAssert(fabs(v.second - 543.21) < 1e-12);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::pair<int, double> v = std::make_pair(123, 456.789);
jitFn(&v, 543.21);
ReleaseAssert(fabs(v.second - 543.21) < 1e-12);
}
}
// For functions which definition resides in different translational units,
// the parameters may have different struct names. For example, struct name 'struct.std::pair.xxx' is given
// for each std::pair in a translational unit where xxx is a label, so the label may differ in different
// translational units for the same type. This test tests that our IR processor correctly
// renames all the struct names in other translational units so they match the name used in
// pochivm_register_runtime.cpp (which is the one we used to generate AstCppTypeLLVMTypeName array).
//
TEST(SanityCallCppFn, LLVMTypeMismatchRenaming)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = double(*)(std::pair<double, float>*, std::pair<double, uint64_t>*);
{
auto [fn, a, b] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(CallFreeFn::TestMismatchedLLVMTypeName(a) + CallFreeFn::TestMismatchedLLVMTypeName2(b))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::pair<double, float> a = std::make_pair(123.45, 456.789);
std::pair<double, uint64_t> b = std::make_pair(876.54, 321);
double r = interpFn(&a, &b);
ReleaseAssert(fabs(r - (123.45 + 456.789 + 876.54 + 321)) < 1e-5);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::pair<double, float> a = std::make_pair(123.45, 456.789);
std::pair<double, uint64_t> b = std::make_pair(876.54, 321);
double r = interpFn(&a, &b);
ReleaseAssert(fabs(r - (123.45 + 456.789 + 876.54 + 321)) < 1e-5);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::pair<double, float> a = std::make_pair(123.45, 456.789);
std::pair<double, uint64_t> b = std::make_pair(876.54, 321);
double r = jitFn(&a, &b);
ReleaseAssert(fabs(r - (123.45 + 456.789 + 876.54 + 321)) < 1e-5);
}
}
TEST(SanityCallCppFn, LLVMTypeMismatchRenaming_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype1 = uint64_t(*)(std::pair<uint16_t, uint32_t>*);
{
auto [fn, a] = NewFunction<FnPrototype1>("testfn");
fn.SetBody(
Return(CallFreeFn::TestMismatchedLLVMTypeName4(a))
);
}
using FnPrototype2 = uint64_t(*)(std::pair<uint32_t, uint16_t>*);
{
auto [fn, a] = NewFunction<FnPrototype2>("testfn2");
fn.SetBody(
Return(CallFreeFn::TestMismatchedLLVMTypeName3(a))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn1 = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype1>("testfn");
auto interpFn2 = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype2>("testfn2");
std::pair<uint16_t, uint32_t> v1 = std::make_pair(123, 456);
ReleaseAssert(interpFn1(&v1) == 123 + 456);
std::pair<uint32_t, uint16_t> v2 = std::make_pair(789, 654);
ReleaseAssert(interpFn2(&v2) == 789 + 654);
}
{
FastInterpFunction<FnPrototype1> interpFn1 = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype1>("testfn");
FastInterpFunction<FnPrototype2> interpFn2 = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype2>("testfn2");
std::pair<uint16_t, uint32_t> v1 = std::make_pair(123, 456);
ReleaseAssert(interpFn1(&v1) == 123 + 456);
std::pair<uint32_t, uint16_t> v2 = std::make_pair(789, 654);
ReleaseAssert(interpFn2(&v2) == 789 + 654);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype1 jitFn1 = jit.GetFunction<FnPrototype1>("testfn");
FnPrototype2 jitFn2 = jit.GetFunction<FnPrototype2>("testfn2");
std::pair<uint16_t, uint32_t> v1 = std::make_pair(123, 456);
ReleaseAssert(jitFn1(&v1) == 123 + 456);
std::pair<uint32_t, uint16_t> v2 = std::make_pair(789, 654);
ReleaseAssert(jitFn2(&v2) == 789 + 654);
}
}
// Test that 'const PT&' parameter is converted to 'PT'
//
TEST(SanityCallCppFn, ConstRefParameterConversion_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype1 = int(*)(int*);
{
auto [fn, a] = NewFunction<FnPrototype1>("testfn");
auto v = fn.NewVariable<int>();
fn.SetBody(
Declare(v, 3),
Return(CallFreeFn::TestConstPrimitiveTypeParam(
Literal<int>(1), *a, a, a, v.Addr(), v.Addr()
))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn1 = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(interpFn1(&v) == 123 * 3 + 3 * 2 + 1);
}
{
FastInterpFunction<FnPrototype1> interpFn1 = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(interpFn1(&v) == 123 * 3 + 3 * 2 + 1);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype1 jitFn1 = jit.GetFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(jitFn1(&v) == 123 * 3 + 3 * 2 + 1);
}
}
TEST(SanityCallCppFn, ConstRefParameterConversion_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype1 = int(*)(int*);
{
auto [fn, a] = NewFunction<FnPrototype1>("testfn");
auto v = fn.NewVariable<int>();
auto v2 = fn.NewVariable<TestConstPrimitiveTypeCtor>();
fn.SetBody(
Declare(v, 3),
Declare(v2, Constructor<TestConstPrimitiveTypeCtor>(
Literal<int>(1), *a, a, a, v.Addr(), v.Addr()
)),
Return(v2.value())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn1 = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(interpFn1(&v) == 123 * 3 + 3 * 2 + 1);
}
{
FastInterpFunction<FnPrototype1> interpFn1 = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(interpFn1(&v) == 123 * 3 + 3 * 2 + 1);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype1 jitFn1 = jit.GetFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(jitFn1(&v) == 123 * 3 + 3 * 2 + 1);
}
}
TEST(SanityCallCppFn, ConstRefParameterConversion_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype1 = int*(*)(int*);
{
auto [fn, a] = NewFunction<FnPrototype1>("testfn");
fn.SetBody(
Return(CallFreeFn::TestAddressOfConstPrimitiveRef(*a))
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn1 = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(interpFn1(&v) == &v);
}
{
FastInterpFunction<FnPrototype1> interpFn1 = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(interpFn1(&v) == &v);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype1 jitFn1 = jit.GetFunction<FnPrototype1>("testfn");
int v = 123;
ReleaseAssert(jitFn1(&v) == &v);
}
}
TEST(SanityCallCppFn, ReturnExprEvaluatedBeforeDestructor)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)();
{
auto [fn] = NewFunction<FnPrototype>("testfn");
auto v = fn.NewVariable<int>();
auto x = fn.NewVariable<TestDestructor1>();
fn.SetBody(
Declare(v, 123),
Declare(x, Constructor<TestDestructor1>(Literal<int>(456), v.Addr())),
Return(v)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
int out = interpFn();
ReleaseAssert(out == 123);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
int out = interpFn();
ReleaseAssert(out == 123);
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(x_isDebugBuild);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
int out = jitFn();
ReleaseAssert(out == 123);
}
}
TEST(SanityCallCppFn, ExceptionEscapingNoExceptFunction)
{
// If a C++ exception escaped a function marked as noexcept,
// std::terminate() shall be called according to C++ standard. This test tests this behavior.
//
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)(int) noexcept;
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
auto x = fn.NewVariable<TestNonTrivialConstructor>();
fn.SetBody(
Declare(x, Variable<TestNonTrivialConstructor>::Create2(v)),
Return(x.GetValue())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
int out = interpFn(123);
ReleaseAssert(out == 123);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(interpFn(12345), "");
#pragma clang diagnostic pop
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
int out = interpFn(123);
ReleaseAssert(out == 123);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(interpFn(12345), "");
#pragma clang diagnostic pop
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
int out = jitFn(123);
ReleaseAssert(out == 123);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(jitFn(12345), "");
#pragma clang diagnostic pop
}
}
TEST(SanityCallCppFn, ExceptionEscapingNoExceptFunction_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = int(*)(int) noexcept;
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
If(v == Literal<int>(12345)).Then(
Throw(v)
),
Return(v)
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
int out = interpFn(123);
ReleaseAssert(out == 123);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(interpFn(12345), "");
#pragma clang diagnostic pop
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
int out = interpFn(123);
ReleaseAssert(out == 123);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(interpFn(12345), "");
#pragma clang diagnostic pop
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
int out = jitFn(123);
ReleaseAssert(out == 123);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wcovered-switch-default"
fprintf(stdout, "DeathTest: Expecting program termination...\n");
fflush(stdout);
ASSERT_DEATH(jitFn(12345), "");
#pragma clang diagnostic pop
}
}
TEST(SanityCallCppFn, CharTypeSanity_1)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = char*(*)(std::string*) noexcept;
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(v->c_str())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::string s("12345");
char* out = interpFn(&s);
ReleaseAssert(out == s.c_str());
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::string s("12345");
char* out = interpFn(&s);
ReleaseAssert(out == s.c_str());
}
thread_pochiVMContext->m_curModule->EmitIR();
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
if (x_isDebugBuild)
{
AssertIsExpectedOutput(dump, "debug_before_opt");
}
else
{
AssertIsExpectedOutput(dump, "nondebug_before_opt");
}
}
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
if (!x_isDebugBuild)
{
std::string _dst;
llvm::raw_string_ostream rso(_dst /*target*/);
thread_pochiVMContext->m_curModule->GetBuiltLLVMModule()->print(rso, nullptr);
std::string& dump = rso.str();
AssertIsExpectedOutput(dump, "after_opt");
}
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::string s("12345");
char* out = jitFn(&s);
ReleaseAssert(out == s.c_str());
}
}
TEST(SanityCallCppFn, CharTypeSanity_2)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = char(*)(std::string*) noexcept;
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return((*v)[Literal<size_t>(2)])
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::string s("12345");
char out = interpFn(&s);
ReleaseAssert(out == s[2]);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::string s("12345");
char out = interpFn(&s);
ReleaseAssert(out == s[2]);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::string s("12345");
char out = jitFn(&s);
ReleaseAssert(out == s[2]);
}
}
TEST(SanityCallCppFn, CharTypeSanity_3)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = char(*)(std::string*) noexcept;
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
fn.SetBody(
Return(v->c_str()[2])
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
std::string s("12345");
char out = interpFn(&s);
ReleaseAssert(out == s[2]);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
std::string s("12345");
char out = interpFn(&s);
ReleaseAssert(out == s[2]);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
std::string s("12345");
char out = jitFn(&s);
ReleaseAssert(out == s[2]);
}
}
TEST(SanityCallCppFn, CharTypeSanity_4)
{
AutoThreadPochiVMContext apv;
AutoThreadErrorContext arc;
AutoThreadLLVMCodegenContext alc;
thread_pochiVMContext->m_curModule = new AstModule("test");
using FnPrototype = size_t(*)(char*) noexcept;
{
auto [fn, v] = NewFunction<FnPrototype>("testfn");
auto s = fn.NewVariable<std::string>();
fn.SetBody(
Declare(s, Constructor<std::string>(v)),
Return(s.size())
);
}
ReleaseAssert(thread_pochiVMContext->m_curModule->Validate());
thread_pochiVMContext->m_curModule->PrepareForDebugInterp();
thread_pochiVMContext->m_curModule->PrepareForFastInterp();
{
auto interpFn = thread_pochiVMContext->m_curModule->
GetDebugInterpGeneratedFunction<FnPrototype>("testfn");
const char* s = "1234567";
size_t out = interpFn(const_cast<char*>(s));
ReleaseAssert(out == 7);
}
{
FastInterpFunction<FnPrototype> interpFn = thread_pochiVMContext->m_curModule->
GetFastInterpGeneratedFunction<FnPrototype>("testfn");
const char* s = "1234567";
size_t out = interpFn(const_cast<char*>(s));
ReleaseAssert(out == 7);
}
thread_pochiVMContext->m_curModule->EmitIR();
thread_pochiVMContext->m_curModule->OptimizeIRIfNotDebugMode(2 /*optLevel*/);
{
SimpleJIT jit;
jit.SetAllowResolveSymbolInHostProcess(true);
jit.SetModule(thread_pochiVMContext->m_curModule);
FnPrototype jitFn = jit.GetFunction<FnPrototype>("testfn");
const char* s = "1234567";
size_t out = jitFn(const_cast<char*>(s));
ReleaseAssert(out == 7);
}
}
| 35.085986 | 141 | 0.575521 | dghosef |
776f8bc0138eb89dff3d759bf1a1164fbecb291c | 67 | cpp | C++ | main/application.cpp | briveramelo/particle-iot-mocks | 26ce0f01aba1df3b7cdc6a2c89c1e10899434f4e | [
"MIT"
] | 1 | 2021-01-05T22:09:40.000Z | 2021-01-05T22:09:40.000Z | main/application.cpp | briveramelo/particle-iot-mocks | 26ce0f01aba1df3b7cdc6a2c89c1e10899434f4e | [
"MIT"
] | null | null | null | main/application.cpp | briveramelo/particle-iot-mocks | 26ce0f01aba1df3b7cdc6a2c89c1e10899434f4e | [
"MIT"
] | null | null | null | #include "application.h"
#include "Arduino.h"
#include "Particle.h" | 22.333333 | 24 | 0.746269 | briveramelo |
a55d8a44778f92a3dd34aa1540fb7c6422cd70a6 | 8,577 | cpp | C++ | Engine/SceneImporter.cpp | solidajenjo/CyberPimpEngine | da4fc5d22bc7c52a45794ea73e2bac903d893178 | [
"MIT"
] | null | null | null | Engine/SceneImporter.cpp | solidajenjo/CyberPimpEngine | da4fc5d22bc7c52a45794ea73e2bac903d893178 | [
"MIT"
] | null | null | null | Engine/SceneImporter.cpp | solidajenjo/CyberPimpEngine | da4fc5d22bc7c52a45794ea73e2bac903d893178 | [
"MIT"
] | null | null | null | #include "SceneImporter.h"
#include "Assimp/include/assimp/cimport.h"
#include "Assimp/include/assimp/postprocess.h"
#include "Assimp/include/assimp/scene.h"
#include "Assimp/include/assimp/material.h"
#include "Assimp/include/assimp/mesh.h"
#include "Application.h"
#include "MathGeoLib/include/Math/Quat.h"
#include "GameObject.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ModuleScene.h"
#include "ModuleFileSystem.h"
#include "MaterialImporter.h"
#include "crossguid/include/crossguid/guid.hpp"
#include "Transform.h"
#include <stack>
bool SceneImporter::Import(const std::string & file) const
{
LOG("Import model %s", file.c_str());
const aiScene* scene = aiImportFile(file.c_str(), aiProcess_Triangulate);
if (scene == nullptr) {
LOG("Error importing model -> %s", aiGetErrorString());
return false;
}
aiNode* rootNode = scene->mRootNode;
assert(rootNode != nullptr);
std::stack<aiNode*> stackNode;
std::stack<GameObject*> stackParent;
unsigned nMaterials = scene->mNumMaterials;
MaterialImporter mi;
std::vector<std::string> materials;
materials.resize(nMaterials);
for (unsigned i = 0u; i < nMaterials; ++i)
{
GameObject* mat = new GameObject("Material", true);
materials[i] = mi.Import(scene->mMaterials[i], mat);
RELEASE(mat->transform);
App->scene->ImportGameObject(mat, ModuleScene::ImportedType::MATERIAL); //import material
}
GameObject* root = new GameObject("Root", true);
for (unsigned i = 0; i < rootNode->mNumChildren; ++i) //skip rootnode
{
stackNode.push(rootNode->mChildren[i]);
stackParent.push(root);
}
std::string meshPath = "Library/Meshes/";
while (!stackNode.empty())
{
//process model
aiNode* node = stackNode.top(); stackNode.pop();
GameObject* gameObjectNode = new GameObject(node->mName.C_Str(), true);
GameObject* parent = stackParent.top(); stackParent.pop();
sprintf_s (gameObjectNode->parentUUID, parent->gameObjectUUID);
parent->InsertChild(gameObjectNode);
for (unsigned i = 0; i < node->mNumChildren; ++i)
{
stackNode.push(node->mChildren[i]);
stackParent.push(gameObjectNode);
}
unsigned nMeshes = node->mNumMeshes;
aiVector3D pos;
aiVector3D scl;
aiQuaternion rot;
node->mTransformation.Decompose(scl, rot, pos);
Quat q(rot.x, rot.y, rot.z, rot.w); //Quat to translate from black math voodoo to human understable
gameObjectNode->transform->SetTransform(float3(pos.x, pos.y, pos.z), q.ToEulerXYZ(), float3(scl.x, scl.y, scl.z));
if (nMeshes >= 1) //is a mesh
{
for (unsigned i = 0u; i < nMeshes; ++i)
{
std::vector<char> bytes;
unsigned bytesPointer = 0u;
xg::Guid guid = xg::newGuid();
char meshUUID[40];
sprintf_s(meshUUID, guid.str().c_str());
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
unsigned nVertices = mesh->mNumVertices;
unsigned nIndices = 0;
if (mesh->HasFaces())
nIndices = mesh->mNumFaces * 3;
unsigned nCoords = 0;
if (mesh->HasTextureCoords(0))
nCoords = mesh->mNumVertices * 2;
unsigned nNormals = 0;
if (mesh->HasNormals())
nNormals = mesh->mNumVertices;
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &nVertices);
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &nIndices);
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &nCoords);
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &nNormals);
writeToBuffer(bytes, bytesPointer, sizeof(float) * 3 * nVertices, &mesh->mVertices[0]);
if (nIndices > 0)
{
std::vector<unsigned> indices = std::vector<unsigned>(nIndices);
unsigned nFaces = mesh->mNumFaces;
for (unsigned j = 0u; j < nFaces; ++j)
{
aiFace face = mesh->mFaces[j];
assert(mesh->mFaces[j].mNumIndices == 3);
indices[j * 3] = face.mIndices[0];
indices[(j * 3) + 1] = face.mIndices[1];
indices[(j * 3) + 2] = face.mIndices[2];
}
writeToBuffer(bytes, bytesPointer, sizeof(unsigned) * indices.size(), &indices[0]);
}
if (nCoords > 0)
{
std::vector<float> coords = std::vector<float>(nCoords);
coords.resize(nCoords);
for (unsigned j = 0; j < nVertices && nCoords > 0; ++j)
{
coords[j * 2] = mesh->mTextureCoords[0][j].x;
coords[(j * 2) + 1] = mesh->mTextureCoords[0][j].y;
}
writeToBuffer(bytes, bytesPointer, sizeof(float) * coords.size(), &coords[0]);
}
if (nNormals > 0)
{
writeToBuffer(bytes, bytesPointer, sizeof(float) * 3 * nNormals, &mesh->mNormals[0]);
}
writeToBuffer(bytes, bytesPointer, sizeof(char) * 1024, materials[mesh->mMaterialIndex].c_str());
std::string meshName = meshPath + std::string(meshUUID) + ".msh";
App->fileSystem->Write(meshName, &bytes[0], bytes.size());
ComponentMesh* newMesh = LoadMesh(meshName.c_str());
if (newMesh != nullptr)
{
gameObjectNode->InsertComponent(newMesh); //insert the mesh on the new node
}
}
}
}
App->scene->ImportGameObject(root, ModuleScene::ImportedType::MODEL);
return true;
}
inline void SceneImporter::writeToBuffer(std::vector<char> &buffer, unsigned & pointer, const unsigned size, const void * data) const
{
buffer.resize(buffer.size() + size);
memcpy(&buffer[pointer], data, size);
pointer += size;
}
ComponentMesh * SceneImporter::LoadMesh(const char path[1024]) const
{
unsigned size = App->fileSystem->Size(std::string(path));
if (size > 0)
{
char* buffer = new char[size];
if (App->fileSystem->Read(std::string(path), buffer, size))
{
//read mesh header
unsigned nVertices, nIndices, nCoords, nNormals;
memcpy(&nVertices, &buffer[0], sizeof(unsigned));
memcpy(&nIndices, &buffer[sizeof(unsigned) * 1], sizeof(unsigned));
memcpy(&nCoords, &buffer[sizeof(unsigned) * 2], sizeof(unsigned));
memcpy(&nNormals, &buffer[sizeof(unsigned) * 3], sizeof(unsigned));
unsigned verticesOffset = 4 * sizeof(unsigned);
unsigned verticesSize = nVertices * sizeof(float) * 3;
unsigned indicesOffset = verticesOffset + verticesSize;
unsigned indicesSize = nIndices * sizeof(unsigned);
unsigned coordsOffset = indicesOffset + indicesSize;
unsigned coordsSize = nCoords * sizeof(float);
unsigned normalsOffset = coordsOffset + coordsSize;
unsigned normalsSize = nNormals * sizeof(float) * 3;
unsigned materialsOffset = normalsOffset + normalsSize;
//create Mesh component
ComponentMesh* newMesh = new ComponentMesh();
newMesh->nVertices = nVertices;
newMesh->nIndices = nIndices;
newMesh->nCoords = nCoords;
newMesh->nNormals = nNormals;
newMesh->meshVertices.resize(nVertices);
memcpy(&newMesh->meshVertices[0], &buffer[verticesOffset], verticesSize);
if (nIndices > 0)
{
newMesh->meshIndices.resize(nIndices);
memcpy(&newMesh->meshIndices[0], &buffer[indicesOffset], indicesSize);
}
if (nCoords > 0)
{
newMesh->meshTexCoords.resize(nCoords);
memcpy(&newMesh->meshTexCoords[0], &buffer[coordsOffset], coordsSize);
}
if (nNormals > 0)
{
newMesh->meshNormals.resize(nNormals);
memcpy(&newMesh->meshNormals[0], &buffer[normalsOffset], normalsSize);
}
char materialPath[1024];
memcpy(&materialPath[0], &buffer[materialsOffset], sizeof(char) * 1024);
std::string matPath(materialPath);
newMesh->material = ComponentMaterial::GetMaterial(matPath);
sprintf_s(newMesh->meshPath, path);
RELEASE(buffer);
return newMesh;
}
RELEASE(buffer);
}
return nullptr;
}
void SceneImporter::SaveMesh(const ComponentMesh* mesh, const char path[1024]) const
{
std::vector<char> bytes;
unsigned bytesPointer = 0u;
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &mesh->nVertices);
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &mesh->nIndices);
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &mesh->nCoords);
writeToBuffer(bytes, bytesPointer, sizeof(unsigned), &mesh->nNormals);
writeToBuffer(bytes, bytesPointer, sizeof(float) * 3 * mesh->nVertices, &mesh->meshVertices[0]);
if (mesh->nIndices > 0)
{
writeToBuffer(bytes, bytesPointer, sizeof(unsigned) * mesh->meshIndices.size(), &mesh->meshIndices[0]);
}
if (mesh->nCoords > 0)
{
writeToBuffer(bytes, bytesPointer, sizeof(float) * mesh->meshTexCoords.size(), &mesh->meshTexCoords[0]);
}
if (mesh->nNormals > 0)
{
writeToBuffer(bytes, bytesPointer, sizeof(float) * 3 * mesh->nNormals, &mesh->meshNormals[0]);
}
writeToBuffer(bytes, bytesPointer, sizeof(char) * 1024, mesh->material->materialPath);
App->fileSystem->Write(path, &bytes[0], bytes.size());
}
| 31.766667 | 133 | 0.684738 | solidajenjo |
a55dae0639153cbaa330affc0ee782540544ed64 | 1,391 | hpp | C++ | include/containers/algorithms/minmax_element.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | include/containers/algorithms/minmax_element.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | include/containers/algorithms/minmax_element.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <containers/algorithms/advance.hpp>
#include <containers/begin_end.hpp>
#include <containers/is_range.hpp>
#include <bounded/detail/comparison_function_object.hpp>
#include <operators/forward.hpp>
namespace containers {
// TODO: minmax_element
constexpr auto min_element(range auto && source, auto compare) {
auto smallest = containers::begin(OPERATORS_FORWARD(source));
auto const last = containers::end(OPERATORS_FORWARD(source));
if (smallest == last) {
return smallest;
}
for (auto it = containers::next(smallest); it != last; ++it) {
if (compare(*it, *smallest)) {
smallest = it;
}
}
return smallest;
}
constexpr auto min_element(range auto && source) {
return containers::min_element(OPERATORS_FORWARD(source), bounded::less());
}
constexpr auto max_element(range auto && source, auto greater) {
auto compare = [cmp = std::move(greater)](auto const & lhs, auto const & rhs) {
return !(cmp(rhs, lhs));
};
return containers::min_element(OPERATORS_FORWARD(source), std::move(compare));
}
constexpr auto max_element(range auto && source) {
return containers::max_element(OPERATORS_FORWARD(source), bounded::greater());
}
} // namespace containers
| 28.387755 | 80 | 0.732566 | davidstone |
a5615e2ba2388eb520677bd1c5ba42c564fdd2a5 | 17,115 | cpp | C++ | library/lattice/test/src/test_tetengo.lattice.string_input.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | null | null | null | library/lattice/test/src/test_tetengo.lattice.string_input.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | 41 | 2021-06-25T14:20:29.000Z | 2022-01-16T02:50:50.000Z | library/lattice/test/src/test_tetengo.lattice.string_input.cpp | tetengo/tetengo | 66e0d03635583c25be4320171f3cc1e7f40a56e6 | [
"MIT"
] | null | null | null | /*! \file
\brief A string input.
Copyright (C) 2019-2022 kaoru https://www.tetengo.org/
*/
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string>
#include <boost/operators.hpp>
#include <boost/preprocessor.hpp>
#include <boost/scope_exit.hpp>
#include <boost/test/unit_test.hpp>
#include <tetengo/lattice/input.h>
#include <tetengo/lattice/input.hpp>
#include <tetengo/lattice/string_input.hpp>
namespace
{
class another_input : public tetengo::lattice::input
{
private:
virtual bool equal_to_impl(const input& /*another*/) const override
{
return true;
}
virtual std::size_t hash_value_impl() const override
{
return 314159;
}
virtual std::size_t length_impl() const override
{
return 0;
}
virtual std::unique_ptr<input> clone_impl() const override
{
return std::make_unique<another_input>();
}
virtual std::unique_ptr<input>
create_subrange_impl(const std::size_t /*offset*/, const std::size_t /*length*/) const override
{
return std::make_unique<another_input>();
}
virtual void append_impl(std::unique_ptr<input>&& /*p_another*/) override {}
};
}
BOOST_AUTO_TEST_SUITE(test_tetengo)
BOOST_AUTO_TEST_SUITE(lattice)
BOOST_AUTO_TEST_SUITE(string_input)
BOOST_AUTO_TEST_CASE(construction)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input{ "hoge" };
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST(p_input);
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput(nullptr);
BOOST_TEST(!p_input);
}
}
BOOST_AUTO_TEST_CASE(value)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input{ "hoge" };
BOOST_TEST(input.value() == "hoge");
}
{
tetengo::lattice::string_input input{ "hoge" };
input.value() = "fuga";
BOOST_TEST(input.value() == "fuga");
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const value = tetengo_lattice_stringInput_value(p_input);
BOOST_TEST(std::string{ value } == "hoge");
}
{
BOOST_TEST(!tetengo_lattice_stringInput_value(nullptr));
}
{
auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto result = tetengo_lattice_stringInput_setValue(p_input, "fuga");
BOOST_TEST_REQUIRE(result);
const auto* const value = tetengo_lattice_stringInput_value(p_input);
BOOST_TEST(std::string{ value } == "fuga");
}
{
const auto result = tetengo_lattice_stringInput_setValue(nullptr, "fuga");
BOOST_TEST(!result);
}
{
auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto result = tetengo_lattice_stringInput_setValue(p_input, nullptr);
BOOST_TEST(!result);
}
}
BOOST_AUTO_TEST_CASE(operator_equal)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input1{ "hoge" };
const tetengo::lattice::string_input input2{ "hoge" };
BOOST_CHECK(input1 == input2);
BOOST_CHECK(input2 == input1);
}
{
const tetengo::lattice::string_input input1{ "hoge" };
const tetengo::lattice::string_input input2{ "fuga" };
BOOST_CHECK(input1 != input2);
BOOST_CHECK(input2 != input1);
}
{
const tetengo::lattice::string_input input1{ "hoge" };
const another_input input2{};
BOOST_CHECK(input1 != input2);
BOOST_CHECK(input2 != input1);
}
{
const auto* const p_input1 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input1)
{
tetengo_lattice_input_destroy(p_input1);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input1);
const auto* const p_input2 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input2)
{
tetengo_lattice_input_destroy(p_input2);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input2);
BOOST_TEST(tetengo_lattice_input_equal(p_input1, p_input2));
}
{
const auto* const p_input1 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input1)
{
tetengo_lattice_input_destroy(p_input1);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input1);
const auto* const p_input2 = tetengo_lattice_input_createStringInput("fuga");
BOOST_SCOPE_EXIT(p_input2)
{
tetengo_lattice_input_destroy(p_input2);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input2);
BOOST_TEST(!tetengo_lattice_input_equal(p_input1, p_input2));
}
{
const auto* const p_input2 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input2)
{
tetengo_lattice_input_destroy(p_input2);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input2);
BOOST_TEST(!tetengo_lattice_input_equal(nullptr, p_input2));
}
{
const auto* const p_input1 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input1)
{
tetengo_lattice_input_destroy(p_input1);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input1);
BOOST_TEST(!tetengo_lattice_input_equal(p_input1, nullptr));
}
{
BOOST_TEST(!tetengo_lattice_input_equal(nullptr, nullptr));
}
}
BOOST_AUTO_TEST_CASE(hash_value)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input1{ "hoge" };
const tetengo::lattice::string_input input2{ "hoge" };
BOOST_TEST(input1.hash_value() == input2.hash_value());
}
{
const tetengo::lattice::string_input input1{ "hoge" };
const tetengo::lattice::string_input input2{ "fuga" };
BOOST_TEST(input1.hash_value() != input2.hash_value());
}
{
const tetengo::lattice::string_input input1{ "hoge" };
const another_input input2{};
BOOST_TEST(input1.hash_value() != input2.hash_value());
}
{
const auto* const p_input1 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input1)
{
tetengo_lattice_input_destroy(p_input1);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input1);
const auto* const p_input2 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input2)
{
tetengo_lattice_input_destroy(p_input2);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input2);
BOOST_TEST(tetengo_lattice_input_hashValue(p_input1) == tetengo_lattice_input_hashValue(p_input2));
}
{
const auto* const p_input1 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input1)
{
tetengo_lattice_input_destroy(p_input1);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input1);
const auto* const p_input2 = tetengo_lattice_input_createStringInput("fuga");
BOOST_SCOPE_EXIT(p_input2)
{
tetengo_lattice_input_destroy(p_input2);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input2);
BOOST_TEST(tetengo_lattice_input_hashValue(p_input1) != tetengo_lattice_input_hashValue(p_input2));
}
{
const auto* const p_input2 = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input2)
{
tetengo_lattice_input_destroy(p_input2);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input2);
BOOST_TEST(tetengo_lattice_input_hashValue(nullptr) == static_cast<size_t>(-1));
}
}
BOOST_AUTO_TEST_CASE(length)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input{ "hoge" };
BOOST_TEST(input.length() == 4U);
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
BOOST_TEST(tetengo_lattice_input_length(p_input) == 4U);
}
{
BOOST_TEST(tetengo_lattice_input_length(nullptr) == static_cast<size_t>(-1));
}
}
BOOST_AUTO_TEST_CASE(clone)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input{ "hoge" };
const auto p_clone = input.clone();
BOOST_REQUIRE(p_clone);
BOOST_TEST_REQUIRE(p_clone->is<tetengo::lattice::string_input>());
BOOST_TEST(p_clone->as<tetengo::lattice::string_input>().value() == "hoge");
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const p_clone = tetengo_lattice_input_clone(p_input);
BOOST_SCOPE_EXIT(p_clone)
{
tetengo_lattice_input_destroy(p_clone);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_clone);
BOOST_TEST(std::string{ tetengo_lattice_stringInput_value(p_clone) } == "hoge");
}
{
const auto* const p_clone = tetengo_lattice_input_clone(nullptr);
BOOST_TEST(!p_clone);
}
}
BOOST_AUTO_TEST_CASE(create_subrange)
{
BOOST_TEST_PASSPOINT();
{
const tetengo::lattice::string_input input{ "hoge" };
const auto p_subrange = input.create_subrange(0, 4);
BOOST_REQUIRE(p_subrange);
BOOST_TEST_REQUIRE(p_subrange->is<tetengo::lattice::string_input>());
BOOST_TEST(p_subrange->as<tetengo::lattice::string_input>().value() == "hoge");
}
{
const tetengo::lattice::string_input input{ "hoge" };
const auto p_subrange = input.create_subrange(1, 2);
BOOST_REQUIRE(p_subrange);
BOOST_TEST_REQUIRE(p_subrange->is<tetengo::lattice::string_input>());
BOOST_TEST(p_subrange->as<tetengo::lattice::string_input>().value() == "og");
}
{
const tetengo::lattice::string_input input{ "hoge" };
const auto p_subrange = input.create_subrange(4, 0);
BOOST_REQUIRE(p_subrange);
BOOST_TEST_REQUIRE(p_subrange->is<tetengo::lattice::string_input>());
BOOST_TEST(p_subrange->as<tetengo::lattice::string_input>().value() == "");
}
{
const tetengo::lattice::string_input input{ "hoge" };
BOOST_CHECK_THROW(const auto p_subrange = input.create_subrange(0, 5), std::out_of_range);
}
{
const tetengo::lattice::string_input input{ "hoge" };
BOOST_CHECK_THROW(const auto p_subrange = input.create_subrange(5, 0), std::out_of_range);
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const p_subrange = tetengo_lattice_input_createSubrange(p_input, 0, 4);
BOOST_SCOPE_EXIT(p_subrange)
{
tetengo_lattice_input_destroy(p_subrange);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_subrange);
BOOST_TEST(std::string{ tetengo_lattice_stringInput_value(p_subrange) } == "hoge");
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const p_subrange = tetengo_lattice_input_createSubrange(p_input, 1, 2);
BOOST_SCOPE_EXIT(p_subrange)
{
tetengo_lattice_input_destroy(p_subrange);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_subrange);
BOOST_TEST(std::string{ tetengo_lattice_stringInput_value(p_subrange) } == "og");
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const p_subrange = tetengo_lattice_input_createSubrange(p_input, 4, 0);
BOOST_SCOPE_EXIT(p_subrange)
{
tetengo_lattice_input_destroy(p_subrange);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_subrange);
BOOST_TEST(std::string{ tetengo_lattice_stringInput_value(p_subrange) } == "");
}
{
const auto* const p_subrange = tetengo_lattice_input_createSubrange(nullptr, 0, 4);
BOOST_TEST(!p_subrange);
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const p_subrange = tetengo_lattice_input_createSubrange(p_input, 0, 5);
BOOST_TEST(!p_subrange);
}
{
const auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto* const p_subrange = tetengo_lattice_input_createSubrange(p_input, 5, 0);
BOOST_TEST(!p_subrange);
}
}
BOOST_AUTO_TEST_CASE(append)
{
BOOST_TEST_PASSPOINT();
{
tetengo::lattice::string_input input{ "hoge" };
input.append(std::make_unique<tetengo::lattice::string_input>("fuga"));
BOOST_TEST(input.value() == "hogefuga");
}
{
tetengo::lattice::string_input input{ "hoge" };
BOOST_CHECK_THROW(input.append(nullptr), std::invalid_argument);
BOOST_CHECK_THROW(input.append(std::make_unique<another_input>()), std::invalid_argument);
}
{
auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
auto* const p_another = tetengo_lattice_input_createStringInput("fuga");
BOOST_TEST_REQUIRE(p_another);
const auto result = tetengo_lattice_input_append(p_input, p_another);
BOOST_TEST_REQUIRE(result);
BOOST_TEST(std::string{ tetengo_lattice_stringInput_value(p_input) } == "hogefuga");
}
{
auto* const p_another = tetengo_lattice_input_createStringInput("fuga");
BOOST_TEST_REQUIRE(p_another);
const auto result = tetengo_lattice_input_append(nullptr, p_another);
BOOST_TEST(!result);
}
{
auto* const p_input = tetengo_lattice_input_createStringInput("hoge");
BOOST_SCOPE_EXIT(p_input)
{
tetengo_lattice_input_destroy(p_input);
}
BOOST_SCOPE_EXIT_END;
BOOST_TEST_REQUIRE(p_input);
const auto result = tetengo_lattice_input_append(p_input, nullptr);
BOOST_TEST(!result);
}
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 30.5625 | 108 | 0.623138 | tetengo |
a574588d367f4ee86b2f57386b0a4171a28702ae | 8,688 | cc | C++ | src/mgl/ScadDebugFile.cc | hugomatic/extrudo | fd9f14d5e7c6869f9e7e7f09787353b655f90f72 | [
"Apache-2.0"
] | null | null | null | src/mgl/ScadDebugFile.cc | hugomatic/extrudo | fd9f14d5e7c6869f9e7e7f09787353b655f90f72 | [
"Apache-2.0"
] | null | null | null | src/mgl/ScadDebugFile.cc | hugomatic/extrudo | fd9f14d5e7c6869f9e7e7f09787353b655f90f72 | [
"Apache-2.0"
] | null | null | null | #include "ScadDebugFile.h"
using namespace std;
using namespace mgl;
using namespace libthing;
#include "log.h"
ScadDebugFile::ScadDebugFile() :filename("")
{}
void ScadDebugFile::open(const char* path)
{
assert(isOpened() == false);
filename = path;
out.open(filename.c_str(), ios::out);
if(!out.good())
{
stringstream ss;
ss << "Can't open \"" << filename.c_str() << "\"";
string tmp = ss.str();
Log::often() << "ERROR: " << tmp << endl;
ScadException problem(ss.str().c_str());
throw (problem);
}
out.precision(5);
out.setf(ios::fixed);
}
string ScadDebugFile::getScadFileName() const
{
return filename;
}
bool ScadDebugFile::isOpened()
{
unsigned int l = filename.length();
return (l > 0);
}
ostream& ScadDebugFile::getOut()
{return out;}
void ScadDebugFile::writeHeader()
{
out << "module corner(x, y, z, diameter, faces, thickness_over_width ){" << endl;
out << " translate([x, y, z]) scale([1,1,thickness_over_width]) sphere( r = diameter/2, $fn = faces );" << endl;
out << "}" << endl;
out << endl;
out << "module tube(x1, y1, z1, x2, y2, z2, diameter1, diameter2, faces, thickness_over_width)" << endl;
out << "{" << endl;
out << " length = sqrt( pow(x1 - x2, 2) + pow(y1 - y2, 2) + pow(z1 - z2, 2) );" << endl;
out << " alpha = ( (y2 - y1 != 0) ? atan( (z2 - z1) / (y2 - y1) ) : 0 );" << endl;
out << " beta = 90 - ( (x2 - x1 != 0) ? atan( (z2 - z1) / (x2 - x1) ) : 0 );" << endl;
out << " gamma = ( (x2 - x1 != 0) ? atan( (y2 - y1) / (x2 - x1) ) : ( (y2 - y1 >= 0) ? 90 : -90 ) ) + ( (x2 - x1 >= 0) ? 0 : -180 );" << endl;
out << " // echo(Length = length, Alpha = alpha, Beta = beta, Gamma = gamma); " << endl;
out << " translate([x1, y1, z1])" << endl;
out << " rotate([ 0, beta, gamma])" << endl;
out << " scale([thickness_over_width,1,1])" << endl;
out << " rotate([0,0,90]) cylinder(h = length, r1 = diameter1/2, r2 = diameter2/2, center = false, $fn = faces );" << endl;
out << "}" << endl;
}
void ScadDebugFile::close()
{
out.close();
filename = "";
}
void ScadDebugFile::writeOutlines(const Polygons &loops, Scalar z, int slice)
{
out << "module outlines_" << slice << "()" << endl;
out << "{" << endl;
out << " points =[" << endl;
for (size_t i=0; i < loops.size(); i++)
{
out << " [" << endl;
const Polygon& loop = loops[i];
for (size_t j=0; j < loop.size(); j++)
{
Scalar x = loop[j].x;
Scalar y = loop[j].y;
out << " [" << x << ", " << y << ", " << z << "]," << endl;
}
out << " ]," << endl;
}
out << " ];" << endl;
out << " segments =[" << endl;
for (size_t i=0; i < loops.size(); i++)
{
out << " [" << endl;
const Polygon& loop = loops[i];
for (size_t j=0; j < loop.size()-1; j++)
{
int a = j;
int b = j+1;
out << " [" << a << ", " << b << "]," << endl;
}
out << " ]," << endl;
}
out << " ];" << endl;
out << endl;
for (size_t i=0; i < loops.size(); i++)
{
out << " outline(points[" << i << "], segments[" << i << "] );" << endl;
}
out << endl;
out << "}" << endl;
}
void ScadDebugFile::writePolygons(const char* moduleName,
const char* implementation,
const Polygons &polygons,
Scalar z,
int slice)
{
//EZLOGGERVLSTREAM << "<writePolygons: " << polygons.size() << " polygons >"<< endl;
out << "module " << moduleName << slice << "()" << endl;
out << "{" << endl;
out << " points =[" << endl;
for (size_t i=0; i < polygons.size(); i++)
{
out << " [" << endl;
const Polygon& poly = polygons[i];
//EZLOGGERVLSTREAM << " Polygon " << i << ": " << poly.size() << " points "<< endl;
for (size_t j=0; j < poly.size(); j++)
{
Scalar x = poly[j].x;
Scalar y = poly[j].y;
out << " [" << x << ", " << y << ", " << z << "]," << endl;
}
out << " ]," << endl;
}
out << " ];" << endl;
out << " segments =[" << endl;
size_t polysCount = polygons.size();
for (size_t i=0; i < polysCount; i++)
{
out << " [" << endl;
const Polygon& poly = polygons[i];
size_t polyCount = poly.size();
for (size_t j=0; j < polyCount-1; j++)
{
// EZLOGGERVLSTREAM << " writePolygons: " << j << " polycount: " << polyCount << endl;
int a = j;
int b = j+1;
out << " [" << a << ", " << b << "]," << endl;
}
out << " ]," << endl;
}
out << " ];" << endl;
out << endl;
for (size_t i=0; i < polygons.size(); i++)
{
out << " " << implementation << "(points[" << i << "], segments[" << i << "] );" << endl;
}
out << endl;
out << "}" << endl;
// EZLOGGERVLSTREAM << "</writePolygons>" << endl;
}
Scalar ScadDebugFile::segment3( ostream &out,
const char* indent,
const char* variableName,
const vector<LineSegment2> &segments,
Scalar z,
Scalar dz)
{
out << indent << variableName<< " =[" << endl;
for (size_t i=0; i < segments.size(); i++)
{
const LineSegment2& segment = segments[i];
Scalar ax = segment.a[0];
Scalar ay = segment.a[1];
Scalar az = z;
Scalar bx = segment.b[0];
Scalar by = segment.b[1];
Scalar bz = z;
out << indent << indent;
out << "[[" << ax << ", " << ay << ", " << az << "],";
out << "[ " << bx << ", " << by << ", " << bz << "]],";
out << endl;
z += dz;
}
out << indent << indent << "];" << endl;
return z;
}
Scalar ScadDebugFile::writeSegments3( const char* name,
const char* implementation,
const vector<LineSegment2> &segments,
Scalar z,
Scalar dz,
int slice)
{
out << "module " << name << slice << "()" << endl;
out << "{" << endl;
z = segment3(out, " ", "segments", segments, z, dz);
out << " " << implementation << "(segments);" << endl;
out << "}" << endl;
out << endl;
return z;
}
void ScadDebugFile::writeSegments2( const char* name,
const char* implementation,
const vector<LineSegment2> &segments,
Scalar z,
int slice)
{
out << "module " << name << slice << "()" << endl;
out << "{" << endl;
out << " segments =[" << endl;
for (size_t i=0; i < segments.size(); i++)
{
const LineSegment2& segment = segments[i];
Scalar ax = segment.a[0];
Scalar ay = segment.a[1];
Scalar bx = segment.b[0];
Scalar by = segment.b[1];
out << " ";
out << "[[" << ax << ", " << ay << "],";
out << "[ " << bx << ", " << by << "]],";
out << endl;
}
out << " ];" << endl;
out << " " << implementation << "(segments," << z <<");" << endl;
out << "}" << endl;
out << endl;
}
// writes a list of triangles into a polyhedron.
// It is used to display the triangles involved in a slice (layerIndex).
void ScadDebugFile::writeTrianglesModule( const char* name,
const vector<Triangle3> &allTriangles,
const TriangleIndices &trianglesForSlice,
unsigned int layerIndex)
{
stringstream ss;
ss.setf(ios::fixed);
ss << "module " << name << layerIndex << "(col=[1,0,0,1])" << endl;
ss << "{" << endl;
ss << " color(col) polyhedron ( points = [";
ss << dec; // set decimal format for floating point numbers
for(size_t i=0; i< trianglesForSlice.size(); i++ )
{
index_t index = trianglesForSlice[i];
const Triangle3 &t = allTriangles[index];
ss << " [" << t[0].x << ", " << t[0].y << ", " << t[0].z << "], ";
ss << "[" << t[1].x << ", " << t[1].y << ", " << t[1].z << "], ";
ss << "[" << t[2].x << ", " << t[2].y << ", " << t[2].z << "], // tri " << i << endl;
}
ss << "]," << endl;
ss << "triangles = [" ;
for (size_t i=0; i < trianglesForSlice.size(); i++)
{
int tri = i * 3;
ss << " [" << tri << ", " << tri+1 << ", " << tri + 2 << "], " << endl;
}
ss << "]);" << endl;
ss << "}" << endl;
ss << endl;
out << ss.str();
}
/*
void writeTrianglesModule(const char* name, const Meshy &mesh,
unsigned int layerIndex)
{
const TriangleIndices &trianglesForSlice = mesh.readSliceTable()[layerIndex];
const vector<Triangle3> &allTriangles = mesh.readAllTriangles();
writeTrianglesModule(name, allTriangles, trianglesForSlice, layerIndex);
}
*/
void ScadDebugFile::writeMinMax(const char*name, const char* implementation, int count)
{
out << "module "<< name << "(min=0, max=" << count-1 <<")" << endl;
out << "{" << endl;
for(int i=0; i< count; i++)
{
out << " if(min <= "<< i <<" && max >=" << i << ")" << endl;
out << " {" << endl;
out << " " << implementation << i << "();"<< endl;
out << " }" << endl;
}
out << "}" << endl;
}
ScadDebugFile::~ScadDebugFile()
{
out.close();
}
| 25.934328 | 144 | 0.498504 | hugomatic |
a5796ec2dd175185170a74ed94140f0730b7fa20 | 311 | cpp | C++ | Advance/extern.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 77 | 2019-10-28T05:38:51.000Z | 2022-03-15T01:53:48.000Z | Advance/extern.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 3 | 2019-12-26T15:39:55.000Z | 2020-10-29T14:55:50.000Z | Advance/extern.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 24 | 2020-01-08T04:12:52.000Z | 2022-03-12T22:26:07.000Z | #include "extern_header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
#include<iostream>
using namespace std;
int main()
{
// Access global_x defined in header file.
extern int global_x;
cout << "global_int = " << global_x<<endl;
} | 18.294118 | 54 | 0.691318 | iarjunphp |
a57de2904f7a1c71d13f316bead9a12a885dc077 | 229 | cpp | C++ | AtCoder/abc142/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc142/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc142/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
double N, cnt = 0; cin >> N;
for (int i = 1; i <= N; ++i) if (i % 2 != 0) cnt++;
printf("%f\n", cnt / N);
} | 22.9 | 55 | 0.550218 | H-Tatsuhiro |
a57e133d4cf637ace821e9892025b5e4be05ca01 | 3,373 | cpp | C++ | export/windows/obj/src/lime/net/HTTPRequest.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/lime/net/HTTPRequest.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/lime/net/HTTPRequest.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_lime_net_HTTPRequest
#include <lime/net/HTTPRequest.h>
#endif
#ifndef INCLUDED_lime_net__HTTPRequest_AbstractHTTPRequest
#include <lime/net/_HTTPRequest/AbstractHTTPRequest.h>
#endif
#ifndef INCLUDED_lime_net__IHTTPRequest
#include <lime/net/_IHTTPRequest.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_b3faec552c086965_25_new,"lime.net.HTTPRequest","new",0xc8d2372f,"lime.net.HTTPRequest.new","lime/net/HTTPRequest.hx",25,0x339db723)
namespace lime{
namespace net{
void HTTPRequest_obj::__construct(::String uri){
HX_STACKFRAME(&_hx_pos_b3faec552c086965_25_new)
HXDLIN( 25) super::__construct(uri);
}
Dynamic HTTPRequest_obj::__CreateEmpty() { return new HTTPRequest_obj; }
void *HTTPRequest_obj::_hx_vtable = 0;
Dynamic HTTPRequest_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< HTTPRequest_obj > _hx_result = new HTTPRequest_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool HTTPRequest_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x618df855) {
return inClassId==(int)0x00000001 || inClassId==(int)0x618df855;
} else {
return inClassId==(int)0x6483967f;
}
}
hx::ObjectPtr< HTTPRequest_obj > HTTPRequest_obj::__new(::String uri) {
hx::ObjectPtr< HTTPRequest_obj > __this = new HTTPRequest_obj();
__this->__construct(uri);
return __this;
}
hx::ObjectPtr< HTTPRequest_obj > HTTPRequest_obj::__alloc(hx::Ctx *_hx_ctx,::String uri) {
HTTPRequest_obj *__this = (HTTPRequest_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(HTTPRequest_obj), true, "lime.net.HTTPRequest"));
*(void **)__this = HTTPRequest_obj::_hx_vtable;
__this->__construct(uri);
return __this;
}
HTTPRequest_obj::HTTPRequest_obj()
{
}
#if HXCPP_SCRIPTABLE
static hx::StorageInfo *HTTPRequest_obj_sMemberStorageInfo = 0;
static hx::StaticInfo *HTTPRequest_obj_sStaticStorageInfo = 0;
#endif
static void HTTPRequest_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(HTTPRequest_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void HTTPRequest_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(HTTPRequest_obj::__mClass,"__mClass");
};
#endif
hx::Class HTTPRequest_obj::__mClass;
void HTTPRequest_obj::__register()
{
hx::Object *dummy = new HTTPRequest_obj;
HTTPRequest_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("lime.net.HTTPRequest","\xbd","\x73","\x25","\x4c");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = HTTPRequest_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = hx::TCanCast< HTTPRequest_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = HTTPRequest_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = HTTPRequest_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = HTTPRequest_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace net
| 31.523364 | 161 | 0.774681 | seanbashaw |
a5838ec6687d07809c4bbf549fa9a084f549a284 | 810 | cpp | C++ | Editor/gui/InspectorWidget/widget/impl/TransformationComponentWidgetItem.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/TransformationComponentWidgetItem.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | Editor/gui/InspectorWidget/widget/impl/TransformationComponentWidgetItem.cpp | obivan43/pawnengine | ec092fa855d41705f3fb55fcf1aa5e515d093405 | [
"MIT"
] | null | null | null | #include "TransformationComponentWidgetItem.h"
namespace editor::impl {
TransformationComponentWidgetItem::TransformationComponentWidgetItem(QTreeWidget* parent)
: QTreeWidgetItem(parent)
, m_TransformationComponentWidget(nullptr)
, m_WidgetWrapper(nullptr)
, m_Entity(nullptr) {
m_WidgetWrapper = new QTreeWidgetItem(this);
m_TransformationComponentWidget = new TransformationComponentWidget(parent);
setText(0, "Transformation");
addChild(m_WidgetWrapper);
}
void TransformationComponentWidgetItem::SetEntity(pawn::engine::GameEntity* entity) {
m_Entity = entity;
if (m_Entity && !m_Entity->IsNull() && m_Entity->IsValid()) {
m_TransformationComponentWidget->SetTransformation(&m_Entity->GetComponent<pawn::engine::TransformationComponent>());
}
}
}
| 32.4 | 121 | 0.760494 | obivan43 |
a58886b327c1a8bdaf68e69cf0d4559eddc8ff89 | 11,869 | hpp | C++ | shelly/stream.hpp | Zaspire/libshelly | 544e09f2d1fe4ef91938295941cb00583ac42926 | [
"MIT"
] | null | null | null | shelly/stream.hpp | Zaspire/libshelly | 544e09f2d1fe4ef91938295941cb00583ac42926 | [
"MIT"
] | null | null | null | shelly/stream.hpp | Zaspire/libshelly | 544e09f2d1fe4ef91938295941cb00583ac42926 | [
"MIT"
] | null | null | null | #ifndef SHELLY_STREAM_HPP
#define SHELLY_STREAM_HPP
#include <set>
#include <vector>
#include <cassert>
#include <algorithm>
#include <functional>
namespace shelly {
namespace stream {
inline namespace v1 {
template<typename Stream, typename In, typename Out, typename Func>
class MapStream;
template<typename Stream, typename In, typename Func>
class FilterStream;
template<typename Stream, typename In, typename Container>
class DistinctStream;
template<typename Stream, typename In, typename Comp>
class SortedStream;
template<typename Stream1, typename Stream2>
class ZipStream;
template<typename Out>
class BaseStream {
public:
virtual std::pair<Out, bool> GetNext() = 0;
virtual BaseStream<Out>& Limit(size_t l) = 0;
virtual BaseStream<Out>& Skip(size_t l) = 0;
virtual ~BaseStream<Out>() = default;
typedef Out OutType;
std::vector<Out> ToVector() {
std::vector<Out> res;
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
res.push_back(p1.first);
}
return res;
}
template<typename Func>
Out Reduce(Out Identity, Func f) {
Out res = Identity;
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
res = f(res, p1.first);
}
return res;
}
template<typename Func>
auto Map(Func f) -> MapStream<BaseStream<Out>, Out, decltype(f(Out())), Func> {
return MapStream<BaseStream<Out>, Out,
decltype(f(Out())), Func>(this, f);
}
template<typename Func>
FilterStream<BaseStream<Out>, Out, Func> Filter(Func f) {
return FilterStream<BaseStream<Out>, Out, Func>(this, f);
}
template<typename Container=std::set<Out>>
DistinctStream<BaseStream<Out>, Out, Container> Distinct() {
return DistinctStream<BaseStream<Out>, Out, Container>(this);
}
template<typename Comp = std::less<Out>>
SortedStream<BaseStream<Out>, Out, Comp> Sorted(Comp c = std::less<Out>()) {
return SortedStream<BaseStream<Out>, Out, Comp>(this, c);
}
template<typename Stream2>
ZipStream<BaseStream<Out>, Stream2> Zip(const Stream2 &other) {
// all temporaries are destroyed as the last step in
// evaluating the full-expression that (lexically) contains the point where they were created
return ZipStream<BaseStream<Out>, Stream2>(this, &const_cast<Stream2&>(other));
}
template<typename S = Out>
S Sum(S o = 0) {
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
o += p1.first;
}
return o;
}
template<typename Func>
void ForEach(Func f) {
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
f(p1.first);
}
}
template<typename Func>
bool AnyMatch(Func f) {
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
if (f(p1.first)) {
return true;
}
}
return false;
}
template<typename Func>
bool NoneMatch(Func f) {
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
if (f(p1.first)) {
return false;
}
}
return true;
}
template<typename Func>
bool AllMatch(Func f) {
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
if (!f(p1.first)) {
return false;
}
}
return true;
}
std::pair<Out, bool> FindAny() {
return GetNext();
}
template<typename Comparator = std::less<Out>>
std::pair<Out, bool> Min(Comparator c = std::less<Out>()) {
std::pair<Out, bool> m;
m.second = false;
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
if (!m.second || c(p1.first, m.first))
m = p1;
}
return m;
}
template<typename Comparator = std::less<Out>>
std::pair<Out, bool> Max(Comparator c = std::less<Out>()) {
std::pair<Out, bool> m;
m.second = false;
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
if (!m.second || c(m.first, p1.first))
m = p1;
}
return m;
}
size_t Count() {
size_t res = 0;
while (true) {
auto p1 = GetNext();
if (!p1.second)
break;
res++;
}
return res;
}
};
template<typename Stream, typename In, typename Container>
class DistinctStream: public BaseStream<In> {
public:
DistinctStream(Stream *stream): _stream(stream), _limit(-1) {
}
std::pair<In, bool> GetNext() override {
while (true) {
std::pair<In, bool> p1;
if (_limit <= _uniq.size()) {
p1.second = false;
return p1;
}
p1 = _stream->GetNext();
if (!p1.second)
return p1;
if (_uniq.insert(p1.first).second)
return p1;
}
}
BaseStream<In>& Skip(size_t l) override {
while (l--) {
auto p1 = GetNext();
if (!p1.second)
break;
}
return *this;
}
BaseStream<In>& Limit(size_t l) override {
_limit = l + _uniq.size();
return *this;
}
private:
Container _uniq;
Stream *_stream;
size_t _limit;
};
template<typename Stream, typename In, typename Comp>
class SortedStream: public BaseStream<In> {
public:
SortedStream(Stream *stream, Comp c): _stream(stream) {
while (true) {
auto p1 = _stream->GetNext();
if (!p1.second)
break;
_all.push_back(p1.first);
}
std::sort(_all.begin(), _all.end(), c);
_it = _all.begin();
}
BaseStream<In>& Skip(size_t l) override {
_it += l;
return *this;
}
BaseStream<In>& Limit(size_t l) override {
size_t offset = _it - _all.begin();
l += offset;
if (l < _all.size())
_all.resize(l);
return *this;
}
std::pair<In, bool> GetNext() override {
std::pair<In, bool> res;
if (_it == _all.end()) {
res.second = false;
return res;
}
res.second = true;
res.first = *_it;
_it++;
return res;
}
private:
typename std::vector<In>::const_iterator _it;
std::vector<In> _all;
Stream *_stream;
};
template<typename Stream, typename In, typename Func>
class FilterStream: public BaseStream<In> {
public:
FilterStream(Stream *stream, Func f): _stream(stream), _f(f), _limit(-1), _pos(0) {
}
BaseStream<In>& Skip(size_t l) override {
while (l--) {
auto p1 = GetNext();
if (!p1.second)
break;
}
return *this;
}
BaseStream<In>& Limit(size_t l) override {
_limit = l + _pos;
return *this;
}
std::pair<In, bool> GetNext() override {
if (_limit <= _pos)
return std::make_pair(In(), false);
while (true) {
auto p1 = _stream->GetNext();
if (!p1.second)
return p1;
if (_f(p1.first)) {
_pos++;
return p1;
}
}
}
private:
Stream *_stream;
Func _f;
size_t _limit, _pos;
};
template<typename Stream, typename In, typename Out, typename Func>
class MapStream: public BaseStream<Out> {
public:
MapStream(Stream *stream, Func f): _stream(stream), _f(f) {
}
BaseStream<Out>& Skip(size_t l) override {
_stream->Skip(l);
return *this;
}
BaseStream<Out>& Limit(size_t l) override {
_stream->Limit(l);
return *this;
}
std::pair<Out, bool> GetNext() override {
auto p1 = _stream->GetNext();
if (!p1.second)
return std::make_pair(Out(), false);
return std::make_pair(_f(p1.first), true);
}
private:
Stream *_stream;
Func _f;
};
template<typename Iterator>
class RangeStream: public BaseStream<Iterator> {
public:
RangeStream(Iterator it1, Iterator it2): _it1(it1), _it2(it2),
_limit(-1), _pos(0) {
}
BaseStream<Iterator>& Skip(size_t l) override {
_it1 += l;
_pos += l;
return *this;
}
BaseStream<Iterator>& Limit(size_t l) override {
_limit = l + _pos;
return *this;
}
std::pair<Iterator, bool> GetNext() override {
if (_it1 >= _it2 || _limit <= _pos)
return std::make_pair(Iterator(), false);
_pos++;
return std::make_pair(_it1++, true);
}
private:
Iterator _it1, _it2;
size_t _limit, _pos;
};
template<typename Container>
class ContainerStream: public BaseStream<typename Container::value_type> {
public:
ContainerStream(const Container &c): _it(c.cbegin()), _end(c.cend()),
_limit(-1), _pos(0) {
}
BaseStream<typename Container::value_type>& Skip(size_t l) override {
_pos += l;
while (l--) {
_it++;
}
return *this;
}
BaseStream<typename Container::value_type>& Limit(size_t l) override {
_limit = l + _pos;
return *this;
}
std::pair<typename Container::value_type, bool> GetNext() override {
if (_it == _end || _limit <= _pos)
return std::make_pair(typename Container::value_type(), false);
_pos++;
return std::make_pair(*(_it++), true);
}
private:
typename Container::const_iterator _it, _end;
size_t _limit, _pos;
};
template<typename Container>
class CopyContainerStream: public BaseStream<typename Container::value_type> {
public:
CopyContainerStream(const Container &c): _c(c), _delegate(_c) {
}
BaseStream<typename Container::value_type>& Skip(size_t l) override {
_delegate.Skip(l);
return *this;
}
BaseStream<typename Container::value_type>& Limit(size_t l) override {
_delegate.Limit(l);
return *this;
}
std::pair<typename Container::value_type, bool> GetNext() override {
return _delegate.GetNext();
}
private:
Container _c;
ContainerStream<Container> _delegate;
};
template<typename In, typename Func>
class IterateStream: public BaseStream<In> {
public:
IterateStream(In e, Func f):
_element(e), _f(f), _limit(-1), _pos(0) {
}
BaseStream<In>& Skip(size_t l) override {
while (l--) {
auto p1 = GetNext();
if (!p1.second)
break;
}
return *this;
}
BaseStream<In>& Limit(size_t l) override {
_limit = l + _pos;
return *this;
}
std::pair<In, bool> GetNext() override {
if (_pos >= _limit)
return std::make_pair(_element, false);
_pos++;
In old = _element;
_element = _f(_element);
return std::make_pair(old, true);
}
private:
In _element;
Func _f;
size_t _limit, _pos;
};
template<typename Stream1, typename Stream2>
class ZipStream: public BaseStream<std::pair<typename Stream1::OutType, typename Stream2::OutType>> {
public:
ZipStream(Stream1 *s1, Stream2 *s2): _s1(s1), _s2(s2) {
}
typedef std::pair<typename Stream1::OutType, typename Stream2::OutType> Out;
BaseStream<Out>& Skip(size_t l) override {
_s1->Skip(l);
_s2->Skip(l);
return *this;
}
BaseStream<Out>& Limit(size_t l) override {
_s1->Limit(l);
_s2->Limit(l);
return *this;
}
std::pair<Out, bool> GetNext() override {
std::pair<Out, bool> res;
auto p1 = _s1->GetNext();
auto p2 = _s2->GetNext();
if (!p1.second || !p2.second) {
res.second = false;
return res;
}
res.second = true;
res.first.first = p1.first;
res.first.second = p2.first;
return res;
}
private:
Stream1 *_s1;
Stream2 *_s2;
};
template<typename T>
RangeStream<T> Range(T a, T b) {
return RangeStream<T>(a, b);
}
template<typename Container>
ContainerStream<Container> From(const Container &c) {
return ContainerStream<Container>(c);
}
template<typename Element, typename... Arguments>
CopyContainerStream<std::vector<Element>> Of(Element f, Arguments... args) {
std::vector<Element> r{f, args...};
return CopyContainerStream<std::vector<Element>>(r);
}
template<typename Element>
CopyContainerStream<std::vector<Element>> Empty() {
std::vector<Element> r;
return CopyContainerStream<std::vector<Element>>(r);
}
template<typename Element, typename Func>
IterateStream<Element, Func> Iterate(Element e, Func f) {
return IterateStream<Element, Func>(e, f);
}
}
}
}
#endif
| 22.143657 | 101 | 0.612857 | Zaspire |
a59714480448a0b391489b10ca3d034c3b60a9ee | 177 | cpp | C++ | src/talkPageParser/grammars/commentEndingGrammar.cpp | lewishamulton/grawitas | e05fc18373af86e5f417be6817bcdbf3a16c272a | [
"MIT"
] | 6 | 2017-12-08T17:09:14.000Z | 2020-05-28T15:42:26.000Z | src/talkPageParser/grammars/commentEndingGrammar.cpp | lewishamulton/grawitas | e05fc18373af86e5f417be6817bcdbf3a16c272a | [
"MIT"
] | 12 | 2017-11-16T09:48:51.000Z | 2022-01-07T16:28:46.000Z | src/talkPageParser/grammars/commentEndingGrammar.cpp | lewishamulton/grawitas | e05fc18373af86e5f417be6817bcdbf3a16c272a | [
"MIT"
] | 7 | 2017-12-08T17:35:58.000Z | 2021-12-16T17:38:46.000Z | #include "commentEndingGrammar_def.hpp"
template Grawitas::CommentEndingGrammar<std::string::const_iterator, boost::spirit::qi::iso8859_1::blank_type>::CommentEndingGrammar();
| 44.25 | 135 | 0.819209 | lewishamulton |
a5984c1ec2ac00c6fc9fcf4ff86dfdcc2f303cd2 | 4,309 | cc | C++ | base/task/sequence_manager/task_order_unittest.cc | qoor/basium | 906addabfe8bd3b17808e8fa88e51bcf55d12473 | [
"BSD-2-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | base/task/sequence_manager/task_order_unittest.cc | qoor/basium | 906addabfe8bd3b17808e8fa88e51bcf55d12473 | [
"BSD-2-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | base/task/sequence_manager/task_order_unittest.cc | qoor/basium | 906addabfe8bd3b17808e8fa88e51bcf55d12473 | [
"BSD-2-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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 "base/task/sequence_manager/task_order.h"
#include "base/task/sequence_manager/enqueue_order.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace base {
namespace sequence_manager {
class TaskOrderTest : public testing::Test {
protected:
static TaskOrder MakeImmediateTaskOrder(int enqueue_order) {
return MakeTaskOrder(enqueue_order, TimeTicks(), enqueue_order);
}
static TaskOrder MakeDelayedTaskOrder(int enqueue_order,
TimeTicks delayed_run_time,
int sequence_num) {
return MakeTaskOrder(enqueue_order, delayed_run_time, sequence_num);
}
void ExpectLessThan(TaskOrder& order1, TaskOrder& order2) {
EXPECT_TRUE(order1 < order2);
EXPECT_TRUE(order1 <= order2);
EXPECT_FALSE(order1 == order2);
EXPECT_TRUE(order1 != order2);
EXPECT_FALSE(order1 >= order2);
EXPECT_FALSE(order1 > order2);
EXPECT_FALSE(order2 < order1);
EXPECT_FALSE(order2 <= order1);
EXPECT_FALSE(order2 == order1);
EXPECT_TRUE(order1 != order2);
EXPECT_TRUE(order2 >= order1);
EXPECT_TRUE(order2 > order1);
}
void ExpectEqual(TaskOrder& order1, TaskOrder& order2) {
EXPECT_FALSE(order1 < order2);
EXPECT_TRUE(order1 <= order2);
EXPECT_TRUE(order1 == order2);
EXPECT_FALSE(order1 != order2);
EXPECT_TRUE(order1 >= order2);
EXPECT_FALSE(order1 > order2);
EXPECT_FALSE(order2 < order1);
EXPECT_TRUE(order2 <= order1);
EXPECT_TRUE(order2 == order1);
EXPECT_FALSE(order1 != order2);
EXPECT_TRUE(order2 >= order1);
EXPECT_FALSE(order2 > order1);
}
private:
static TaskOrder MakeTaskOrder(int enqueue_order,
TimeTicks delayed_run_time,
int sequence_num) {
return TaskOrder::CreateForTesting(
EnqueueOrder::FromIntForTesting(enqueue_order), delayed_run_time,
sequence_num);
}
};
TEST_F(TaskOrderTest, ImmediateTasksNotEqual) {
TaskOrder order1 = MakeImmediateTaskOrder(/*enqueue_order=*/10);
TaskOrder order2 = MakeImmediateTaskOrder(/*enqueue_order=*/11);
ExpectLessThan(order1, order2);
}
TEST_F(TaskOrderTest, ImmediateTasksEqual) {
TaskOrder order1 = MakeImmediateTaskOrder(/*enqueue_order=*/10);
TaskOrder order2 = MakeImmediateTaskOrder(/*enqueue_order=*/10);
ExpectEqual(order1, order2);
}
TEST_F(TaskOrderTest, DelayedTasksOrderedByEnqueueNumberFirst) {
// Enqueued earlier but has and a later delayed run time and posting order.
TaskOrder order1 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(2),
/*sequence_num=*/2);
TaskOrder order2 = MakeDelayedTaskOrder(
/*enqueue_order=*/11, /*delayed_run_time=*/TimeTicks() + Seconds(1),
/*sequence_num=*/1);
ExpectLessThan(order1, order2);
}
TEST_F(TaskOrderTest, DelayedTasksSameEnqueueOrder) {
TaskOrder order1 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(1),
/*sequence_num=*/2);
TaskOrder order2 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(2),
/*sequence_num=*/1);
ExpectLessThan(order1, order2);
}
TEST_F(TaskOrderTest, DelayedTasksSameEnqueueOrderAndRunTime) {
TaskOrder order1 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(1),
/*sequence_num=*/1);
TaskOrder order2 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(1),
/*sequence_num=*/2);
ExpectLessThan(order1, order2);
}
TEST_F(TaskOrderTest, DelayedTasksEqual) {
TaskOrder order1 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(1),
/*sequence_num=*/1);
TaskOrder order2 = MakeDelayedTaskOrder(
/*enqueue_order=*/10, /*delayed_run_time=*/TimeTicks() + Seconds(1),
/*sequence_num=*/1);
ExpectEqual(order1, order2);
}
} // namespace sequence_manager
} // namespace base
| 33.146154 | 77 | 0.696913 | qoor |
a599085877c1c6c86feac1c428f1bac90102b736 | 3,531 | cpp | C++ | src/Player.cpp | ingmarinho/wappie-jump | b869825222997c4ff068e03fe02e2b94ecd5e450 | [
"BSL-1.0"
] | null | null | null | src/Player.cpp | ingmarinho/wappie-jump | b869825222997c4ff068e03fe02e2b94ecd5e450 | [
"BSL-1.0"
] | null | null | null | src/Player.cpp | ingmarinho/wappie-jump | b869825222997c4ff068e03fe02e2b94ecd5e450 | [
"BSL-1.0"
] | null | null | null | #include "Player.hpp"
namespace WappieJump
{
Player::Player(GameDataRef data) : _data(data)
{
_player = _data->characterSprite;
_player.setPosition(SCREEN_WIDTH / 2, SCREEN_HEIGHT - 100.0f);
}
bool Player::hasReachedMaxDistance()
{
return _reachedMaxDistance;
}
sf::Sprite* Player::GetPlayerSprite()
{
return &_player;
}
Player::Movement Player::GetPlayerMovement()
{
return _playerMovement;
}
void Player::SetJumpVelocity(float newVelocity)
{
_jumpVelocity = newVelocity;
}
void Player::SetPlayerPosition(float x, float y)
{
_player.setPosition(x, y);
}
sf::Vector2f Player::GetPlayerVelocity()
{
return _velocity;
}
void Player::SetPlayerVelocityY(float velocity)
{
_velocity.y = velocity;
}
void Player::SetPlayerAngle(Angle newPlayerAngle)
{
switch (newPlayerAngle)
{
case LEFT:
if (_playerAngle != Player::LEFT)
{
_player.setScale(1, 1);
_player.move(-_player.getGlobalBounds().width, 0);
_playerAngle = Player::LEFT;
}
break;
case RIGHT:
if (_playerAngle != Player::RIGHT)
{
_player.setScale(-1, 1);
_player.move(_player.getGlobalBounds().width, 0);
_playerAngle = Player::RIGHT;
}
break;
}
}
void Player::SetPlayerMovement(Movement newPlayerMovement)
{
if (_playerMovement == DEATHFALL) return;
switch (newPlayerMovement)
{
case JUMPING:
_playerMovement = JUMPING;
break;
case RISING:
_playerMovement = RISING;
break;
case FLOATING:
_playerMovement = FLOATING;
break;
case FALLING:
_playerMovement = FALLING;
break;
case DEATHFALL:
_playerMovement = DEATHFALL;
break;
}
}
void Player::ChangePoisonColor()
{
if (_poisonFadeValue == 155) return;
_poisonFadeValue += 2.5f;
_player.setColor(sf::Color(100 + _poisonFadeValue, 255, 100 + _poisonFadeValue, 255));
}
void Player::SetPoisonColor()
{
_player.setColor(sf::Color(100, 255, 100, 255));
_poisonFadeValue = 0;
}
void Player::SetPlayerDeathColor()
{
_player.setColor(sf::Color(255, 100, 100, 255));
}
void Player::Draw()
{
_data->window.draw(_player);
}
void Player::MoveRight()
{
if (_velocity.x < PLAYER_VELOCITY_X_MAX) _velocity.x += PLAYER_ACCELERATION_X;
_player.move(_velocity.x, 0);
}
void Player::MoveLeft()
{
if (_velocity.x > -PLAYER_VELOCITY_X_MAX) _velocity.x -= PLAYER_ACCELERATION_X;
_player.move(_velocity.x, 0);
}
void Player::Decelleration()
{
if (_velocity.x > 0.0f)
{
_velocity.x -= PLAYER_ACCELERATION_X;
// if (_velocity.x < 0.0f) _velocity.x = 0.0f;
}
else if (_velocity.x < 0.0f)
{
_velocity.x += PLAYER_ACCELERATION_X;
// if (_velocity.x > 0.0f) _velocity.x = 0.0f;
}
if (_velocity.x != 0.0f) _player.move(_velocity.x, 0);
}
void Player::Update()
{
switch (_playerMovement)
{
case JUMPING:
_velocity.y = _jumpVelocity;
_player.move(0, _velocity.y);
_playerMovement = RISING;
break;
case RISING:
if (_velocity.y + GRAVITY > 0) _velocity.y -= GRAVITY;
else _velocity.y += GRAVITY;
_player.move(0, _velocity.y);
if (_velocity.y == 0.0f)
{
_reachedMaxDistance = true;
_playerMovement = FALLING;
}
break;
case FLOATING:
break;
case FALLING:
_reachedMaxDistance = false;
_velocity.y += GRAVITY;
_player.move(0, _velocity.y);
break;
case DEATHFALL:
if (_velocity.y < -10.0f) _velocity.y = -10.0f;
_velocity.y += GRAVITY;
_player.move(0, _velocity.y);
break;
}
}
} | 17.923858 | 88 | 0.657604 | ingmarinho |
a59fe3020a142e2cead64a15edbf4a8a933a16a1 | 1,330 | cpp | C++ | The Snake/The Snake/Logic.cpp | septimomend/The-Snake | d79399f34e5693bf256c0966b9328a22472e47b9 | [
"MIT"
] | null | null | null | The Snake/The Snake/Logic.cpp | septimomend/The-Snake | d79399f34e5693bf256c0966b9328a22472e47b9 | [
"MIT"
] | null | null | null | The Snake/The Snake/Logic.cpp | septimomend/The-Snake | d79399f34e5693bf256c0966b9328a22472e47b9 | [
"MIT"
] | null | null | null | // Logic.cpp >> defines game logic
#include "stdafx.h"
#include "Global.h"
#include "The Snake Dec.h"
using namespace std;
void Logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
// move snake's some item and remove the last
//
for (int i = 1; i < nTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
// determine the direction
//
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
// hard difficulty. Make all walls as solid stuff
//
if (isHard == true)
{
if (x == width || x < 0 || y == height || y < 0)
{
gameOver = true;
GameOver();
}
}
if (x >= width)
x = 0;
else if (x < 0)
x = width - 1;
if (y >= height)
y = 0;
else if (y < 0)
y = height - 1;
// determine head to tail crash
//
for (int i = 0; i < nTail; i++)
{
if (tailX[i] == x && tailY[i] == y)
{
gameOver = true;
GameOver();
}
}
// if snake eat food
//
if (x == foodX && y == foodY)
{
score += 10; // add 10 scores for each eaten food
foodX = rand() % width; // generate new
foodY = rand() % height; // place for food
nTail++; // increase snake's size
}
} | 15.833333 | 51 | 0.542105 | septimomend |
a5a1369f2736012f66742a8db545de7fc2b5aa02 | 9,656 | cpp | C++ | src/register.cpp | Marcin648/ets2-telemetry-udp | e68ee4d2fd65715a5b961e31fe814bb2b5553138 | [
"MIT"
] | null | null | null | src/register.cpp | Marcin648/ets2-telemetry-udp | e68ee4d2fd65715a5b961e31fe814bb2b5553138 | [
"MIT"
] | null | null | null | src/register.cpp | Marcin648/ets2-telemetry-udp | e68ee4d2fd65715a5b961e31fe814bb2b5553138 | [
"MIT"
] | null | null | null | #include "register.hpp"
#include <cstdio>
#include "store.hpp"
#define REG_EVENT(type, callback) (register_for_event(type, callback, NULL))
#define REG_INDEXED_CHANNEL(name, index, type, target) register_for_channel(SCS_TELEMETRY_##name, index, SCS_VALUE_TYPE_##type, SCS_TELEMETRY_CHANNEL_FLAG_each_frame, telemetry_store_##type, target)
#define REG_CHANNEL(name, type, target) REG_INDEXED_CHANNEL(name, SCS_U32_NIL, type, target)
scs_telemetry_register_for_channel_t register_for_channel;
scs_telemetry_register_for_event_t register_for_event;
void register_event(const scs_event_t type, scs_telemetry_event_callback_t callback){
REG_EVENT(type, callback);
}
// Common channel
void register_common(telemetry_common_s &telemetry_common){
REG_CHANNEL(CHANNEL_local_scale, float, &telemetry_common.local_scale);
REG_CHANNEL(CHANNEL_game_time, u32, &telemetry_common.game_time);
REG_CHANNEL(CHANNEL_next_rest_stop, s32, &telemetry_common.next_rest_stop);
}
// Truck channel
void register_truck(telemetry_truck_s &telemetry_truck){
REG_CHANNEL(TRUCK_CHANNEL_world_placement, dplacement, &telemetry_truck.world_placement);
REG_CHANNEL(TRUCK_CHANNEL_local_linear_velocity, fvector, &telemetry_truck.local_linear_velocity);
REG_CHANNEL(TRUCK_CHANNEL_local_angular_velocity, fvector, &telemetry_truck.local_angular_velocity);
REG_CHANNEL(TRUCK_CHANNEL_local_linear_acceleration, fvector, &telemetry_truck.local_linear_acceleration);
REG_CHANNEL(TRUCK_CHANNEL_local_angular_acceleration, fvector, &telemetry_truck.local_angular_acceleration);
REG_CHANNEL(TRUCK_CHANNEL_cabin_offset, fplacement, &telemetry_truck.cabin_offset);
REG_CHANNEL(TRUCK_CHANNEL_cabin_angular_velocity, fvector, &telemetry_truck.cabin_angular_velocity);
REG_CHANNEL(TRUCK_CHANNEL_cabin_angular_acceleration, fvector, &telemetry_truck.cabin_angular_acceleration);
REG_CHANNEL(TRUCK_CHANNEL_head_offset, fplacement, &telemetry_truck.head_offset);
REG_CHANNEL(TRUCK_CHANNEL_speed, float, &telemetry_truck.speed);
REG_CHANNEL(TRUCK_CHANNEL_engine_rpm, float, &telemetry_truck.engine_rpm);
REG_CHANNEL(TRUCK_CHANNEL_engine_gear, s32, &telemetry_truck.engine_gear);
REG_CHANNEL(TRUCK_CHANNEL_displayed_gear, s32, &telemetry_truck.displayed_gear);
REG_CHANNEL(TRUCK_CHANNEL_input_steering, float, &telemetry_truck.input_steering);
REG_CHANNEL(TRUCK_CHANNEL_input_throttle, float, &telemetry_truck.input_throttle);
REG_CHANNEL(TRUCK_CHANNEL_input_brake, float, &telemetry_truck.input_brake);
REG_CHANNEL(TRUCK_CHANNEL_input_clutch, float, &telemetry_truck.input_clutch);
REG_CHANNEL(TRUCK_CHANNEL_effective_steering, float, &telemetry_truck.effective_steering);
REG_CHANNEL(TRUCK_CHANNEL_effective_throttle, float, &telemetry_truck.effective_throttle);
REG_CHANNEL(TRUCK_CHANNEL_effective_brake, float, &telemetry_truck.effective_brake);
REG_CHANNEL(TRUCK_CHANNEL_effective_clutch, float, &telemetry_truck.effective_clutch);
REG_CHANNEL(TRUCK_CHANNEL_cruise_control, float, &telemetry_truck.cruise_control);
REG_CHANNEL(TRUCK_CHANNEL_hshifter_slot, u32, &telemetry_truck.hshifter_slot);
REG_CHANNEL(TRUCK_CHANNEL_parking_brake, bool, &telemetry_truck.parking_brake);
REG_CHANNEL(TRUCK_CHANNEL_motor_brake, bool, &telemetry_truck.motor_brake);
REG_CHANNEL(TRUCK_CHANNEL_retarder_level, u32, &telemetry_truck.retarder_level);
REG_CHANNEL(TRUCK_CHANNEL_brake_air_pressure, float, &telemetry_truck.brake_air_pressure);
REG_CHANNEL(TRUCK_CHANNEL_brake_air_pressure_warning, bool, &telemetry_truck.brake_air_pressure_warning);
REG_CHANNEL(TRUCK_CHANNEL_brake_air_pressure_emergency, bool, &telemetry_truck.brake_air_pressure_emergency);
REG_CHANNEL(TRUCK_CHANNEL_brake_temperature, float, &telemetry_truck.brake_temperature);
REG_CHANNEL(TRUCK_CHANNEL_fuel, float, &telemetry_truck.fuel);
REG_CHANNEL(TRUCK_CHANNEL_fuel_warning, bool, &telemetry_truck.fuel_warning);
REG_CHANNEL(TRUCK_CHANNEL_fuel_average_consumption, float, &telemetry_truck.fuel_average_consumption);
REG_CHANNEL(TRUCK_CHANNEL_fuel_range, float, &telemetry_truck.fuel_range);
REG_CHANNEL(TRUCK_CHANNEL_adblue, float, &telemetry_truck.adblue);
REG_CHANNEL(TRUCK_CHANNEL_adblue_warning, bool, &telemetry_truck.adblue_warning);
REG_CHANNEL(TRUCK_CHANNEL_adblue_average_consumption, float, &telemetry_truck.adblue_average_consumption);
REG_CHANNEL(TRUCK_CHANNEL_oil_pressure, float, &telemetry_truck.oil_pressure);
REG_CHANNEL(TRUCK_CHANNEL_oil_pressure_warning, bool, &telemetry_truck.oil_pressure_warning);
REG_CHANNEL(TRUCK_CHANNEL_oil_temperature, float, &telemetry_truck.oil_temperature);
REG_CHANNEL(TRUCK_CHANNEL_water_temperature, float, &telemetry_truck.water_temperature);
REG_CHANNEL(TRUCK_CHANNEL_water_temperature_warning, bool, &telemetry_truck.water_temperature_warning);
REG_CHANNEL(TRUCK_CHANNEL_battery_voltage, float, &telemetry_truck.battery_voltage);
REG_CHANNEL(TRUCK_CHANNEL_battery_voltage_warning, bool, &telemetry_truck.battery_voltage_warning);
REG_CHANNEL(TRUCK_CHANNEL_electric_enabled, bool, &telemetry_truck.electric_enabled);
REG_CHANNEL(TRUCK_CHANNEL_engine_enabled, bool, &telemetry_truck.engine_enabled);
REG_CHANNEL(TRUCK_CHANNEL_lblinker, bool, &telemetry_truck.lblinker);
REG_CHANNEL(TRUCK_CHANNEL_rblinker, bool, &telemetry_truck.rblinker);
REG_CHANNEL(TRUCK_CHANNEL_light_lblinker, bool, &telemetry_truck.light_lblinker);
REG_CHANNEL(TRUCK_CHANNEL_light_rblinker, bool, &telemetry_truck.light_rblinker);
REG_CHANNEL(TRUCK_CHANNEL_light_parking, bool, &telemetry_truck.light_parking);
REG_CHANNEL(TRUCK_CHANNEL_light_low_beam, bool, &telemetry_truck.light_low_beam);
REG_CHANNEL(TRUCK_CHANNEL_light_high_beam, bool, &telemetry_truck.light_high_beam);
REG_CHANNEL(TRUCK_CHANNEL_light_aux_front, u32, &telemetry_truck.light_aux_front);
REG_CHANNEL(TRUCK_CHANNEL_light_aux_roof, u32, &telemetry_truck.light_aux_roof);
REG_CHANNEL(TRUCK_CHANNEL_light_beacon, bool, &telemetry_truck.light_beacon);
REG_CHANNEL(TRUCK_CHANNEL_light_brake, bool, &telemetry_truck.light_brake);
REG_CHANNEL(TRUCK_CHANNEL_light_reverse, bool, &telemetry_truck.light_reverse);
REG_CHANNEL(TRUCK_CHANNEL_wipers, bool, &telemetry_truck.wipers);
REG_CHANNEL(TRUCK_CHANNEL_dashboard_backlight, float, &telemetry_truck.dashboard_backlight);
REG_CHANNEL(TRUCK_CHANNEL_wear_engine, float, &telemetry_truck.wear_engine);
REG_CHANNEL(TRUCK_CHANNEL_wear_transmission, float, &telemetry_truck.wear_transmission);
REG_CHANNEL(TRUCK_CHANNEL_wear_cabin, float, &telemetry_truck.wear_cabin);
REG_CHANNEL(TRUCK_CHANNEL_wear_chassis, float, &telemetry_truck.wear_chassis);
REG_CHANNEL(TRUCK_CHANNEL_wear_wheels, float, &telemetry_truck.wear_wheels);
REG_CHANNEL(TRUCK_CHANNEL_odometer, float, &telemetry_truck.odometer);
REG_CHANNEL(TRUCK_CHANNEL_navigation_distance, float, &telemetry_truck.navigation_distance);
REG_CHANNEL(TRUCK_CHANNEL_navigation_time, float, &telemetry_truck.navigation_time);
REG_CHANNEL(TRUCK_CHANNEL_navigation_speed_limit, float, &telemetry_truck.navigation_speed_limit);
for(size_t i = 0; i < TELE_TRUCK_WHEEL_COUNT; i++){
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_susp_deflection, i, float, &telemetry_truck.wheel_susp_deflection[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_on_ground, i, bool, &telemetry_truck.wheel_on_ground[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_substance, i, u32, &telemetry_truck.wheel_substance[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_velocity, i, float, &telemetry_truck.wheel_velocity[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_steering, i, float, &telemetry_truck.wheel_steering[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_rotation, i, float, &telemetry_truck.wheel_rotation[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_lift, i, float, &telemetry_truck.wheel_lift[i]);
REG_INDEXED_CHANNEL(TRUCK_CHANNEL_wheel_lift_offset, i, float, &telemetry_truck.wheel_lift_offset[i]);
}
}
// Trailer channel
void register_trailer(telemetry_trailer_s &telemetry_trailer){
REG_CHANNEL(TRAILER_CHANNEL_connected, bool, &telemetry_trailer.connected);
REG_CHANNEL(TRAILER_CHANNEL_world_placement, fplacement, &telemetry_trailer.world_placement);
REG_CHANNEL(TRAILER_CHANNEL_local_linear_velocity, fvector, &telemetry_trailer.local_linear_velocity);
REG_CHANNEL(TRAILER_CHANNEL_local_angular_velocity, fvector, &telemetry_trailer.local_angular_velocity);
REG_CHANNEL(TRAILER_CHANNEL_local_linear_acceleration, fvector, &telemetry_trailer.local_linear_acceleration);
REG_CHANNEL(TRAILER_CHANNEL_local_angular_acceleration, fvector, &telemetry_trailer.local_angular_acceleration);
REG_CHANNEL(TRAILER_CHANNEL_wear_chassis, float, &telemetry_trailer.wear_chassis);
for(size_t i = 0; i < TELE_TRAILER_WHEEL_COUNT; i++){
REG_INDEXED_CHANNEL(TRAILER_CHANNEL_wheel_susp_deflection, i, float, &telemetry_trailer.wheel_susp_deflection[i]);
REG_INDEXED_CHANNEL(TRAILER_CHANNEL_wheel_on_ground, i, bool, &telemetry_trailer.wheel_on_ground[i]);
REG_INDEXED_CHANNEL(TRAILER_CHANNEL_wheel_substance, i, u32, &telemetry_trailer.wheel_substance[i]);
REG_INDEXED_CHANNEL(TRAILER_CHANNEL_wheel_velocity, i, float, &telemetry_trailer.wheel_velocity[i]);
REG_INDEXED_CHANNEL(TRAILER_CHANNEL_wheel_steering, i, float, &telemetry_trailer.wheel_steering[i]);
REG_INDEXED_CHANNEL(TRAILER_CHANNEL_wheel_rotation, i, float, &telemetry_trailer.wheel_rotation[i]);
}
} | 76.634921 | 198 | 0.831504 | Marcin648 |
a5a273f6bc5fa8ce4c636fdf9e0002ecd30ad38a | 3,219 | cpp | C++ | SuiteLibrary/AboutDlg.cpp | edwig/Kwatta | ce1ca2907608e65ed62d7dbafa9ab1d030caccfe | [
"MIT"
] | 1 | 2021-12-31T17:20:01.000Z | 2021-12-31T17:20:01.000Z | SuiteLibrary/AboutDlg.cpp | edwig/Kwatta | ce1ca2907608e65ed62d7dbafa9ab1d030caccfe | [
"MIT"
] | 10 | 2022-01-14T13:28:32.000Z | 2022-02-13T12:46:34.000Z | SuiteLibrary/AboutDlg.cpp | edwig/Kwatta | ce1ca2907608e65ed62d7dbafa9ab1d030caccfe | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// ██╗░░██╗░██╗░░░░░░░██╗░█████╗░████████╗████████╗░█████╗░
// ██║░██╔╝░██║░░██╗░░██║██╔══██╗╚══██╔══╝╚══██╔══╝██╔══██╗
// █████═╝░░╚██╗████╗██╔╝███████║░░░██║░░░░░░██║░░░███████║
// ██╔═██╗░░░████╔═████║░██╔══██║░░░██║░░░░░░██║░░░██╔══██║
// ██║░╚██╗░░╚██╔╝░╚██╔╝░██║░░██║░░░██║░░░░░░██║░░░██║░░██║
// ╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚═╝░░╚═╝
//
//
// This product: KWATTA (KWAliTy Test API) Test suite for Command-line SOAP/JSON/HTTP internet API's
// This program: SuiteLibrary
// This File : AboutDlg.cpp
// What it does: General About dialog for all programs
// Author : ir. W.E. Huisman
// License : See license.md file in the root directory
//
///////////////////////////////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "SuiteLibrary.h"
#include "AboutDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
// AboutDlg dialog
IMPLEMENT_DYNAMIC(AboutDlg, StyleDialog)
AboutDlg::AboutDlg(CWnd* pParent /*=nullptr*/)
:StyleDialog(IDD_ABOUT, pParent)
{
}
AboutDlg::~AboutDlg()
{
}
void AboutDlg::DoDataExchange(CDataExchange* pDX)
{
StyleDialog::DoDataExchange(pDX);
DDX_Control(pDX,IDC_ABOUT,m_editText);
DDX_Control(pDX,IDOK, m_buttonOK);
if(pDX->m_bSaveAndValidate == FALSE)
{
m_editText.SetRTFText(m_text);
CString test = m_editText.GetRTFText();
}
}
BEGIN_MESSAGE_MAP(AboutDlg, StyleDialog)
END_MESSAGE_MAP()
BOOL
AboutDlg::OnInitDialog()
{
StyleDialog::OnInitDialog();
SetWindowText("About");
ShowCloseButton();
m_text = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1043{\\fonttbl{\\f0\\fnil\\fcharset0 Verdana;}}\n"
"\\viewkind4\\uc1\\pard\\f0\\fs20\n"
"\\tab{\\b KWATTA}\\par\n"
"\\par\n"
"KWALITY TEST API - Program\\par\n"
"\\par\n"
"Named after the 'Ateles Paniscus'\\par\n"
"monkey. Also named the spider-monkey,\\par\n"
"Jungle-devil or Bosduivel.\\par\n"
"\\par\n"
"This program is named {\\b Kwatta} as a\\par\n"
"short for {\\b Kwa}li{\\b T}y {\\b T}est {\\b A}pi program.\\par\n"
"To programmers the protests of a\\par\n"
"professional tester is somewhat like\\par\n"
"the screeching of the spider-monkey.\\par\n"
"After having accomplished a difficult\\par\n"
"task in programming, the programmer\\par\n"
"sits back in humble satisfaction.\\par\n"
"\\par\n"
"But his/her peace gets quickly disturbed\\par\n"
"by the noises of the quality testers\\par\n"
"who gets busy in the aftermath of the\\par\n"
"programming day......\\par\n"
"\\par\n";
CString version;
version.Format("{\\b VERSION: %s}}",KWATTA_VERSION);
m_text += version;
// Perform the streaming
m_editText.SetBorderColor(ThemeColor::_Color1);
m_editText.SetTextMode(TM_RICHTEXT);
UpdateData(FALSE);
return TRUE;
}
// AboutDlg message handlers
| 30.367925 | 104 | 0.522523 | edwig |
a5a5171da5795cf7179afc0cfa567031eb3d5268 | 1,181 | cpp | C++ | code/sequential.cpp | V1ccus/Searching | 1ed7a6178b6644c82305b6ec914ca577ec78d940 | [
"MIT"
] | 1 | 2022-03-10T17:04:38.000Z | 2022-03-10T17:04:38.000Z | code/sequential.cpp | V1ccus/Searching | 1ed7a6178b6644c82305b6ec914ca577ec78d940 | [
"MIT"
] | null | null | null | code/sequential.cpp | V1ccus/Searching | 1ed7a6178b6644c82305b6ec914ca577ec78d940 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
//...
int n,m,x;
int o=0;
int data[x];
//...
cout
<< "=== [ Sequential Searching ] ===\n"
<< ". . .\n"
<< "Input total data : ";cin>>n;
//...
system("cls");
cout << "( INPUT DATA )\n";
for(x=0;x<n;x++){
cout << "masukkan data : ";
cin >> data[x];
}
//...
system("cls");
cout
<< "( Searching )\n"
<< "...\n"
<< "mesin pencarian : ";
cin >> m;
//...
system("cls");
cout
<< "( Hasil )\n"
<< "...\n";
for(x=0;x<n;x++){
if(data[x]==m){
cout
<< "Data "<<m<<", ditemukan!\nIndex : " <<x+1;
o++;
cout << "\n";
}
}
cout <<"...\n";
if(o==0){
system("cls");
cout << "Data "<<m<<", tidak ditemukan!\n";
}
else{
cout << "Total data : " <<o <<endl;
}
system("pause");
} | 23.62 | 66 | 0.288738 | V1ccus |
a5a5da7a338313925b4f92828704b4b73083d60c | 642 | cc | C++ | src/xenia/ui/spirv/spirv_util.cc | cloudhaacker/xenia | 54b211ed1885cdfb9ef6d74e60f7e615aaf56d45 | [
"BSD-3-Clause"
] | 3,100 | 2018-05-03T10:04:39.000Z | 2022-03-31T04:51:53.000Z | src/xenia/ui/spirv/spirv_util.cc | cloudhaacker/xenia | 54b211ed1885cdfb9ef6d74e60f7e615aaf56d45 | [
"BSD-3-Clause"
] | 671 | 2018-05-04T00:51:22.000Z | 2022-03-31T15:20:22.000Z | src/xenia/ui/spirv/spirv_util.cc | cloudhaacker/xenia | 54b211ed1885cdfb9ef6d74e60f7e615aaf56d45 | [
"BSD-3-Clause"
] | 877 | 2018-05-03T21:01:17.000Z | 2022-03-31T19:43:14.000Z | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/spirv/spirv_util.h"
namespace xe {
namespace ui {
namespace spirv {
//
} // namespace spirv
} // namespace ui
} // namespace xe
| 30.571429 | 79 | 0.364486 | cloudhaacker |
a5a9eb0628eeda6adf7dc0841f8e783ee56da3b2 | 973 | cpp | C++ | src/Source/DxbcContainerHeader.cpp | tgjones/slimshader-cpp | a1833e2eccf32cccfe33aa7613772503eca963ee | [
"MIT"
] | 20 | 2015-03-29T02:14:03.000Z | 2021-11-14T12:27:02.000Z | src/Source/DxbcContainerHeader.cpp | tgjones/slimshader-cpp | a1833e2eccf32cccfe33aa7613772503eca963ee | [
"MIT"
] | null | null | null | src/Source/DxbcContainerHeader.cpp | tgjones/slimshader-cpp | a1833e2eccf32cccfe33aa7613772503eca963ee | [
"MIT"
] | 12 | 2015-05-04T06:39:10.000Z | 2022-02-23T06:48:04.000Z | #include "PCH.h"
#include "DxbcContainerHeader.h"
using namespace SlimShader;
DxbcContainerHeader DxbcContainerHeader::Parse(BytecodeReader& reader)
{
auto fourCc = reader.ReadUInt32();
if (fourCc != 'CBXD')
throw new std::runtime_error("Invalid FourCC");
DxbcContainerHeader result;
result._fourCc = fourCc;
result._uniqueKey[0] = reader.ReadUInt32();
result._uniqueKey[1] = reader.ReadUInt32();
result._uniqueKey[2] = reader.ReadUInt32();
result._uniqueKey[3] = reader.ReadUInt32();
result._one = reader.ReadUInt32();
result._totalSize = reader.ReadUInt32();
result._chunkCount = reader.ReadUInt32();
return result;
}
uint32_t DxbcContainerHeader::GetFourCc()
{
return _fourCc;
}
uint32_t* DxbcContainerHeader::GetUniqueKey()
{
return _uniqueKey;
}
uint32_t DxbcContainerHeader::GetOne()
{
return _one;
}
uint32_t DxbcContainerHeader::GetTotalSize()
{
return _totalSize;
}
uint32_t DxbcContainerHeader::GetChunkCount()
{
return _chunkCount;
} | 20.270833 | 70 | 0.758479 | tgjones |
a5ac6409b69e83489a2863310e082573c7b88a8c | 1,228 | cpp | C++ | environment_sim/src/environ.cpp | sarvesh0303/gazebo_experiments | f3f83f4aa5ac5fd4eadaedab799e2a5d6670aacc | [
"MIT"
] | null | null | null | environment_sim/src/environ.cpp | sarvesh0303/gazebo_experiments | f3f83f4aa5ac5fd4eadaedab799e2a5d6670aacc | [
"MIT"
] | null | null | null | environment_sim/src/environ.cpp | sarvesh0303/gazebo_experiments | f3f83f4aa5ac5fd4eadaedab799e2a5d6670aacc | [
"MIT"
] | null | null | null | #include "../lib/environ.hh"
Environ::Environ(void) {
signalpath = "templates/signal.sdf";
roadpath = "templates/road.sdf";
greenpath = "templates/green.sdf";
redpath = "templates/red.sdf";
roads = new Road(roadpath);
}
void Environ::insert_road(double x, double y) {
roads->create(x,y);
}
void Environ::remove_road(double x, double y) {
roads->remove(x,y);
}
void Environ::insert_signal(std::string name, double x, double y) {
double pos2[] = {x,y};
sig_list.push_back(Signal(name,pos2,redpath,greenpath,signalpath));
}
Signal* Environ::access_signal(std::string findname) {
for (int i = 0; i < sig_list.size(); i++) {
if (sig_list[i].name == findname)
return &(sig_list[i]);
}
return NULL;
}
void Environ::load(gazebo::physics::WorldPtr world) {
std::vector<std::string> addsdf = roads->load();
std::vector<std::string> sigsdf;
for (int i = 0; i < sig_list.size(); i++) {
sigsdf = sig_list[i].load();
addsdf.insert(addsdf.end(),sigsdf.begin(),sigsdf.end());
}
for (int i = 0; i < addsdf.size(); i++) {
world->InsertModelString(addsdf[i]);
}
}
void Environ::update(double t, gazebo::physics::WorldPtr world) {
for (int i = 0; i < sig_list.size(); i++) {
sig_list[i].update(t,world);
}
} | 25.583333 | 68 | 0.659609 | sarvesh0303 |
a5adb803ee1b80ad69427730898a538c07829726 | 12,458 | cpp | C++ | src/cedar/scheduler.cpp | cedar-lang/cedar | 04b13546d8520dcd7a01983a4a88408348a245f8 | [
"MIT"
] | 3 | 2020-10-02T05:46:42.000Z | 2021-11-14T20:33:24.000Z | src/cedar/scheduler.cpp | nickwanninger/cedar | 04b13546d8520dcd7a01983a4a88408348a245f8 | [
"MIT"
] | 2 | 2019-01-09T07:37:08.000Z | 2019-02-20T21:54:43.000Z | src/cedar/scheduler.cpp | cedar-lang/cedar | 04b13546d8520dcd7a01983a4a88408348a245f8 | [
"MIT"
] | 1 | 2019-01-02T14:12:25.000Z | 2019-01-02T14:12:25.000Z | /*
* MIT License
*
* Copyright (c) 2018 Nick Wanninger
*
* 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 <cedar/event_loop.h>
#include <cedar/globals.h>
#include <cedar/modules.h>
#include <cedar/object/fiber.h>
#include <cedar/object/lambda.h>
#include <cedar/objtype.h>
#include <cedar/scheduler.h>
#include <cedar/thread.h>
#include <cedar/types.h>
#include <unistd.h>
#include <uv.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <flat_hash_map.hpp>
#include <cedar/jit.h>
#include <mutex>
#define GC_THREADS
#include <gc/gc.h>
using namespace cedar;
/**
* The number of jobs that have yet to be completed. This number is used
* to track if the main thread should exit or not, and if a certain thread
* should wait or not. When a job is pushed to the scheduler, this value is
* incremented, and is decremented when a job is deemed completed.
*
* This number is an unsigned 64 bit integer, because cedar will eventually
* be able to run a huge number of these jobs concurrently. :)
*/
static std::atomic<i64> jobc;
/**
* ncpus is how many worker threads to maintain at any given time.
*/
static unsigned ncpus = 8;
/**
* the listing of all worker threads and a fast lookup map to the same
* information
* TODO: more docs
*/
static std::mutex worker_thread_mutex;
static std::vector<worker_thread *> worker_threads;
static std::vector<std::thread> thread_handles;
static thread_local fiber *_current_fiber = nullptr;
static thread_local worker_thread *_current_worker = nullptr;
static thread_local bool _is_worker_thread = false;
static thread_local int sched_depth = 0;
static worker_thread *lookup_or_create_worker() {
static int next_wid = 0;
if (_current_worker != nullptr) {
return _current_worker;
}
worker_thread_mutex.lock();
worker_thread *w;
w = new worker_thread();
w->wid = next_wid++;
worker_threads.push_back(w);
_current_worker = w;
worker_thread_mutex.unlock();
return w;
}
fiber *cedar::current_fiber() { return _current_fiber; }
void cedar::add_job(fiber *f) {
std::lock_guard guard(worker_thread_mutex);
int ind = rand() % worker_threads.size();
worker_threads[ind]->local_queue.push(f);
f->worker = worker_threads[ind];
worker_threads[ind]->work_cv.notify_all();
}
void _do_schedule_callback(uv_idle_t *handle) {
auto *t = static_cast<worker_thread *>(handle->data);
schedule(t);
if (t->local_queue.size() == 0) {
uv_idle_stop(handle);
}
}
static std::thread spawn_worker_thread(void) {
return std::thread([](void) -> void {
register_thread();
_is_worker_thread = true;
worker_thread *thd = lookup_or_create_worker();
thd->internal = true;
while (true) schedule(thd, true);
deregister_thread();
return;
});
}
/**
* schedule a single job on the caller thread, it's up to the caller to manage
* where the job goes after the job yields
*/
void schedule_job(fiber *proc) {
static int sched_time = 2;
static bool read_env = false;
if (!read_env) {
static const char *SCHED_TIME_ENV = getenv("CDRTIMESLICE");
if (SCHED_TIME_ENV != nullptr) sched_time = atol(SCHED_TIME_ENV);
if (sched_time < 2) {
throw cedar::make_exception("$CDRTIMESLICE must be larger than 2ms");
}
}
read_env = true;
if (proc == nullptr) return;
u64 time = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
int state = proc->state.load();
if (state == SLEEPING) {
if (time < (proc->last_ran + proc->sleep)) {
return;
}
}
// #define LOG_RUN_TIME
#ifdef LOG_RUN_TIME
auto start = std::chrono::steady_clock::now();
#endif
fiber *old_fiber = _current_fiber;
_current_fiber = proc;
proc->resume();
_current_fiber = old_fiber;
#ifdef LOG_RUN_TIME
auto end = std::chrono::steady_clock::now();
std::cout << "ran: "
<< std::chrono::duration_cast<std::chrono::microseconds>(end -
start)
.count()
<< " us" << std::endl;
#endif
/* store the last time of execution in the job. This is an
* approximation as getting the ms from epoch takes too long */
proc->last_ran = time + sched_time;
/* and increment the ticks for this job */
proc->ticks++;
}
/**
* return if all work has been completed or not
*/
bool cedar::all_work_done(void) {
// if there are no pending jobs, we must be done with all work.
return jobc.load() == 0;
}
static void init_scheduler(void) {
// the number of worker threads is the number of cpus the host machine
// has, minus one as the main thread does work
ncpus = std::thread::hardware_concurrency();
static const char *CDRMAXPROCS = getenv("CDRMAXPROCS");
if (CDRMAXPROCS != nullptr) ncpus = atol(CDRMAXPROCS);
if (ncpus < 1) ncpus = 1;
// spawn 'ncpus' worker threads
for (unsigned i = 0; i < ncpus; i++) {
auto t = spawn_worker_thread();
t.detach();
}
}
void cedar::schedule(worker_thread *worker, bool internal_worker) {
sched_depth++;
if (worker == nullptr) {
worker = lookup_or_create_worker();
}
bool steal = true;
bool wait_for_work_cv = true;
size_t pool_size = 0;
int i1, i2;
worker_thread *w1, *w2;
TOP:
if (false && (current_fiber() != nullptr || sched_depth > 1)) {
printf("worker: %14p %d current: %14p depth: %d\n", worker,
_is_worker_thread, current_fiber(), sched_depth);
}
// work is the thing that will eventually be done, while looking for work,
// it will be set and checked for equality to nullptr. If at any point it
// is not nullptr, it will immediately be scheduled.
fiber *work = nullptr;
// first check the local queue
work = worker->local_queue.steal();
if (work != nullptr) goto SCHEDULE;
if (steal) {
worker_thread_mutex.lock();
// now look through other threads in the thread pool for work to steal
pool_size = worker_threads.size();
i1 = rand() % pool_size;
i2 = rand() % pool_size;
w1 = worker_threads[i1];
w2 = worker_threads[i2];
if (w1->local_queue.size() > w2->local_queue.size()) {
work = w1->local_queue.steal();
} else {
work = w2->local_queue.steal();
}
worker_thread_mutex.unlock();
if (work != nullptr) {
goto SCHEDULE;
}
}
if (internal_worker) {
if (wait_for_work_cv) {
std::unique_lock lk(worker->lock);
worker->work_cv.wait_for(lk, std::chrono::milliseconds(2));
lk.unlock();
goto TOP;
}
}
CLEANUP:
sched_depth--;
return;
SCHEDULE:
work->worker = worker;
worker->ticks++;
schedule_job(work);
bool replace = true;
auto state = work->state.load();
if (state == STOPPED || state == BLOCKING) replace = false;
if (state == STOPPED) {
for (auto &j : work->dependents) {
add_job(j);
}
work->dependents.clear();
}
// since we did some work, we should put it back in the local queue
// but only if it isn't done.
if (replace) {
worker->local_queue.push(work);
}
if (internal_worker) {
goto TOP;
}
goto CLEANUP;
}
// forward declare this function
namespace cedar {
void bind_stdlib(void);
};
void init_binding(cedar::vm::machine *m);
/**
* this is the primary entry point for cedar, this function
* should be called before ANY code is run.
*/
void cedar::init(void) {
init_scheduler();
init_ev();
type_init();
init_binding(nullptr);
bind_stdlib();
core_mod = require("core");
}
/**
* eval_lambda is an 'async' evaluator. This means it will add the
* job to the thread pool with a future-like concept attached, then
* run the scheduler until the fiber has completed it's work, then
* return to the caller in C++. It works in this way so that calling
* cedar functions from within C++ won't fully block the event loop
* when someone tries to get a mutex lock or something from within
* such a call
*/
ref cedar::eval_lambda(call_state call) {
fiber *f = new fiber(call);
worker_thread *my_worker = lookup_or_create_worker();
add_job(f);
// printf("eval_lambda %d\n", sched_depth);
fiber *cur = current_fiber();
if (false && cur != nullptr) {
f->dependents.push_back(cur);
cur->set_state(fiber_state::BLOCKING);
yield();
return f->return_value;
}
// my_worker->local_queue.push(&f);
while (!f->done) {
schedule(my_worker);
}
return f->return_value;
}
ref cedar::call_function(lambda *fn, int argc, ref *argv, call_context *ctx) {
// printf("%p\n", fn);
if (fn->code_type == lambda::function_binding_type) {
function_callback c(fn->self, argc, argv, ctx->coro, ctx->mod);
fn->call(c);
return c.get_return();
}
return eval_lambda(fn->prime(argc, argv));
}
// yield is just a wrapper around yield nil
void cedar::yield() { cedar::yield(nullptr); }
void cedar::yield(ref val) {
auto current = current_fiber();
if (current == nullptr) {
throw std::logic_error("Attempt to yield without a current fiber failed\n");
}
current->yield(val);
}
//////////////////////////////////////////////////////////////////////////////
static void *cedar_unoptimisable;
#define cedar_setsp(x) \
cedar_unoptimisable = alloca((char *)alloca(sizeof(size_t)) - (char *)(x));
static size_t cedar_stack_size = 4096 * 4;
static size_t get_stack_size(void) { return cedar_stack_size; }
/* Get memory page size. The query is done once. The value is cached. */
static size_t get_page_size(void) {
static long pgsz = 0;
if (pgsz != 0) return (size_t)pgsz;
pgsz = sysconf(_SC_PAGE_SIZE);
return (size_t)pgsz;
}
static thread_local std::vector<char *> stacks;
void finalizer(void *ptr, void *data) { printf("finalized %p\n", ptr); }
static char *stackalloc() {
char *stk;
stk = (char *)GC_MALLOC(get_stack_size());
return stk;
}
extern "C" void *get_sp(void);
extern "C" void *GC_call_with_stack_base(GC_stack_base_func, void *);
extern "C" int GC_register_my_thread(const struct GC_stack_base *);
extern "C" int GC_unregister_my_thread(void);
coro::coro(std::function<void(coro *)> fn) {
set_func(fn);
coro();
}
coro::coro() {
stk = stackalloc();
stack_base = stk;
stack_base += get_stack_size();
}
void coro::set_func(std::function<void(coro *)> fn) { func = fn; }
coro::~coro(void) {
}
bool coro::is_done(void) { return done; }
void coro::yield(void) { yield(nullptr); }
void coro::yield(ref v) {
value = v;
if (!setjmp(ctx)) {
longjmp(return_ctx, 1);
}
}
ref coro::resume(void) {
if (done) {
fprintf(stderr, "Error: Resuming a complete coroutine\n");
return nullptr;
}
if (!setjmp(return_ctx)) {
if (!initialized) {
initialized = true;
// calculate the new stack pointer
size_t sp = (size_t)(stk);
sp += get_stack_size();
sp &= ~15;
// inline assembly macro to set the stack pointer
struct GC_stack_base stack_base;
GC_get_stack_base(&stack_base);
stack_base.mem_base = (void *)sp;
GC_register_my_thread(&stack_base);
cedar_setsp(sp-8);
func(this);
done = true;
// switch back to the calling context
longjmp(return_ctx, 1);
return value;
}
longjmp(ctx, 1);
return value;
}
return value;
}
| 22.6098 | 80 | 0.662466 | cedar-lang |
a5aeb33f4231c5cbee3529ff96663cfdf204a458 | 866 | hpp | C++ | src/Game/Mount.hpp | ananace/LD44 | 472e5134a1f846d9c2244b31fe3753d08963b71e | [
"MIT"
] | null | null | null | src/Game/Mount.hpp | ananace/LD44 | 472e5134a1f846d9c2244b31fe3753d08963b71e | [
"MIT"
] | null | null | null | src/Game/Mount.hpp | ananace/LD44 | 472e5134a1f846d9c2244b31fe3753d08963b71e | [
"MIT"
] | null | null | null | #pragma once
#include "Attachement.hpp"
#include "Hardpoint.hpp"
#include <functional>
#include <deque>
namespace Game
{
class Weapon;
class Mount : public Attachement
{
public:
virtual bool isMount() const override { return true; }
std::size_t getHardpointCount() const;
Hardpoint& getHardpoint(std::size_t aId);
const Hardpoint& getHardpoint(std::size_t aId) const;
void visitHardpoints(const std::function<void(Hardpoint&)>& aMethod);
void visitHardpoints(const std::function<void(const Hardpoint&)>& aMethod) const;
void visitWeapons(const std::function<void(Weapon&)>& aMethod);
void visitWeapons(const std::function<void(const Weapon&)>& aMethod) const;
protected:
void addHardpoint(const Hardpoint& aHardpoint);
void addHardpoint(Hardpoint&& aHardpoint);
private:
std::deque<Hardpoint> m_hardpoints;
};
}
| 23.405405 | 85 | 0.729792 | ananace |
a5b1d3d4921deaccdef036edcba41be523f71ea5 | 927 | cpp | C++ | Engine/Material.cpp | larso0/Engine | 6078646fd92ea86c737f6769d50be9bd18c6dac8 | [
"MIT"
] | null | null | null | Engine/Material.cpp | larso0/Engine | 6078646fd92ea86c737f6769d50be9bd18c6dac8 | [
"MIT"
] | 1 | 2017-04-04T23:58:04.000Z | 2017-04-04T23:58:04.000Z | Engine/Material.cpp | larso0/Engine | 6078646fd92ea86c737f6769d50be9bd18c6dac8 | [
"MIT"
] | null | null | null | /*
* File: Material.cpp
* Author: larso
*
* Created on 2. januar 2016, 21:18
*/
#include "Material.h"
namespace Engine
{
Material::Material() :
color(1.f, 1.f, 1.f, 1.f),
lightSource(nullptr),
texture(nullptr)
{
}
Material::Material(glm::vec4 color) :
color(color),
lightSource(nullptr),
texture(nullptr)
{
}
Material::~Material()
{
}
void Material::setColor(glm::vec4 color)
{
this->color = color;
}
void Material::setColor(float r, float g, float b, float a)
{
color = glm::vec4(r, g, b, a);
}
void Material::setLightSource(Light* lightSource)
{
this->lightSource = lightSource;
}
void Material::setTexture(Texture* texture)
{
this->texture = texture;
}
const glm::vec4& Material::getColor() const
{
return color;
}
const Light* Material::getLightSource() const
{
return lightSource;
}
const Texture* Material::getTexture() const
{
return texture;
}
}
| 13.632353 | 60 | 0.649407 | larso0 |
a5b38bb8354dd4da401e817f28624c212bc2ee19 | 17,025 | cpp | C++ | stochepi/src/parprior.cpp | eeg-lanl/sarscov2-selection | c2087cbaf55de9930736aa6677a57008a2397583 | [
"BSD-3-Clause"
] | null | null | null | stochepi/src/parprior.cpp | eeg-lanl/sarscov2-selection | c2087cbaf55de9930736aa6677a57008a2397583 | [
"BSD-3-Clause"
] | null | null | null | stochepi/src/parprior.cpp | eeg-lanl/sarscov2-selection | c2087cbaf55de9930736aa6677a57008a2397583 | [
"BSD-3-Clause"
] | null | null | null | #include "parprior.hpp"
#include <sstream>
#include <cmath> // fmod, sqrt...
#include <limits> // for infinity
#include "macros.hpp"
/* methods for ParPrior */
ParPrior::ParPrior() :
name(""), elements(1), // use default value defined for ParElt
lboundbool(false), lbound(0.0),
uboundbool(false), ubound(0.0),
homotopy_support(HomotopyClass::CONTRACTIBLE),
prior(nullptr), rw_rule([](double t){return true;}),
stepcounter(0), acceptcounter(0), ac(0), uc(1),
selectionbool(false), selection(0),
random_effects(false), loc(nullptr), scale(nullptr) {
/* empty */
}
ParPrior::ParPrior(double value) :
name(""), elements(1, ParElt(value)),
lboundbool(false), lbound(0.0),
uboundbool(false), ubound(0.0),
homotopy_support(HomotopyClass::CONTRACTIBLE),
prior(nullptr), rw_rule([](double t){return true;}),
stepcounter(0), acceptcounter(0), ac(0), uc(1),
selectionbool(false), selection(0),
random_effects(false), loc(nullptr), scale(nullptr) {
/* empty */
}
ParPrior::ParPrior(const std::vector<double> & values) :
name(""), lboundbool(false), lbound(0.0),
uboundbool(false), ubound(0.0),
homotopy_support(HomotopyClass::CONTRACTIBLE),
prior(nullptr), rw_rule([](double t){return true;}),
stepcounter(0), acceptcounter(0), ac(0), uc(1),
selectionbool(false), selection(0),
random_effects(false), loc(nullptr), scale(nullptr) {
// copy values to elements
elements.resize(values.size());
for ( size_t r = 0; r < values.size(); ++r ) {
elements[r] = ParElt(values[r]);
}
}
ParPrior::ParPrior(int n, double value) :
name(""), elements(n, ParElt(value)),
lboundbool(false), lbound(0.0),
uboundbool(false), ubound(0.0),
homotopy_support(HomotopyClass::CONTRACTIBLE),
prior(nullptr), rw_rule([](double t){return true;}),
stepcounter(0), acceptcounter(0), ac(0), uc(1),
selectionbool(false), selection(0),
random_effects(false), loc(nullptr), scale(nullptr) {
/* empty */
}
// TODO: name!!
ParPrior::ParPrior(InitType ip, double value, double pstd) :
name(""), elements(1, ParElt(value, pstd)),
lboundbool(false), lbound(0.0),
uboundbool(false), ubound(0.0),
homotopy_support(HomotopyClass::CONTRACTIBLE),
prior(nullptr), rw_rule([](double t){return true;}),
stepcounter(0), acceptcounter(0), ac(0), uc(1),
selectionbool(false), selection(0),
random_effects(false), loc(nullptr), scale(nullptr) { // some common constructions
switch ( ip ) {
case UNRESTRICTED: {
break;
}
case POSITIVE: {
lboundbool = true;
lbound = 0.0;
break;
}
case NEGATIVE: {
uboundbool = true;
ubound = 0.0;
break;
}
default: {
throw std::logic_error("invalid InitType" + RIGHT_HERE);
break; // redundant
}
}
}
ParPrior::ParPrior(double value, double pstd, Prior* prior, std::string name) :
name(name), elements(1, ParElt(value, pstd)),
lboundbool(false), lbound(0.0),
uboundbool(false), ubound(0.0),
homotopy_support(HomotopyClass::CONTRACTIBLE),
prior(prior), rw_rule([](double t){return true;}),
stepcounter(0), acceptcounter(0), ac(0), uc(1),
selectionbool(false), selection(0),
random_effects(false), loc(nullptr), scale(nullptr) {
/* empty */
}
ParPrior::ParPrior(const ParPrior & pp) {
/* NB: don't call clear(), since members are not initialized.
* in particular: pointers are not NULL
*/
copy(pp);
}
ParPrior::~ParPrior() {
clear();
}
ParPrior & ParPrior::operator=(const ParPrior & pp) {
if ( this != &pp ) {
clear(); // deletes pointers to prior, loc ans scale
copy(pp); // copies data from pp
}
return *this;
}
void ParPrior::copy(const ParPrior & pp) {
name = pp.name;
elements = pp.elements;
lboundbool = pp.lboundbool;
lbound = pp.lbound;
uboundbool = pp.uboundbool;
ubound = pp.ubound;
stepcounter = pp.stepcounter;
acceptcounter = pp.acceptcounter;
ac = pp.ac;
uc = pp.uc;
if ( pp.prior != nullptr ) {
prior = pp.prior->dup();
} else {
prior = nullptr;
}
homotopy_support = pp.homotopy_support;
rw_rule = pp.rw_rule;
selectionbool = pp.selectionbool;
selection = pp.selection;
// copy random effects data
random_effects = pp.random_effects;
if ( pp.random_effects ) {
// pp.random_effects == true guarentees that pp.loc isn't NULL or garbage
loc = pp.loc->dup();
scale = pp.scale->dup();
} else {
loc = nullptr;
scale = nullptr;
}
}
void ParPrior::clear() {
delete prior;
delete loc;
delete scale;
}
ParPrior & ParPrior::operator=(double new_value) {
if ( !inBounds(new_value) ) {
throw std::invalid_argument("new value is not within range" + RIGHT_HERE);
}
for ( auto & elt : elements ) {
elt.old_value = elt.value;
elt.value = new_value;
}
return *this;
}
ParPrior & ParPrior::operator=(const std::vector<double> & new_values) {
elements.resize(new_values.size());
for ( size_t r = 0; r < new_values.size(); ++r ) {
if ( !inBounds(new_values[r]) ) {
throw std::invalid_argument("new value is not within range" + RIGHT_HERE);
}
elements[r] = ParElt(new_values[r]);
}
// turn off previous selection, as it may no longer be valid
selectionbool = false;
selection = 0;
return *this;
}
ParPrior & ParPrior::operator*=(double x) {
for ( auto & elt : elements ) {
double new_value = elt.value * x;
if ( !inBounds(new_value) ) {
throw std::invalid_argument("new value is not within range" + RIGHT_HERE);
}
elt.old_value = elt.value;
elt.value = new_value;
}
return *this;
}
ParPrior & ParPrior::operator/=(double x) {
if ( x == 0 ) {
throw std::invalid_argument("denominator is zero" + RIGHT_HERE);
}
for ( auto & elt : elements ) {
double new_value = elt.value / x;
if ( !inBounds(new_value) ) {
throw std::invalid_argument("new value is not within range" + RIGHT_HERE);
}
elt.old_value = elt.value;
elt.value = new_value;
}
return *this;
}
ParPrior & ParPrior::operator+=(double x) {
for ( auto & elt : elements ) {
double new_value = elt.value + x;
if ( !inBounds(new_value) ) {
throw std::invalid_argument("new value is not within range" + RIGHT_HERE);
}
elt.old_value = elt.value;
elt.value = new_value;
}
return *this;
}
ParPrior & ParPrior::operator-=(double x) {
for ( auto & elt : elements ) {
double new_value = elt.value - x;
if ( !inBounds(new_value) ) {
throw std::invalid_argument("new value is not within range" + RIGHT_HERE);
}
elt.old_value = elt.value;
elt.value = new_value;
}
return *this;
}
/** Use the getValue method to retrieve the correct value
* which can depend on isLocked()
*/
ParPrior::operator double() const {
return getValue();
}
/** Manually get one of the values */
const double & ParPrior::operator[](size_t r) const {
if ( r >= elements.size() ) {
throw std::range_error("selection not in range of elements" + RIGHT_HERE);
} // else...
return elements[r].value;
}
double & ParPrior::operator[](size_t r) {
if ( r >= elements.size() ) {
throw std::range_error("selection not in range of elements" + RIGHT_HERE);
} // else...
return elements[r].value;
}
ParPrior* ParPrior::dup() const {
return new ParPrior(*this);
}
void ParPrior::lock() {
// keep locked tot current value
for ( auto & elt : elements ) {
elt.locked = true;
}
if ( random_effects ) {
loc->lock(); scale->lock();
}
}
void ParPrior::lockAllBut(int s) {
// locks all elements to current value, unlocks r-th element
for ( int r = 0; r < int(elements.size()); ++r ) {
elements[r].locked = (r != s);
}
}
void ParPrior::removeSingleLocks() {
if ( !isLocked() ) {
unlock();
}
}
void ParPrior::unlock() {
for ( auto & elt : elements ) {
elt.locked = false;
}
if ( random_effects ) {
loc->unlock(); scale->unlock();
}
}
bool ParPrior::isLocked() const {
// are all parameters locked?
for ( auto & elt : elements ) {
if ( !elt.locked ) {
return false; // return false if ANY one of the parameters is not locked
}
}
if ( random_effects && (!loc->isLocked() || !scale->isLocked()) ) {
// NB: && operator short-circuits
return false;
}
// at reaching this point, we know that all elements are locked
return true;
}
void ParPrior::setPrior(Prior* new_prior) {
delete prior;
prior = new_prior;
}
void ParPrior::setBounds(double lbound, double ubound) {
this->lbound = lbound;
lboundbool = true;
this->ubound = ubound;
uboundbool = true;
// check validity
for ( auto & elt : elements ) {
if ( !inBounds(elt.value) ) {
std::stringstream ss;
ss << "given bounds for '" << getName() << "' do not contain value " << elt.value << RIGHT_HERE;
throw std::logic_error(ss.str());
}
}
}
void ParPrior::setNameBoundsPstdAndUnlock(std::string name, double lbound,
double ubound, double pstd) {
setName(name);
setBounds(lbound, ubound);
setPstd(pstd);
unlock();
}
void ParPrior::setRWRule(RWRule rw_rule) {
this->rw_rule = rw_rule;
}
void ParPrior::setLBound(double lbound) {
this->lbound = lbound;
lboundbool = true;
// check validity
for ( auto & elt : elements ) {
if ( !inBounds(elt.value) ) {
std::stringstream ss;
ss << "given bounds for '" << getName() << "' do not contain value " << elt.value << RIGHT_HERE;
throw std::logic_error(ss.str());
}
}
}
void ParPrior::setUBound(double ubound) {
this->ubound = ubound;
uboundbool = true;
// check validity
for ( auto & elt : elements ) {
if ( !inBounds(elt.value) ) {
std::stringstream ss;
ss << "given bounds for '" << getName() << "' do not contain value " << elt.value << RIGHT_HERE;
throw std::logic_error(ss.str());
}
}
}
void ParPrior::setRandomEffects(double loc_val, double loc_pstd, double scale_val, double scale_pstd) {
if ( random_effects ) {
// first delete any old loc and scale
delete loc; delete scale;
}
random_effects = true;
loc = new ParPrior(UNRESTRICTED, loc_val, loc_pstd);
loc->setName(name + "__loc");
scale = new ParPrior(POSITIVE, scale_val, scale_pstd);
scale->setName(name + "__scale");
setPrior(new StdNormalPrior()); // TODO: other options...
}
bool ParPrior::isRandomEffects() const {
return random_effects;
}
const ParPrior* ParPrior::getLoc() const {
return loc;
}
const ParPrior* ParPrior::getScale() const {
return scale;
}
ParPrior* ParPrior::getLoc() {
return loc;
}
ParPrior* ParPrior::getScale() {
return scale;
}
bool ParPrior::isBounded() const {
return lboundbool && uboundbool;
}
bool ParPrior::inBounds(double x) const {
// check if the argument is between lbound and ubound
return ((!uboundbool || x <= ubound) && (!lboundbool || x >= lbound));
}
double ParPrior::getLengthInterval() const {
if ( isBounded() ) {
return ubound - lbound;
} else {
return std::numeric_limits<double>::infinity();
}
}
void ParPrior::setHomotopy(HomotopyClass hc) {
switch ( hc ) {
case HomotopyClass::CONTRACTIBLE: {
homotopy_support = HomotopyClass::CONTRACTIBLE;
break;
}
case HomotopyClass::CIRCULAR: {
if ( lboundbool && uboundbool ) {
homotopy_support = HomotopyClass::CIRCULAR;
}
else {
throw std::logic_error("can't make an unbounded support CIRCULAR" + RIGHT_HERE);
}
break;
}
default: {
throw std::logic_error("invalid HomotopyClass given" + RIGHT_HERE);
break;
}
}
}
void ParPrior::select(int r) {
if ( r < 0 || r >= int(elements.size()) ) {
throw std::range_error("selection not in range of elements" + RIGHT_HERE);
} // else...
selectionbool = true;
selection = r;
}
void ParPrior::deselect() {
selectionbool = false;
selection = 0;
}
double ParPrior::getValue() const {
if ( size() > 1 ) {
if ( selectionbool ) {
return elements[selection].value;
} else {
std::cout << *this << std::endl; // TESTING!
throw std::logic_error("call to getValue() of vector-valued ParPrior is ambiguous" + RIGHT_HERE);
}
} else { // scalar
return elements[0].value;
}
}
void ParPrior::setPstd(double pstd) {
for ( auto & elt : elements ) {
elt.pstd = pstd;
}
}
double ParPrior::getAr() const {
if ( stepcounter > 0 ) {
return double(acceptcounter) / stepcounter;
} else {
return 0.0;
}
}
double ParPrior::loglike() const {
if ( random_effects ) {
LinearTransformation fun(loc->getValue(), scale->getValue());
return loglike(&fun);
} else {
return loglike(nullptr);
}
}
double ParPrior::loglike(Transformation* fun) const {
double ll = 0.0;
for ( auto & elt : elements ) {
if ( prior != nullptr ) {
if ( fun == nullptr ) {
ll += prior->loglike(elt.value);
} else {
ll += prior->loglike(fun->evalFun(elt.value)) + fun->evalLogAbsJac(elt.value);
}
} else if ( fun != nullptr ) {
// assume that prior is not informative
ll += fun->evalLogAbsJac(elt.value);
}
}
if ( random_effects ) {
ll += loc->loglike() + scale->loglike();
}
return ll;
}
/** if lboundbool, mirror in lbound. if uboundbool, mirror in ubound
* if both uboundbool and lboundbool, mirror in both bounds,
* by using a combination of mirroring and modulus
* the optional parameter rel_temp can be used for cooling-down schemes
* e.g. in simulated annealing
*/
void ParPrior::mutate(Rng & rng, double rel_temp, double t) {
// first check if the rw_rule allows mutation...
if ( !rw_rule(t) ) return;
// then run through individual elements
for ( auto & elt : elements ) {
if ( elt.locked ) continue;
// else...
elt.old_value = elt.value;
elt.value = elt.value + rng.stdNormal() * elt.pstd * rel_temp; // normal proposal
if ( lboundbool ) {
if ( uboundbool ) { // the 'difficult' case
double interval = (ubound-lbound); // length interval
switch ( homotopy_support ) {
case HomotopyClass::CONTRACTIBLE: { // apply double mirroring
elt.value = fmod(elt.value-lbound, 2*interval);
// remainder after dividion by denominator
if ( elt.value < 0.0 ) elt.value += 2*interval;
// fmod does not always return non-negative numbers
if ( elt.value > interval ) elt.value = 2*interval - elt.value;
// mirror
elt.value += lbound;
// translate back to the 'true' interval
break;
}
case HomotopyClass::CIRCULAR: { // value modulo interval
elt.value = fmod(elt.value-lbound, interval);
if ( elt.value < 0.0 ) elt.value += interval;
// fmod can return negative
elt.value += lbound; // translate back
break;
}
default: { // POINT handled above...
throw std::logic_error("invalid HomotopyClass" + RIGHT_HERE);
break;
}
}
} else { // mirror in lbound?
if ( elt.value < lbound ) {
elt.value = 2*lbound - elt.value;
}
}
} else { // lboundbool == false!!
if ( uboundbool ) { // mirror in ubound?
if ( elt.value > ubound ) {
elt.value = 2*ubound - elt.value;
}
}
// else: uboundbool == false && uboundbool == false, so value is valid!
}
} // for elt in elements
if ( random_effects ) {
loc->mutate(rng, rel_temp, t); scale->mutate(rng, rel_temp, t);
}
stepcounter++;
}
void ParPrior::accept() {
if ( !isLocked() ) {
ac++; // used by updatePvar
acceptcounter++; // used for diagnostics
}
if ( random_effects ) {
loc->accept(); scale->accept();
}
}
void ParPrior::reject() {
for ( auto & elt : elements ) {
if ( !elt.locked ) {
elt.value = elt.old_value;
}
}
if ( random_effects ) {
loc->reject(); scale->reject();
}
}
void ParPrior::updatePstd() {
for ( auto & elt : elements ) {
if ( !elt.locked ) {
if ( stepcounter % PVAR_UPDATE_INTERVAL == 0 ) {
double ar = double(ac) / PVAR_UPDATE_INTERVAL;
// lower, or increase the proposal variance
if ( ar < OPTIMAL_ACCEPTANCE_RATE ) {
elt.pstd *= exp(-0.5/sqrt(uc)); // jumps are too big!
} else {
elt.pstd *= exp(0.5/sqrt(uc)); // jumps are too small!
}
// do some checks to prevent explosions
if ( isBounded() ) {
elt.pstd = std::min(elt.pstd, getLengthInterval());
}
// update/reset counters
ac = 0; // reset acceptance counter
uc++; // increase update counter
}
} // if ! locked... else do nothing
}
if ( random_effects ) {
loc->updatePstd(); scale->updatePstd();
}
}
std::string ParPrior::getName() const {
return name;
}
void ParPrior::setName(std::string name) {
this->name = name;
}
size_t ParPrior::size() const {
return elements.size();
}
void ParPrior::print(std::ostream & os) const {
os << "<param " << "name='" << name << "' "
<< "re='" << std::boolalpha << random_effects << std::noboolalpha << "' "
<< ">" << std::endl;
for ( size_t r = 0; r < elements.size(); ++r ) {
auto & elt = elements[r]; // alias
os << "<elt "
<< "idx='" << r << "' "
<< "val='" << elt.value << "' "
<< "pstd='" << elt.pstd << "' "
<< "lock='" << std::boolalpha << elt.locked << std::noboolalpha << "' "
<< "/>" << std::endl;
}
// don't print hyper parameters: taken care of by Parameters class
os << "</param>";
}
// non menber-functions for ParPrior
std::istream & operator>>(std::istream & is, ParPrior & par) {
// read value from stream
double value;
is >> value; // use standard stream for double
par = value; // use ParPrior::operator=(double )
return is;
}
| 25.222222 | 103 | 0.64605 | eeg-lanl |
a5ba8f31c1311dc7fb390ba9cfec09bd8c82eb09 | 1,727 | cpp | C++ | grading_students.cpp | power-factory/hackerrank | a0f6c6a40a1eff4f0430fd866061378ebd2b5204 | [
"MIT"
] | null | null | null | grading_students.cpp | power-factory/hackerrank | a0f6c6a40a1eff4f0430fd866061378ebd2b5204 | [
"MIT"
] | null | null | null | grading_students.cpp | power-factory/hackerrank | a0f6c6a40a1eff4f0430fd866061378ebd2b5204 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
/*
* Complete the 'gradingStudents' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY grades as parameter.
*/
vector<int> gradingStudents(vector<int> grades)
{
std::vector<int> roundedGrades;
for (int grade : grades)
{
if (grade >= 38)
{
float highestMultiplier = floor(grade / 5);
int diff = ((highestMultiplier+1)*5)-grade;
if (diff < 3 && diff != 0)
{
grade = (highestMultiplier + 1) * 5;
roundedGrades.push_back(grade);
}
else
{
roundedGrades.push_back(grade);
}
}
else
{
roundedGrades.push_back(grade);
}
}
return roundedGrades;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
vector<int> grades;
grades = {4, 73, 67, 38, 33};
vector<int> result = gradingStudents(grades);
for (size_t i = 0; i < result.size(); i++)
{
fout << result[i];
if (i != result.size() - 1)
{
fout << "\n";
}
}
fout << "\n";
fout.close();
return 0;
}
string ltrim(const string &str)
{
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
return s;
}
string rtrim(const string &str)
{
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end());
return s;
}
| 18.178947 | 79 | 0.507238 | power-factory |
a5bd71f0c77425d4f89651aa34913807939c56e8 | 3,179 | cpp | C++ | mod/assimp/assimp_material.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 45 | 2018-08-24T12:57:38.000Z | 2021-11-12T11:21:49.000Z | mod/assimp/assimp_material.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | null | null | null | mod/assimp/assimp_material.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 4 | 2019-09-16T02:48:42.000Z | 2020-07-10T03:50:31.000Z | #include "assimp.h"
using namespace L;
bool assimp_material_loader(ResourceSlot& slot, Material::Intermediate& intermediate) {
if(!assimp_supported_extensions.find(slot.ext)) {
return false;
}
Buffer buffer = slot.read_source_file();
const aiScene* scene = aiImportFileFromMemory((const char*)buffer.data(), (unsigned int)buffer.size(), assimp_import_flags, slot.ext);
if(!scene) {
warning("assimp: %s", aiGetErrorString());
return false;
}
uint32_t material_index = 0;
slot.parameter("material", material_index);
const aiMesh* mesh = scene->mMeshes[material_index];
const aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
Vector4f color_factor = Vector4f(1.f, 1.f, 1.f, 1.f);
float metallic_factor = 0.f;
float roughness_factor = 0.75f;
aiGetMaterialColor(material, AI_MATKEY_COLOR_DIFFUSE, (aiColor4D*)&color_factor);
aiGetMaterialColor(material, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, (aiColor4D*)&color_factor);
aiGetMaterialFloat(material, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, &metallic_factor);
aiGetMaterialFloat(material, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, &roughness_factor);
aiString color_texture_path;
const bool has_color_texture =
!material->GetTexture(aiTextureType_BASE_COLOR, 0, &color_texture_path) ||
!material->GetTexture(aiTextureType_DIFFUSE, 0, &color_texture_path);
aiString normal_texture_path;
const bool has_normal_texture = !material->GetTexture(aiTextureType_NORMALS, 0, &normal_texture_path);
aiString metal_rough_texture_path;
const bool has_metal_rough_texture = !material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &metal_rough_texture_path);
String shader_options;
String mesh_format = "pn";
const bool textured = has_color_texture || has_normal_texture || has_metal_rough_texture;
if(has_color_texture) {
intermediate.texture("color_texture", slot.path + "?comp=bc1&texture=" + (color_texture_path.C_Str() + 1));
shader_options += "&color_texture";
}
if(has_normal_texture) {
intermediate.texture("normal_texture", slot.path + "?comp=bc1&texture=" + (normal_texture_path.C_Str() + 1));
shader_options += "&normal_texture";
mesh_format += "t"; // Need tangents
}
if(has_metal_rough_texture) {
intermediate.texture("metal_rough_texture", slot.path + "?comp=bc1&texture=" + (metal_rough_texture_path.C_Str() + 1));
shader_options += "&metal_rough_texture";
}
if(textured) {
mesh_format += "u"; // Need texcoords
}
if(mesh->HasVertexColors(0)) {
mesh_format += "c";
}
if(mesh->HasBones()) {
mesh_format += "jw";
}
shader_options += "&fmt=" + mesh_format;
intermediate.mesh(slot.path + "?fmt=" + mesh_format + "&mesh=" + to_string(material_index));
intermediate.shader(ShaderStage::Fragment, ".assimp?stage=frag" + shader_options);
intermediate.shader(ShaderStage::Vertex, ".assimp?stage=vert" + shader_options);
intermediate.vector("color_factor", color_factor);
intermediate.vector("metal_rough_factor", Vector4f(
0.f,
roughness_factor,
metallic_factor
));
return true;
}
| 38.301205 | 151 | 0.745517 | Lyatus |
a5caed45284fa8671f5b2c1a1b0b5ff2ca2fc0ce | 985 | cpp | C++ | code/source/audio/audioreceiver.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/audio/audioreceiver.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/audio/audioreceiver.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #include "audioreceiver.hpp"
#include "global/event.hpp"
namespace clover {
namespace audio {
AudioReceiver::AudioReceiver()
: created(false)
, lowpass(1.0){
}
AudioReceiver::AudioReceiver(AudioReceiver&& other)
: created(other.created)
, position(std::move(other.position))
, lowpass(other.lowpass){
}
AudioReceiver::~AudioReceiver(){
ensure(!created);
}
void AudioReceiver::create(){
ensure(!created);
global::Event e(global::Event::OnAudioReceiverCreate);
e(global::Event::Object)= this;
e.send();
created= true;
}
void AudioReceiver::destroy(){
ensure(created);
global::Event e(global::Event::OnAudioReceiverDestroy);
e(global::Event::Object)= this;
e.send();
created= false;
}
void AudioReceiver::setPosition(const util::Vec2d& pos){
util::LockGuard<util::Mutex> lock(accessMutex);
position= pos;
}
util::Vec2d AudioReceiver::getPosition() const {
util::LockGuard<util::Mutex> lock(accessMutex);
return position;
}
} // audio
} // clover | 18.240741 | 56 | 0.711675 | crafn |
a5cbea2efd96f41229ef523eddd1b3186ba8206f | 1,032 | hpp | C++ | apps/router/engine/assfire/router/engine/EngineDistanceMatrixFactory.hpp | Eaglegor/assfire-suite | 6c8140e848932b6ce22b6addd07a93abba652c01 | [
"MIT"
] | null | null | null | apps/router/engine/assfire/router/engine/EngineDistanceMatrixFactory.hpp | Eaglegor/assfire-suite | 6c8140e848932b6ce22b6addd07a93abba652c01 | [
"MIT"
] | null | null | null | apps/router/engine/assfire/router/engine/EngineDistanceMatrixFactory.hpp | Eaglegor/assfire-suite | 6c8140e848932b6ce22b6addd07a93abba652c01 | [
"MIT"
] | null | null | null | #pragma once
#include "assfire/router/api/RouterEngineType.hpp"
#include "assfire/router/api/DistanceMatrixCachingPolicy.hpp"
#include "assfire/router/api/DistanceMatrixErrorPolicy.hpp"
#include "assfire/router/api/RoutingProfile.hpp"
#include "assfire/router/api/DistanceMatrix.hpp"
#include "assfire/router/api/RouteProviderSettings.hpp"
#include <assfire/router/api/RoutingContext.hpp>
#include <memory>
#include <atomic>
namespace assfire::router {
class EngineDistanceMatrixFactory {
public:
EngineDistanceMatrixFactory(const RoutingContext& routing_context);
DistanceMatrix createDistanceMatrix(RouterEngineType engine_type, DistanceMatrixCachingPolicy caching_policy, const RoutingProfile &routing_profile, const RouteProviderSettings &settings,
DistanceMatrixErrorPolicy error_policy = DistanceMatrixErrorPolicy::ON_ERROR_RETURN_INFINITY) const;
private:
RoutingContext routing_context;
mutable std::atomic_int tag_counter;
};
} | 41.28 | 195 | 0.773256 | Eaglegor |
a5d2e4c8682ac34ddd16ff3dc8b2f6ce920e5783 | 22,359 | cpp | C++ | sdl1/rockbot/editor/conversor/main.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/rockbot/editor/conversor/main.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/rockbot/editor/conversor/main.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | #include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iostream>
#include <map>
#include "defines.h"
#include "file/format/st_hitPoints.h"
#include "../../file/format/st_common.h"
#include "fio_v1.h"
#include "file/file_io.h"
#include "file/fio_strings.h"
//#undef main
std::string FILEPATH;
std::string GAMEPATH;
std::string SAVEPATH;
std::string GAMENAME;
CURRENT_FILE_FORMAT::file_game game_data;
CURRENT_FILE_FORMAT::file_stages stage_data;
CURRENT_FILE_FORMAT::file_map maps_data[FS_MAX_STAGES][FS_STAGE_MAX_MAPS]; // stage, map_n
std::vector<CURRENT_FILE_FORMAT::file_npc> enemy_list;
std::vector<CURRENT_FILE_FORMAT::file_object> object_list;
std::vector<CURRENT_FILE_FORMAT::file_artificial_inteligence> ai_list;
std::vector<CURRENT_FILE_FORMAT::file_projectile> projectile_list;
std::vector<CURRENT_FILE_FORMAT::file_scene_list> scene_list;
std::map<int, int> npc_id_list;
std::map<int, int> object_id_list;
std::vector<std::string> common_strings;
CURRENT_FILE_FORMAT::file_io fio;
CURRENT_FILE_FORMAT::fio_strings fio_str;
fio_common fio_cmm;
void convert_dialog_strings(v1_file_stage stage_v1, CURRENT_FILE_FORMAT::file_stage& stage_v2, short stage_id) {
sprintf(stage_v2.dialog_face_graphics_filename, "%s", stage_v1.intro_dialog.face_graphics_filename);
stage_v2.dialog_top_side = stage_v1.intro_dialog.top_side;
std::vector<std::string> dialog_strings;
// *** INTRO DIALOGS *** //
// line-1
for (int i=0; i<V1_FS_DIALOG_LINES; i++) {
std::string line = std::string(stage_v1.intro_dialog.line1[i]) + "\n";
std::cout << "LINE#1[" << i << "]: " << line << ", common_strings.size(): " << dialog_strings.size() << std::endl;
dialog_strings.push_back(line);
}
// line-2
for (int i=0; i<V1_FS_DIALOG_LINES; i++) {
std::string line = std::string(stage_v1.intro_dialog.line2[i]) + "\n";
dialog_strings.push_back(line);
}
for (int i=0; i<V1_FS_MAX_PLAYERS; i++) {
// answer-1
for (int j=0; j<V1_FS_DIALOG_LINES; j++) {
std::string line = std::string(stage_v1.intro_dialog.answer1[i][j]) + "\n";
dialog_strings.push_back(line);
}
// answer-2
for (int j=0; j<V1_FS_DIALOG_LINES; j++) {
std::string line = std::string(stage_v1.intro_dialog.answer2[i][j]) + "\n";
dialog_strings.push_back(line);
}
}
// *** BOSS DIALOGS *** //
// line-1
for (int i=0; i<V1_FS_DIALOG_LINES; i++) {
std::string line = std::string(stage_v1.boss_dialog.line1[i]) + "\n";
dialog_strings.push_back(line);
}
// line-2
for (int i=0; i<V1_FS_DIALOG_LINES; i++) {
std::string line = std::string(stage_v1.boss_dialog.line2[i]) + "\n";
dialog_strings.push_back(line);
}
for (int i=0; i<V1_FS_MAX_PLAYERS; i++) {
// answer-1
for (int j=0; j<V1_FS_DIALOG_LINES; j++) {
std::string line = std::string(stage_v1.boss_dialog.answer1[i][j]) + "\n";
dialog_strings.push_back(line);
}
// answer-2
for (int j=0; j<V1_FS_DIALOG_LINES; j++) {
std::string line = std::string(stage_v1.boss_dialog.answer2[i][j]) + "\n";
dialog_strings.push_back(line);
}
}
fio_str.save_stage_dialogs(stage_id, dialog_strings);
}
st_position_uint8 convert_uint8_pos(v1_st_position_uint8 pos) {
st_position_uint8 res;
res.x = pos.x;
res.y = pos.y;
return res;
}
st_color convert_color(v1_st_color color) {
st_color res;
res.r = color.r;
res.g = color.g;
res.b = color.b;
return res;
}
st_rectangle convert_rectangle(v1_st_rectangle v1_rect) {
st_rectangle res;
res.h = v1_rect.h;
res.w = v1_rect.w;
res.x = v1_rect.x;
res.y = v1_rect.y;
return res;
}
void convert_stage_maps(int stage_id, v1_file_stage& stage_v1) {
for (int i=0; i<V1_FS_STAGE_MAX_MAPS; i++) {
for (int j=0; j<2; j++) {
maps_data[stage_id][i].backgrounds[j].adjust_y = stage_v1.maps[i].backgrounds[j].adjust_y;
maps_data[stage_id][i].backgrounds[j].auto_scroll = false;
sprintf(maps_data[stage_id][i].backgrounds[j].filename, "%s", stage_v1.maps[i].backgrounds[j].filename);
maps_data[stage_id][i].backgrounds[j].speed = stage_v1.maps[i].backgrounds[j].speed;
}
maps_data[stage_id][i].background_color = convert_color(stage_v1.maps[i].background_color);
for (int j=0; j<V1_FS_MAX_MAP_NPCS; j++) {
// check for invalid NPCs
std::map<int, int>::iterator it;
it = npc_id_list.find(stage_v1.maps[i].map_npcs[j].id_npc);
if (it == npc_id_list.end()) {
maps_data[stage_id][i].map_npcs[j].id_npc = -1;
} else {
int new_id = it->second;
maps_data[stage_id][i].map_npcs[j].direction = stage_v1.maps[i].map_npcs[j].direction;
maps_data[stage_id][i].map_npcs[j].id_npc = new_id;
maps_data[stage_id][i].map_npcs[j].start_point.x = stage_v1.maps[i].map_npcs[j].start_point.x;
maps_data[stage_id][i].map_npcs[j].start_point.y = stage_v1.maps[i].map_npcs[j].start_point.y;
}
}
for (int j=0; j<V1_FS_MAX_MAP_OBJECTS; j++) {
maps_data[stage_id][i].map_objects[j].direction = stage_v1.maps[i].map_objects[j].direction;
maps_data[stage_id][i].map_objects[j].id_object = stage_v1.maps[i].map_objects[j].id_object;
maps_data[stage_id][i].map_objects[j].link_dest.x = stage_v1.maps[i].map_objects[j].link_dest.x;
maps_data[stage_id][i].map_objects[j].link_dest.y = stage_v1.maps[i].map_objects[j].link_dest.y;
maps_data[stage_id][i].map_objects[j].map_dest = stage_v1.maps[i].map_objects[j].map_dest;
maps_data[stage_id][i].map_objects[j].start_point.x = stage_v1.maps[i].map_objects[j].start_point.x;
maps_data[stage_id][i].map_objects[j].start_point.y = stage_v1.maps[i].map_objects[j].start_point.y;
}
for (int j=0; j<V1_MAP_W; j++) {
for (int k=0; k<V1_MAP_H; k++) {
maps_data[stage_id][i].tiles[j][k].locked = stage_v1.maps[i].tiles[j][k].locked;
maps_data[stage_id][i].tiles[j][k].tile1.x = stage_v1.maps[i].tiles[j][k].tile1.x;
maps_data[stage_id][i].tiles[j][k].tile1.y = stage_v1.maps[i].tiles[j][k].tile1.y;
maps_data[stage_id][i].tiles[j][k].tile3.x = stage_v1.maps[i].tiles[j][k].tile3.x;
maps_data[stage_id][i].tiles[j][k].tile3.y = stage_v1.maps[i].tiles[j][k].tile3.y;
}
}
}
}
void convert_stages_and_maps(v1_file_stages& stages) {
for (int i=0; i<V1_FS_MAX_STAGES; i++) {
v1_file_stage temp_v1 = stages.stages[i];
CURRENT_FILE_FORMAT::file_stage temp_v2;
for (int j=0; j<FS_STAGE_MAX_MAPS; j++) {
temp_v2.autoscroll[j] = false;
}
sprintf(temp_v2.bgmusic_filename, "%s", temp_v1.bgmusic_filename);
temp_v2.boss.id_npc = temp_v1.boss.id_npc;
temp_v2.boss.id_weapon = temp_v1.boss.id_weapon;
sprintf(temp_v2.boss.name, "%s", temp_v1.boss.name);
convert_dialog_strings(temp_v1, temp_v2, i);
temp_v2.cutscene_pos = -1;
temp_v2.cutscene_pre = -1;
for (int i=0; i<FS_STAGE_MAX_LINKS; i++) {
temp_v2.links[i].bidirecional = temp_v1.links[i].bidirecional;
temp_v2.links[i].id_map_destiny = temp_v1.links[i].id_map_destiny;
temp_v2.links[i].id_map_origin = temp_v1.links[i].id_map_origin;
temp_v2.links[i].is_door = temp_v1.links[i].is_door;
temp_v2.links[i].pos_destiny.x = temp_v1.links[i].pos_destiny.x;
temp_v2.links[i].pos_destiny.y = temp_v1.links[i].pos_destiny.y;
temp_v2.links[i].pos_origin.x = temp_v1.links[i].pos_origin.x;
temp_v2.links[i].pos_origin.y = temp_v1.links[i].pos_origin.y;
temp_v2.links[i].size = temp_v1.links[i].size;
temp_v2.links[i].type = temp_v1.links[i].type;
}
sprintf(temp_v2.name, "%s", temp_v1.name);
sprintf(temp_v2.tileset_filename, "%s", "default.png");
stage_data.stages[i] = temp_v2;
convert_stage_maps(i, temp_v1);
}
}
void convert_ai_types(v1_file_game& game_v1) {
for (int n=0; n<V1_FS_GAME_MAX_NPCS; n++) {
int i = game_v1.game_npcs[n].IA_type;
std::string name(game_v1.ai_types[i].name);
if (name.length() < 1) {
continue;
}
CURRENT_FILE_FORMAT::file_artificial_inteligence new_ai;
sprintf(new_ai.name, "%s", game_v1.ai_types[i].name);
for (int j=0; j<MAX_AI_REACTIONS; j++) {
new_ai.reactions[j].action = game_v1.ai_types[i].reactions[j].action;
new_ai.reactions[j].extra_parameter = game_v1.ai_types[i].reactions[j].extra_parameter;
new_ai.reactions[j].go_to = game_v1.ai_types[i].reactions[j].go_to;
new_ai.reactions[j].go_to_delay = game_v1.ai_types[i].reactions[j].go_to_delay;
}
for (int j=0; j<AI_MAX_STATES; j++) {
new_ai.states[j].action = game_v1.ai_types[i].states[j].action;
new_ai.states[j].chance = game_v1.ai_types[i].states[j].chance;
new_ai.states[j].extra_parameter = game_v1.ai_types[i].states[j].extra_parameter;
new_ai.states[j].go_to = game_v1.ai_types[i].states[j].go_to;
new_ai.states[j].go_to_delay = game_v1.ai_types[i].states[j].go_to_delay;
}
ai_list.push_back(new_ai);
}
}
void convert_game_npcs(v1_file_game& game_v1) {
for (int i=0; i<V1_FS_GAME_MAX_NPCS; i++) {
std::string name(game_v1.game_npcs[i].name);
// ignore ones using default name
if (name == "NPC") {
std::cout << "npc[" << i << "] invalid. id: " << (int)game_v1.game_npcs[i].id << std::endl;
continue;
}
CURRENT_FILE_FORMAT::file_npc new_enemy;
new_enemy.attack_frame = 0;
sprintf(new_enemy.bg_graphic_filename, "%s", game_v1.game_npcs[i].bg_graphic_filename);
new_enemy.direction = game_v1.game_npcs[i].direction;
new_enemy.facing = game_v1.game_npcs[i].facing;
new_enemy.fly_flag = game_v1.game_npcs[i].fly_flag;
new_enemy.frame_size.width = game_v1.game_npcs[i].frame_size.width;
new_enemy.frame_size.height = game_v1.game_npcs[i].frame_size.height;
sprintf(new_enemy.graphic_filename, "%s", game_v1.game_npcs[i].graphic_filename);
new_enemy.hp.current = game_v1.game_npcs[i].hp.current;
new_enemy.hp.total = game_v1.game_npcs[i].hp.total;
new_enemy.IA_type = game_v1.game_npcs[i].IA_type;
new_enemy.id = game_v1.game_npcs[i].id;
new_enemy.is_boss = game_v1.game_npcs[i].is_boss;
new_enemy.is_ghost = game_v1.game_npcs[i].is_ghost;
new_enemy.is_sub_boss = game_v1.game_npcs[i].is_sub_boss;
sprintf(new_enemy.name, "%s", game_v1.game_npcs[i].name);
new_enemy.projectile_id[0] = game_v1.game_npcs[i].projectile_id[0];
new_enemy.projectile_id[1] = game_v1.game_npcs[i].projectile_id[1];
new_enemy.respawn_delay = game_v1.game_npcs[i].respawn_delay;
new_enemy.shield_type = game_v1.game_npcs[i].shield_type;
new_enemy.speed = game_v1.game_npcs[i].speed;
for (int j=0; j<V1_ANIM_TYPE_COUNT; j++) {
for (int k=0; k<V1_ANIM_FRAMES_COUNT; k++) {
new_enemy.sprites[j][k].colision_rect = convert_rectangle(game_v1.game_npcs[i].sprites[j][k].colision_rect);
new_enemy.sprites[j][k].duration = game_v1.game_npcs[i].sprites[j][k].duration;
new_enemy.sprites[j][k].sprite_graphic_pos_x = game_v1.game_npcs[i].sprites[j][k].sprite_graphic_pos_x;
new_enemy.sprites[j][k].used = game_v1.game_npcs[i].sprites[j][k].used;
}
}
new_enemy.sprites_pos_bg.x = game_v1.game_npcs[i].sprites_pos_bg.x;
new_enemy.sprites_pos_bg.y = game_v1.game_npcs[i].sprites_pos_bg.y;
new_enemy.start_point.x = game_v1.game_npcs[i].start_point.x;
new_enemy.start_point.y = game_v1.game_npcs[i].start_point.y;
new_enemy.walk_range = game_v1.game_npcs[i].walk_range;
for (int j=0; j<V1_FS_NPC_WEAKNESSES; j++) {
new_enemy.weakness[j].damage_multiplier = game_v1.game_npcs[i].weakness[j].damage_multiplier;
new_enemy.weakness[j].weapon_id = game_v1.game_npcs[i].weakness[j].weapon_id;
}
enemy_list.push_back(new_enemy);
// store the old npc position and the new one into a list so we can use in map-npcs
//std::cout << "old-id: " << i << ", new-id: " << (enemy_list.size()-1) << std::endl;
npc_id_list.insert(std::pair<int, int>(i, (enemy_list.size()-1)));
}
}
void convert_game_objects(v1_file_game& game_v1) {
for (int i=0; i<V1_FS_GAME_MAX_NPCS; i++) {
std::string name(game_v1.objects[i].name);
if (name.length() < 1 || name == "Object") {
continue;
}
CURRENT_FILE_FORMAT::file_object new_object;
new_object.animation_auto_start = game_v1.objects[i].animation_auto_start;
new_object.animation_loop = game_v1.objects[i].animation_loop;
new_object.animation_reverse = game_v1.objects[i].animation_reverse;
new_object.direction = game_v1.objects[i].direction;
new_object.distance = game_v1.objects[i].distance;
new_object.frame_duration = game_v1.objects[i].frame_duration;
sprintf(new_object.graphic_filename, "%s", game_v1.objects[i].graphic_filename);
new_object.limit = game_v1.objects[i].limit;
sprintf(new_object.name, "%s", game_v1.objects[i].name);
new_object.size.width = game_v1.objects[i].size.width;
new_object.size.height = game_v1.objects[i].size.height;
new_object.speed = game_v1.objects[i].speed;
new_object.timer = game_v1.objects[i].timer;
new_object.type = game_v1.objects[i].type;
object_list.push_back(new_object);
}
}
void convert_projectiles(v1_file_game& game_v1) {
for (int i=0; i<V1_FS_MAX_PROJECTILES; i++) {
CURRENT_FILE_FORMAT::file_projectile new_projectile;
new_projectile.can_be_reflected = game_v1.projectiles[i].can_be_reflected;
new_projectile.damage = game_v1.projectiles[i].damage;
sprintf(new_projectile.graphic_filename, "%s", game_v1.projectiles[i].graphic_filename);
new_projectile.hp = game_v1.projectiles[i].hp;
new_projectile.is_destructible = game_v1.projectiles[i].is_destructible;
new_projectile.max_shots = game_v1.projectiles[i].max_shots;
sprintf(new_projectile.name, "%s", game_v1.projectiles[i].name);
sprintf(new_projectile.sfx_filename, "%s", game_v1.projectiles[i].sfx_filename);
new_projectile.size.width = game_v1.projectiles[i].size.width;
new_projectile.size.height = game_v1.projectiles[i].size.height;
new_projectile.spawn_npc_id = game_v1.projectiles[i].spawn_npc_id;
new_projectile.spawn_npc_n = game_v1.projectiles[i].spawn_npc_n;
new_projectile.speed = game_v1.projectiles[i].speed;
new_projectile.trajectory = (int)game_v1.projectiles[i].trajectory;
projectile_list.push_back(new_projectile);
}
}
void convert_game_players(v1_file_game& game_v1) {
std::vector<CURRENT_FILE_FORMAT::file_player> res;
for (int j=0; j<FS_MAX_PLAYERS; j++) {
CURRENT_FILE_FORMAT::file_player temp;
temp.can_air_dash = game_v1.players[j].can_air_dash;
temp.can_charge_shot = game_v1.players[j].can_charge_shot;
temp.can_double_jump = game_v1.players[j].can_double_jump;
temp.can_slide = game_v1.players[j].can_slide;
temp.damage_modifier = game_v1.players[j].damage_modifier;
sprintf(temp.face_filename, "%s", game_v1.players[j].face_filename);
temp.full_charged_projectile_id = game_v1.players[j].full_charged_projectile_id;
sprintf(temp.graphic_filename, "%s", game_v1.players[j].graphic_filename);
temp.have_shield = game_v1.players[j].have_shield;
temp.HP = game_v1.players[j].HP;
temp.max_shots = game_v1.players[j].max_shots;
sprintf(temp.name, "%s", game_v1.players[j].name);
temp.simultaneous_shots = game_v1.players[j].simultaneous_shots;
for (int k=0; k<V1_ANIM_TYPE_COUNT; k++) {
for (int l=0; l<V1_ANIM_FRAMES_COUNT; l++) {
temp.sprites[k][l].colision_rect = convert_rectangle(game_v1.players[j].sprites[k][l].colision_rect);
temp.sprites[k][l].duration = game_v1.players[j].sprites[k][l].duration;
temp.sprites[k][l].sprite_graphic_pos_x = game_v1.players[j].sprites[k][l].sprite_graphic_pos_x;
temp.sprites[k][l].used = game_v1.players[j].sprites[k][l].used;
}
}
temp.sprite_hit_area = convert_rectangle(game_v1.players[j].sprite_hit_area);
temp.sprite_size.width = game_v1.players[j].sprite_size.width;
temp.sprite_size.height = game_v1.players[j].sprite_size.height;
for (int k=0; k<V1_MAX_WEAPON_N; k++) {
temp.weapon_colors[k].color1 = convert_color(game_v1.players[j].weapon_colors[k].color1);
temp.weapon_colors[k].color2 = convert_color(game_v1.players[j].weapon_colors[k].color2);
temp.weapon_colors[k].color3 = convert_color(game_v1.players[j].weapon_colors[k].color3);
}
res.push_back(temp);
}
fio_cmm.save_data_to_disk<CURRENT_FILE_FORMAT::file_player>("player_list.dat", res);
}
void convert_game(v1_file_game& game_v1) {
for (int i=0; i<V1_FS_PLAYER_ARMOR_PIECES_MAX; i++) {
for (int j=0; j<FS_MAX_PLAYERS; j++) {
for (int k=0; k<FS_DIALOG_LINES; k++) {
std::string line = std::string(game_v1.armor_pieces[i].got_message[j][k]);
if (line.length() > 0) {
common_strings.push_back(line);
game_data.armor_pieces[i].got_message[j][k] = common_strings.size()-1;
} else {
game_data.armor_pieces[i].got_message[j][k] = -1;
}
}
}
for (int j=0; j<FS_MAX_PLAYERS; j++) {
game_data.armor_pieces[i].special_ability[j] = game_v1.armor_pieces[i].special_ability[j];
}
}
/// @TODO - add old hardcoded attacks like hadouken
sprintf(game_data.name, "%s", game_v1.name);
for (int k=0; k<V1_FS_PLATER_ITEMS_N; k++) {
game_data.player_items[k] = game_v1.player_items[k];
}
game_data.semi_charged_projectile_id = game_v1.semi_charged_projectile_id;
for (int k=0; k<V1_MAX_STAGES; k++) {
sprintf(game_data.stage_face_filename[k], "%s", game_v1.stage_face_filename[k]);
}
for (int k=0; k<V1_TROPHIES_MAX; k++) {
game_data.trophies[k].condition = game_v1.trophies[k].condition;
sprintf(game_data.trophies[k].filename, "%s", game_v1.trophies[k].filename);
sprintf(game_data.trophies[k].name, "%s", game_v1.trophies[k].name);
}
game_data.version = game_v1.version;
for (int k=0; k<V1_FS_MAX_WEAPONS; k++) {
game_data.weapons[k].damage = game_v1.weapons[k].damage;
game_data.weapons[k].id_projectile = game_v1.weapons[k].id_projectile;
sprintf(game_data.weapons[k].name, "%s", game_v1.weapons[k].name);
}
convert_ai_types(game_v1);
convert_game_npcs(game_v1);
convert_game_objects(game_v1);
convert_projectiles(game_v1);
convert_game_players(game_v1);
}
void set_rockbot1_hardcoded() {
/// @TODO: set the hardcoded parts:
// ROCKBOT 1 HARDCODED PARTS //
game_data.game_style = 0;
sprintf(game_data.stages_face_name[0], "%s", "INTRO");
sprintf(game_data.stages_face_name[1], "%s", "APE");
sprintf(game_data.stages_face_name[2], "%s", "DAISIE");
sprintf(game_data.stages_face_name[3], "%s", "SEAHORSE");
sprintf(game_data.stages_face_name[4], "%s", "MUMMY");
sprintf(game_data.stages_face_name[5], "%s", "MAGE");
sprintf(game_data.stages_face_name[6], "%s", "DYNAMITE");
sprintf(game_data.stages_face_name[7], "%s", "SPIKE");
sprintf(game_data.stages_face_name[8], "%s", "TECHNO");
sprintf(game_data.stages_face_name[9], "%s", "CASTLE");
/// music (boss battle, final boss, game_over, got_weapon)
sprintf(game_data.boss_music_filename, "%s", "boss_battle.mod");
sprintf(game_data.final_boss_music_filename, "%s", "final_boss.mod");
sprintf(game_data.got_weapon_music_filename, "%s", "got_weapon.mod");
sprintf(game_data.game_over_music_filename, "%s", "OTHER.xm");
sprintf(game_data.stage_select_music_filename, "%s", "menu.mod");
sprintf(game_data.game_start_screen_music_filename, "%s", "opening.mod");
/// projectiles (see doc code-changes)
/// armor-pieces weapon powers
/// anim tiles
}
int main(int argc, char *argv[])
{
std::string EXEC_NAME("conversor");
#ifndef WIN32
EXEC_NAME = "conversor";
#else
EXEC_NAME = "conversor.exe";
#endif
std::string argvString = std::string(argv[0]);
GAMEPATH = argvString.substr(0, argvString.size()-EXEC_NAME.size());
FILEPATH = GAMEPATH;
GAMENAME = "Rockbot1";
fio_v1 fv1;
v1_file_game game_v1;
fv1.read_game(game_v1);
v1_file_stages stages_v1;
fv1.read_all_stages(stages_v1);
convert_game(game_v1);
convert_stages_and_maps(stages_v1);
set_rockbot1_hardcoded();
FILEPATH += "/out/";
fio.write_all_stages(stage_data);
fio.write_all_maps(maps_data);
fio.write_game(game_data);
fio_cmm.save_data_to_disk<CURRENT_FILE_FORMAT::file_npc>("game_enemy_list.dat", enemy_list);
fio_cmm.save_data_to_disk<CURRENT_FILE_FORMAT::file_object>("game_object_list.dat", object_list);
fio_cmm.save_data_to_disk<CURRENT_FILE_FORMAT::file_artificial_inteligence>("game_ai_list.dat", ai_list);
fio_cmm.save_data_to_disk<CURRENT_FILE_FORMAT::file_projectile>("game_projectile_list.dat", projectile_list);
CURRENT_FILE_FORMAT::fio_strings fio_str;
fio_str.save_common_strings(common_strings);
return 1;
}
| 43.415534 | 124 | 0.65562 | pdpdds |
77776bafa6cffa8f633bd3ea17301651d423b3c1 | 3,711 | cpp | C++ | tests/LFOT.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 281 | 2019-06-06T05:58:59.000Z | 2022-03-06T12:20:09.000Z | tests/LFOT.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 590 | 2019-09-22T00:26:10.000Z | 2022-03-31T19:21:58.000Z | tests/LFOT.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 44 | 2019-10-08T08:24:20.000Z | 2022-02-26T04:21:44.000Z | // SPDX-License-Identifier: BSD-2-Clause
// This code is part of the sfizz library and is licensed under a BSD 2-clause
// license. You should have receive a LICENSE.md file along with the code.
// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz
#include "DataHelpers.h"
#include "sfizz/Synth.h"
#include "sfizz/LFO.h"
#include "sfizz/Region.h"
#include "catch2/catch.hpp"
static bool computeLFO(DataPoints& dp, const fs::path& sfzPath, double sampleRate, size_t numFrames)
{
sfz::Synth synth;
sfz::Resources& resources = synth.getResources();
if (!synth.loadSfzFile(sfzPath))
return false;
if (synth.getNumRegions() != 1)
return false;
size_t bufferSize = static_cast<size_t>(synth.getSamplesPerBlock());
const std::vector<sfz::LFODescription>& desc = synth.getRegionView(0)->lfos;
size_t numLfos = desc.size();
std::vector<std::unique_ptr<sfz::LFO>> lfos(numLfos);
for (size_t l = 0; l < numLfos; ++l) {
sfz::LFO* lfo = new sfz::LFO(resources);
lfos[l].reset(lfo);
lfo->setSampleRate(sampleRate);
lfo->configure(&desc[l]);
}
std::vector<float> outputMemory(numLfos * numFrames);
for (size_t l = 0; l < numLfos; ++l) {
lfos[l]->start(0);
}
std::vector<absl::Span<float>> lfoOutputs(numLfos);
for (size_t l = 0; l < numLfos; ++l) {
lfoOutputs[l] = absl::MakeSpan(&outputMemory[l * numFrames], numFrames);
for (size_t i = 0, currentFrames; i < numFrames; i += currentFrames) {
currentFrames = std::min(numFrames - i, bufferSize);
lfos[l]->process(lfoOutputs[l].subspan(i, currentFrames));
}
}
dp.rows = numFrames;
dp.cols = numLfos + 1;
dp.data.reset(new float[dp.rows * dp.cols]);
for (size_t i = 0; i < numFrames; ++i) {
dp(i, 0) = i / sampleRate;
for (size_t l = 0; l < numLfos; ++l)
dp(i, 1 + l) = lfoOutputs[l][i];
}
return true;
}
double meanSquareError(const float* a, const float* b, size_t count, size_t step)
{
double sum = 0;
for (size_t i = 0; i < count; ++i) {
double diff = a[i * step] - b[i * step];
sum += diff * diff;
}
return sum / count;
}
static constexpr double mseThreshold = 1e-3;
TEST_CASE("[LFO] Waves")
{
DataPoints ref;
REQUIRE(load_txt_file(ref, "tests/lfo/lfo_waves_reference.dat"));
DataPoints cur;
REQUIRE(computeLFO(cur, "tests/lfo/lfo_waves.sfz", 100.0, ref.rows));
REQUIRE(ref.rows == cur.rows);
REQUIRE(ref.cols == cur.cols);
for (size_t l = 1; l < cur.cols; ++l) {
double mse = meanSquareError(&ref.data[l], &cur.data[l], ref.rows, ref.cols);
REQUIRE(mse < mseThreshold);
}
}
TEST_CASE("[LFO] Subwave")
{
DataPoints ref;
REQUIRE(load_txt_file(ref, "tests/lfo/lfo_subwave_reference.dat"));
DataPoints cur;
REQUIRE(computeLFO(cur, "tests/lfo/lfo_subwave.sfz", 100.0, ref.rows));
REQUIRE(ref.rows == cur.rows);
REQUIRE(ref.cols == cur.cols);
for (size_t l = 1; l < cur.cols; ++l) {
double mse = meanSquareError(&ref.data[l], &cur.data[l], ref.rows, ref.cols);
REQUIRE(mse < mseThreshold);
}
}
TEST_CASE("[LFO] Fade and delay")
{
DataPoints ref;
REQUIRE(load_txt_file(ref, "tests/lfo/lfo_fade_and_delay_reference.dat"));
DataPoints cur;
REQUIRE(computeLFO(cur, "tests/lfo/lfo_fade_and_delay.sfz", 100.0, ref.rows));
REQUIRE(ref.rows == cur.rows);
REQUIRE(ref.cols == cur.cols);
for (size_t l = 1; l < cur.cols; ++l) {
double mse = meanSquareError(&ref.data[l], &cur.data[l], ref.rows, ref.cols);
REQUIRE(mse < mseThreshold);
}
}
| 29.220472 | 100 | 0.619779 | michaelwillis |
7780fac57c339cfe9c2e9c1f0b3dc94ee2e3c2d8 | 5,515 | cpp | C++ | Source/Framework/Utility/Utility/TeUUID.cpp | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 57 | 2019-09-02T01:10:37.000Z | 2022-01-11T06:28:10.000Z | Source/Framework/Utility/Utility/TeUUID.cpp | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | null | null | null | Source/Framework/Utility/Utility/TeUUID.cpp | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 6 | 2020-02-29T17:19:30.000Z | 2021-10-30T04:29:22.000Z | #include "Utility/TeUUID.h"
#include "Utility/TePlatformUtility.h"
namespace
{
constexpr const char HEX_TO_LITERAL[16] =
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
constexpr const te::UINT8 LITERAL_TO_HEX[256] =
{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
// 0 through 9 translate to 0 though 9
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
// A through F translate to 10 though 15
0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
// a through f translate to 10 though 15
0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
}
namespace te
{
UUID UUID::EMPTY;
UUID::UUID(const String& uuid)
{
memset(_data, 0, sizeof(_data));
if (uuid.size() < 36)
return;
UINT32 idx = 0;
// First group: 8 digits
for (INT32 i = 7; i >= 0; --i)
{
char charVal = uuid[idx++];
UINT8 hexVal = LITERAL_TO_HEX[(int)charVal];
_data[0] |= hexVal << (i * 4);
}
idx++;
// Second group: 4 digits
for (INT32 i = 7; i >= 4; --i)
{
char charVal = uuid[idx++];
UINT8 hexVal = LITERAL_TO_HEX[(int)charVal];
_data[1] |= hexVal << (i * 4);
}
idx++;
// Third group: 4 digits
for (INT32 i = 3; i >= 0; --i)
{
char charVal = uuid[idx++];
UINT8 hexVal = LITERAL_TO_HEX[(int)charVal];
_data[1] |= hexVal << (i * 4);
}
idx++;
// Fourth group: 4 digits
for (INT32 i = 7; i >= 4; --i)
{
char charVal = uuid[idx++];
UINT8 hexVal = LITERAL_TO_HEX[(int)charVal];
_data[2] |= hexVal << (i * 4);
}
idx++;
// Fifth group: 12 digits
for (INT32 i = 3; i >= 0; --i)
{
char charVal = uuid[idx++];
UINT8 hexVal = LITERAL_TO_HEX[(int)charVal];
_data[2] |= hexVal << (i * 4);
}
for (INT32 i = 7; i >= 0; --i)
{
char charVal = uuid[idx++];
UINT8 hexVal = LITERAL_TO_HEX[(int)charVal];
_data[3] |= hexVal << (i * 4);
}
}
String UUID::ToString() const
{
UINT8 output[36];
UINT32 idx = 0;
// First group: 8 digits
for (INT32 i = 7; i >= 0; --i)
{
UINT32 hexVal = (_data[0] >> (i * 4)) & 0xF;
output[idx++] = HEX_TO_LITERAL[hexVal];
}
output[idx++] = '-';
// Second group: 4 digits
for (INT32 i = 7; i >= 4; --i)
{
UINT32 hexVal = (_data[1] >> (i * 4)) & 0xF;
output[idx++] = HEX_TO_LITERAL[hexVal];
}
output[idx++] = '-';
// Third group: 4 digits
for (INT32 i = 3; i >= 0; --i)
{
UINT32 hexVal = (_data[1] >> (i * 4)) & 0xF;
output[idx++] = HEX_TO_LITERAL[hexVal];
}
output[idx++] = '-';
// Fourth group: 4 digits
for (INT32 i = 7; i >= 4; --i)
{
UINT32 hexVal = (_data[2] >> (i * 4)) & 0xF;
output[idx++] = HEX_TO_LITERAL[hexVal];
}
output[idx++] = '-';
// Fifth group: 12 digits
for (INT32 i = 3; i >= 0; --i)
{
UINT32 hexVal = (_data[2] >> (i * 4)) & 0xF;
output[idx++] = HEX_TO_LITERAL[hexVal];
}
for (INT32 i = 7; i >= 0; --i)
{
UINT32 hexVal = (_data[3] >> (i * 4)) & 0xF;
output[idx++] = HEX_TO_LITERAL[hexVal];
}
return String((const char*)output, 36);
}
UUID UUIDGenerator::GenerateRandom()
{
return PlatformUtility::GenerateUUID();
}
} | 32.827381 | 118 | 0.470172 | GameDevery |
778e88fb99be6de595b832ff5ded79063eef0573 | 450 | hpp | C++ | include/cslibs_indexed_storage/backend/array/array_options.hpp | doge-of-the-day/cslibs_indexed_storage | 044a5e60cc1a1c0ac41631b1e6c0a79db7aa4c84 | [
"BSD-3-Clause"
] | null | null | null | include/cslibs_indexed_storage/backend/array/array_options.hpp | doge-of-the-day/cslibs_indexed_storage | 044a5e60cc1a1c0ac41631b1e6c0a79db7aa4c84 | [
"BSD-3-Clause"
] | null | null | null | include/cslibs_indexed_storage/backend/array/array_options.hpp | doge-of-the-day/cslibs_indexed_storage | 044a5e60cc1a1c0ac41631b1e6c0a79db7aa4c84 | [
"BSD-3-Clause"
] | 2 | 2019-08-05T07:13:19.000Z | 2021-02-22T16:39:11.000Z | #pragma once
#include <cslibs_indexed_storage/utility/options.hpp>
namespace cslibs_indexed_storage {
namespace option {
namespace tags
{
struct array_size {};
struct array_offset {};
}
template<std::size_t... sizes>
struct array_size : define_value_option<tags::array_size, std::size_t, sizes...> {};
template<typename offset_t, offset_t... offsets>
struct array_offset : define_value_option<tags::array_offset, offset_t, offsets...> {};
}
}
| 19.565217 | 87 | 0.757778 | doge-of-the-day |
778f96d165cc63c8ffabcb660677e280a20fbda6 | 499 | cpp | C++ | smallest.cpp | hskhakh81/cpp | f43f10e8b4e505e3a07a87e4e717b97c72788a8f | [
"Apache-2.0"
] | null | null | null | smallest.cpp | hskhakh81/cpp | f43f10e8b4e505e3a07a87e4e717b97c72788a8f | [
"Apache-2.0"
] | null | null | null | smallest.cpp | hskhakh81/cpp | f43f10e8b4e505e3a07a87e4e717b97c72788a8f | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int a,b,c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
cout << "Smallest number is ";
if (a < b ) {
//a is less than b
if (a < c) {
//a is less than both b and c
cout << a << endl;
} else {
cout << c << endl;
}
} else if (b < c) {
cout << b << endl;
} else {
cout << c << endl;
}
getchar();
return 0;
}
| 15.59375 | 42 | 0.396794 | hskhakh81 |
779168e78d7cd3a75bffafe6539f02369c33edfa | 1,909 | hpp | C++ | include/Util/Tween.hpp | FoxelCode/Barkanoid | 3e582cbfb4bf13aa522d344489c8b0bac77fa8c5 | [
"Unlicense"
] | null | null | null | include/Util/Tween.hpp | FoxelCode/Barkanoid | 3e582cbfb4bf13aa522d344489c8b0bac77fa8c5 | [
"Unlicense"
] | null | null | null | include/Util/Tween.hpp | FoxelCode/Barkanoid | 3e582cbfb4bf13aa522d344489c8b0bac77fa8c5 | [
"Unlicense"
] | null | null | null | #pragma once
#include <functional>
#include <vector>
#include "Ease.hpp"
class Tween
{
public:
typedef std::function<void(float)> TweenUpdate;
typedef std::function<void()> TweenComplete;
enum Type
{
OneShot,
Boomerang
};
struct TweenInstance
{
TweenInstance(Ease::Type type, float start, float end, float duration,TweenUpdate update,
TweenComplete complete = nullptr, Type tweenType = Type::OneShot, float delay = 0.0f)
: easeType(type), start(start), change(end - start), time(0.0f), delay(delay),
duration(duration), done(false), update(update), complete(complete), tweenType(tweenType), persist(false) {}
void Reset()
{
time = 0.0f;
done = false;
}
void Finish()
{
time = duration;
done = true;
}
Ease::Type easeType;
Type tweenType;
float start;
float change;
float time;
float delay;
float duration;
bool done;
TweenUpdate update;
TweenComplete complete;
bool persist;
};
/// <summary>
/// <para>Creates a TweenInstance with the given parameters and runs it.</para>
/// </summary>
/// <param name="type">Easing function to use.</param>
/// <param name="update">Function to run every frame the tween is updated.</param>
/// <param name="complete">Function to run when the tween is complete.</param>
/// <param name="delay">Time (in seconds) to wait before running the tween.</param>
static void Start(Ease::Type type, float start, float end, float duration, TweenUpdate update,
TweenComplete complete = nullptr, Type tweenType = Type::OneShot, float delay = 0.0f);
/// <summary>
/// <para>Runs an existing TweenInstance.</para>
/// </summary>
static void Run(TweenInstance* tween);
static void UpdateTweens(float delta);
static void StopAll();
static void RemoveTween(TweenInstance* tween);
private:
static void UpdateTween(TweenInstance& tween, float delta);
static std::vector<TweenInstance*> tweens;
}; | 26.150685 | 111 | 0.701414 | FoxelCode |
7793741c5e572186e66db4decf7bc22fbcb56148 | 744 | hpp | C++ | src/backup.hpp | awilk003/assignment-02 | b9423385959296790a4de864c1c314d9abdf431f | [
"BSD-3-Clause"
] | 1 | 2017-02-23T05:55:41.000Z | 2017-02-23T05:55:41.000Z | src/backup.hpp | awilk003/assignment-02 | b9423385959296790a4de864c1c314d9abdf431f | [
"BSD-3-Clause"
] | null | null | null | src/backup.hpp | awilk003/assignment-02 | b9423385959296790a4de864c1c314d9abdf431f | [
"BSD-3-Clause"
] | null | null | null | #ifndef _BACKUP_H_
#define _BACKUP_H_
#include "cmdline.hpp"
#include "in.hpp"
class Backup
{
public:
Backup();
Backup(const string &filename);
bool execute(const vector<string> &lhs, const vector<string> &rhs, int (& currFD)[2]);
string checkSymbol(vector<string> input, string& path);
//virtual bool isValid() = 0;
};
class mPipe : public Backup
{
public:
mPipe();
mPipe(string Input);
bool execute(const vector<string> &lhs, const vector<string> &rhs, int (& currFD)[2]);
bool reExecute(const vector<string> &lhs, const vector<string> &rhs, int (& currFD)[2]);
bool finalExecute(const vector<string> &lhs, const vector<string> &rhs, int (& currFD)[2]);
void remove();
private:
string otherPath;
};
#endif
| 17.714286 | 93 | 0.68414 | awilk003 |
7798d6f5ac29752e357acd8f06b49568e12da74f | 540 | cpp | C++ | Aggregation Composition Assignment Question/MotherBoard.cpp | asharbinkhalil/OOP | d9a5fe5233ae3fcc631f00390b53a47da99989e3 | [
"MIT"
] | null | null | null | Aggregation Composition Assignment Question/MotherBoard.cpp | asharbinkhalil/OOP | d9a5fe5233ae3fcc631f00390b53a47da99989e3 | [
"MIT"
] | null | null | null | Aggregation Composition Assignment Question/MotherBoard.cpp | asharbinkhalil/OOP | d9a5fe5233ae3fcc631f00390b53a47da99989e3 | [
"MIT"
] | null | null | null | /*
* MotherBoard.cpp
*
* Created on: Nov 29, 2021
* Author: asharbinkhalil
*/
#include "MotherBoard.h"
MotherBoard::MotherBoard()
{
ports=NULL;
mm= NULL;
}
MotherBoard::MotherBoard(Port *portt, MainMemory *mmm)
{
this->mm=mmm;
ports = new Port[100];
this->ports =portt;
}
Port*& MotherBoard::getPorts()
{
return ports;
}
void MotherBoard::setPorts( Port *port)
{
this->ports=port;
}
MainMemory*& MotherBoard::getMm(){
return mm;
}
void MotherBoard::setMm( MainMemory *&mm) {
this->mm = mm;
}
| 14.594595 | 56 | 0.633333 | asharbinkhalil |
7799ef317865f1290846f2f9d9a0e638caee193b | 3,945 | cpp | C++ | apps/barologger.cpp | freepax/rpi-device-lib | e38bf0481bb96e9dfa9847cc9e1122624f8cc15e | [
"MIT"
] | null | null | null | apps/barologger.cpp | freepax/rpi-device-lib | e38bf0481bb96e9dfa9847cc9e1122624f8cc15e | [
"MIT"
] | null | null | null | apps/barologger.cpp | freepax/rpi-device-lib | e38bf0481bb96e9dfa9847cc9e1122624f8cc15e | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <bmp180.h>
static const int samples = 1;
static const int fileNameSize = 20;
unsigned char oss_mode = ModeOss3;
/// create file name string from date and time
int fileNameString(char *buffer)
{
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime (&rawtime);
memset(buffer, 0, fileNameSize);
int size = sprintf((char*)buffer, "%04d-%02d-%02d-%02d-baro.log", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour);
if (size < 0) {
std::cerr << __func__ << ":" << __LINE__ << "snprintf failed (" << size << ")" << std::endl;
return -1;
}
return size;
}
/// create file name string from date and time
int logTimeString(char *buffer)
{
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime (&rawtime);
memset(buffer, 0, fileNameSize);
int size = sprintf((char*)buffer, "%04d-%02d-%02d %02d:%02d:%02d", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
if (size < 0) {
std::cerr << __func__ << ":" << __LINE__ << "snprintf failed (" << size << ")" << std::endl;
return -1;
}
return size;
}
int openFile()
{
char filename[fileNameSize];
if (fileNameString(filename) < 0) {
std::cerr << __func__ << ":" << __LINE__ << " fileNameString failed" << std::endl;
return 0;
}
int fd = open(filename, O_CREAT | O_APPEND | O_WRONLY);
if (fd < 0)
std::cerr << __func__ << ":" << __LINE__ << " open failed" << std::endl;
return fd;
}
int main(int argc, char **argv)
{
/// create bmp180 instance - set device to "/dev/i2c-1"
Bmp180 bmp180((char*)FirmwareI2CDeviceses::i2c_1);
/// open device (this will also read calibration data)
if (bmp180.openDevice() < 0) {
std::cerr << __func__ << ":" << __LINE__ << " openDevice failed" << std::endl;
return -1;
}
/// read chip ID (should be 0x55)
int id = bmp180.readChipId();
if (id < 0) {
std::cerr << __func__ << ":" << __LINE__ << " readChipId failed" << std::endl;
return -2;
}
std::cout << "Chip ID 0x" << std::hex << id << std::dec << std::endl;
/// read temperature and pressure 10 times
while (1) {
float temperature = 0.0;
/// temperature...
if (bmp180.readTemperature(&temperature) < 0) {
std::cerr << __func__ << ":" << __LINE__ << " readTemperature failed" << std::endl;
return -1;
}
long pressure = 0.0;
/// pressure...
if (bmp180.readPressure(&pressure, oss_mode, 1, true) < 0) {
std::cerr << __func__ << ":" << __LINE__ << " readPressure failed" << std::endl;
return 0;
}
char buf[80];
memset(buf, 0, 80);
int size = logTimeString(buf);
if (size < 0) {
std::cerr << __func__ << ":" << __LINE__ << " logTimeString failed" << std::endl;
return 0;
}
size += sprintf(buf+size, " %3.1f %ld\n", temperature, pressure);
//printf("time string %s\n", buf);
int fd = openFile();
if (fd < 0) {
std::cerr << __func__ << ":" << __LINE__ << " openFile failed" << std::endl;
return 0;
}
if (write(fd, buf, size) != size) {
std::cerr << __func__ << ":" << __LINE__ << " write failed" << std::endl;
close(fd);
return 0;
}
close(fd);
/// sleep for one minute
sleep(60);
}
if (bmp180.closeDevice() < 0) {
std::cerr << __func__ << ":" << __LINE__ << " closeDevice failed" << std::endl;
return 0;
}
return 0;
}
| 26.3 | 193 | 0.54398 | freepax |
779a7afc3f0d526d53f1b9c77f29a74d8b63d139 | 2,478 | cpp | C++ | src/chessAI.cpp | ReaLNeroM/Chess-Engine | 66e0f69dd8b9d64f78c270cce2bb0c26a57d1609 | [
"MIT"
] | null | null | null | src/chessAI.cpp | ReaLNeroM/Chess-Engine | 66e0f69dd8b9d64f78c270cce2bb0c26a57d1609 | [
"MIT"
] | null | null | null | src/chessAI.cpp | ReaLNeroM/Chess-Engine | 66e0f69dd8b9d64f78c270cce2bb0c26a57d1609 | [
"MIT"
] | null | null | null | #include "chessAI.h"
#include <ctime>
namespace AI {
const double INF = 1e9;
double checkWin(){
bool check = GameHandler::isKingAttacked(BoardStructure::currMoveColor);
bool movesLeft = GameHandler::movePossible(BoardStructure::currMoveColor, check);
if(check and !movesLeft){
return -INF;
} else if(!movesLeft){
return INF/2.0;
}
return 0;
}
std::pair<sf::Vector2i, sf::Vector2i> bestFirstAction;
double dfs(int movesLeft, double alpha, double beta){
double checkValue = checkWin();
if(checkValue != 0.0){
return checkValue;
}
double value = BoardStructure::getBoardValue();
if(movesLeft == Magic::propagationLimit){
return value;
}
double bestAction = -2.0*INF;
for(int i = 0; i < Magic::boardSize; i++){
for(int j = 0; j < Magic::boardSize; j++){
if(!BoardStructure::board[i][j].checkDestroyed() and
BoardStructure::board[i][j].getColor() == BoardStructure::currMoveColor){
sf::Vector2i startPos = sf::Vector2i(j, i);
for(int k = 0; k < Magic::boardSize; k++){
for(int l = 0; l < Magic::boardSize; l++){
sf::Vector2i newPos = sf::Vector2i(l, k);
if(Helper::withinBounds(newPos) and startPos != newPos and (BoardStructure::board[newPos.y][newPos.x].checkDestroyed() or
BoardStructure::board[newPos.y][newPos.x].getColor() != BoardStructure::currMoveColor)){
if(GameHandler::validatePieceMove(startPos, newPos, BoardStructure::board[startPos.y][startPos.x], false) and
GameHandler::attemptMove(BoardStructure::board[startPos.y][startPos.x], newPos, false)){
auto response = dfs(movesLeft + 1, alpha, beta);
response *= -1;
if(response > bestAction){
bestAction = response;
if(movesLeft == 0){
bestFirstAction = {startPos, newPos};
}
}
BoardStructure::undoMove();
if(BoardStructure::currMoveColor == Magic::color::white){
alpha = std::max(alpha, response);
} else {
beta = std::min(beta, -response);
}
if(alpha >= beta){
i = j = k = l = Magic::boardSize;
}
}
}
}
}
}
}
}
return bestAction;
}
std::pair<sf::Vector2i, sf::Vector2i> getBestMove(){
bestFirstAction = {{-1, -1}, {-1, -1}};
if(BoardStructure::currMoveColor == Magic::playerColor){
return bestFirstAction;
}
dfs(0, -INF, INF);
return bestFirstAction;
}
}
| 27.533333 | 128 | 0.608555 | ReaLNeroM |
779c2d1f078a8625d18e620577a22388f4fcd7d0 | 780 | cpp | C++ | letter_pyramid.cpp | saurabhkakade21/Cpp-Practice-Code | ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60 | [
"MIT"
] | null | null | null | letter_pyramid.cpp | saurabhkakade21/Cpp-Practice-Code | ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60 | [
"MIT"
] | null | null | null | letter_pyramid.cpp | saurabhkakade21/Cpp-Practice-Code | ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
system("clear");
cout << "Enter the string for letter pyramid: ";
string input_string {};
getline(cin,input_string);
size_t length = input_string.length();
for(size_t i=0; i < length; i++)
{
cout << " ";
for(size_t j = 0;j < length-i;j++)
{
cout << " ";
}
string str = input_string.substr(0,i+1);
reverse(str.begin(), str.end());
cout << input_string.substr(0,i+1) + str.substr(1,str.length()-1);
for(size_t j = 0;j < i+1;j++)
{
cout << " ";
}
cout << endl;
}
return 0;
} | 19.02439 | 74 | 0.478205 | saurabhkakade21 |
77a0ec555011909ee9c5d5bd2557f02bd81c29d7 | 3,950 | cpp | C++ | src/inspector/InspectorDBusInterface.cpp | azubieta/AppImageService | 103e1ef79f23f59a3e2bb54afbd4eac79d1023fa | [
"MIT"
] | 3 | 2019-07-30T17:31:06.000Z | 2019-12-15T01:58:01.000Z | src/inspector/InspectorDBusInterface.cpp | azubieta/AppImageService | 103e1ef79f23f59a3e2bb54afbd4eac79d1023fa | [
"MIT"
] | null | null | null | src/inspector/InspectorDBusInterface.cpp | azubieta/AppImageService | 103e1ef79f23f59a3e2bb54afbd4eac79d1023fa | [
"MIT"
] | 1 | 2019-08-04T22:42:02.000Z | 2019-08-04T22:42:02.000Z | // system
#include <sstream>
// libraries
#include <appimage/appimage++.h>
#include <appimage/utils/ResourcesExtractor.h>
#include <XdgUtils/DesktopEntry/DesktopEntry.h>
// local
#include "utils.h"
#include "InspectorDBusInterface.h"
// generated by `qt5_add_dbus_adaptor` cmake function
#include "inspectoradaptor.h"
InspectorDBusInterface::InspectorDBusInterface(QObject* parent) : QObject(parent) {
new InspectorAdaptor(this);
QDBusConnection dbus = QDBusConnection::sessionBus();
bool operationSucceed;
operationSucceed = dbus.registerObject(INSPECTOR_DBUS_OBJECT_PATH, this);
if (!operationSucceed)
qCritical() << "Unable to register d-bus object: " << INSPECTOR_DBUS_OBJECT_PATH;
operationSucceed = dbus.registerService(INSPECTOR_DBUS_INTERFACE_NAME);
if (!operationSucceed)
qCritical() << "Unable to register d-bus service: " << INSPECTOR_DBUS_INTERFACE_NAME;
}
QStringList InspectorDBusInterface::listContents(const QString& appImagePath) {
QStringList files;
try {
QString path = removeUriProtocolFromPath(appImagePath);
appimage::core::AppImage appImage(path.toStdString());
for (const auto& entry: appImage.files())
files << QString::fromStdString(entry);
} catch (const appimage::core::AppImageError& error) {
qWarning() << "Unable to list AppImage contents: " << appImagePath;
}
return files;
}
QString InspectorDBusInterface::getApplicationInfo(QString appImagePath) {
try {
QString path = removeUriProtocolFromPath(appImagePath);
if (QFile::exists(path)) {
AppImageInfoReader reader(path);
QVariantMap appInfo = reader.readAppInfo();
QJsonDocument document(QJsonObject::fromVariantMap(appInfo));
return document.toJson();
} else {
return "{\"error\":\"Invalid path\"}";
}
} catch (std::runtime_error error) {
std::cerr << "Error: " << error.what() << std::endl;
return "{\"error\":\"" + QString::fromStdString(error.what()) + "\"}";
}
}
bool InspectorDBusInterface::extractFile(QString appImagePath, QString source, QString target) {
try {
QString path = removeUriProtocolFromPath(appImagePath);
appimage::core::AppImage appImage(path.toStdString());
appimage::utils::ResourcesExtractor extractor(appImage);
std::map<std::string, std::string> extractArgs = {{source.toStdString(), target.toStdString()}};
extractor.extractTo(extractArgs);
return true;
} catch (const std::runtime_error& error) {
qWarning() << "Unable to extract AppImage file " << source << " to " << target << " error: " << error.what();
return false;
}
}
bool InspectorDBusInterface::extractApplicationIcon(const QString& appImagePath, const QString& targetPath) {
std::string iconPath;
try {
QString path = removeUriProtocolFromPath(appImagePath);
appimage::core::AppImage appImage(path.toStdString());
appimage::utils::ResourcesExtractor extractor(appImage);
std::string desktopEntryPath = extractor.getDesktopEntryPath();
std::stringstream stream(extractor.extractText(desktopEntryPath));
XdgUtils::DesktopEntry::DesktopEntry desktopEntry(stream);
std::string iconName = static_cast<std::string>(desktopEntry["Desktop Entry/Icon"]);
std::vector<std::string> iconPaths = extractor.getIconFilePaths(iconName);
iconPath = iconPaths.empty() ? ".DirIcon" : iconPaths[0];
extractor.extractTo({{iconPath, targetPath.toStdString()}});
return true;
} catch (const std::runtime_error& error) {
qWarning() << "Unable to extract AppImage icon " << QString::fromStdString(iconPath) << " to " << targetPath
<< " error: " << error.what();
return false;
}
}
InspectorDBusInterface::~InspectorDBusInterface() = default;
| 38.72549 | 117 | 0.677468 | azubieta |
77a2c4cb19b899252c40e62bf376ef877098475c | 1,098 | cpp | C++ | src/lib/math/math.cpp | epochx64/epochx64 | 15dd18ef0708000c8ac123dc59c8416db4c56e6b | [
"MIT"
] | null | null | null | src/lib/math/math.cpp | epochx64/epochx64 | 15dd18ef0708000c8ac123dc59c8416db4c56e6b | [
"MIT"
] | null | null | null | src/lib/math/math.cpp | epochx64/epochx64 | 15dd18ef0708000c8ac123dc59c8416db4c56e6b | [
"MIT"
] | null | null | null | #include <math/math.h>
namespace math
{
//TODO: Fix this trash
void integrate(double interval, double *result)
{
double precision = 10000;
double dx = interval/precision;
double iterator = 0.0;
for (uint64_t i = 0; i < (uint64_t)precision; i++)
{
*result += (iterator*iterator)*dx;
iterator += dx;
}
}
// In radians
double sin(double theta)
{
if(theta < 0.0) return -1*sin(theta);
theta = fmod(theta, 2*PI);
if(PI < theta&&theta < (2*PI)) return -1*sin(theta - PI);
if(theta > (PI/2)) return sin(PI - theta);
return double(theta - (1/6.0)*pow(theta, 3) + (1/120.0)*pow(theta, 5) - (1/5040.0)*pow(theta, 7) );
}
double cos(double theta)
{
return sin(theta + (PI/2));
}
double LogisticMap(double r, double x0, UINT64 Iterations)
{
double Result = x0;
for(UINT64 i = 0; i < Iterations; i++) Result = r*Result*(1-Result);
return Result;
}
} | 26.142857 | 107 | 0.503643 | epochx64 |
77a3b14f9a704748bc6dea5fadb39fa52b905050 | 41,022 | cpp | C++ | windows/cpp/samples/DataBurnerEx/DataBurnerDlg.cpp | primoburner/primoburner-samples | 4b5e30ffec23569a21f07d4cb8200459273f7a0c | [
"MIT"
] | null | null | null | windows/cpp/samples/DataBurnerEx/DataBurnerDlg.cpp | primoburner/primoburner-samples | 4b5e30ffec23569a21f07d4cb8200459273f7a0c | [
"MIT"
] | null | null | null | windows/cpp/samples/DataBurnerEx/DataBurnerDlg.cpp | primoburner/primoburner-samples | 4b5e30ffec23569a21f07d4cb8200459273f7a0c | [
"MIT"
] | null | null | null | // This is a part of the High Performance CD Engine Library.
// Copyright (C) 2001-2003 Primo Software Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// High Performance CD Engine Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// High Performance CD Engine product.
// DataBurnerDlg.cpp : implementation file
//
#include "stdafx.h"
#include "DataBurner.h"
#include "DataBurnerDlg.h"
#include "DialogProgress.h"
#include <io.h>
#include ".\databurnerdlg.h"
#include "FileDataStream.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDataBurnerDlg dialog
CDataBurnerDlg::CDataBurnerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CDataBurnerDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CDataBurnerDlg)
m_bTest = FALSE;
m_strRootDir = _T("");
m_strVolume = _T("");
m_strFreeSpace = _T("");
m_strRequiredSpace = _T("");
m_bEject = FALSE;
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_DATA_ICON);
m_nRequiredSpace=0;
m_strVolume="DATADISC";
m_ctx.bEject=FALSE;
m_ctx.bStopRequest=FALSE;
m_ctx.bSimulate=FALSE;
m_ctx.nMode = 0;
m_ctx.bRaw = FALSE;
m_ctx.bCloseDisc = TRUE;
m_ctx.nOperation = OPERATION_INVALID;
m_ctx.nSpeedKB = -1;
m_ctx.strImageFile = "";
m_hOperationStartedEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_hNotifyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
InitializeCriticalSection(&m_cs);
m_pDevice = NULL;
m_notify.nPercent = 0;
m_notify.nUsedCachePercent = 0;
m_notify.strText = "";
}
void CDataBurnerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_COMBO_SPEED, m_comboSpeed);
DDX_Control(pDX, IDC_STATIC_REQUIRED_SPACE, m_staticRequiredSpace);
DDX_Control(pDX, IDC_STATIC_FREE_SPACE, m_staticFreeSpace);
DDX_Control(pDX, IDC_EDIT_VOLUME, m_editVolume);
DDX_Control(pDX, IDC_BUTTON_CREATE, m_btnCreate);
DDX_Control(pDX, IDC_EDIT_ROOT, m_editRootDir);
DDX_Check(pDX, IDC_CHECK_TEST, m_bTest);
DDX_Text(pDX, IDC_EDIT_ROOT, m_strRootDir);
DDX_Text(pDX, IDC_EDIT_VOLUME, m_strVolume);
DDX_Text(pDX, IDC_STATIC_FREE_SPACE, m_strFreeSpace);
DDX_Text(pDX, IDC_STATIC_REQUIRED_SPACE, m_strRequiredSpace);
DDX_Check(pDX, IDC_CHECK_EJECT, m_bEject);
DDX_Control(pDX, IDC_BUTTON_ERASE, m_btnErase);
DDX_Control(pDX, IDC_CHECK_QUICK, m_chkQuick);
DDX_Control(pDX, IDC_STATIC_FREE_SPACE, m_staticFreeSpace);
DDX_Control(pDX, IDC_COMBO_SPEED, m_comboSpeed);
DDX_Control(pDX, IDC_COMBO_DEVICES, m_comboDevices);
DDX_Control(pDX, IDC_CHECK_TEST, m_chkTest);
DDX_Control(pDX, IDC_CHECK_EJECT, m_chkEject);
DDX_Control(pDX, IDC_COMBO_MODE, m_comboMode);
DDX_Control(pDX, IDC_CHECK_CLOSE_DISK, m_chkCloseDisc);
DDX_Control(pDX, IDC_CHECK_RAW, m_chkRaw);
DDX_Control(pDX, IDC_COMBO_IMAGE_TYPE, m_comboImageType);
DDX_Control(pDX, IDC_RADIO_JOLIET_ALL, m_radioJolietAll);
DDX_Control(pDX, IDC_RADIO_ISO_ALL, m_radioIsoAll);
DDX_Control(pDX, IDC_CHECK_TREE_DEPTH, m_checkIsoTreeDepth);
DDX_Control(pDX, IDC_TRANSLATE_NAMES, m_checkIsoTranslateNames);
DDX_Control(pDX, IDC_STATIC_ISO, m_groupIsoAll);
DDX_Control(pDX, IDC_STATIC_JOLIET, m_groupJolietAll);
DDX_Control(pDX, IDC_CHECK_LOAD_LAST_TRACK, m_chkLoadLastTrack);
}
BEGIN_MESSAGE_MAP(CDataBurnerDlg, CDialog)
//{{AFX_MSG_MAP(CDataBurnerDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_BROWSE, OnButtonBrowse)
ON_WM_CTLCOLOR()
ON_EN_CHANGE(IDC_EDIT_ROOT, OnChangeEditRoot)
ON_BN_CLICKED(IDC_BUTTON_CREATE, OnButtonCreate)
ON_WM_DESTROY()
ON_EN_CHANGE(IDC_EDIT_VOLUME, OnChangeEditVolume)
ON_BN_CLICKED(IDC_BUTTON_BURN_IMAGE, OnButtonBurnImage)
ON_BN_CLICKED(IDC_BUTTON_CREATE_IMAGE, OnButtonCreateImage)
ON_MESSAGE( WM_DEVICECHANGE, OnDeviceChange)
ON_CBN_SELCHANGE(IDC_COMBO_DEVICES, OnCbnSelchangeComboDevices)
ON_CBN_SELCHANGE(IDC_COMBO_DEVICES, OnCbnSelchangeComboDevices)
ON_CBN_SELCHANGE(IDC_COMBO_MODE, OnCbnSelchangeComboMode)
ON_BN_CLICKED(IDC_BUTTON_EJECTIN, OnBnClickedButtonEjectin)
ON_BN_CLICKED(IDC_BUTTON_EJECTOUT, OnBnClickedButtonEjectout)
ON_BN_CLICKED(IDC_BUTTON_ERASE, OnBnClickedButtonErase)
ON_BN_CLICKED(IDC_RADIO_ISO_LEVEL1, OnBnClickedRadioIsoLevel1)
ON_BN_CLICKED(IDC_RADIO_ISO_LEVEL2, OnBnClickedRadioIsoLevel2)
ON_BN_CLICKED(IDC_RADIO_ISO_ALL, OnBnClickedRadioIsoAll)
ON_CBN_SELCHANGE(IDC_COMBO_IMAGE_TYPE, OnCbnSelchangeComboImageType)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDataBurnerDlg message handlers
void CDataBurnerDlg::SetDeviceControls()
{
int nDevice = m_comboDevices.GetCurSel();
if (-1 == nDevice)
return;
Device* pDevice= m_pEnum->createDevice(m_arIndices[nDevice]);
if (pDevice == NULL)
{
TRACE(_T("Function CDataBurnerDlg::SetDeviceControls : Unable to get device object\nPossible reason : auto-insert notification enabled\nwhile writing (or any other) operation is in progress.\nThis is just a warning message - your CD is not damaged."));
return; // Protection from AI notification...
}
m_nCapacity = pDevice->mediaFreeSpace();
m_nCapacity *= BlockSize::CDRom;
if (0 == m_nCapacity || m_nCapacity < m_nRequiredSpace)
{
m_btnCreate.EnableWindow(FALSE);
}
else
{
m_btnCreate.EnableWindow();
}
// Speeds
int nCurSel, nCurSpeedKB, nMaxSpeedKB;
nCurSel = m_comboSpeed.GetCurSel();
nCurSpeedKB = (INT32)m_comboSpeed.GetItemData(nCurSel);
nMaxSpeedKB = pDevice->maxWriteSpeedKB();
m_comboSpeed.ResetContent();
SpeedEnum* pSpeeds = pDevice->createWriteSpeedEnumerator();
for (int i = 0; i < pSpeeds->count(); i++)
{
SpeedDescriptor* pSpeed = pSpeeds->at(i);
CString sSpeed;
int nSpeedKB = pSpeed->transferRateKB();
sSpeed.Format(_T("%1.0fx"), (double)nSpeedKB / (pDevice->isMediaDVD() ? Speed1xKB::DVD : Speed1xKB::CD));
m_comboSpeed.InsertString(-1, sSpeed);
m_comboSpeed.SetItemData(i, nSpeedKB);
}
pSpeeds->release();
// Restore speed...
if (nCurSel != -1 && nCurSpeedKB <= nMaxSpeedKB)
{
CString sSpeed;
sSpeed.Format(_T("%dx"), nCurSpeedKB / Speed1xKB::CD);
m_comboSpeed.SelectString(-1, sSpeed);
}
if (-1 == m_comboSpeed.GetCurSel())
m_comboSpeed.SetCurSel(0);
BOOL bRW, bRWDisk;
bRW = isRewritePossible(pDevice);
bRWDisk = pDevice->isMediaRewritable();
if (bRW && bRWDisk)
{
m_chkQuick.EnableWindow();
m_btnErase.EnableWindow();
}
else
{
m_chkQuick.EnableWindow(FALSE);
m_btnErase.EnableWindow(FALSE);
}
m_bRawDao = pDevice->cdFeatures()->canWriteRawDao();
OnCbnSelchangeComboMode();
CString str;
str.Format(_T("Required space : %dM"), m_nRequiredSpace/(1024*1024));
m_staticRequiredSpace.SetWindowText(str);
str.Format(_T("Free space : %dM"), m_nCapacity/(1024*1024));
m_staticFreeSpace.SetWindowText(str);
pDevice->release();
}
void CDataBurnerDlg::EnableIsoGroup(BOOL bEnable)
{
m_groupIsoAll.EnableWindow(bEnable);
GetDlgItem(IDC_RADIO_ISO_ALL)->EnableWindow(bEnable);
GetDlgItem(IDC_RADIO_ISO_LEVEL2)->EnableWindow(bEnable);
GetDlgItem(IDC_RADIO_ISO_LEVEL1)->EnableWindow(bEnable);
m_checkIsoTreeDepth.EnableWindow(bEnable);
m_checkIsoTranslateNames.EnableWindow(bEnable);
}
void CDataBurnerDlg::EnableJolietGroup(BOOL bEnable)
{
m_groupJolietAll.EnableWindow(bEnable);
GetDlgItem(IDC_RADIO_JOLIET_ALL)->EnableWindow(bEnable);
GetDlgItem(IDC_RADIO_JOLIET_SHORTNAMES)->EnableWindow(bEnable);
}
BOOL CDataBurnerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
m_nRequiredSpace = 0;
m_nDevicesCount = 0;
// Session Mode
m_comboMode.InsertString(0, _T("Disk-At-Once"));
m_comboMode.InsertString(1, _T("Session-At-Once"));
m_comboMode.InsertString(2, _T("Track-At-Once"));
m_comboMode.InsertString(3, _T("Packet"));
m_comboMode.SetCurSel(2);
// Image Types
m_comboImageType.InsertString(0, _T("ISO9660"));
m_comboImageType.InsertString(1, _T("Joliet"));
m_comboImageType.InsertString(2, _T("UDF"));
m_comboImageType.InsertString(3, _T("UDF & ISO9660"));
m_comboImageType.InsertString(4, _T("UDF & Joliet"));
m_comboImageType.SetCurSel(1);
OnCbnSelchangeComboImageType();
// ISO
CheckRadioButton(IDC_RADIO_ISO_ALL, IDC_RADIO_ISO_LEVEL2, IDC_RADIO_ISO_ALL);
CheckRadioButton(IDC_RADIO_JOLIET_ALL, IDC_RADIO_JOLIET_SHORTNAMES, IDC_RADIO_JOLIET_ALL);
// Write parameters
m_chkTest.SetCheck(FALSE);
m_chkEject.SetCheck(FALSE);
m_chkCloseDisc.SetCheck(TRUE);
m_chkRaw.SetCheck(FALSE);
m_chkQuick.SetCheck(TRUE);
// Multisession
m_chkLoadLastTrack.SetCheck(TRUE);
// Fill in devices list
Library::enableTraceLog(NULL, TRUE);
m_pEngine = Library::createEngine();
BOOL bResult = m_pEngine->initialize();
if (!bResult)
{
AfxMessageBox(_T("Unable to initialize CD writing engine."));
EndModalLoop(-1);
if (m_pEnum)
{
m_pEnum->release();
m_pEnum = NULL;
}
return FALSE;
}
m_pEnum = m_pEngine->createDeviceEnumerator();
int nDevices = m_pEnum->count();
if (!nDevices)
{
AfxMessageBox(_T("No CD devices available."));
EndModalLoop(-1);
if (m_pEnum)
{
m_pEnum->release();
m_pEnum = NULL;
}
return FALSE;
}
m_nDevicesCount = 0;
for (int i=0; i < nDevices;i++)
{
Device* pDevice = m_pEnum->createDevice(i);
if (!pDevice)
continue;
BOOL bWrite = isWritePossible(pDevice);
if (bWrite)
{
TCHAR tchLetter = pDevice->driveLetter();
TCHAR tcsName[256] = {0};
_stprintf(tcsName, _T("(%C:) - %s"), tchLetter, pDevice->description());
m_arDeviceNames.Add(tcsName);
m_arIndices.Add(i);
m_comboDevices.AddString(m_arDeviceNames[m_nDevicesCount++]);
}
pDevice->release();
}
if (m_nDevicesCount)
{
m_comboDevices.SetCurSel(0);
SetDeviceControls();
}
else
{
AfxMessageBox(_T("Could not find any CD-R devices."));
if (m_pEnum)
{
m_pEnum->release();
m_pEnum = NULL;
}
return FALSE;
}
return TRUE; // return TRUE unless you set the focus to a control
}
void CDataBurnerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CDataBurnerDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CDataBurnerDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
// Uses FindFile and WIN32_FIND_DATA to get the file list
void CDataBurnerDlg::ProcessInputTree(DataFile * pCurrentFile, CString & sCurrentPath)
{
WIN32_FIND_DATA FindFileData;
const primo::burner::ImageTypeFlags::Enum allImageTypes = (primo::burner::ImageTypeFlags::Enum)
(primo::burner::ImageTypeFlags::Udf |
primo::burner::ImageTypeFlags::Iso9660 |
primo::burner::ImageTypeFlags::Joliet);
CString sSearchFor = sCurrentPath + _T("\\*") ;
HANDLE hfind = FindFirstFile (sSearchFor, &FindFileData);
if (hfind == INVALID_HANDLE_VALUE)
throw ProcessInputTreeException("File not found.");
do
{
// Keep the original file name
CString sFileName = FindFileData.cFileName;
// Get the full path
CString sFullPath;
sFullPath.Format(_T("%s\\%s"), sCurrentPath, sFileName);
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// Skip the curent folder . and the parent folder ..
if (sFileName == _T(".") || sFileName == _T(".."))
continue;
// Create a folder entry and scan it for the files
DataFile * pDataFile = Library::createDataFile();
pDataFile->setDirectory(TRUE);
pDataFile->setPath((LPCTSTR)sFileName);
pDataFile->setLongFilename((LPCTSTR)sFileName);
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
pDataFile->setHiddenMask(allImageTypes);
pDataFile->setCreationTime(FindFileData.ftCreationTime);
// Search for all files
ProcessInputTree(pDataFile, sFullPath);
// Add this folder to the tree
pCurrentFile->children()->add(pDataFile);
pDataFile->release();
}
else
{
// File
DataFile * pDataFile = Library::createDataFile();
pDataFile->setDirectory(FALSE);
// Use DataStream
pDataFile->setDataSource(DataSource::Stream);
// create a data stream instance
CFileStream* pStream = new CFileStream(sFullPath);
m_Streams.Add(pStream);
// Our implementation of a DataFileStream is for illustration purposes only and simply reads the data
// from the real file;
pDataFile->setStream(pStream);
pDataFile->setLongFilename((LPCTSTR)sFileName);
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
pDataFile->setHiddenMask(allImageTypes);
pDataFile->setCreationTime(FindFileData.ftCreationTime);
// Add to the tree
pCurrentFile->children()->add(pDataFile);
pDataFile->release();
}
} while (FindNextFile (hfind, &FindFileData));
FindClose(hfind);
}
BOOL CDataBurnerDlg::SetImageLayoutFromFolder(DataDisc* pDataCD, LPCTSTR fname)
{
DataFile * pDataFile = Library::createDataFile();
// Entry for the root of the image file system
pDataFile->setDirectory(TRUE);
pDataFile->setPath(_T("\\"));
pDataFile->setLongFilename(_T("\\"));
DestroyStreams();
try
{
CString sFullPath = fname;
ProcessInputTree(pDataFile, sFullPath);
}
catch(ProcessInputTreeException &ex)
{
TRACE(_T("SetImageLayoutFromFolder Error: %s") , ex.what());
pDataFile->release();
return FALSE;
}
BOOL bRes = pDataCD->setImageLayout(pDataFile);
pDataFile->release();
return bRes;
}
void CDataBurnerDlg::OnButtonBrowse()
{
TCHAR szPath[MAX_PATH];
memset(szPath, 0, sizeof(szPath));
BROWSEINFO bi = {0};
bi.hwndOwner = m_hWnd;
bi.pidlRoot = NULL;
bi.lpszTitle = _T("Select a destination folder");
bi.ulFlags = BIF_EDITBOX;
bi.lpfn = NULL;
bi.lParam = NULL;
bi.pszDisplayName = szPath;
LPITEMIDLIST pidl = ::SHBrowseForFolder(&bi);
if (NULL == pidl)
return;
::SHGetPathFromIDList(pidl, szPath);
CoTaskMemFree(pidl);
pidl = NULL;
m_strRootDir = szPath;
m_editRootDir.SetWindowText(m_strRootDir);
DataDisc* pDataCD = Library::createDataDisc();
pDataCD->setImageType(GetImageType());
CWaitCursor wc;
BOOL bRes = SetImageLayoutFromFolder(pDataCD, m_strRootDir);
if (!bRes)
{
CString str;
str.Format(_T("A problem occured when trying to set directory:\n%s"), m_strRootDir);
AfxMessageBox(str);
m_strRootDir="";
}
else
{
m_nRequiredSpace = pDataCD->imageSizeInBytes();
}
SetDeviceControls();
pDataCD->release();
}
BOOL CDataBurnerDlg::IsDirectoryExists()
{
TCHAR tcs[1024];
m_editRootDir.GetWindowText(tcs, 1024);
if (_taccess(tcs, 0)!=-1)
return TRUE;
else
return FALSE;
}
HBRUSH CDataBurnerDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Return a different brush if the default is not desired
if ((CTLCOLOR_EDIT==nCtlColor) && pWnd->GetDlgCtrlID() == IDC_EDIT_ROOT) {
if (IsDirectoryExists())
pDC->SetTextColor(RGB(0, 0, 0));
else
pDC->SetTextColor(RGB(255, 0, 0));
}
if ((CTLCOLOR_EDIT==nCtlColor) && pWnd->GetDlgCtrlID() == IDC_EDIT_VOLUME) {
COLORREF color;
TCHAR tcs[1024];
m_editVolume.GetWindowText(tcs, 1024);
if (_tcslen(tcs)>16)
color=RGB(255, 0, 0);
else
color=RGB(0, 0, 0);
pDC->SetTextColor(color);
}
return hbr;
}
void CDataBurnerDlg::OnChangeEditRoot()
{
m_editRootDir.Invalidate(FALSE);
}
BOOL CDataBurnerDlg::ValidateMedia(int nOperation)
{
if (OPERATION_BURN_ON_THE_FLY == nOperation ||
OPERATION_IMAGE_BURN == nOperation)
{
int nDevice = m_comboDevices.GetCurSel();
// No devices and not an OPERATION_IMAGE_CREATE
if (-1 == nDevice)
{
AfxMessageBox(_T("Please select a device."));
return FALSE;
}
// Get device object.
Device* pDevice = m_pEnum->createDevice(m_arIndices[nDevice], FALSE);
if (NULL == pDevice)
return TRUE;
// Verify that the media in the device is CD
if (!pDevice->isMediaCD())
{
AfxMessageBox(_T("This samples works with CD media only. For DVD media, please see the DVDBurner sample. For Blu-Ray media, please see the BluRayBurner sample."));
pDevice->release();
return FALSE;
}
pDevice->release();
return TRUE;
}
return TRUE;
}
BOOL CDataBurnerDlg::ValidateForm()
{
if (!IsDirectoryExists())
{
AfxMessageBox(_T("Please specify a valid source folder."));
m_editRootDir.SetFocus();
return FALSE;
}
if (m_strVolume.GetLength()>16)
{
AfxMessageBox(_T("Volume name can contain maximum 16 characters"));
m_editVolume.SetFocus();
return FALSE;
}
if (m_strRootDir[m_strRootDir.GetLength()-1]=='\\' || m_strRootDir[m_strRootDir.GetLength()-1]=='/')
{
m_strRootDir=m_strRootDir.Left(m_strRootDir.GetLength()-1);
}
return TRUE;
}
void CDataBurnerDlg::RunOperation(int nOperation)
{
EnableWindow(FALSE);
CDialogProgress dlg;
dlg.Create();
dlg.ShowWindow(SW_SHOW);
dlg.UpdateWindow();
int nSel;
m_ctx.bStopRequest = FALSE;
m_ctx.bErasing = FALSE;
m_ctx.bSimulate = m_bTest;
m_ctx.bEject = m_bEject;
nSel = m_comboSpeed.GetCurSel();
m_ctx.nSpeedKB = (int)m_comboSpeed.GetItemData(nSel);
m_ctx.nOperation = nOperation;
m_ctx.nMode = m_comboMode.GetCurSel();
m_ctx.bCloseDisc = m_chkCloseDisc.GetCheck();
m_ctx.imageType = GetImageType();
m_ctx.iso.nLimits = GetCheckedRadioButton(IDC_RADIO_ISO_ALL, IDC_RADIO_ISO_LEVEL1);
m_ctx.iso.bTreeDepth = m_checkIsoTreeDepth.GetCheck();
m_ctx.iso.bTranslateNames = m_checkIsoTranslateNames.GetCheck();
m_ctx.joliet.nLimits = GetCheckedRadioButton(IDC_RADIO_JOLIET_ALL, IDC_RADIO_JOLIET_SHORTNAMES);
m_ctx.bLoadLastTrack = (BST_CHECKED == m_chkLoadLastTrack.GetCheck());
ResetEvent(m_hOperationStartedEvent);
ResetEvent(m_hNotifyEvent);
// Create thread to execute the current operation
DWORD dwId;
m_hThread = CreateThread(NULL, NULL, ThreadProc, this, NULL, &dwId);
WaitForSingleObject(m_hOperationStartedEvent, INFINITE);
while (WaitForSingleObject(m_hThread, 50) == WAIT_TIMEOUT)
{
___PumpMessages();
if (dlg.m_bStopped)
m_ctx.bStopRequest=TRUE;
if (WaitForSingleObject(m_hNotifyEvent, 0)==WAIT_OBJECT_0)
{
ResetEvent(m_hNotifyEvent);
EnterCriticalSection(&m_cs);
dlg.SetStatus(m_notify.strText);
dlg.SetProgress(m_notify.nPercent);
dlg.SetInternalBuffer(m_notify.nUsedCachePercent);
LeaveCriticalSection(&m_cs);
}
}
dlg.DestroyWindow();
EnableWindow();
BringWindowToTop();
SetActiveWindow();
m_notify.nPercent=0;
m_notify.nUsedCachePercent = 0;
m_notify.strText="";
SetDeviceControls();
}
void CDataBurnerDlg::___PumpMessages()
{
MSG msg;
while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
}
// Operation thread...
DWORD CDataBurnerDlg::ThreadProc(LPVOID pParam)
{
CDataBurnerDlg* pThis=(CDataBurnerDlg* )pParam;
return pThis->Process();
}
int CDataBurnerDlg::GetLastCompleteTrack(Device * pDevice)
{
// Get the last track number from the last session if multisession option was specified
int nLastTrack = 0;
// Check for DVD+RW and DVD-RW RO random writable media.
MediaProfile::Enum mp = pDevice->mediaProfile();
if ((MediaProfile::DVDPlusRW == mp) || (MediaProfile::DVDMinusRWRO == mp) ||
(MediaProfile::BDRE == mp) || (MediaProfile::BDRSrmPow == mp) || (MediaProfile::DVDRam == mp))
{
// DVD+RW and DVD-RW RO has only one session with one track
if (pDevice->mediaFreeSpace() > 0)
nLastTrack = 1;
}
else
{
// All other media is recorded using tracks and sessions and multi-session is no different
// than with the CD.
// Use the ReadDiskInfo method to get the last track number
DiscInfo *pDI = pDevice->readDiscInfo();
if(NULL != pDI)
{
nLastTrack = pDI->lastTrack();
// readDiskInfo reports the empty space as a track too
// That's why we need to go back one track to get the last completed track
if ((DiscStatus::Open == pDI->discStatus()) || (DiscStatus::Empty == pDI->discStatus()))
nLastTrack--;
pDI->release();
}
}
return nLastTrack;
}
// Thread main function
DWORD CDataBurnerDlg::Process()
{
SetEvent(m_hOperationStartedEvent);
// Get a device
int nDevice = m_comboDevices.GetCurSel();
if (-1 == nDevice && OPERATION_IMAGE_CREATE == m_ctx.nOperation)
{
ImageCreate(NULL, 0);
return 0;
}
// No devices and not an OPERATION_IMAGE_CREATE - nothing to do here
if (-1 == nDevice)
return -1;
m_pDevice = m_pEnum->createDevice(m_arIndices[nDevice]);
if (NULL == m_pDevice)
return -2;
if (m_ctx.bErasing)
{
m_ctx.bErasing = FALSE;
m_pDevice->setWriteSpeedKB(m_ctx.nSpeedKB);
m_pDevice->erase(m_ctx.bQuick);
m_pDevice->release();
m_pDevice = NULL;
return 0;
}
// Get the last track number from the last session if multisession option was specified
int nPrevTrackNumber = 0;
if (m_ctx.bLoadLastTrack)
nPrevTrackNumber = GetLastCompleteTrack(m_pDevice);
switch (m_ctx.nOperation)
{
case OPERATION_INVALID:
break;
case OPERATION_IMAGE_CREATE:
ImageCreate(m_pDevice, 0);
break;
case OPERATION_IMAGE_BURN:
ImageBurn(m_pDevice, 0);
break;
case OPERATION_BURN_ON_THE_FLY:
BurnOnTheFly(m_pDevice, nPrevTrackNumber);
break;
}
if (NULL != m_pDevice)
{
m_pDevice->release();
m_pDevice = NULL;
}
return 0;
}
void CDataBurnerDlg::OnButtonCreate()
{
if (!UpdateData())
return;
if (!ValidateForm())
return;
if (!ValidateMedia(OPERATION_BURN_ON_THE_FLY))
return;
RunOperation(OPERATION_BURN_ON_THE_FLY);
}
LRESULT CDataBurnerDlg::OnDeviceChange(WPARAM wParam, LPARAM lParam)
{
SetDeviceControls();
return 0;
}
void CDataBurnerDlg::OnDestroy()
{
CDialog::OnDestroy();
DestroyStreams();
if (m_pEnum)
m_pEnum->release();
if (m_pEngine)
{
m_pEngine->shutdown();
m_pEngine->release();
}
Library::disableTraceLog();
}
void CDataBurnerDlg::OnChangeEditVolume()
{
m_editVolume.Invalidate(FALSE);
}
void CDataBurnerDlg::onProgress(int64_t bytesWritten, int64_t all)
{
EnterCriticalSection(&m_cs);
double dd = (double)__int64(bytesWritten) * 100.0 / (double)__int64(all);
m_notify.nPercent=(int)dd;
if (m_pDevice)
{
dd = (double) m_pDevice->internalCacheUsedSpace();
dd = dd * 100.0 / (double)m_pDevice->internalCacheCapacity();
m_notify.nUsedCachePercent = (int)dd;
// ATLTRACE("CACHE USAGE: %d\n", m_notify.nUsedCachePercent);
}
else
m_notify.nUsedCachePercent = 0;
LeaveCriticalSection(&m_cs);
SetEvent(m_hNotifyEvent);
}
CString CDataBurnerDlg::GetTextStatus(DataDiscStatus::Enum eStatus)
{
switch(eStatus)
{
case DataDiscStatus::BuildingFileSystem:
return CString("Building filesystem...");
case DataDiscStatus::WritingFileSystem:
return CString("Writing filesystem...");
case DataDiscStatus::WritingImage:
return CString("Writing image...");
case DataDiscStatus::CachingSmallFiles:
return CString("Caching small files...");
case DataDiscStatus::CachingNetworkFiles:
return CString("Caching network files...");
case DataDiscStatus::CachingCDRomFiles:
return CString("Caching CDROM files...");
case DataDiscStatus::Initializing:
return CString("Initializing and writing lead-in...");
case DataDiscStatus::Writing:
return CString("Writing...");
case DataDiscStatus::WritingLeadOut:
return CString("Writing lead-out and flushing cache...");
}
return CString("Unknown status...");
}
bool CDataBurnerDlg::isWritePossible(Device *device) const
{
CDFeatures *cdfeatures = device->cdFeatures();
DVDFeatures *dvdfeatures = device->dvdFeatures();
BDFeatures *bdfeatures = device->bdFeatures();
bool cdWritePossible = cdfeatures->canWriteCDR() || cdfeatures->canWriteCDRW();
bool dvdWritePossible = dvdfeatures->canWriteDVDMinusR() || dvdfeatures->canWriteDVDMinusRDL() ||
dvdfeatures->canWriteDVDPlusR() || dvdfeatures->canWriteDVDPlusRDL() ||
dvdfeatures->canWriteDVDMinusRW() || dvdfeatures->canWriteDVDPlusRW() ||
dvdfeatures->canWriteDVDRam();
bool bdWritePossible = bdfeatures->canWriteBDR() || bdfeatures->canWriteBDRE();
return cdWritePossible || dvdWritePossible || bdWritePossible;
}
bool CDataBurnerDlg::isRewritePossible(Device *device) const
{
CDFeatures *cdfeatures = device->cdFeatures();
DVDFeatures *dvdfeatures = device->dvdFeatures();
BDFeatures *bdfeatures = device->bdFeatures();
bool cdRewritePossible = cdfeatures->canWriteCDRW();
bool dvdRewritePossible = dvdfeatures->canWriteDVDMinusRW() || dvdfeatures->canWriteDVDPlusRW() ||
dvdfeatures->canWriteDVDRam();
bool bdRewritePossible = bdfeatures->canWriteBDRE();
return cdRewritePossible || dvdRewritePossible || bdRewritePossible;
}
void CDataBurnerDlg::onStatus(DataDiscStatus::Enum eStatus)
{
EnterCriticalSection(&m_cs);
m_notify.strText = GetTextStatus(eStatus);
LeaveCriticalSection(&m_cs);
SetEvent(m_hNotifyEvent);
}
void CDataBurnerDlg::onFileStatus(int32_t fileNumber, const char_t* filename, int32_t percentWritten)
{
// ATLTRACE("%d\n", nPercent);
}
BOOL CDataBurnerDlg::onContinueWrite()
{
if (m_ctx.bStopRequest)
return FALSE;
return TRUE;
}
DWORD GetConstraints(TOperationContext & ctx)
{
DWORD dwRes = 0;
if (0 == ctx.iso.nLimits - IDC_RADIO_ISO_ALL)
dwRes |= ImageConstraintFlags::IsoLongLevel2;
if (1 == ctx.iso.nLimits - IDC_RADIO_ISO_ALL)
dwRes |= ImageConstraintFlags::IsoLevel2;
if (2 == ctx.iso.nLimits - IDC_RADIO_ISO_ALL)
dwRes |= ImageConstraintFlags::IsoLevel1;
if (!ctx.iso.bTreeDepth)
dwRes = dwRes & ~ImageConstraintFlags::IsoTreeDepth;
return dwRes;
}
BOOL CDataBurnerDlg::ImageCreate(Device* pDevice, int nPrevTrackNumber)
{
DataDisc* pDataCD = Library::createDataDisc();
SetVolumeProperties(pDataCD, m_strVolume, m_ctx.imageType);
pDataCD->setImageType(m_ctx.imageType);
pDataCD->setImageConstraints(GetConstraints(m_ctx));
pDataCD->setFilenameTranslation(m_ctx.iso.bTranslateNames);
pDataCD->setSessionStartAddress(0);
pDataCD->setCallback(this);
BOOL bRes = SetImageLayoutFromFolder(pDataCD, m_strRootDir);
if (!bRes)
{
ShowErrorMessage(pDataCD->error());
pDataCD->release();
return FALSE;
}
bRes = pDataCD->writeToImageFile(m_ctx.strImageFile);
if (!bRes)
{
ShowErrorMessage(pDataCD->error());
pDataCD->release();
return FALSE;
}
pDataCD->release();
return TRUE;
}
BOOL CDataBurnerDlg::ImageBurn(Device * pDevice, int nPrevTrackNumber)
{
pDevice->setWriteSpeedKB(m_ctx.nSpeedKB);
DataDisc* pDataCD = Library::createDataDisc();
pDataCD->setCallback(this);
pDataCD->setDevice(pDevice);
pDataCD->setSessionStartAddress(pDevice->newSessionStartAddress());
pDataCD->setSimulateBurn(m_ctx.bSimulate);
// Set write mode
if (!m_ctx.bRaw && (0 == m_ctx.nMode || 1 == m_ctx.nMode))
// Session-At-Once (also called Disc-At-Once)
pDataCD->setWriteMethod(WriteMethod::Sao);
else if (m_ctx.bRaw)
// RAW Disc-At-Once
pDataCD->setWriteMethod(WriteMethod::RawDao);
else if (2 == m_ctx.nMode)
// Track-At-Once
pDataCD->setWriteMethod(WriteMethod::Tao);
else
// Packet
pDataCD->setWriteMethod(WriteMethod::Packet);
pDataCD->setCloseDisc(m_ctx.bCloseDisc);
BOOL bRes = pDataCD->writeImageToDisc(m_ctx.strImageFile);
if (!bRes)
{
ShowErrorMessage(pDataCD->error());
pDataCD->release();
return FALSE;
}
if (m_ctx.bEject)
pDevice->eject(TRUE);
pDataCD->release();
return TRUE;
}
BOOL CDataBurnerDlg::BurnOnTheFly(Device* pDevice, int nPrevTrackNumber)
{
if (!pDevice)
return FALSE;
pDevice->setWriteSpeedKB(m_ctx.nSpeedKB);
// Create a data cd instance that we will use to burn
DataDisc* pDataCD = Library::createDataDisc();
pDataCD->setDevice(pDevice);
// Set the session start address. Must do this before intializing the directory structure.
pDataCD->setSessionStartAddress(pDevice->newSessionStartAddress());
// Multi-session. Load previous track
if (nPrevTrackNumber > 0)
pDataCD->setLayoutLoadTrack(nPrevTrackNumber);
// Set burning parameters
pDataCD->setImageType(m_ctx.imageType);
pDataCD->setImageConstraints(GetConstraints(m_ctx));
pDataCD->setFilenameTranslation(m_ctx.iso.bTranslateNames);
SetVolumeProperties(pDataCD, m_strVolume, m_ctx.imageType);
pDataCD->setCallback(this);
pDataCD->setSimulateBurn(m_ctx.bSimulate);
// Set write mode
if (!m_ctx.bRaw && (0 == m_ctx.nMode || 1 == m_ctx.nMode))
// Session-At-Once (also called Disc-At-Once)
pDataCD->setWriteMethod(WriteMethod::Sao);
else if (m_ctx.bRaw)
// RAW Disc-At-Once
pDataCD->setWriteMethod(WriteMethod::RawDao);
else if (2 == m_ctx.nMode)
// Track-At-Once
pDataCD->setWriteMethod(WriteMethod::Tao);
else
// Packet
pDataCD->setWriteMethod(WriteMethod::Packet);
// CloseDisc controls multi-session. Disk must be left open when multi-sessions are desired.
pDataCD->setCloseSession(TRUE);
pDataCD->setCloseDisc(m_ctx.bCloseDisc);
BOOL bRes = SetImageLayoutFromFolder(pDataCD, m_strRootDir);
if (!bRes)
{
ShowErrorMessage(pDataCD->error());
pDataCD->release();
return FALSE;
}
// Burn
while (true)
{
// Try to write the image
bRes = pDataCD->writeToDisc();
if (!bRes)
{
// Check if the error is: Cannot load image layout.
// If so most likely it is an empty formatted DVD+RW or empty formatted DVD-RW RO with one track.
if((pDataCD->error()->facility() == ErrorFacility::DataDisc) &&
(pDataCD->error()->code() == DataDiscError::CannotLoadImageLayout))
{
// Set to 0 to disable previous data session loading
pDataCD->setLayoutLoadTrack(0);
// try to write it again
continue;
}
}
break;
}
// Check result and show error message
if (!bRes)
{
ShowErrorMessage(pDataCD->error());
pDataCD->release();
return FALSE;
}
if (m_ctx.bEject)
pDevice->eject(TRUE);
pDataCD->release();
return TRUE;
}
void CDataBurnerDlg::ShowErrorMessage(const ErrorInfo *pErrInfo)
{
CString strMessage;
switch(pErrInfo->facility())
{
case ErrorFacility::SystemWindows:
{
TCHAR tcsErrorMessage[1024];
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, pErrInfo->code(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), tcsErrorMessage, 1024, NULL);
strMessage.Format(_T("System Error: 0x%06x - %s\n"), pErrInfo->code(), tcsErrorMessage);
}
break;
case ErrorFacility::Device:
strMessage.Format(_T("Device Error: 0x%06x - %s \n"), pErrInfo->code(), pErrInfo->message());
break;
case ErrorFacility::DeviceEnumerator:
strMessage.Format(_T("DeviceEnumerator Error: 0x%06x - %s \n"), pErrInfo->code(), pErrInfo->message());
break;
case ErrorFacility::DataDisc:
strMessage.Format(_T("DataDisc Error: 0x%06x - %s \n"), pErrInfo->code(), pErrInfo->message());
break;
default:
strMessage.Format(_T("Error Facility: 0x%06x Code: 0x%06x - %s \n"), pErrInfo->facility(), pErrInfo->code(), pErrInfo->message());
break;
}
AfxMessageBox(strMessage);
}
ImageTypeFlags::Enum CDataBurnerDlg::GetImageType()
{
switch(m_comboImageType.GetCurSel())
{
case 0:
return ImageTypeFlags::Iso9660;
case 1:
return ImageTypeFlags::Joliet;
case 2:
return ImageTypeFlags::Udf;
case 3:
return ImageTypeFlags::UdfIso;
case 4:
return ImageTypeFlags::UdfJoliet;
default:
return ImageTypeFlags::Joliet;
}
}
void CDataBurnerDlg::OnButtonBurnImage()
{
if (!UpdateData())
return;
CFileDialog dlg(TRUE, _T("*.iso"), NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
_T("Image File (*.iso)|*.iso||"), NULL );
if(IDOK!=dlg.DoModal())
return;
m_ctx.strImageFile = dlg.m_ofn.lpstrFile;
HANDLE hFile = CreateFile(m_ctx.strImageFile, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
CString str;
str.Format(_T("Unable to open file %s"), m_ctx.strImageFile);
AfxMessageBox(str);
return;
}
DWORD dwFileSize = GetFileSize(hFile, NULL);
CloseHandle(hFile);
if (dwFileSize > (DWORD)m_nCapacity)
{
CString str;
str.Format(_T("Cannot write image file %s.\nThe file is too big."), m_ctx.strImageFile);
AfxMessageBox(str);
return;
}
if (!ValidateMedia(OPERATION_IMAGE_BURN))
return;
RunOperation(OPERATION_IMAGE_BURN);
}
void CDataBurnerDlg::OnButtonCreateImage()
{
if (!UpdateData())
return;
if (!ValidateForm())
return;
CFileDialog dlg(false, _T("*.iso"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NONETWORKBUTTON,
_T("Image File (*.iso)|*.iso||"), NULL );
if(IDOK!=dlg.DoModal())
return;
m_ctx.strImageFile = dlg.m_ofn.lpstrFile;
RunOperation(OPERATION_IMAGE_CREATE);
}
void CDataBurnerDlg::OnCbnSelchangeComboDevices()
{
int nCurSel = m_comboDevices.GetCurSel();
if (-1 != nCurSel)
SetDeviceControls();
}
void CDataBurnerDlg::OnCbnSelchangeComboMode()
{
if (m_bRawDao && 0 == m_comboMode.GetCurSel())
{
m_chkRaw.EnableWindow(TRUE);
m_chkCloseDisc.SetCheck(1);
m_chkCloseDisc.EnableWindow(FALSE);
}
// SAO
else if (1 == m_comboMode.GetCurSel())
{
m_chkCloseDisc.EnableWindow(TRUE);
m_chkRaw.SetCheck(0);
m_chkRaw.EnableWindow(FALSE);
}
// TAO
else
{
m_chkCloseDisc.EnableWindow(TRUE);
m_chkRaw.SetCheck(0);
m_chkRaw.EnableWindow(FALSE);
}
OnBnClickedCheckRaw();
}
void CDataBurnerDlg::OnBnClickedCheckRaw()
{
if (0 == m_comboMode.GetCurSel())
{
if (1 == m_chkRaw.GetCheck())
m_chkCloseDisc.SetCheck(1);
m_chkCloseDisc.EnableWindow(0 == m_chkRaw.GetCheck());
}
}
void CDataBurnerDlg::OnBnClickedButtonEjectin()
{
int nDevice = m_comboDevices.GetCurSel();
Device* pDevice = m_pEnum->createDevice(m_arIndices[nDevice]);
if(pDevice)
{
pDevice->eject(0);
pDevice->release();
}
}
void CDataBurnerDlg::OnBnClickedButtonEjectout()
{
int nDevice = m_comboDevices.GetCurSel();
Device* pDevice = m_pEnum->createDevice(m_arIndices[nDevice]);
if (pDevice)
{
pDevice->eject(1);
pDevice->release();
}
}
void CDataBurnerDlg::OnBnClickedButtonErase()
{
EnableWindow(FALSE);
CDialogProgress dlg;
dlg.Create();
dlg.ShowWindow(SW_SHOW);
dlg.UpdateWindow();
dlg.GetDlgItem(IDOK)->EnableWindow(FALSE);
dlg.SetStatus("Erasing disc. Please wait...");
m_ctx.bErasing=TRUE;
m_ctx.bQuick=m_chkQuick.GetCheck();
ResetEvent(m_hOperationStartedEvent);
DWORD dwId;
m_hThread=CreateThread(NULL, NULL, ThreadProc, this, NULL, &dwId);
WaitForSingleObject(m_hOperationStartedEvent, INFINITE);
while (WaitForSingleObject(m_hThread, 0)==WAIT_TIMEOUT)
{
___PumpMessages();
Sleep(50);
}
dlg.DestroyWindow();
EnableWindow();
BringWindowToTop();
SetActiveWindow();
SetDeviceControls();
}
void CDataBurnerDlg::OnBnClickedRadioIsoLevel1()
{
}
void CDataBurnerDlg::OnBnClickedRadioIsoLevel2()
{
}
void CDataBurnerDlg::OnBnClickedRadioIsoAll()
{
}
void CDataBurnerDlg::OnCbnSelchangeComboImageType()
{
ImageTypeFlags::Enum nImageType = GetImageType();
bool bIso = (nImageType & ImageTypeFlags::Iso9660) > 0;
bool bJoliet = (nImageType & ImageTypeFlags::Joliet) > 0;
EnableJolietGroup(bJoliet);
EnableIsoGroup(bIso);
}
void CDataBurnerDlg::DestroyStreams()
{
for (int nStream = 0; nStream < m_Streams.GetSize(); nStream++)
{
CFileStream* pStream = (CFileStream* )m_Streams[nStream];
if (pStream)
delete pStream;
}
m_Streams.RemoveAll();
}
void CDataBurnerDlg::SetVolumeProperties(DataDisc* pDataDisc, const CString& volumeLabel, primo::burner::ImageTypeFlags::Enum imageType)
{
// set volume times
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME ft;
SystemTimeToFileTime(&st, &ft);
if((ImageTypeFlags::Iso9660 & imageType) ||
(ImageTypeFlags::Joliet & imageType))
{
IsoVolumeProps *iso = pDataDisc->isoVolumeProps();
iso->setVolumeLabel(volumeLabel);
// Sample settings. Replace with your own data or leave empty
iso->setSystemID(_T("WINDOWS"));
iso->setVolumeSet(_TEXT("SET"));
iso->setPublisher(_T("PUBLISHER"));
iso->setDataPreparer(_T("PREPARER"));
iso->setApplication(_T("DVDBURNER"));
iso->setCopyrightFile(_T("COPYRIGHT.TXT"));
iso->setAbstractFile(_T("ABSTRACT.TXT"));
iso->setBibliographicFile(_T("BIBLIO.TXT"));
iso->setVolumeCreationTime(ft);
}
if(ImageTypeFlags::Joliet & imageType)
{
JolietVolumeProps *joliet = pDataDisc->jolietVolumeProps();
joliet->setVolumeLabel(volumeLabel);
// Sample settings. Replace with your own data or leave empty
joliet->setSystemID(_T("WINDOWS"));
joliet->setVolumeSet(_TEXT("SET"));
joliet->setPublisher(_T("PUBLISHER"));
joliet->setDataPreparer(_T("PREPARER"));
joliet->setApplication(_T("DVDBURNER"));
joliet->setCopyrightFile(_T("COPYRIGHT.TXT"));
joliet->setAbstractFile(_T("ABSTRACT.TXT"));
joliet->setBibliographicFile(_T("BIBLIO.TXT"));
joliet->setVolumeCreationTime(ft);
}
if(ImageTypeFlags::Udf & imageType)
{
UdfVolumeProps *udf = pDataDisc->udfVolumeProps();
udf->setVolumeLabel(volumeLabel);
// Sample settings. Replace with your own data or leave empty
udf->setVolumeSet(_TEXT("SET"));
udf->setCopyrightFile(_T("COPYRIGHT.TXT"));
udf->setAbstractFile(_T("ABSTRACT.TXT"));
udf->setVolumeCreationTime(ft);
}
}
| 25.848771 | 255 | 0.696821 | primoburner |
77ad6cb48aa0dae50ccaec2352ee4ae8bb6d6fb3 | 446 | cpp | C++ | pra/2-6.cpp | zhaojing1995/CCF | 53bffeea7c781ae9609f0b1610e106cce14296d2 | [
"MIT"
] | 1 | 2019-09-10T08:17:02.000Z | 2019-09-10T08:17:02.000Z | pra/2-6.cpp | zhaojing1995/CCF | 53bffeea7c781ae9609f0b1610e106cce14296d2 | [
"MIT"
] | null | null | null | pra/2-6.cpp | zhaojing1995/CCF | 53bffeea7c781ae9609f0b1610e106cce14296d2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#define INF 1000000000
using namespace std;
int main(){
int n;
int kase=0;
// int array[];
while(scanf("%d",&n)==1 && n){ //循环输入n
int min=INF,max=-INF,s=0;
for(int i=0;i<n;i++){
int x;
scanf("%d",&x);
s+=x;
if(x>max)max=x;
if(x<min)min=x;
}
if(kase) printf("\n");
printf("Case %d: %d %d %.3f\n",++kase,min,max,(double)s/n);
}
//跳出循环之后应该输出结果才对
return 0;
}
// 坑真多啊... | 17.84 | 62 | 0.544843 | zhaojing1995 |
77beae06fbb30367f42202ba358ac662369901b7 | 6,952 | hpp | C++ | include/boost/gil/extension/io/png/detail/supported_types.hpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | include/boost/gil/extension/io/png/detail/supported_types.hpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | include/boost/gil/extension/io/png/detail/supported_types.hpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | //
// Copyright 2007-2008 Christian Henning, Andreas Pokorny, Lubomir Bourdev
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_EXTENSION_IO_PNG_DETAIL_SUPPORTED_TYPES_HPP
#define BOOST_GIL_EXTENSION_IO_PNG_DETAIL_SUPPORTED_TYPES_HPP
#include <boost/gil/extension/io/png/tags.hpp>
#ifdef BOOST_GIL_IO_ENABLE_GRAY_ALPHA
#include <boost/gil/extension/toolbox/color_spaces/gray_alpha.hpp>
#endif // BOOST_GIL_IO_ENABLE_GRAY_ALPHA
#include <cstddef>
#include <type_traits>
namespace boost {
namespace gil {
namespace detail {
static const size_t PNG_BYTES_TO_CHECK = 4;
// Read support
template <png_bitdepth::type BitDepth, png_color_type::type ColorType>
struct png_rw_support_base {
static const png_bitdepth::type _bit_depth = BitDepth;
static const png_color_type::type _color_type = ColorType;
};
template <typename Channel, typename ColorSpace>
struct png_read_support : read_support_false,
png_rw_support_base<1, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_read_support<packed_dynamic_channel_reference<BitField, 1, Mutable>,
gray_t>
: read_support_true, png_rw_support_base<1, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_read_support<packed_dynamic_channel_reference<BitField, 2, Mutable>,
gray_t>
: read_support_true, png_rw_support_base<2, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_read_support<packed_dynamic_channel_reference<BitField, 4, Mutable>,
gray_t>
: read_support_true, png_rw_support_base<4, PNG_COLOR_TYPE_GRAY> {};
template <>
struct png_read_support<uint8_t, gray_t>
: read_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_GRAY> {};
#ifdef BOOST_GIL_IO_ENABLE_GRAY_ALPHA
template <>
struct png_read_support<uint8_t, gray_alpha_t>
: read_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_GA> {};
#endif // BOOST_GIL_IO_ENABLE_GRAY_ALPHA
template <>
struct png_read_support<uint8_t, rgb_t>
: read_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_RGB> {};
template <>
struct png_read_support<uint8_t, rgba_t>
: read_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_RGBA> {};
template <>
struct png_read_support<uint16_t, gray_t>
: read_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_GRAY> {};
template <>
struct png_read_support<uint16_t, rgb_t>
: read_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_RGB> {};
template <>
struct png_read_support<uint16_t, rgba_t>
: read_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_RGBA> {};
#ifdef BOOST_GIL_IO_ENABLE_GRAY_ALPHA
template <>
struct png_read_support<uint16_t, gray_alpha_t>
: read_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_GA> {};
#endif // BOOST_GIL_IO_ENABLE_GRAY_ALPHA
// Write support
template <typename Channel, typename ColorSpace>
struct png_write_support : write_support_false,
png_rw_support_base<1, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_write_support<packed_dynamic_channel_reference<BitField, 1, Mutable>,
gray_t>
: write_support_true, png_rw_support_base<1, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_write_support<
packed_dynamic_channel_reference<BitField, 1, Mutable> const, gray_t>
: write_support_true, png_rw_support_base<1, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_write_support<packed_dynamic_channel_reference<BitField, 2, Mutable>,
gray_t>
: write_support_true, png_rw_support_base<2, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_write_support<
packed_dynamic_channel_reference<BitField, 2, Mutable> const, gray_t>
: write_support_true, png_rw_support_base<2, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_write_support<packed_dynamic_channel_reference<BitField, 4, Mutable>,
gray_t>
: write_support_true, png_rw_support_base<4, PNG_COLOR_TYPE_GRAY> {};
template <typename BitField, bool Mutable>
struct png_write_support<
packed_dynamic_channel_reference<BitField, 4, Mutable> const, gray_t>
: write_support_true, png_rw_support_base<4, PNG_COLOR_TYPE_GRAY> {};
template <>
struct png_write_support<uint8_t, gray_t>
: write_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_GRAY> {};
#ifdef BOOST_GIL_IO_ENABLE_GRAY_ALPHA
template <>
struct png_write_support<uint8_t, gray_alpha_t>
: write_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_GA> {};
#endif // BOOST_GIL_IO_ENABLE_GRAY_ALPHA
template <>
struct png_write_support<uint8_t, rgb_t>
: write_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_RGB> {};
template <>
struct png_write_support<uint8_t, rgba_t>
: write_support_true, png_rw_support_base<8, PNG_COLOR_TYPE_RGBA> {};
template <>
struct png_write_support<uint16_t, gray_t>
: write_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_GRAY> {};
template <>
struct png_write_support<uint16_t, rgb_t>
: write_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_RGB> {};
template <>
struct png_write_support<uint16_t, rgba_t>
: write_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_RGBA> {};
#ifdef BOOST_GIL_IO_ENABLE_GRAY_ALPHA
template <>
struct png_write_support<uint16_t, gray_alpha_t>
: write_support_true, png_rw_support_base<16, PNG_COLOR_TYPE_GA> {};
#endif // BOOST_GIL_IO_ENABLE_GRAY_ALPHA
} // namespace detail
template <typename Pixel>
struct is_read_supported<Pixel, png_tag>
: std::integral_constant<
bool, detail::png_read_support<
typename channel_type<Pixel>::type,
typename color_space_type<Pixel>::type>::is_supported> {
using parent_t =
detail::png_read_support<typename channel_type<Pixel>::type,
typename color_space_type<Pixel>::type>;
static const png_bitdepth::type _bit_depth = parent_t::_bit_depth;
static const png_color_type::type _color_type = parent_t::_color_type;
};
template <typename Pixel>
struct is_write_supported<Pixel, png_tag>
: std::integral_constant<
bool, detail::png_write_support<
typename channel_type<Pixel>::type,
typename color_space_type<Pixel>::type>::is_supported> {
using parent_t =
detail::png_write_support<typename channel_type<Pixel>::type,
typename color_space_type<Pixel>::type>;
static const png_bitdepth::type _bit_depth = parent_t::_bit_depth;
static const png_color_type::type _color_type = parent_t::_color_type;
};
} // namespace gil
} // namespace boost
#endif
| 35.835052 | 80 | 0.757768 | sdebionne |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.