text stringlengths 54 60.6k |
|---|
<commit_before>// BoundingBox.cpp
// Implements the cBoundingBox class representing an axis-aligned bounding box with floatingpoint coords
#include "Globals.h"
#include "BoundingBox.h"
#include "Defines.h"
#if SELF_TEST
/// A simple self-test that is executed on program start, used to verify bbox functionality
class SelfTest
{
public:
SelfTest(void)
{
Vector3d Min(1, 1, 1);
Vector3d Max(2, 2, 2);
Vector3d LineDefs[] =
{
Vector3d(1.5, 4, 1.5), Vector3d(1.5, 3, 1.5), // Should intersect at 2, face 1 (YP)
Vector3d(1.5, 0, 1.5), Vector3d(1.5, 4, 1.5), // Should intersect at 0.25, face 0 (YM)
Vector3d(0, 0, 0), Vector3d(2, 2, 2), // Should intersect at 0.5, face 0, 3 or 5 (anyM)
Vector3d(0.999, 0, 1.5), Vector3d(0.999, 4, 1.5), // Should not intersect
Vector3d(1.999, 0, 1.5), Vector3d(1.999, 4, 1.5), // Should intersect at 0.25, face 0 (YM)
Vector3d(2.001, 0, 1.5), Vector3d(2.001, 4, 1.5), // Should not intersect
} ;
bool Results[] = {true,true,true,false,true,false};
double LineCoeffs[] = {2,0.25,0.5,0,0.25,0};
for (size_t i = 0; i < ARRAYCOUNT(LineDefs) / 2; i++)
{
double LineCoeff;
eBlockFace Face;
Vector3d Line1 = LineDefs[2 * i];
Vector3d Line2 = LineDefs[2 * i + 1];
bool res = cBoundingBox::CalcLineIntersection(Min, Max, Line1, Line2, LineCoeff, Face);
if (res != Results[i])
{
fprintf(stderr,"LineIntersection({%.02f, %.02f, %.02f}, {%.02f, %.02f, %.02f}) -> %d, %.05f, %d\n",
Line1.x, Line1.y, Line1.z,
Line2.x, Line2.y, Line2.z,
res ? 1 : 0, LineCoeff, Face
);
abort();
}
if (res)
{
if (LineCoeff != LineCoeffs[i])
{
fprintf(stderr,"LineIntersection({%.02f, %.02f, %.02f}, {%.02f, %.02f, %.02f}) -> %d, %.05f, %d\n",
Line1.x, Line1.y, Line1.z,
Line2.x, Line2.y, Line2.z,
res ? 1 : 0, LineCoeff, Face
);
abort();
}
}
} // for i - LineDefs[]
fprintf(stderr,"BoundingBox selftest complete.");
}
} Test;
#endif
cBoundingBox::cBoundingBox(double a_MinX, double a_MaxX, double a_MinY, double a_MaxY, double a_MinZ, double a_MaxZ) :
m_Min(a_MinX, a_MinY, a_MinZ),
m_Max(a_MaxX, a_MaxY, a_MaxZ)
{
}
cBoundingBox::cBoundingBox(const Vector3d & a_Min, const Vector3d & a_Max) :
m_Min(a_Min),
m_Max(a_Max)
{
}
cBoundingBox::cBoundingBox(const Vector3d & a_Pos, double a_Radius, double a_Height) :
m_Min(a_Pos.x - a_Radius, a_Pos.y, a_Pos.z - a_Radius),
m_Max(a_Pos.x + a_Radius, a_Pos.y + a_Height, a_Pos.z + a_Radius)
{
}
cBoundingBox::cBoundingBox(const cBoundingBox & a_Orig) :
m_Min(a_Orig.m_Min),
m_Max(a_Orig.m_Max)
{
}
void cBoundingBox::Move(double a_OffX, double a_OffY, double a_OffZ)
{
m_Min.x += a_OffX;
m_Min.y += a_OffY;
m_Min.z += a_OffZ;
m_Max.x += a_OffX;
m_Max.y += a_OffY;
m_Max.z += a_OffZ;
}
void cBoundingBox::Move(const Vector3d & a_Off)
{
m_Min.x += a_Off.x;
m_Min.y += a_Off.y;
m_Min.z += a_Off.z;
m_Max.x += a_Off.x;
m_Max.y += a_Off.y;
m_Max.z += a_Off.z;
}
void cBoundingBox::Expand(double a_ExpandX, double a_ExpandY, double a_ExpandZ)
{
m_Min.x -= a_ExpandX;
m_Min.y -= a_ExpandY;
m_Min.z -= a_ExpandZ;
m_Max.x += a_ExpandX;
m_Max.y += a_ExpandY;
m_Max.z += a_ExpandZ;
}
bool cBoundingBox::DoesIntersect(const cBoundingBox & a_Other)
{
return (
((a_Other.m_Min.x <= m_Max.x) && (a_Other.m_Max.x >= m_Min.x)) && // X coords intersect
((a_Other.m_Min.y <= m_Max.y) && (a_Other.m_Max.y >= m_Min.y)) && // Y coords intersect
((a_Other.m_Min.z <= m_Max.z) && (a_Other.m_Max.z >= m_Min.z)) // Z coords intersect
);
}
cBoundingBox cBoundingBox::Union(const cBoundingBox & a_Other)
{
return cBoundingBox(
std::min(m_Min.x, a_Other.m_Min.x),
std::min(m_Min.y, a_Other.m_Min.y),
std::min(m_Min.z, a_Other.m_Min.z),
std::max(m_Max.x, a_Other.m_Max.x),
std::max(m_Max.y, a_Other.m_Max.y),
std::max(m_Max.z, a_Other.m_Max.z)
);
}
bool cBoundingBox::IsInside(const Vector3d & a_Point)
{
return IsInside(m_Min, m_Max, a_Point);
}
bool cBoundingBox::IsInside(double a_X, double a_Y,double a_Z)
{
return IsInside(m_Min, m_Max, a_X, a_Y, a_Z);
}
bool cBoundingBox::IsInside(cBoundingBox & a_Other)
{
// If both a_Other's coords are inside this, then the entire a_Other is inside
return (IsInside(a_Other.m_Min) && IsInside(a_Other.m_Max));
}
bool cBoundingBox::IsInside(const Vector3d & a_Min, const Vector3d & a_Max)
{
// If both coords are inside this, then the entire a_Other is inside
return (IsInside(a_Min) && IsInside(a_Max));
}
bool cBoundingBox::IsInside(const Vector3d & a_Min, const Vector3d & a_Max, const Vector3d & a_Point)
{
return (
((a_Point.x >= a_Min.x) && (a_Point.x <= a_Max.x)) &&
((a_Point.y >= a_Min.y) && (a_Point.y <= a_Max.y)) &&
((a_Point.z >= a_Min.z) && (a_Point.z <= a_Max.z))
);
}
bool cBoundingBox::IsInside(const Vector3d & a_Min, const Vector3d & a_Max, double a_X, double a_Y, double a_Z)
{
return (
((a_X >= a_Min.x) && (a_X <= a_Max.x)) &&
((a_Y >= a_Min.y) && (a_Y <= a_Max.y)) &&
((a_Z >= a_Min.z) && (a_Z <= a_Max.z))
);
}
bool cBoundingBox::CalcLineIntersection(const Vector3d & a_Line1, const Vector3d & a_Line2, double & a_LineCoeff, eBlockFace & a_Face)
{
return CalcLineIntersection(m_Min, m_Max, a_Line1, a_Line2, a_LineCoeff, a_Face);
}
bool cBoundingBox::CalcLineIntersection(const Vector3d & a_Min, const Vector3d & a_Max, const Vector3d & a_Line1, const Vector3d & a_Line2, double & a_LineCoeff, eBlockFace & a_Face)
{
if (IsInside(a_Min, a_Max, a_Line1))
{
// The starting point is inside the bounding box.
a_LineCoeff = 0;
a_Face = BLOCK_FACE_NONE; // No faces hit
return true;
}
eBlockFace Face = BLOCK_FACE_NONE;
double Coeff = Vector3d::NO_INTERSECTION;
// Check each individual bbox face for intersection with the line, remember the one with the lowest coeff
double c = a_Line1.LineCoeffToXYPlane(a_Line2, a_Min.z);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.z > a_Line2.z) ? BLOCK_FACE_ZP : BLOCK_FACE_ZM;
Coeff = c;
}
c = a_Line1.LineCoeffToXYPlane(a_Line2, a_Max.z);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.z > a_Line2.z) ? BLOCK_FACE_ZP : BLOCK_FACE_ZM;
Coeff = c;
}
c = a_Line1.LineCoeffToXZPlane(a_Line2, a_Min.y);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.y > a_Line2.y) ? BLOCK_FACE_YP : BLOCK_FACE_YM;
Coeff = c;
}
c = a_Line1.LineCoeffToXZPlane(a_Line2, a_Max.y);
if ((c >= 0) && (c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.y > a_Line2.y) ? BLOCK_FACE_YP : BLOCK_FACE_YM;
Coeff = c;
}
c = a_Line1.LineCoeffToYZPlane(a_Line2, a_Min.x);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.x > a_Line2.x) ? BLOCK_FACE_XP : BLOCK_FACE_XM;
Coeff = c;
}
c = a_Line1.LineCoeffToYZPlane(a_Line2, a_Max.x);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.x > a_Line2.x) ? BLOCK_FACE_XP : BLOCK_FACE_XM;
Coeff = c;
}
if (Coeff >= Vector3d::NO_INTERSECTION)
{
// There has been no intersection
return false;
}
a_LineCoeff = Coeff;
a_Face = Face;
return true;
}
bool cBoundingBox::Intersect(const cBoundingBox & a_Other, cBoundingBox & a_Intersection)
{
a_Intersection.m_Min.x = std::max(m_Min.x, a_Other.m_Min.x);
a_Intersection.m_Max.x = std::min(m_Max.x, a_Other.m_Max.x);
if (a_Intersection.m_Min.x >= a_Intersection.m_Max.x)
{
return false;
}
a_Intersection.m_Min.y = std::max(m_Min.y, a_Other.m_Min.y);
a_Intersection.m_Max.y = std::min(m_Max.y, a_Other.m_Max.y);
if (a_Intersection.m_Min.y >= a_Intersection.m_Max.y)
{
return false;
}
a_Intersection.m_Min.z = std::max(m_Min.z, a_Other.m_Min.z);
a_Intersection.m_Max.z = std::min(m_Max.z, a_Other.m_Max.z);
if (a_Intersection.m_Min.z >= a_Intersection.m_Max.z)
{
return false;
}
return true;
}
<commit_msg>Fixed cBoundingBox self-test code-style.<commit_after>// BoundingBox.cpp
// Implements the cBoundingBox class representing an axis-aligned bounding box with floatingpoint coords
#include "Globals.h"
#include "BoundingBox.h"
#include "Defines.h"
#if SELF_TEST
/** A simple self-test that is executed on program start, used to verify bbox functionality */
static class SelfTest_BoundingBox
{
public:
SelfTest_BoundingBox(void)
{
Vector3d Min(1, 1, 1);
Vector3d Max(2, 2, 2);
Vector3d LineDefs[] =
{
Vector3d(1.5, 4, 1.5), Vector3d(1.5, 3, 1.5), // Should intersect at 2, face 1 (YP)
Vector3d(1.5, 0, 1.5), Vector3d(1.5, 4, 1.5), // Should intersect at 0.25, face 0 (YM)
Vector3d(0, 0, 0), Vector3d(2, 2, 2), // Should intersect at 0.5, face 0, 3 or 5 (anyM)
Vector3d(0.999, 0, 1.5), Vector3d(0.999, 4, 1.5), // Should not intersect
Vector3d(1.999, 0, 1.5), Vector3d(1.999, 4, 1.5), // Should intersect at 0.25, face 0 (YM)
Vector3d(2.001, 0, 1.5), Vector3d(2.001, 4, 1.5), // Should not intersect
} ;
bool Results[] = {true, true, true, false, true, false};
double LineCoeffs[] = {2, 0.25, 0.5, 0, 0.25, 0};
for (size_t i = 0; i < ARRAYCOUNT(LineDefs) / 2; i++)
{
double LineCoeff;
eBlockFace Face;
Vector3d Line1 = LineDefs[2 * i];
Vector3d Line2 = LineDefs[2 * i + 1];
bool res = cBoundingBox::CalcLineIntersection(Min, Max, Line1, Line2, LineCoeff, Face);
if (res != Results[i])
{
fprintf(stderr, "LineIntersection({%.02f, %.02f, %.02f}, {%.02f, %.02f, %.02f}) -> %d, %.05f, %d\n",
Line1.x, Line1.y, Line1.z,
Line2.x, Line2.y, Line2.z,
res ? 1 : 0, LineCoeff, Face
);
abort();
}
if (res)
{
if (LineCoeff != LineCoeffs[i])
{
fprintf(stderr, "LineIntersection({%.02f, %.02f, %.02f}, {%.02f, %.02f, %.02f}) -> %d, %.05f, %d\n",
Line1.x, Line1.y, Line1.z,
Line2.x, Line2.y, Line2.z,
res ? 1 : 0, LineCoeff, Face
);
abort();
}
}
} // for i - LineDefs[]
fprintf(stderr, "BoundingBox selftest complete.\n");
}
} gTest;
#endif
cBoundingBox::cBoundingBox(double a_MinX, double a_MaxX, double a_MinY, double a_MaxY, double a_MinZ, double a_MaxZ) :
m_Min(a_MinX, a_MinY, a_MinZ),
m_Max(a_MaxX, a_MaxY, a_MaxZ)
{
}
cBoundingBox::cBoundingBox(const Vector3d & a_Min, const Vector3d & a_Max) :
m_Min(a_Min),
m_Max(a_Max)
{
}
cBoundingBox::cBoundingBox(const Vector3d & a_Pos, double a_Radius, double a_Height) :
m_Min(a_Pos.x - a_Radius, a_Pos.y, a_Pos.z - a_Radius),
m_Max(a_Pos.x + a_Radius, a_Pos.y + a_Height, a_Pos.z + a_Radius)
{
}
cBoundingBox::cBoundingBox(const cBoundingBox & a_Orig) :
m_Min(a_Orig.m_Min),
m_Max(a_Orig.m_Max)
{
}
void cBoundingBox::Move(double a_OffX, double a_OffY, double a_OffZ)
{
m_Min.x += a_OffX;
m_Min.y += a_OffY;
m_Min.z += a_OffZ;
m_Max.x += a_OffX;
m_Max.y += a_OffY;
m_Max.z += a_OffZ;
}
void cBoundingBox::Move(const Vector3d & a_Off)
{
m_Min.x += a_Off.x;
m_Min.y += a_Off.y;
m_Min.z += a_Off.z;
m_Max.x += a_Off.x;
m_Max.y += a_Off.y;
m_Max.z += a_Off.z;
}
void cBoundingBox::Expand(double a_ExpandX, double a_ExpandY, double a_ExpandZ)
{
m_Min.x -= a_ExpandX;
m_Min.y -= a_ExpandY;
m_Min.z -= a_ExpandZ;
m_Max.x += a_ExpandX;
m_Max.y += a_ExpandY;
m_Max.z += a_ExpandZ;
}
bool cBoundingBox::DoesIntersect(const cBoundingBox & a_Other)
{
return (
((a_Other.m_Min.x <= m_Max.x) && (a_Other.m_Max.x >= m_Min.x)) && // X coords intersect
((a_Other.m_Min.y <= m_Max.y) && (a_Other.m_Max.y >= m_Min.y)) && // Y coords intersect
((a_Other.m_Min.z <= m_Max.z) && (a_Other.m_Max.z >= m_Min.z)) // Z coords intersect
);
}
cBoundingBox cBoundingBox::Union(const cBoundingBox & a_Other)
{
return cBoundingBox(
std::min(m_Min.x, a_Other.m_Min.x),
std::min(m_Min.y, a_Other.m_Min.y),
std::min(m_Min.z, a_Other.m_Min.z),
std::max(m_Max.x, a_Other.m_Max.x),
std::max(m_Max.y, a_Other.m_Max.y),
std::max(m_Max.z, a_Other.m_Max.z)
);
}
bool cBoundingBox::IsInside(const Vector3d & a_Point)
{
return IsInside(m_Min, m_Max, a_Point);
}
bool cBoundingBox::IsInside(double a_X, double a_Y,double a_Z)
{
return IsInside(m_Min, m_Max, a_X, a_Y, a_Z);
}
bool cBoundingBox::IsInside(cBoundingBox & a_Other)
{
// If both a_Other's coords are inside this, then the entire a_Other is inside
return (IsInside(a_Other.m_Min) && IsInside(a_Other.m_Max));
}
bool cBoundingBox::IsInside(const Vector3d & a_Min, const Vector3d & a_Max)
{
// If both coords are inside this, then the entire a_Other is inside
return (IsInside(a_Min) && IsInside(a_Max));
}
bool cBoundingBox::IsInside(const Vector3d & a_Min, const Vector3d & a_Max, const Vector3d & a_Point)
{
return (
((a_Point.x >= a_Min.x) && (a_Point.x <= a_Max.x)) &&
((a_Point.y >= a_Min.y) && (a_Point.y <= a_Max.y)) &&
((a_Point.z >= a_Min.z) && (a_Point.z <= a_Max.z))
);
}
bool cBoundingBox::IsInside(const Vector3d & a_Min, const Vector3d & a_Max, double a_X, double a_Y, double a_Z)
{
return (
((a_X >= a_Min.x) && (a_X <= a_Max.x)) &&
((a_Y >= a_Min.y) && (a_Y <= a_Max.y)) &&
((a_Z >= a_Min.z) && (a_Z <= a_Max.z))
);
}
bool cBoundingBox::CalcLineIntersection(const Vector3d & a_Line1, const Vector3d & a_Line2, double & a_LineCoeff, eBlockFace & a_Face)
{
return CalcLineIntersection(m_Min, m_Max, a_Line1, a_Line2, a_LineCoeff, a_Face);
}
bool cBoundingBox::CalcLineIntersection(const Vector3d & a_Min, const Vector3d & a_Max, const Vector3d & a_Line1, const Vector3d & a_Line2, double & a_LineCoeff, eBlockFace & a_Face)
{
if (IsInside(a_Min, a_Max, a_Line1))
{
// The starting point is inside the bounding box.
a_LineCoeff = 0;
a_Face = BLOCK_FACE_NONE; // No faces hit
return true;
}
eBlockFace Face = BLOCK_FACE_NONE;
double Coeff = Vector3d::NO_INTERSECTION;
// Check each individual bbox face for intersection with the line, remember the one with the lowest coeff
double c = a_Line1.LineCoeffToXYPlane(a_Line2, a_Min.z);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.z > a_Line2.z) ? BLOCK_FACE_ZP : BLOCK_FACE_ZM;
Coeff = c;
}
c = a_Line1.LineCoeffToXYPlane(a_Line2, a_Max.z);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.z > a_Line2.z) ? BLOCK_FACE_ZP : BLOCK_FACE_ZM;
Coeff = c;
}
c = a_Line1.LineCoeffToXZPlane(a_Line2, a_Min.y);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.y > a_Line2.y) ? BLOCK_FACE_YP : BLOCK_FACE_YM;
Coeff = c;
}
c = a_Line1.LineCoeffToXZPlane(a_Line2, a_Max.y);
if ((c >= 0) && (c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.y > a_Line2.y) ? BLOCK_FACE_YP : BLOCK_FACE_YM;
Coeff = c;
}
c = a_Line1.LineCoeffToYZPlane(a_Line2, a_Min.x);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.x > a_Line2.x) ? BLOCK_FACE_XP : BLOCK_FACE_XM;
Coeff = c;
}
c = a_Line1.LineCoeffToYZPlane(a_Line2, a_Max.x);
if ((c >= 0) && (c < Coeff) && IsInside(a_Min, a_Max, a_Line1 + (a_Line2 - a_Line1) * c))
{
Face = (a_Line1.x > a_Line2.x) ? BLOCK_FACE_XP : BLOCK_FACE_XM;
Coeff = c;
}
if (Coeff >= Vector3d::NO_INTERSECTION)
{
// There has been no intersection
return false;
}
a_LineCoeff = Coeff;
a_Face = Face;
return true;
}
bool cBoundingBox::Intersect(const cBoundingBox & a_Other, cBoundingBox & a_Intersection)
{
a_Intersection.m_Min.x = std::max(m_Min.x, a_Other.m_Min.x);
a_Intersection.m_Max.x = std::min(m_Max.x, a_Other.m_Max.x);
if (a_Intersection.m_Min.x >= a_Intersection.m_Max.x)
{
return false;
}
a_Intersection.m_Min.y = std::max(m_Min.y, a_Other.m_Min.y);
a_Intersection.m_Max.y = std::min(m_Max.y, a_Other.m_Max.y);
if (a_Intersection.m_Min.y >= a_Intersection.m_Max.y)
{
return false;
}
a_Intersection.m_Min.z = std::max(m_Min.z, a_Other.m_Min.z);
a_Intersection.m_Max.z = std::min(m_Max.z, a_Other.m_Max.z);
if (a_Intersection.m_Min.z >= a_Intersection.m_Max.z)
{
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include "mysql.hpp"
#include "CQuery.hpp"
#include "CConnection.hpp"
#include "CDispatcher.hpp"
#include "COptions.hpp"
#include "CLog.hpp"
CConnection::CConnection(const string &host, const string &user, const string &passw, const string &db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG,
"CConnection::CConnection(this={}, host='{}', user='{}', passw='****', db='{}', options={})",
static_cast<const void *>(this), host, user, db, static_cast<const void *>(options));
assert(options != nullptr);
//initialize
m_Connection = mysql_init(nullptr);
if (m_Connection == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - MySQL initialization failed (not enough memory available)");
return;
}
if (options->GetOption<bool>(COptions::Type::SSL_ENABLE))
{
string
key = options->GetOption<string>(COptions::Type::SSL_KEY_FILE),
cert = options->GetOption<string>(COptions::Type::SSL_CERT_FILE),
ca = options->GetOption<string>(COptions::Type::SSL_CA_FILE),
capath = options->GetOption<string>(COptions::Type::SSL_CA_PATH),
cipher = options->GetOption<string>(COptions::Type::SSL_CIPHER);
mysql_ssl_set(m_Connection,
key.empty() ? nullptr : key.c_str(),
cert.empty() ? nullptr : cert.c_str(),
ca.empty() ? nullptr : ca.c_str(),
capath.empty() ? nullptr : capath.c_str(),
cipher.empty() ? nullptr : cipher.c_str());
}
//prepare connection flags through passed options
unsigned long connect_flags = 0;
if (options->GetOption<bool>(COptions::Type::MULTI_STATEMENTS) == true)
connect_flags |= CLIENT_MULTI_STATEMENTS;
//connect
auto *result = mysql_real_connect(m_Connection, host.c_str(),
user.c_str(), passw.c_str(), db.c_str(),
options->GetOption<unsigned int>(COptions::Type::SERVER_PORT),
nullptr, connect_flags);
if (result == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - establishing connection to MySQL database failed: #{} '{}'",
mysql_errno(m_Connection), mysql_error(m_Connection));
return;
}
m_IsConnected = true;
//set additional connection options
my_bool reconnect = options->GetOption<bool>(COptions::Type::AUTO_RECONNECT);
mysql_options(m_Connection, MYSQL_OPT_RECONNECT, &reconnect);
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::CConnection - new connection = {}",
static_cast<const void *>(m_Connection));
}
CConnection::~CConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::~CConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
if (IsConnected())
mysql_close(m_Connection);
}
bool CConnection::EscapeString(const char *src, string &dest)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::EscapeString(src='{}', this={}, connection={})",
src, static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false || src == nullptr)
return false;
const size_t src_len = strlen(src);
char *tmp_str = static_cast<char *>(malloc((src_len * 2 + 1) * sizeof(char)));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
mysql_real_escape_string(m_Connection, tmp_str, src, src_len);
dest.assign(tmp_str);
free(tmp_str);
return true;
}
bool CConnection::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::SetCharset(charset='{}', this={}, connection={})",
charset, static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false || charset.empty())
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
int error = mysql_set_character_set(m_Connection, charset.c_str());
if (error != 0)
return false;
return true;
}
bool CConnection::GetCharset(string &charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetCharset(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
charset = mysql_character_set_name(m_Connection);
return true;
}
bool CConnection::Execute(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::Execute(query={}, this={}, connection={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this),
static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
return IsConnected() && query->Execute(m_Connection);
}
bool CConnection::GetError(unsigned int &id, string &msg)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetError(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (m_Connection == nullptr)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
id = mysql_errno(m_Connection);
msg = mysql_error(m_Connection);
return true;
}
bool CConnection::GetStatus(string &stat)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetStatus(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
const char *stat_raw = mysql_stat(m_Connection);
if (stat_raw == nullptr)
return false;
stat = stat_raw;
return true;
}
CThreadedConnection::CThreadedConnection(
const string &host, const string &user, const string &passw, const string &db,
const COptions *options)
:
m_Connection(host, user, passw, db, options),
m_WorkerThreadActive(true),
m_WorkerThread(std::bind(&CThreadedConnection::WorkerFunc, this))
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
}
void CThreadedConnection::WorkerFunc()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::WorkerFunc(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
mysql_thread_init();
while (m_WorkerThreadActive)
{
Query_t query;
while (m_Queue.pop(query))
{
DispatchFunction_t func;
if (m_Connection.Execute(query))
{
func = std::bind(&CQuery::CallCallback, query);
}
else
{
unsigned int errorid = 0;
string error;
m_Connection.GetError(errorid, error);
func = std::bind(&CQuery::CallErrorCallback, query, errorid, error);
}
CDispatcher::Get()->Dispatch(std::move(func));
}
boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
}
mysql_thread_end();
}
CThreadedConnection::~CThreadedConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::~CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
while(m_Queue.empty() == false)
boost::this_thread::sleep_for(boost::chrono::milliseconds(20));
m_WorkerThreadActive = false;
m_WorkerThread.join();
}
CConnectionPool::CConnectionPool(
const size_t size, const string &host, const string &user, const string &passw, const string &db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::(size={}, this={})",
size, static_cast<const void *>(this));
SConnectionNode *node = m_CurrentNode = new SConnectionNode;
for (size_t i = 0; i != size; ++i)
{
node->Connection = new CThreadedConnection(host, user, passw, db, options);
node->Next = ((i + 1) != size) ? m_CurrentNode : (node = new SConnectionNode);
}
}
bool CConnectionPool::Queue(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::Queue(query={}, this={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
auto *connection = m_CurrentNode->Connection;
m_CurrentNode = m_CurrentNode->Next;
assert(m_CurrentNode != nullptr && connection != nullptr);
return connection->Queue(query);
}
bool CConnectionPool::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::SetCharset(charset='{}', this={})",
charset, static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
if (node->Connection->SetCharset(charset) == false)
return false;
} while ((node = node->Next) != m_CurrentNode);
return true;
}
CConnectionPool::~CConnectionPool()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::~CConnectionPool(this={})",
static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
delete node->Connection;
auto *old_node = node;
node = node->Next;
delete old_node;
} while (node != m_CurrentNode);
}
<commit_msg>lower sleep intervals<commit_after>#include "mysql.hpp"
#include "CQuery.hpp"
#include "CConnection.hpp"
#include "CDispatcher.hpp"
#include "COptions.hpp"
#include "CLog.hpp"
CConnection::CConnection(const string &host, const string &user, const string &passw, const string &db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG,
"CConnection::CConnection(this={}, host='{}', user='{}', passw='****', db='{}', options={})",
static_cast<const void *>(this), host, user, db, static_cast<const void *>(options));
assert(options != nullptr);
//initialize
m_Connection = mysql_init(nullptr);
if (m_Connection == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - MySQL initialization failed (not enough memory available)");
return;
}
if (options->GetOption<bool>(COptions::Type::SSL_ENABLE))
{
string
key = options->GetOption<string>(COptions::Type::SSL_KEY_FILE),
cert = options->GetOption<string>(COptions::Type::SSL_CERT_FILE),
ca = options->GetOption<string>(COptions::Type::SSL_CA_FILE),
capath = options->GetOption<string>(COptions::Type::SSL_CA_PATH),
cipher = options->GetOption<string>(COptions::Type::SSL_CIPHER);
mysql_ssl_set(m_Connection,
key.empty() ? nullptr : key.c_str(),
cert.empty() ? nullptr : cert.c_str(),
ca.empty() ? nullptr : ca.c_str(),
capath.empty() ? nullptr : capath.c_str(),
cipher.empty() ? nullptr : cipher.c_str());
}
//prepare connection flags through passed options
unsigned long connect_flags = 0;
if (options->GetOption<bool>(COptions::Type::MULTI_STATEMENTS) == true)
connect_flags |= CLIENT_MULTI_STATEMENTS;
//connect
auto *result = mysql_real_connect(m_Connection, host.c_str(),
user.c_str(), passw.c_str(), db.c_str(),
options->GetOption<unsigned int>(COptions::Type::SERVER_PORT),
nullptr, connect_flags);
if (result == nullptr)
{
CLog::Get()->Log(LogLevel::ERROR,
"CConnection::CConnection - establishing connection to MySQL database failed: #{} '{}'",
mysql_errno(m_Connection), mysql_error(m_Connection));
return;
}
m_IsConnected = true;
//set additional connection options
my_bool reconnect = options->GetOption<bool>(COptions::Type::AUTO_RECONNECT);
mysql_options(m_Connection, MYSQL_OPT_RECONNECT, &reconnect);
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::CConnection - new connection = {}",
static_cast<const void *>(m_Connection));
}
CConnection::~CConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::~CConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
if (IsConnected())
mysql_close(m_Connection);
}
bool CConnection::EscapeString(const char *src, string &dest)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::EscapeString(src='{}', this={}, connection={})",
src, static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false || src == nullptr)
return false;
const size_t src_len = strlen(src);
char *tmp_str = static_cast<char *>(malloc((src_len * 2 + 1) * sizeof(char)));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
mysql_real_escape_string(m_Connection, tmp_str, src, src_len);
dest.assign(tmp_str);
free(tmp_str);
return true;
}
bool CConnection::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::SetCharset(charset='{}', this={}, connection={})",
charset, static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false || charset.empty())
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
int error = mysql_set_character_set(m_Connection, charset.c_str());
if (error != 0)
return false;
return true;
}
bool CConnection::GetCharset(string &charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetCharset(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
charset = mysql_character_set_name(m_Connection);
return true;
}
bool CConnection::Execute(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::Execute(query={}, this={}, connection={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this),
static_cast<const void *>(m_Connection));
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
return IsConnected() && query->Execute(m_Connection);
}
bool CConnection::GetError(unsigned int &id, string &msg)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetError(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (m_Connection == nullptr)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
id = mysql_errno(m_Connection);
msg = mysql_error(m_Connection);
return true;
}
bool CConnection::GetStatus(string &stat)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnection::GetStatus(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(m_Connection));
if (IsConnected() == false)
return false;
boost::lock_guard<boost::mutex> lock_guard(m_Mutex);
const char *stat_raw = mysql_stat(m_Connection);
if (stat_raw == nullptr)
return false;
stat = stat_raw;
return true;
}
CThreadedConnection::CThreadedConnection(
const string &host, const string &user, const string &passw, const string &db,
const COptions *options)
:
m_Connection(host, user, passw, db, options),
m_WorkerThreadActive(true),
m_WorkerThread(std::bind(&CThreadedConnection::WorkerFunc, this))
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
}
void CThreadedConnection::WorkerFunc()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::WorkerFunc(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
mysql_thread_init();
while (m_WorkerThreadActive)
{
Query_t query;
while (m_Queue.pop(query))
{
DispatchFunction_t func;
if (m_Connection.Execute(query))
{
func = std::bind(&CQuery::CallCallback, query);
}
else
{
unsigned int errorid = 0;
string error;
m_Connection.GetError(errorid, error);
func = std::bind(&CQuery::CallErrorCallback, query, errorid, error);
}
CDispatcher::Get()->Dispatch(std::move(func));
}
boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
}
mysql_thread_end();
}
CThreadedConnection::~CThreadedConnection()
{
CLog::Get()->Log(LogLevel::DEBUG, "CThreadedConnection::~CThreadedConnection(this={}, connection={})",
static_cast<const void *>(this), static_cast<const void *>(&m_Connection));
while(m_Queue.empty() == false)
boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
m_WorkerThreadActive = false;
m_WorkerThread.join();
}
CConnectionPool::CConnectionPool(
const size_t size, const string &host, const string &user, const string &passw, const string &db,
const COptions *options)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::(size={}, this={})",
size, static_cast<const void *>(this));
SConnectionNode *node = m_CurrentNode = new SConnectionNode;
for (size_t i = 0; i != size; ++i)
{
node->Connection = new CThreadedConnection(host, user, passw, db, options);
node->Next = ((i + 1) != size) ? m_CurrentNode : (node = new SConnectionNode);
}
}
bool CConnectionPool::Queue(Query_t query)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::Queue(query={}, this={})",
static_cast<const void *>(query.get()), static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
auto *connection = m_CurrentNode->Connection;
m_CurrentNode = m_CurrentNode->Next;
assert(m_CurrentNode != nullptr && connection != nullptr);
return connection->Queue(query);
}
bool CConnectionPool::SetCharset(string charset)
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::SetCharset(charset='{}', this={})",
charset, static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
if (node->Connection->SetCharset(charset) == false)
return false;
} while ((node = node->Next) != m_CurrentNode);
return true;
}
CConnectionPool::~CConnectionPool()
{
CLog::Get()->Log(LogLevel::DEBUG, "CConnectionPool::~CConnectionPool(this={})",
static_cast<const void *>(this));
boost::lock_guard<boost::mutex> lock_guard(m_PoolMutex);
SConnectionNode *node = m_CurrentNode;
do
{
delete node->Connection;
auto *old_node = node;
node = node->Next;
delete old_node;
} while (node != m_CurrentNode);
}
<|endoftext|> |
<commit_before>#include "ModuleManager.hpp"
#include <QPluginLoader>
#include <QApplication>
#include <QObject>
#include <QDir>
#include <QObjectList>
#include <QStringList>
#include <string>
#include "Logger.hpp"
#include "ModuleBase.hpp"
#include "ModuleInterface.hpp"
#include "ErrorException.hpp"
#include "InvalidConfigException.hpp"
#include "DataManager.hpp"
#include "GUIEventDispatcher.hpp"
using namespace uipf;
using namespace std;
// loads the configuration and stores in the ModuleManager
/*
conf Configuration file, which has to be executed
*/
ModuleManager::ModuleManager()
{
initModules();
}
ModuleManager::~ModuleManager()
{
// delete all the pluginloaders
map<string, QPluginLoader*>::iterator it = plugins_.begin();
for (; it!=plugins_.end(); ++it) {
delete it->second;
}
}
// executes the Configuration file
/*
*/
void ModuleManager::run(Configuration config){
//reset StopSignal
context_.bStopRequested_ = false;
// get processing chain
map<string, ProcessingStep> chain = config.getProcessingChain();
map<string, ProcessingStep> chainTmp;
chainTmp.insert(chain.begin(), chain.end());
// contains the names of the processing steps in the correct order
vector<string> sortedChain;
// iterate over all processing steps and order them
while(!chainTmp.empty()){
map<string, ProcessingStep>::iterator itProSt = chainTmp.begin();
while(itProSt!=chainTmp.end()) {
// add all modules without any dependencies
if(itProSt->second.inputs.size() == 0){
sortedChain.push_back(itProSt->first);
// delete and set pointer to next element
itProSt = chainTmp.erase(itProSt);
} else {
// go through dependencies, and add only the modules, where module
// on which they depend have already been added
map<string, pair<string,string> >::iterator it = itProSt->second.inputs.begin();
int i = 1;
for (; it!=itProSt->second.inputs.end(); ++it) {
if (find(sortedChain.begin(), sortedChain.end(), it->second.first) != sortedChain.end()){
i *=1;
} else{
i *=0;
}
}
if (i == 1){
sortedChain.push_back(itProSt->first);
// delete and set pointer to next element
itProSt = chainTmp.erase(itProSt);
} else {
// try next element
++itProSt;
}
}
}
}
// contains the outputs of the processing steps
map<string, map<string, Data::ptr>* > stepsOutputs;
LOG_I( "Starting processing chain." );
// iterate over the sortedChain and run the modules in the order given by the chain
for (unsigned int i=0; i<sortedChain.size(); i++){
ProcessingStep proSt = chain[sortedChain[i]];
// load the module
ModuleInterface* module;
string moduleName = proSt.module;
if (hasModule(moduleName)) {
module = loadModule(moduleName);
context_.processingStepName_ = proSt.name;
module->setContext(&context_);
} else {
LOG_E( "Module '" + moduleName + "' could not be found." );
break;
}
// prepare an empty map of outputs that will be filled by the module
map<string, Data::ptr >* outputs = new map<string, Data::ptr>();
// inputs are references to the data pointer to allow sending one output to multiple steps
map<string, Data::ptr& > inputs;
// fill the inputs of the current processing step by taking it from the stored outputs
map<string, pair<string, string> >::iterator it = proSt.inputs.begin();
for (; it!=proSt.inputs.end(); ++it) {
map<string, Data::ptr>* out = stepsOutputs[it->second.first];
Data::ptr& pt = out->find(it->second.second)->second;
inputs.insert(pair<string, Data::ptr&>(it->first, pt));
}
LOG_I( "Running step '" + proSt.name + "'..." );
try {
DataManager dataMnrg(inputs, proSt.params, *outputs);
module->run(dataMnrg);
} catch (ErrorException& e) {
LOG_E( string("Error: ") + e.what() );
break;
} catch (InvalidConfigException& e) {
LOG_E( string("Invalid config: ") + e.what() );
break;
} catch (std::exception& e) {
LOG_E( string("Error: module threw exception: ") + e.what() );
break;
}
// update the progress bar in the GUI
GUIEventDispatcher::instance()->triggerReportProgress(static_cast<float>(i+1)/static_cast<float>(sortedChain.size())*100.0f);
LOG_I( "Done with step '" + proSt.name + "'." );
// check if stop button was pressed
if (context_.bStopRequested_ )
{
LOG_I("processing stopped");
break;
}
// fill the outputs of the current processing step
stepsOutputs.insert(pair<string, map<string, Data::ptr>* > (proSt.name, outputs));
// TODO delete module, check for side effects with the data pointers first
}
// delete the ouput map
map<string, map<string, Data::ptr>* >::iterator it = stepsOutputs.begin();
for (; it!=stepsOutputs.end(); ++it) {
delete it->second;
}
LOG_I( "Finished processing chain." );
}
// initialize all modules by creating a map of module names and the plugin loader instance
// that can be used later to instantiate the module
void ModuleManager::initModules()
{
QDir pluginsDir = QDir(qApp->applicationDirPath());
foreach (QString fileName, pluginsDir.entryList(QDir::Files))
{
QPluginLoader* loader = new QPluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader->instance();
if (plugin) {
Logger::instance()->Info("found module: " + fileName.toStdString());
ModuleInterface* iModule = qobject_cast<ModuleInterface* >(plugin);
plugins_.insert( std::pair<std::string, QPluginLoader*>(iModule->name(), loader) );
delete iModule;
}
}
}
// check whether a module exists
bool ModuleManager::hasModule(const std::string& name){
return (plugins_.count(name) > 0);
}
// creates an instance of a module and returns it
ModuleInterface* ModuleManager::loadModule(const std::string& name)
{
if (plugins_.count(name) > 0) {
QPluginLoader* loader = plugins_[name];
QObject *plugin = loader->instance();
if (plugin) {
// Logger::instance()->Info("load module: " + name);
return qobject_cast<ModuleInterface* >(plugin);
}
}
return nullptr;
}
// returns the meta data of a module
MetaData ModuleManager::getModuleMetaData(const std::string& name)
{
ModuleInterface* module = loadModule(name);
MetaData metaData = module->getMetaData();
delete module;
return metaData;
}
// returns the meta data for all modules indexed by module name
map<string, MetaData> ModuleManager::getAllModuleMetaData()
{
map<string, MetaData> result;
for(auto it = plugins_.cbegin(); it != plugins_.end(); ++it) {
result.insert( pair<string, MetaData>( it->first, getModuleMetaData(it->first) ) );
}
return result;
}
<commit_msg>delete unused output of modules<commit_after>#include "ModuleManager.hpp"
#include <QPluginLoader>
#include <QApplication>
#include <QObject>
#include <QDir>
#include <QObjectList>
#include <QStringList>
#include <string>
#include "Logger.hpp"
#include "ModuleBase.hpp"
#include "ModuleInterface.hpp"
#include "ErrorException.hpp"
#include "InvalidConfigException.hpp"
#include "DataManager.hpp"
#include "GUIEventDispatcher.hpp"
using namespace uipf;
using namespace std;
// loads the configuration and stores in the ModuleManager
/*
conf Configuration file, which has to be executed
*/
ModuleManager::ModuleManager()
{
initModules();
}
ModuleManager::~ModuleManager()
{
// delete all the pluginloaders
map<string, QPluginLoader*>::iterator it = plugins_.begin();
for (; it!=plugins_.end(); ++it) {
delete it->second;
}
}
// executes the Configuration file
/*
*/
void ModuleManager::run(Configuration config){
//reset StopSignal
context_.bStopRequested_ = false;
// get processing chain
map<string, ProcessingStep> chain = config.getProcessingChain();
map<string, ProcessingStep> chainTmp;
chainTmp.insert(chain.begin(), chain.end());
// contains the names of the processing steps in the correct order
vector<string> sortedChain;
// iterate over all processing steps and order them
while(!chainTmp.empty()){
map<string, ProcessingStep>::iterator itProSt = chainTmp.begin();
while(itProSt!=chainTmp.end()) {
// add all modules without any dependencies
if(itProSt->second.inputs.size() == 0){
sortedChain.push_back(itProSt->first);
// delete and set pointer to next element
itProSt = chainTmp.erase(itProSt);
} else {
// go through dependencies, and add only the modules, where module
// on which they depend have already been added
map<string, pair<string,string> >::iterator it = itProSt->second.inputs.begin();
int i = 1;
for (; it!=itProSt->second.inputs.end(); ++it) {
if (find(sortedChain.begin(), sortedChain.end(), it->second.first) != sortedChain.end()){
i *=1;
} else{
i *=0;
}
}
if (i == 1){
sortedChain.push_back(itProSt->first);
// delete and set pointer to next element
itProSt = chainTmp.erase(itProSt);
} else {
// try next element
++itProSt;
}
}
}
}
// contains the outputs of the processing steps
map<string, map<string, Data::ptr>* > stepsOutputs;
LOG_I( "Starting processing chain." );
// iterate over the sortedChain and run the modules in the order given by the chain
for (unsigned int i=0; i<sortedChain.size(); i++){
ProcessingStep proSt = chain[sortedChain[i]];
// load the module
ModuleInterface* module;
string moduleName = proSt.module;
if (hasModule(moduleName)) {
module = loadModule(moduleName);
context_.processingStepName_ = proSt.name;
module->setContext(&context_);
} else {
LOG_E( "Module '" + moduleName + "' could not be found." );
break;
}
// prepare an empty map of outputs that will be filled by the module
map<string, Data::ptr >* outputs = new map<string, Data::ptr>();
// inputs are references to the data pointer to allow sending one output to multiple steps
map<string, Data::ptr& > inputs;
// fill the inputs of the current processing step by taking it from the stored outputs
map<string, pair<string, string> >::iterator it = proSt.inputs.begin();
for (; it!=proSt.inputs.end(); ++it) {
map<string, Data::ptr>* out = stepsOutputs[it->second.first];
Data::ptr& pt = out->find(it->second.second)->second;
inputs.insert(pair<string, Data::ptr&>(it->first, pt));
}
LOG_I( "Running step '" + proSt.name + "'..." );
try {
DataManager dataMnrg(inputs, proSt.params, *outputs);
module->run(dataMnrg);
} catch (ErrorException& e) {
LOG_E( string("Error: ") + e.what() );
break;
} catch (InvalidConfigException& e) {
LOG_E( string("Invalid config: ") + e.what() );
break;
} catch (std::exception& e) {
LOG_E( string("Error: module threw exception: ") + e.what() );
break;
}
// update the progress bar in the GUI
GUIEventDispatcher::instance()->triggerReportProgress(static_cast<float>(i+1)/static_cast<float>(sortedChain.size())*100.0f);
LOG_I( "Done with step '" + proSt.name + "'." );
// check if stop button was pressed
if (context_.bStopRequested_ )
{
LOG_I("processing stopped");
break;
}
// fill the outputs of the current processing step
stepsOutputs.insert(pair<string, map<string, Data::ptr>* > (proSt.name, outputs));
// TODO delete module, check for side effects with the data pointers first
// free some outputs that are not needed anymore
map<string, map<string, Data::ptr>* >::iterator osit = stepsOutputs.begin();
for (; osit!=stepsOutputs.end(); ++osit) {
string outputStep = osit->first;
for (auto oit = osit->second->begin(); oit!=osit->second->end(); ++oit) {
string outputName = oit->first;
// iterate over the future steps to see if this output is requested
bool requested = false;
for (unsigned int s = i + 1; s<sortedChain.size() && !requested; s++){
ProcessingStep fstep = chain[sortedChain[s]];
for (auto iit=fstep.inputs.cbegin(); iit != fstep.inputs.end(); ++iit) {
if (outputStep.compare(iit->second.first) == 0 && outputName.compare(iit->second.second) == 0) {
requested = true;
break;
}
}
}
if (!requested) {
// output is not requested in any further step, delete it
LOG_I(string("deleted ") + outputStep + string(".") + outputName);
oit = osit->second->erase(oit);
}
}
}
}
// delete the ouput map
map<string, map<string, Data::ptr>* >::iterator it = stepsOutputs.begin();
for (; it!=stepsOutputs.end(); ++it) {
delete it->second;
}
LOG_I( "Finished processing chain." );
}
// initialize all modules by creating a map of module names and the plugin loader instance
// that can be used later to instantiate the module
void ModuleManager::initModules()
{
QDir pluginsDir = QDir(qApp->applicationDirPath());
foreach (QString fileName, pluginsDir.entryList(QDir::Files))
{
QPluginLoader* loader = new QPluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader->instance();
if (plugin) {
Logger::instance()->Info("found module: " + fileName.toStdString());
ModuleInterface* iModule = qobject_cast<ModuleInterface* >(plugin);
plugins_.insert( std::pair<std::string, QPluginLoader*>(iModule->name(), loader) );
delete iModule;
}
}
}
// check whether a module exists
bool ModuleManager::hasModule(const std::string& name){
return (plugins_.count(name) > 0);
}
// creates an instance of a module and returns it
ModuleInterface* ModuleManager::loadModule(const std::string& name)
{
if (plugins_.count(name) > 0) {
QPluginLoader* loader = plugins_[name];
QObject *plugin = loader->instance();
if (plugin) {
// Logger::instance()->Info("load module: " + name);
return qobject_cast<ModuleInterface* >(plugin);
}
}
return nullptr;
}
// returns the meta data of a module
MetaData ModuleManager::getModuleMetaData(const std::string& name)
{
ModuleInterface* module = loadModule(name);
MetaData metaData = module->getMetaData();
delete module;
return metaData;
}
// returns the meta data for all modules indexed by module name
map<string, MetaData> ModuleManager::getAllModuleMetaData()
{
map<string, MetaData> result;
for(auto it = plugins_.cbegin(); it != plugins_.end(); ++it) {
result.insert( pair<string, MetaData>( it->first, getModuleMetaData(it->first) ) );
}
return result;
}
<|endoftext|> |
<commit_before>#include "segmatch/descriptors/eigenvalue_based.hpp"
#include <cfenv>
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <glog/logging.h>
#pragma STDC FENV_ACCESS on
namespace segmatch {
/// \brief Utility function for swapping two values.
template<typename T>
bool swap_if_gt(T& a, T& b) {
if (a > b) {
std::swap(a, b);
return true;
}
return false;
}
// EigenvalueBasedDescriptor methods definition
EigenvalueBasedDescriptor::EigenvalueBasedDescriptor(const DescriptorsParameters& parameters) {}
void EigenvalueBasedDescriptor::describe(const Segment& segment, Features* features) {
CHECK_NOTNULL(features);
std::feclearexcept(FE_ALL_EXCEPT);
// Find the variances.
const size_t kNPoints = segment.point_cloud.points.size();
PointCloud variances;
for (size_t i = 0u; i < kNPoints; ++i) {
variances.push_back(PclPoint());
variances.points[i].x = segment.point_cloud.points[i].x - segment.centroid.x;
variances.points[i].y = segment.point_cloud.points[i].y - segment.centroid.y;
variances.points[i].z = segment.point_cloud.points[i].z - segment.centroid.z;
}
// Find the covariance matrix. Since it is symmetric, we only bother with the upper diagonal.
const std::vector<size_t> row_indices_to_access = {0,0,0,1,1,2};
const std::vector<size_t> col_indices_to_access = {0,1,2,1,2,2};
Eigen::Matrix3f covariance_matrix;
for (size_t i = 0u; i < row_indices_to_access.size(); ++i) {
const size_t row = row_indices_to_access[i];
const size_t col = col_indices_to_access[i];
double covariance = 0;
for (size_t k = 0u; k < kNPoints; ++k) {
covariance += variances.points[k].data[row] * variances.points[k].data[col];
}
covariance /= kNPoints;
covariance_matrix(row,col) = covariance;
covariance_matrix(col,row) = covariance;
}
// Compute eigenvalues of covariance matrix.
constexpr bool compute_eigenvectors = false;
Eigen::EigenSolver<Eigen::Matrix3f> eigenvalues_solver(covariance_matrix, compute_eigenvectors);
std::vector<float> eigenvalues(3, 0.0);
eigenvalues.at(0) = eigenvalues_solver.eigenvalues()[0].real();
eigenvalues.at(1) = eigenvalues_solver.eigenvalues()[1].real();
eigenvalues.at(2) = eigenvalues_solver.eigenvalues()[2].real();
if (eigenvalues_solver.eigenvalues()[0].imag() != 0.0 ||
eigenvalues_solver.eigenvalues()[1].imag() != 0.0 ||
eigenvalues_solver.eigenvalues()[2].imag() != 0.0 ) {
LOG(ERROR) << "Eigenvalues should not have non-zero imaginary component.";
}
// Sort eigenvalues from smallest to largest.
swap_if_gt(eigenvalues.at(0), eigenvalues.at(1));
swap_if_gt(eigenvalues.at(0), eigenvalues.at(2));
swap_if_gt(eigenvalues.at(1), eigenvalues.at(2));
// Normalize eigenvalues.
double sum_eigenvalues = eigenvalues.at(0) + eigenvalues.at(1) + eigenvalues.at(2);
double e1 = eigenvalues.at(0) / sum_eigenvalues;
double e2 = eigenvalues.at(1) / sum_eigenvalues;
double e3 = eigenvalues.at(2) / sum_eigenvalues;
LOG_IF(ERROR, e1 == e2 || e2 == e3 || e1 == e3) << "Eigenvalues should not be equal.";
// Store inside features.
const double sum_of_eigenvalues = e1 + e2 + e3;
constexpr double kOneThird = 1.0/3.0;
CHECK_NE(e1, 0.0);
CHECK_NE(sum_of_eigenvalues, 0.0);
Feature eigenvalue_feature;
eigenvalue_feature.push_back(FeatureValue("linearity", (e1 - e2) / e1));
eigenvalue_feature.push_back(FeatureValue("planarity", (e2 - e3) / e1));
eigenvalue_feature.push_back(FeatureValue("scattering", e3 / e1));
eigenvalue_feature.push_back(FeatureValue("omnivariance", std::pow(e1 * e2 * e3, kOneThird)));
eigenvalue_feature.push_back(FeatureValue("anisotropy", (e1 - e3) / e1));
eigenvalue_feature.push_back(FeatureValue("eigen_entropy",
(e1 * std::log(e1)) + (e2 * std::log(e2)) + (e3 * std::log(e3))));
eigenvalue_feature.push_back(FeatureValue("change_of_curvature", e3 / sum_of_eigenvalues));
CHECK_EQ(eigenvalue_feature.size(), kDimension) << "Feature has the wrong dimension";
features->push_back(eigenvalue_feature);
// Check that there were no overflows, underflows, or invalid float operations.
if (std::fetestexcept(FE_OVERFLOW)) {
LOG(ERROR) << "Overflow error in eigenvalue feature computation.";
} else if (std::fetestexcept(FE_UNDERFLOW)) {
LOG(ERROR) << "Underflow error in eigenvalue feature computation.";
} else if (std::fetestexcept(FE_INVALID)) {
LOG(ERROR) << "Invalid Flag error in eigenvalue feature computation.";
} else if (std::fetestexcept(FE_DIVBYZERO)) {
LOG(ERROR) << "Divide by zero error in eigenvalue feature computation.";
}
}
} // namespace segmatch
<commit_msg>added normalization of eigen features<commit_after>#include "segmatch/descriptors/eigenvalue_based.hpp"
#include <cfenv>
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <glog/logging.h>
#pragma STDC FENV_ACCESS on
namespace segmatch {
/// \brief Utility function for swapping two values.
template<typename T>
bool swap_if_gt(T& a, T& b) {
if (a > b) {
std::swap(a, b);
return true;
}
return false;
}
// EigenvalueBasedDescriptor methods definition
EigenvalueBasedDescriptor::EigenvalueBasedDescriptor(const DescriptorsParameters& parameters) {}
void EigenvalueBasedDescriptor::describe(const Segment& segment, Features* features) {
CHECK_NOTNULL(features);
std::feclearexcept(FE_ALL_EXCEPT);
// Find the variances.
const size_t kNPoints = segment.point_cloud.points.size();
PointCloud variances;
for (size_t i = 0u; i < kNPoints; ++i) {
variances.push_back(PclPoint());
variances.points[i].x = segment.point_cloud.points[i].x - segment.centroid.x;
variances.points[i].y = segment.point_cloud.points[i].y - segment.centroid.y;
variances.points[i].z = segment.point_cloud.points[i].z - segment.centroid.z;
}
// Find the covariance matrix. Since it is symmetric, we only bother with the upper diagonal.
const std::vector<size_t> row_indices_to_access = {0,0,0,1,1,2};
const std::vector<size_t> col_indices_to_access = {0,1,2,1,2,2};
Eigen::Matrix3f covariance_matrix;
for (size_t i = 0u; i < row_indices_to_access.size(); ++i) {
const size_t row = row_indices_to_access[i];
const size_t col = col_indices_to_access[i];
double covariance = 0;
for (size_t k = 0u; k < kNPoints; ++k) {
covariance += variances.points[k].data[row] * variances.points[k].data[col];
}
covariance /= kNPoints;
covariance_matrix(row,col) = covariance;
covariance_matrix(col,row) = covariance;
}
// Compute eigenvalues of covariance matrix.
constexpr bool compute_eigenvectors = false;
Eigen::EigenSolver<Eigen::Matrix3f> eigenvalues_solver(covariance_matrix, compute_eigenvectors);
std::vector<float> eigenvalues(3, 0.0);
eigenvalues.at(0) = eigenvalues_solver.eigenvalues()[0].real();
eigenvalues.at(1) = eigenvalues_solver.eigenvalues()[1].real();
eigenvalues.at(2) = eigenvalues_solver.eigenvalues()[2].real();
if (eigenvalues_solver.eigenvalues()[0].imag() != 0.0 ||
eigenvalues_solver.eigenvalues()[1].imag() != 0.0 ||
eigenvalues_solver.eigenvalues()[2].imag() != 0.0 ) {
LOG(ERROR) << "Eigenvalues should not have non-zero imaginary component.";
}
// Sort eigenvalues from smallest to largest.
swap_if_gt(eigenvalues.at(0), eigenvalues.at(1));
swap_if_gt(eigenvalues.at(0), eigenvalues.at(2));
swap_if_gt(eigenvalues.at(1), eigenvalues.at(2));
// Normalize eigenvalues.
double sum_eigenvalues = eigenvalues.at(0) + eigenvalues.at(1) + eigenvalues.at(2);
double e1 = eigenvalues.at(0) / sum_eigenvalues;
double e2 = eigenvalues.at(1) / sum_eigenvalues;
double e3 = eigenvalues.at(2) / sum_eigenvalues;
LOG_IF(ERROR, e1 == e2 || e2 == e3 || e1 == e3) << "Eigenvalues should not be equal.";
// Store inside features.
const double sum_of_eigenvalues = e1 + e2 + e3;
constexpr double kOneThird = 1.0/3.0;
CHECK_NE(e1, 0.0);
CHECK_NE(sum_of_eigenvalues, 0.0);
const double kNormalizationPercentile = 0.9;
const double kLinearityMax = 28890.9 / kNormalizationPercentile;
const double kPlanarityMax = 95919.2 / kNormalizationPercentile;
const double kScatteringMax = 124811 / kNormalizationPercentile;
const double kOmnivarianceMax = 0.278636 / kNormalizationPercentile;
const double kAnisotropyMax = 124810 / kNormalizationPercentile;
const double kEigenEntropyMax = 0.956129 / kNormalizationPercentile;
const double kChangeOfCurvatureMax = 0.99702 / kNormalizationPercentile;
Feature eigenvalue_feature;
eigenvalue_feature.push_back(FeatureValue("linearity", (e1 - e2) / e1 / kLinearityMax));
eigenvalue_feature.push_back(FeatureValue("planarity", (e2 - e3) / e1 / kPlanarityMax));
eigenvalue_feature.push_back(FeatureValue("scattering", e3 / e1 / kScatteringMax));
eigenvalue_feature.push_back(FeatureValue("omnivariance", std::pow(e1 * e2 * e3, kOneThird) / kOmnivarianceMax));
eigenvalue_feature.push_back(FeatureValue("anisotropy", (e1 - e3) / e1 / kAnisotropyMax));
eigenvalue_feature.push_back(FeatureValue("eigen_entropy",
(e1 * std::log(e1)) + (e2 * std::log(e2)) + (e3 * std::log(e3)) / kEigenEntropyMax));
eigenvalue_feature.push_back(FeatureValue("change_of_curvature", e3 / sum_of_eigenvalues / kChangeOfCurvatureMax));
CHECK_EQ(eigenvalue_feature.size(), kDimension) << "Feature has the wrong dimension";
features->push_back(eigenvalue_feature);
// Check that there were no overflows, underflows, or invalid float operations.
if (std::fetestexcept(FE_OVERFLOW)) {
LOG(ERROR) << "Overflow error in eigenvalue feature computation.";
} else if (std::fetestexcept(FE_UNDERFLOW)) {
LOG(ERROR) << "Underflow error in eigenvalue feature computation.";
} else if (std::fetestexcept(FE_INVALID)) {
LOG(ERROR) << "Invalid Flag error in eigenvalue feature computation.";
} else if (std::fetestexcept(FE_DIVBYZERO)) {
LOG(ERROR) << "Divide by zero error in eigenvalue feature computation.";
}
}
} // namespace segmatch
<|endoftext|> |
<commit_before>/* StreamedMedia channel client-side proxy
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2009 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/StreamedMediaChannel>
#include "TelepathyQt4/Client/_gen/streamed-media-channel.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/ContactManager>
#include <TelepathyQt4/Client/PendingVoidMethodCall>
#include <QHash>
namespace Telepathy
{
namespace Client
{
struct MediaStream::Private
{
Private(StreamedMediaChannel *channel, uint id,
uint contactHandle, MediaStreamType type,
MediaStreamState state, MediaStreamDirection direction,
MediaStreamPendingSend pendingSend)
: id(id), type(type), state(state),
direction(direction), pendingSend(pendingSend)
{
ContactManager *contactManager = channel->connection()->contactManager();
contact = contactManager->lookupContactByHandle(contactHandle);
}
StreamedMediaChannel *channel;
uint id;
QSharedPointer<Contact> contact;
MediaStreamType type;
MediaStreamState state;
MediaStreamDirection direction;
MediaStreamPendingSend pendingSend;
};
MediaStream::MediaStream(StreamedMediaChannel *channel, uint id,
uint contactHandle, MediaStreamType type,
MediaStreamState state, MediaStreamDirection direction,
MediaStreamPendingSend pendingSend)
: QObject(),
mPriv(new Private(channel, id, contactHandle, type,
state, direction, pendingSend))
{
}
MediaStream::~MediaStream()
{
delete mPriv;
}
StreamedMediaChannel *MediaStream::channel() const
{
return mPriv->channel;
}
uint MediaStream::id() const
{
return mPriv->id;
}
QSharedPointer<Contact> MediaStream::contact() const
{
return mPriv->contact;
}
Telepathy::MediaStreamState MediaStream::state() const
{
return mPriv->state;
}
Telepathy::MediaStreamType MediaStream::type() const
{
return mPriv->type;
}
bool MediaStream::sending() const
{
return (mPriv->direction & Telepathy::MediaStreamDirectionSend ||
mPriv->direction & Telepathy::MediaStreamDirectionBidirectional);
}
bool MediaStream::receiving() const
{
return (mPriv->direction & Telepathy::MediaStreamDirectionReceive ||
mPriv->direction & Telepathy::MediaStreamDirectionBidirectional);
}
bool MediaStream::localSendingRequested() const
{
return mPriv->pendingSend & MediaStreamPendingLocalSend;
}
bool MediaStream::remoteSendingRequested() const
{
return mPriv->pendingSend & MediaStreamPendingRemoteSend;
}
Telepathy::MediaStreamDirection MediaStream::direction() const
{
return mPriv->direction;
}
Telepathy::MediaStreamPendingSend MediaStream::pendingSend() const
{
return mPriv->pendingSend;
}
PendingOperation *MediaStream::remove()
{
return mPriv->channel->removeStreams(Telepathy::UIntList() << mPriv->id);
}
PendingOperation *MediaStream::requestStreamDirection(
Telepathy::MediaStreamDirection direction)
{
return new PendingVoidMethodCall(this,
mPriv->channel->streamedMediaInterface()->RequestStreamDirection(mPriv->id, direction));
}
void MediaStream::setDirection(Telepathy::MediaStreamDirection direction,
Telepathy::MediaStreamPendingSend pendingSend)
{
mPriv->direction = direction;
mPriv->pendingSend = pendingSend;
emit directionChanged(direction, pendingSend);
}
void MediaStream::setState(Telepathy::MediaStreamState state)
{
mPriv->state = state;
emit stateChanged(state);
}
struct StreamedMediaChannel::Private
{
Private(StreamedMediaChannel *parent);
~Private();
static void introspectStreams(Private *self);
// Public object
StreamedMediaChannel *parent;
ReadinessHelper *readinessHelper;
// Introspection
bool initialStreamsReceived;
QHash<uint, QSharedPointer<MediaStream> > streams;
};
StreamedMediaChannel::Private::Private(StreamedMediaChannel *parent)
: parent(parent),
readinessHelper(parent->readinessHelper()),
initialStreamsReceived(false)
{
ReadinessHelper::Introspectables introspectables;
ReadinessHelper::Introspectable introspectableStreams(
QSet<uint>() << 0, // makesSenseForStatuses
Features() << Channel::FeatureCore, // dependsOnFeatures (core)
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &Private::introspectStreams,
this);
introspectables[FeatureStreams] = introspectableStreams;
readinessHelper->addIntrospectables(introspectables);
}
StreamedMediaChannel::Private::~Private()
{
}
void StreamedMediaChannel::Private::introspectStreams(StreamedMediaChannel::Private *self)
{
StreamedMediaChannel *parent = self->parent;
ChannelTypeStreamedMediaInterface *streamedMediaInterface =
parent->streamedMediaInterface();
parent->connect(streamedMediaInterface,
SIGNAL(StreamAdded(uint, uint, uint)),
SLOT(onStreamAdded(uint, uint, uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamRemoved(uint)),
SLOT(onStreamRemoved(uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamDirectionChanged(uint, uint, uint)),
SLOT(onStreamDirectionChanged(uint, uint, uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamStateChanged(uint, uint)),
SLOT(onStreamStateChanged(uint, uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamError(uint, uint, const QString &)),
SLOT(onStreamError(uint, uint, const QString &)));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
streamedMediaInterface->ListStreams(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(gotStreams(QDBusPendingCallWatcher *)));
}
/**
* \class StreamedMediaChannel
* \ingroup clientchannel
* \headerfile TelepathyQt4/Client/streamed-media-channel.h <TelepathyQt4/Client/StreamedMediaChannel>
*
* High-level proxy object for accessing remote %Channel objects of the
* StreamedMedia channel type.
*
* This subclass of Channel will eventually provide a high-level API for the
* StreamedMedia interface. Until then, it's just a Channel.
*/
const Feature StreamedMediaChannel::FeatureStreams = Feature(StreamedMediaChannel::staticMetaObject.className(), 0);
/**
* Creates a StreamedMediaChannel associated with the given object on the same
* service as the given connection.
*
* \param connection Connection owning this StreamedMediaChannel, and
* specifying the service.
* \param objectPath Path to the object on the service.
* \param immutableProperties The immutable properties of the channel, as
* signalled by NewChannels or returned by
* CreateChannel or EnsureChannel
* \param parent Passed to the parent class constructor.
*/
StreamedMediaChannel::StreamedMediaChannel(Connection *connection,
const QString &objectPath,
const QVariantMap &immutableProperties,
QObject *parent)
: Channel(connection, objectPath, immutableProperties, parent),
mPriv(new Private(this))
{
}
/**
* Class destructor.
*/
StreamedMediaChannel::~StreamedMediaChannel()
{
delete mPriv;
}
MediaStreams StreamedMediaChannel::streams() const
{
return mPriv->streams.values();
}
bool StreamedMediaChannel::awaitingLocalAnswer() const
{
return groupSelfHandleIsLocalPending();
}
bool StreamedMediaChannel::awaitingRemoteAnswer() const
{
return !groupRemotePendingContacts().isEmpty();
}
PendingOperation *StreamedMediaChannel::acceptCall()
{
return groupAddSelfHandle();
}
PendingOperation *StreamedMediaChannel::removeStreams(MediaStreams streams)
{
Telepathy::UIntList ids;
foreach (const QSharedPointer<MediaStream> &stream, streams) {
ids << stream->id();
}
return removeStreams(ids);
}
PendingOperation *StreamedMediaChannel::removeStreams(const Telepathy::UIntList &ids)
{
return new PendingVoidMethodCall(this,
streamedMediaInterface()->RemoveStreams(ids));
}
PendingOperation *StreamedMediaChannel::requestStreams(
QSharedPointer<Telepathy::Client::Contact> contact,
QList<Telepathy::MediaStreamType> types)
{
Telepathy::UIntList l;
foreach (Telepathy::MediaStreamType type, types) {
l << type;
}
return new PendingVoidMethodCall(this,
streamedMediaInterface()->RequestStreams(
contact->handle()[0], l));
}
void StreamedMediaChannel::gotStreams(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "StreamedMedia::ListStreams()"
" failed with " << reply.error().name() << ": " <<
reply.error().message();
mPriv->readinessHelper->setIntrospectCompleted(FeatureStreams,
false, reply.error());
return;
}
debug() << "Got reply to StreamedMedia::ListStreams()";
mPriv->initialStreamsReceived = true;
MediaStreamInfoList list = qdbus_cast<MediaStreamInfoList>(reply.value());
foreach (const MediaStreamInfo &streamInfo, list) {
mPriv->streams.insert(streamInfo.identifier,
QSharedPointer<MediaStream>(
new MediaStream(this,
streamInfo.identifier,
streamInfo.contact,
(Telepathy::MediaStreamType) streamInfo.type,
(Telepathy::MediaStreamState) streamInfo.state,
(Telepathy::MediaStreamDirection) streamInfo.direction,
(Telepathy::MediaStreamPendingSend) streamInfo.pendingSendFlags)));
}
mPriv->readinessHelper->setIntrospectCompleted(FeatureStreams, true);
watcher->deleteLater();
}
void StreamedMediaChannel::onStreamAdded(uint streamId,
uint contactHandle, uint streamType)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(!mPriv->streams.contains(streamId));
}
QSharedPointer<MediaStream> stream = QSharedPointer<MediaStream>(
new MediaStream(this, streamId,
contactHandle,
(Telepathy::MediaStreamType) streamType,
// TODO where to get this info from?
Telepathy::MediaStreamStateDisconnected,
Telepathy::MediaStreamDirectionNone,
(Telepathy::MediaStreamPendingSend) 0));
mPriv->streams.insert(streamId, stream);
if (mPriv->initialStreamsReceived) {
emit streamAdded(stream);
}
}
void StreamedMediaChannel::onStreamRemoved(uint streamId)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
emit stream->removed();
mPriv->streams.remove(streamId);
}
}
void StreamedMediaChannel::onStreamDirectionChanged(uint streamId,
uint streamDirection, uint pendingFlags)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
stream->setDirection(
(Telepathy::MediaStreamDirection) streamDirection,
(Telepathy::MediaStreamPendingSend) pendingFlags);
}
}
void StreamedMediaChannel::onStreamStateChanged(uint streamId,
uint streamState)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
stream->setState((Telepathy::MediaStreamState) streamState);
}
}
void StreamedMediaChannel::onStreamError(uint streamId,
uint errorCode, const QString &errorMessage)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
emit stream->error((Telepathy::MediaStreamError) errorCode,
errorMessage);
}
}
} // Telepathy::Client
} // Telepathy
<commit_msg>StreamedMediaChannel: Added some docs.<commit_after>/* StreamedMedia channel client-side proxy
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2009 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/StreamedMediaChannel>
#include "TelepathyQt4/Client/_gen/streamed-media-channel.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Client/Connection>
#include <TelepathyQt4/Client/ContactManager>
#include <TelepathyQt4/Client/PendingVoidMethodCall>
#include <QHash>
namespace Telepathy
{
namespace Client
{
struct MediaStream::Private
{
Private(StreamedMediaChannel *channel, uint id,
uint contactHandle, MediaStreamType type,
MediaStreamState state, MediaStreamDirection direction,
MediaStreamPendingSend pendingSend)
: id(id), type(type), state(state),
direction(direction), pendingSend(pendingSend)
{
ContactManager *contactManager = channel->connection()->contactManager();
contact = contactManager->lookupContactByHandle(contactHandle);
}
StreamedMediaChannel *channel;
uint id;
QSharedPointer<Contact> contact;
MediaStreamType type;
MediaStreamState state;
MediaStreamDirection direction;
MediaStreamPendingSend pendingSend;
};
MediaStream::MediaStream(StreamedMediaChannel *channel, uint id,
uint contactHandle, MediaStreamType type,
MediaStreamState state, MediaStreamDirection direction,
MediaStreamPendingSend pendingSend)
: QObject(),
mPriv(new Private(channel, id, contactHandle, type,
state, direction, pendingSend))
{
}
MediaStream::~MediaStream()
{
delete mPriv;
}
StreamedMediaChannel *MediaStream::channel() const
{
return mPriv->channel;
}
/**
* Return the stream id.
*
* \return An integer representing the stream id.
*/
uint MediaStream::id() const
{
return mPriv->id;
}
/**
* Return the contact who the stream is with.
*
* \return The contact who the stream is with.
*/
QSharedPointer<Contact> MediaStream::contact() const
{
return mPriv->contact;
}
/**
* Return the stream state.
*
* \return The stream state.
*/
Telepathy::MediaStreamState MediaStream::state() const
{
return mPriv->state;
}
/**
* Return the stream type.
*
* \return The stream type.
*/
Telepathy::MediaStreamType MediaStream::type() const
{
return mPriv->type;
}
/**
* Return whether media is being sent on this stream.
*
* \return A boolean indicating whether media is being sent on this stream.
*/
bool MediaStream::sending() const
{
return (mPriv->direction & Telepathy::MediaStreamDirectionSend ||
mPriv->direction & Telepathy::MediaStreamDirectionBidirectional);
}
/**
* Return whether media is being received on this stream.
*
* \return A boolean indicating whether media is being received on this stream.
*/
bool MediaStream::receiving() const
{
return (mPriv->direction & Telepathy::MediaStreamDirectionReceive ||
mPriv->direction & Telepathy::MediaStreamDirectionBidirectional);
}
/**
* Return whether the local user has been asked to send media by the remote user.
*
* \return A boolean indicating whether the local user has been asked to
* send media by the remote user.
*/
bool MediaStream::localSendingRequested() const
{
return mPriv->pendingSend & MediaStreamPendingLocalSend;
}
/**
* Return whether the remote user has been asked to send media by the local user.
*
* \return A boolean indicating whether the remote user has been asked to
* send media by the local user.
*/
bool MediaStream::remoteSendingRequested() const
{
return mPriv->pendingSend & MediaStreamPendingRemoteSend;
}
/**
* Return the stream direction.
*
* \return The stream direction.
*/
Telepathy::MediaStreamDirection MediaStream::direction() const
{
return mPriv->direction;
}
/**
* Return the stream pending send flags.
*
* \return The stream pending send flags.
*/
Telepathy::MediaStreamPendingSend MediaStream::pendingSend() const
{
return mPriv->pendingSend;
}
/**
* Request this stream to be removed.
*
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
*/
PendingOperation *MediaStream::remove()
{
return mPriv->channel->removeStreams(Telepathy::UIntList() << mPriv->id);
}
/**
* Request a change in the direction of this stream. In particular, this
* might be useful to stop sending media of a particular type, or inform the
* peer that you are no longer using media that is being sent to you.
*
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
*/
PendingOperation *MediaStream::requestStreamDirection(
Telepathy::MediaStreamDirection direction)
{
return new PendingVoidMethodCall(this,
mPriv->channel->streamedMediaInterface()->RequestStreamDirection(mPriv->id, direction));
}
void MediaStream::setDirection(Telepathy::MediaStreamDirection direction,
Telepathy::MediaStreamPendingSend pendingSend)
{
mPriv->direction = direction;
mPriv->pendingSend = pendingSend;
emit directionChanged(direction, pendingSend);
}
void MediaStream::setState(Telepathy::MediaStreamState state)
{
mPriv->state = state;
emit stateChanged(state);
}
struct StreamedMediaChannel::Private
{
Private(StreamedMediaChannel *parent);
~Private();
static void introspectStreams(Private *self);
// Public object
StreamedMediaChannel *parent;
ReadinessHelper *readinessHelper;
// Introspection
bool initialStreamsReceived;
QHash<uint, QSharedPointer<MediaStream> > streams;
};
StreamedMediaChannel::Private::Private(StreamedMediaChannel *parent)
: parent(parent),
readinessHelper(parent->readinessHelper()),
initialStreamsReceived(false)
{
ReadinessHelper::Introspectables introspectables;
ReadinessHelper::Introspectable introspectableStreams(
QSet<uint>() << 0, // makesSenseForStatuses
Features() << Channel::FeatureCore, // dependsOnFeatures (core)
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &Private::introspectStreams,
this);
introspectables[FeatureStreams] = introspectableStreams;
readinessHelper->addIntrospectables(introspectables);
}
StreamedMediaChannel::Private::~Private()
{
}
void StreamedMediaChannel::Private::introspectStreams(StreamedMediaChannel::Private *self)
{
StreamedMediaChannel *parent = self->parent;
ChannelTypeStreamedMediaInterface *streamedMediaInterface =
parent->streamedMediaInterface();
parent->connect(streamedMediaInterface,
SIGNAL(StreamAdded(uint, uint, uint)),
SLOT(onStreamAdded(uint, uint, uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamRemoved(uint)),
SLOT(onStreamRemoved(uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamDirectionChanged(uint, uint, uint)),
SLOT(onStreamDirectionChanged(uint, uint, uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamStateChanged(uint, uint)),
SLOT(onStreamStateChanged(uint, uint)));
parent->connect(streamedMediaInterface,
SIGNAL(StreamError(uint, uint, const QString &)),
SLOT(onStreamError(uint, uint, const QString &)));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
streamedMediaInterface->ListStreams(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(gotStreams(QDBusPendingCallWatcher *)));
}
/**
* \class StreamedMediaChannel
* \ingroup clientchannel
* \headerfile <TelepathyQt4/Client/streamed-media-channel.h> <TelepathyQt4/Client/StreamedMediaChannel>
*
* High-level proxy object for accessing remote %Channel objects of the
* StreamedMedia channel type.
*
* This subclass of Channel will eventually provide a high-level API for the
* StreamedMedia interface. Until then, it's just a Channel.
*/
const Feature StreamedMediaChannel::FeatureStreams = Feature(StreamedMediaChannel::staticMetaObject.className(), 0);
/**
* Creates a StreamedMediaChannel associated with the given object on the same
* service as the given connection.
*
* \param connection Connection owning this StreamedMediaChannel, and
* specifying the service.
* \param objectPath Path to the object on the service.
* \param immutableProperties The immutable properties of the channel, as
* signalled by NewChannels or returned by
* CreateChannel or EnsureChannel
* \param parent Passed to the parent class constructor.
*/
StreamedMediaChannel::StreamedMediaChannel(Connection *connection,
const QString &objectPath,
const QVariantMap &immutableProperties,
QObject *parent)
: Channel(connection, objectPath, immutableProperties, parent),
mPriv(new Private(this))
{
}
/**
* Class destructor.
*/
StreamedMediaChannel::~StreamedMediaChannel()
{
delete mPriv;
}
/**
* Return a list of streams in this channel. This list is empty unless
* the FeatureStreams Feature has been enabled.
*
* Streams are added to the list when they are received; the streamAdded signal
* is emitted.
*
* \return The streams in this channel.
*/
MediaStreams StreamedMediaChannel::streams() const
{
return mPriv->streams.values();
}
bool StreamedMediaChannel::awaitingLocalAnswer() const
{
return groupSelfHandleIsLocalPending();
}
bool StreamedMediaChannel::awaitingRemoteAnswer() const
{
return !groupRemotePendingContacts().isEmpty();
}
PendingOperation *StreamedMediaChannel::acceptCall()
{
return groupAddSelfHandle();
}
/**
* Remove the specified streams from this channel.
*
* \param streams List of streams to remove.
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
*/
PendingOperation *StreamedMediaChannel::removeStreams(MediaStreams streams)
{
Telepathy::UIntList ids;
foreach (const QSharedPointer<MediaStream> &stream, streams) {
ids << stream->id();
}
return removeStreams(ids);
}
/**
* Remove the specified streams from this channel.
*
* \param streams List of ids corresponding to the streams to remove.
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
*/
PendingOperation *StreamedMediaChannel::removeStreams(const Telepathy::UIntList &ids)
{
return new PendingVoidMethodCall(this,
streamedMediaInterface()->RemoveStreams(ids));
}
PendingOperation *StreamedMediaChannel::requestStreams(
QSharedPointer<Telepathy::Client::Contact> contact,
QList<Telepathy::MediaStreamType> types)
{
Telepathy::UIntList l;
foreach (Telepathy::MediaStreamType type, types) {
l << type;
}
return new PendingVoidMethodCall(this,
streamedMediaInterface()->RequestStreams(
contact->handle()[0], l));
}
void StreamedMediaChannel::gotStreams(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "StreamedMedia::ListStreams()"
" failed with " << reply.error().name() << ": " <<
reply.error().message();
mPriv->readinessHelper->setIntrospectCompleted(FeatureStreams,
false, reply.error());
return;
}
debug() << "Got reply to StreamedMedia::ListStreams()";
mPriv->initialStreamsReceived = true;
MediaStreamInfoList list = qdbus_cast<MediaStreamInfoList>(reply.value());
foreach (const MediaStreamInfo &streamInfo, list) {
mPriv->streams.insert(streamInfo.identifier,
QSharedPointer<MediaStream>(
new MediaStream(this,
streamInfo.identifier,
streamInfo.contact,
(Telepathy::MediaStreamType) streamInfo.type,
(Telepathy::MediaStreamState) streamInfo.state,
(Telepathy::MediaStreamDirection) streamInfo.direction,
(Telepathy::MediaStreamPendingSend) streamInfo.pendingSendFlags)));
}
mPriv->readinessHelper->setIntrospectCompleted(FeatureStreams, true);
watcher->deleteLater();
}
void StreamedMediaChannel::onStreamAdded(uint streamId,
uint contactHandle, uint streamType)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(!mPriv->streams.contains(streamId));
}
QSharedPointer<MediaStream> stream = QSharedPointer<MediaStream>(
new MediaStream(this, streamId,
contactHandle,
(Telepathy::MediaStreamType) streamType,
// TODO where to get this info from?
Telepathy::MediaStreamStateDisconnected,
Telepathy::MediaStreamDirectionNone,
(Telepathy::MediaStreamPendingSend) 0));
mPriv->streams.insert(streamId, stream);
if (mPriv->initialStreamsReceived) {
emit streamAdded(stream);
}
}
void StreamedMediaChannel::onStreamRemoved(uint streamId)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
emit stream->removed();
mPriv->streams.remove(streamId);
}
}
void StreamedMediaChannel::onStreamDirectionChanged(uint streamId,
uint streamDirection, uint pendingFlags)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
stream->setDirection(
(Telepathy::MediaStreamDirection) streamDirection,
(Telepathy::MediaStreamPendingSend) pendingFlags);
}
}
void StreamedMediaChannel::onStreamStateChanged(uint streamId,
uint streamState)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
stream->setState((Telepathy::MediaStreamState) streamState);
}
}
void StreamedMediaChannel::onStreamError(uint streamId,
uint errorCode, const QString &errorMessage)
{
if (mPriv->initialStreamsReceived) {
Q_ASSERT(mPriv->streams.contains(streamId));
}
if (mPriv->streams.contains(streamId)) {
QSharedPointer<MediaStream> stream = mPriv->streams[streamId];
emit stream->error((Telepathy::MediaStreamError) errorCode,
errorMessage);
}
}
} // Telepathy::Client
} // Telepathy
<|endoftext|> |
<commit_before>#include <babylon/probes/reflection_probe.h>
#include <babylon/cameras/camera.h>
#include <babylon/engine/engine.h>
#include <babylon/engine/scene.h>
#include <babylon/materials/textures/render_target_texture.h>
#include <babylon/mesh/abstract_mesh.h>
namespace BABYLON {
ReflectionProbe::ReflectionProbe(const string_t& name, const ISize& size,
Scene* scene, bool generateMipMaps)
: invertYAxis{false}
, position{Vector3::Zero()}
, _scene{scene}
, _viewMatrix{Matrix::Identity()}
, _target{Vector3::Zero()}
, _add{Vector3::Zero()}
, _attachedMesh{nullptr}
{
_renderTargetTexture = ::std::make_unique<RenderTargetTexture>(
name, size, scene, generateMipMaps, true,
EngineConstants::TEXTURETYPE_UNSIGNED_INT, true);
_renderTargetTexture->onBeforeRenderObservable.add(
[this](int* faceIndex, EventState&) {
switch (*faceIndex) {
case 0:
_add.copyFromFloats(1.f, 0.f, 0.f);
break;
case 1:
_add.copyFromFloats(-1.f, 0.f, 0.f);
break;
case 2:
_add.copyFromFloats(0.f, invertYAxis ? 1.f : -1.f, 0.f);
break;
case 3:
_add.copyFromFloats(0.f, invertYAxis ? -1.f : 1.f, 0.f);
break;
case 4:
_add.copyFromFloats(0.f, 0.f, 1.f);
break;
case 5:
_add.copyFromFloats(0.f, 0.f, -1.f);
break;
default:
break;
}
if (_attachedMesh) {
position.copyFrom(*_attachedMesh->getAbsolutePosition());
}
position.addToRef(_add, _target);
Matrix::LookAtLHToRef(position, _target, Vector3::Up(), _viewMatrix);
_scene->setTransformMatrix(_viewMatrix, _projectionMatrix);
});
_renderTargetTexture->onAfterUnbindObservable.add(
[this](RenderTargetTexture*, EventState&) {
_scene->updateTransformMatrix(true);
});
_projectionMatrix = Matrix::PerspectiveFovLH(
Math::PI_2, 1.f, scene->activeCamera->minZ, scene->activeCamera->maxZ);
}
ReflectionProbe::~ReflectionProbe()
{
}
void ReflectionProbe::addToScene(
unique_ptr_t<ReflectionProbe>&& newReflectionProbe)
{
_scene->reflectionProbes.emplace_back(::std::move(newReflectionProbe));
}
unsigned int ReflectionProbe::samples() const
{
return _renderTargetTexture->samples();
}
void ReflectionProbe::setSamples(unsigned int value)
{
_renderTargetTexture->setSamples(value);
}
int ReflectionProbe::refreshRate() const
{
return _renderTargetTexture->refreshRate();
}
void ReflectionProbe::setRefreshRate(int value)
{
_renderTargetTexture->setRefreshRate(value);
}
Scene* ReflectionProbe::getScene() const
{
return _scene;
}
RenderTargetTexture* ReflectionProbe::cubeTexture()
{
return _renderTargetTexture.get();
}
vector_t<AbstractMesh*>& ReflectionProbe::renderList()
{
return _renderTargetTexture->renderList;
}
void ReflectionProbe::attachToMesh(AbstractMesh* mesh)
{
_attachedMesh = mesh;
}
void ReflectionProbe::setRenderingAutoClearDepthStencil(
unsigned int renderingGroupId, bool autoClearDepthStencil)
{
_renderTargetTexture->setRenderingAutoClearDepthStencil(
renderingGroupId, autoClearDepthStencil);
}
void ReflectionProbe::dispose(bool /*doNotRecurse*/)
{
// Remove from the scene if found
_scene->reflectionProbes.erase(
::std::remove_if(
_scene->reflectionProbes.begin(), _scene->reflectionProbes.end(),
[this](const unique_ptr_t<ReflectionProbe>& reflectionProbe) {
return reflectionProbe.get() == this;
}),
_scene->reflectionProbes.end());
if (_renderTargetTexture) {
_renderTargetTexture->dispose();
_renderTargetTexture.reset(nullptr);
}
}
} // end of namespace BABYLON
<commit_msg>Updated reflection probe to latest version 3.1.0<commit_after>#include <babylon/probes/reflection_probe.h>
#include <babylon/cameras/camera.h>
#include <babylon/engine/engine.h>
#include <babylon/engine/scene.h>
#include <babylon/materials/textures/render_target_texture.h>
#include <babylon/mesh/abstract_mesh.h>
namespace BABYLON {
ReflectionProbe::ReflectionProbe(const string_t& name, const ISize& size,
Scene* scene, bool generateMipMaps)
: invertYAxis{false}
, position{Vector3::Zero()}
, _scene{scene}
, _viewMatrix{Matrix::Identity()}
, _target{Vector3::Zero()}
, _add{Vector3::Zero()}
, _attachedMesh{nullptr}
{
_renderTargetTexture = ::std::make_unique<RenderTargetTexture>(
name, size, scene, generateMipMaps, true,
EngineConstants::TEXTURETYPE_UNSIGNED_INT, true);
_renderTargetTexture->onBeforeRenderObservable.add(
[this](int* faceIndex, EventState&) {
switch (*faceIndex) {
case 0:
_add.copyFromFloats(1.f, 0.f, 0.f);
break;
case 1:
_add.copyFromFloats(-1.f, 0.f, 0.f);
break;
case 2:
_add.copyFromFloats(0.f, invertYAxis ? 1.f : -1.f, 0.f);
break;
case 3:
_add.copyFromFloats(0.f, invertYAxis ? -1.f : 1.f, 0.f);
break;
case 4:
_add.copyFromFloats(0.f, 0.f, 1.f);
break;
case 5:
_add.copyFromFloats(0.f, 0.f, -1.f);
break;
default:
break;
}
if (_attachedMesh) {
position.copyFrom(*_attachedMesh->getAbsolutePosition());
}
position.addToRef(_add, _target);
Matrix::LookAtLHToRef(position, _target, Vector3::Up(), _viewMatrix);
_scene->setTransformMatrix(_viewMatrix, _projectionMatrix);
_scene->_forcedViewPosition = ::std::make_unique<Vector3>(position);
});
_renderTargetTexture->onAfterUnbindObservable.add(
[this](RenderTargetTexture*, EventState&) {
_scene->_forcedViewPosition = nullptr;
_scene->updateTransformMatrix(true);
});
if (scene->activeCamera) {
_projectionMatrix = Matrix::PerspectiveFovLH(
Math::PI_2, 1.f, scene->activeCamera->minZ, scene->activeCamera->maxZ);
}
}
ReflectionProbe::~ReflectionProbe()
{
}
void ReflectionProbe::addToScene(
unique_ptr_t<ReflectionProbe>&& newReflectionProbe)
{
_scene->reflectionProbes.emplace_back(::std::move(newReflectionProbe));
}
unsigned int ReflectionProbe::samples() const
{
return _renderTargetTexture->samples();
}
void ReflectionProbe::setSamples(unsigned int value)
{
_renderTargetTexture->setSamples(value);
}
int ReflectionProbe::refreshRate() const
{
return _renderTargetTexture->refreshRate();
}
void ReflectionProbe::setRefreshRate(int value)
{
_renderTargetTexture->setRefreshRate(value);
}
Scene* ReflectionProbe::getScene() const
{
return _scene;
}
RenderTargetTexture* ReflectionProbe::cubeTexture()
{
return _renderTargetTexture.get();
}
vector_t<AbstractMesh*>& ReflectionProbe::renderList()
{
return _renderTargetTexture->renderList;
}
void ReflectionProbe::attachToMesh(AbstractMesh* mesh)
{
_attachedMesh = mesh;
}
void ReflectionProbe::setRenderingAutoClearDepthStencil(
unsigned int renderingGroupId, bool autoClearDepthStencil)
{
_renderTargetTexture->setRenderingAutoClearDepthStencil(
renderingGroupId, autoClearDepthStencil);
}
void ReflectionProbe::dispose(bool /*doNotRecurse*/)
{
// Remove from the scene if found
_scene->reflectionProbes.erase(
::std::remove_if(
_scene->reflectionProbes.begin(), _scene->reflectionProbes.end(),
[this](const unique_ptr_t<ReflectionProbe>& reflectionProbe) {
return reflectionProbe.get() == this;
}),
_scene->reflectionProbes.end());
if (_renderTargetTexture) {
_renderTargetTexture->dispose();
_renderTargetTexture.reset(nullptr);
}
}
} // end of namespace BABYLON
<|endoftext|> |
<commit_before><commit_msg>Added `const` modifiers to function arguments.<commit_after><|endoftext|> |
<commit_before>#include "gtest/gtest.h"
// Include pugixml
#include "pugixml.hpp"
#include "pugixml.cpp"
// Include standard headers
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
TEST(xml_must_be_loaded_as_expected, exactum_and_physicum)
{
const char* exactum_physicum_osm_char = "Exactum_Physicum_Helsinki_Finland.osm";
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(exactum_physicum_osm_char);
pugi::xml_node osm = doc.child("osm");
pugi::xpath_node_set restaurants = doc.select_nodes("/osm/node/tag[@v='Unicafe']");
uint32_t n_restaurants = 0;
for (pugi::xpath_node_set::const_iterator it = restaurants.begin(); it != restaurants.end(); ++it)
{
n_restaurants++;
}
std::cout << "Number of restaurants: " << n_restaurants << "\n";
ASSERT_EQ(n_restaurants, 2);
pugi::xpath_node exactum_tag = doc.select_node("/osm/way/tag[@k='name' and @v='Exactum']");
ASSERT_TRUE(exactum_tag != nullptr);
pugi::xml_node exactum_way = exactum_tag.parent();
ASSERT_TRUE(exactum_way != nullptr);
ASSERT_EQ(strcmp(exactum_way.attribute("id").value(), "16790295"), 0);
}
TEST(xml_must_be_loaded_as_expected, hofinkatu_and_isafjordinkatu)
{
const char* hofinkatu_and_isafjordinkatu_osm_char = "Hofinkatu_Isafjordinkatu_Joensuu_Finland.osm";
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(hofinkatu_and_isafjordinkatu_osm_char);
pugi::xpath_node_set buildings = doc.select_nodes("/osm/way/tag[@k='building']");
uint32_t n_buildings = 0;
for (pugi::xpath_node_set::const_iterator it = buildings.begin(); it != buildings.end(); ++it)
{
n_buildings++;
}
std::cout << "Number of buildings: " << n_buildings << "\n";
ASSERT_EQ(n_buildings, 85);
}
<commit_msg>Assertions for the `"playground"` `"id"` inside Hofinkatu.<commit_after>#include "gtest/gtest.h"
// Include pugixml
#include "pugixml.hpp"
#include "pugixml.cpp"
// Include standard headers
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <iostream> // std::cout, std::cin, std::cerr
TEST(xml_must_be_loaded_as_expected, exactum_and_physicum)
{
const char* exactum_physicum_osm_char = "Exactum_Physicum_Helsinki_Finland.osm";
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(exactum_physicum_osm_char);
pugi::xml_node osm = doc.child("osm");
pugi::xpath_node_set restaurants = doc.select_nodes("/osm/node/tag[@v='Unicafe']");
uint32_t n_restaurants = 0;
for (pugi::xpath_node_set::const_iterator it = restaurants.begin(); it != restaurants.end(); ++it)
{
n_restaurants++;
}
std::cout << "Number of restaurants: " << n_restaurants << "\n";
ASSERT_EQ(n_restaurants, 2);
pugi::xpath_node exactum_tag = doc.select_node("/osm/way/tag[@k='name' and @v='Exactum']");
ASSERT_TRUE(exactum_tag != nullptr);
pugi::xml_node exactum_way = exactum_tag.parent();
ASSERT_TRUE(exactum_way != nullptr);
ASSERT_EQ(strcmp(exactum_way.attribute("id").value(), "16790295"), 0);
}
TEST(xml_must_be_loaded_as_expected, hofinkatu_and_isafjordinkatu)
{
const char* hofinkatu_and_isafjordinkatu_osm_char = "Hofinkatu_Isafjordinkatu_Joensuu_Finland.osm";
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(hofinkatu_and_isafjordinkatu_osm_char);
pugi::xpath_node_set buildings = doc.select_nodes("/osm/way/tag[@k='building']");
uint32_t n_buildings = 0;
for (pugi::xpath_node_set::const_iterator it = buildings.begin(); it != buildings.end(); ++it)
{
n_buildings++;
}
std::cout << "Number of buildings: " << n_buildings << "\n";
ASSERT_EQ(n_buildings, 85);
pugi::xpath_node playground_tag = doc.select_node("/osm/way/tag[@k='leisure' and @v='playground']");
ASSERT_TRUE(playground_tag != nullptr);
pugi::xml_node playground_way = playground_tag.parent();
ASSERT_TRUE(playground_way != nullptr);
ASSERT_EQ(strcmp(playground_way.attribute("id").value(), "435869079"), 0);
}
<|endoftext|> |
<commit_before>#include "CurlHttpPost.h"
CurlHttpPost::CurlHttpPost () : first( NULL ), last( NULL )
{
this->reset();
}
CurlHttpPost::~CurlHttpPost ()
{
this->reset();
}
void CurlHttpPost::reset()
{
curl_httppost *current = this->first;
while ( current ) {
curl_httppost *next = current->next;
if ( current->contenttype )
free( current->contenttype );
if ( current->contents )
free( current->contents );
if ( current->buffer )
free( current->buffer );
if ( current->name )
free( current->buffer );
free( current );
current = next;
}
this->first = NULL;
this->last = NULL;
}
void CurlHttpPost::append()
{
if ( !this->first ) {
this->first = ( curl_httppost* ) calloc( 1, sizeof( curl_httppost ) );
this->last = this->first;
} else {
this->last->next = ( curl_httppost* ) calloc( 1, sizeof( curl_httppost ) );
this->last = this->last->next;
}
}
void CurlHttpPost::set( int field, char *value, long length )
{
value = strndup( value, length );
switch ( field ) {
case NAME:
last->name = value;
last->namelength = length;
break;
case TYPE:
last->contenttype = value;
break;
case FILE:
last->flags |= HTTPPOST_FILENAME;
case CONTENTS:
last->contents = value;
last->contentslength = length;
break;
default:
// `default` should never be reached.
free(value);
break;
}
}<commit_msg>Fix incorrect value being passed to free.<commit_after>#include "CurlHttpPost.h"
CurlHttpPost::CurlHttpPost () : first( NULL ), last( NULL )
{
this->reset();
}
CurlHttpPost::~CurlHttpPost ()
{
this->reset();
}
void CurlHttpPost::reset()
{
curl_httppost *current = this->first;
while ( current ) {
curl_httppost *next = current->next;
if ( current->contenttype )
free( current->contenttype );
if ( current->contents )
free( current->contents );
if ( current->buffer )
free( current->buffer );
if ( current->name )
free( current->name );
free( current );
current = next;
}
this->first = NULL;
this->last = NULL;
}
void CurlHttpPost::append()
{
if ( !this->first ) {
this->first = ( curl_httppost* ) calloc( 1, sizeof( curl_httppost ) );
this->last = this->first;
} else {
this->last->next = ( curl_httppost* ) calloc( 1, sizeof( curl_httppost ) );
this->last = this->last->next;
}
}
void CurlHttpPost::set( int field, char *value, long length )
{
value = strndup( value, length );
switch ( field ) {
case NAME:
last->name = value;
last->namelength = length;
break;
case TYPE:
last->contenttype = value;
break;
case FILE:
last->flags |= HTTPPOST_FILENAME;
case CONTENTS:
last->contents = value;
last->contentslength = length;
break;
default:
// `default` should never be reached.
free(value);
break;
}
}<|endoftext|> |
<commit_before>#include "List.h"
template <class T>
List<T>::List()
: count(0), tailleMax(LIST_MAX_VALUE)
{
templateList = new T*[tailleMax];
}
template <class T>
List<T>::List(int _setTailleMax)
: count(0), tailleMax(_setTailleMax)
{
templateList = new T*[tailleMax];
}
template <class T>
List<T>::~List()
{
delete[] templateList;
}
template <class T>
void List<T>::Add(T* _object)
{
if (count >= tailleMax)
{
listBackup = new T*[tailleMax];
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
tailleMax *= 2;
delete[] templateList;
templateList = new T*[tailleMax];
memcpy(templateList, listBackup, sizeof(T) * tailleMax);
delete[] listBackup;
}
templateList[count] = _object;
count++;
}
template <class T>
void List<T>::Remove(int _target)
{
listBackup = new T*[tailleMax];
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
delete[] templateList;
templateList = new T*[tailleMax];
for (int i = 0; i < _target; i++)
{
templateList[i] = listBackup[i];
}
count--;
for (int i = _target; i < count; i++)
{
templateList[i] = listBackup[i + 1];
}
}
template <class T>
void List<T>::RemoveFirst()
{
//create a new backup List
listBackup = new T*[tailleMax];
//copy templatelist from array position 2 to last one into listBackup
for (int i = 0, i < count - 2; i++)
{
listBackup[i] = templateList[i + 1];
}
//delete template list and initiate a new empty one
delete[] templateList;
templateList = new T*[tailleMax];
//copy templateList that contains all the information of the initial template list exept the first one into the new template list
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
//delete the backup list
delete[] listBackup;
//adjust count variable
count--;
}
template <class T>
void List<T>::RemoveLast()
{
//overide the last initialized object of the list by a new empty(trash) one
templateList[count - 1] = new T*();
//adjust count variable
count--;
}
template <class T>
void List<T>::Insert()
{
}
template<class T>
inline T& List<T>::operator[](int i)
{
return templateList[i];
}
template <class T>
void List<T>::MoveToLast(int _target)
{
int counting = 0;
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
delete[] templateList;
templateList = new T*[tailleMax];
for (int i = 0; i < _target; i++)
{
templateList[i] = listBackup[i];
counting++;
}
for (int i = _target; i < count - 1; i++)
{
templateList[i] = listBackup[i + 1];
counting++;
}
templateList[counting] = listBackup[_target];
}<commit_msg>Adjust Return on Operator in List.inl<commit_after>#include "List.h"
template <class T>
List<T>::List()
: count(0), tailleMax(LIST_MAX_VALUE)
{
templateList = new T*[tailleMax];
}
template <class T>
List<T>::List(int _setTailleMax)
: count(0), tailleMax(_setTailleMax)
{
templateList = new T*[tailleMax];
}
template <class T>
List<T>::~List()
{
delete[] templateList;
}
template <class T>
void List<T>::Add(T* _object)
{
if (count >= tailleMax)
{
listBackup = new T*[tailleMax];
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
tailleMax *= 2;
delete[] templateList;
templateList = new T*[tailleMax];
memcpy(templateList, listBackup, sizeof(T) * tailleMax);
delete[] listBackup;
}
templateList[count] = _object;
count++;
}
template <class T>
void List<T>::Remove(int _target)
{
listBackup = new T*[tailleMax];
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
delete[] templateList;
templateList = new T*[tailleMax];
for (int i = 0; i < _target; i++)
{
templateList[i] = listBackup[i];
}
count--;
for (int i = _target; i < count; i++)
{
templateList[i] = listBackup[i + 1];
}
}
template <class T>
void List<T>::RemoveFirst()
{
//create a new backup List
listBackup = new T*[tailleMax];
//copy templatelist from array position 2 to last one into listBackup
for (int i = 0, i < count - 2; i++)
{
listBackup[i] = templateList[i + 1];
}
//delete template list and initiate a new empty one
delete[] templateList;
templateList = new T*[tailleMax];
//copy templateList that contains all the information of the initial template list exept the first one into the new template list
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
//delete the backup list
delete[] listBackup;
//adjust count variable
count--;
}
template <class T>
void List<T>::RemoveLast()
{
//overide the last initialized object of the list by a new empty(trash) one
templateList[count - 1] = new T*();
//adjust count variable
count--;
}
template <class T>
void List<T>::Insert()
{
}
template<class T>
inline T& List<T>::operator[](int i)
{
return *templateList[i];
}
template <class T>
void List<T>::MoveToLast(int _target)
{
int counting = 0;
memcpy(listBackup, templateList, sizeof(T) * tailleMax);
delete[] templateList;
templateList = new T*[tailleMax];
for (int i = 0; i < _target; i++)
{
templateList[i] = listBackup[i];
counting++;
}
for (int i = _target; i < count - 1; i++)
{
templateList[i] = listBackup[i + 1];
counting++;
}
templateList[counting] = listBackup[_target];
}<|endoftext|> |
<commit_before>/*
This file is part of Csound.
Copyright (C) 2014 Rory Walsh
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include "OpcodeBase.hpp"
#include <cmath>
#include <sys/types.h>
#include <dirent.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/* this function will load all samples of supported types into function
tables number 'index' and upwards.
It return the number of samples loaded */
int loadSamplesToTables(CSOUND *csound, int index, char* directory,
int skiptime, int format, int channel);
//-----------------------------------------------------------------
// i-rate class
//-----------------------------------------------------------------
class iftsamplebank : public OpcodeBase<iftsamplebank>
{
public:
// Outputs.
MYFLT* numberOfFiles;
// Inputs.
STRINGDAT* sDirectory;
MYFLT* index;
MYFLT* trigger;
MYFLT* skiptime;
MYFLT* format;
MYFLT* channel;
iftsamplebank() {}
//init-pass
int init(CSOUND *csound)
{
*numberOfFiles = loadSamplesToTables(csound, *index,
(char* )sDirectory->data,
*skiptime, *format, *channel);
return OK;
}
int noteoff(CSOUND *)
{
return OK;
}
};
//-----------------------------------------------------------------
// k-rate class
//-----------------------------------------------------------------
class kftsamplebank : public OpcodeBase<kftsamplebank>
{
public:
// Outputs.
MYFLT* numberOfFiles;
// Inputs.
STRINGDAT* sDirectory;
MYFLT* index;
MYFLT* trigger;
MYFLT* skiptime;
MYFLT* format;
MYFLT* channel;
int internalCounter;
kftsamplebank():internalCounter(0){}
//init-pass
int init(CSOUND *csound)
{
*numberOfFiles = 0;
//loadSamplesToTables(csound, *index, fileNames,
// (char* )sDirectory->data, *skiptime, *format, *channel);
//csound->Message(csound, (char* )sDirectory->data);
*trigger=0;
return OK;
}
int noteoff(CSOUND *)
{
return OK;
}
int kontrol(CSOUND* csound)
{
//if directry changes update tables..
if (*trigger==1) {
*numberOfFiles = loadSamplesToTables(csound, *index,
(char* )sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
}
return OK;
}
};
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
int loadSamplesToTables(CSOUND *csound, int index, char* directory,
int skiptime, int format, int channel)
{
if (directory) {
DIR *dir = opendir(directory);
std::vector<std::string> fileNames;
std::vector<std::string> fileExtensions;
int noOfFiles = 0;
fileExtensions.push_back(".wav");
fileExtensions.push_back(".aiff");
fileExtensions.push_back(".ogg");
fileExtensions.push_back(".flac");
//check for valid path first
if(dir) {
struct dirent *ent;
while((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
//only use supported file types
for(int i=0;i<fileExtensions.size();i++)
if(std::string(ent->d_name).find(fileExtensions[i])!=std::string::npos)
{
if(strlen(directory)>2)
{
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end() );
// push statements to score, starting with table number 'index'
for(int y = 0; y < fileNames.size(); y++)
{
std::ostringstream statement;
statement << "f" << index+y << " 0 0 1 \"" << fileNames[y] <<
"\" " << skiptime << " " << format << " " << channel << "\n";
//csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());
csound->InputMessage(csound, statement.str().c_str());
}
}
else
{
csound->Message(csound,
Str("Cannot load file. Error opening directory: %s\n"),
directory);
}
//return number of files
return noOfFiles;
}
else
return 0;
}
typedef struct {
OPDS h;
ARRAYDAT* outArr;
STRINGDAT *directoryName;
MYFLT* extension;
} DIR_STRUCT;
/* this function will looks for files of a set type, in a particular directory */
std::vector<std::string> searchDir(CSOUND *csound,
char* directory, char* extension);
/* from Opcodes/arrays.c */
static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size)
{
if (p->data==NULL || p->dimensions == 0 ||
(p->dimensions==1 && p->sizes[0] < size)) {
size_t ss;
if (p->data == NULL) {
CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);
p->arrayMemberSize = var->memBlockSize;
}
ss = p->arrayMemberSize*size;
if (p->data==NULL) p->data = (MYFLT*)csound->Calloc(csound, ss);
else p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);
p->dimensions = 1;
p->sizes = (int*)csound->Malloc(csound, sizeof(int));
p->sizes[0] = size;
}
}
static int directory(CSOUND *csound, DIR_STRUCT* p)
{
int inArgCount = p->INOCOUNT;
char *extension, *file;
std::vector<std::string> fileNames;
if (inArgCount==0)
return
csound->InitError(csound,
Str("Error: you must pass a directory as a string."));
if(inArgCount==1)
{
fileNames = searchDir(csound, p->directoryName->data, (char *)"");
}
else if(inArgCount==2)
{
CS_TYPE* argType = csound->GetTypeForArg(p->extension);
if(strcmp("S", argType->varTypeName) == 0)
{
extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);
fileNames = searchDir(csound, p->directoryName->data, extension);
}
else
return csound->InitError(csound,
Str("Error: second parameter to directory"
" must be a string"));
}
int numberOfFiles = fileNames.size();
tabensure(csound, p->outArr, numberOfFiles);
STRINGDAT *strings = (STRINGDAT *) p->outArr->data;
for(int i=0; i < numberOfFiles; i++)
{
file = &fileNames[i][0u];
strings[i].size = strlen(file) + 1;
strings[i].data = csound->Strdup(csound, file);
}
fileNames.clear();
return OK;
}
//-----------------------------------------------------------------
// load samples into functoin tables
//-----------------------------------------------------------------
std::vector<std::string> searchDir(CSOUND *csound, char* directory, char* extension)
{
std::vector<std::string> fileNames;
if(directory)
{
DIR *dir = opendir(directory);
std::string fileExtension(extension);
int noOfFiles = 0;
//check for valid path first
if(dir)
{
struct dirent *ent;
while((ent = readdir(dir)) != NULL)
{
std::ostringstream fullFileName;
if(std::string(ent->d_name).find(fileExtension)!=
std::string::npos && strlen(ent->d_name)>2)
{
if(strlen(directory)>2)
{
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end() );
}
else {
csound->Message(csound,
Str("Cannot find directory. "
"Error opening directory: %s\n"), directory);
}
}
return fileNames;
}
extern "C" {
PUBLIC int csoundModuleCreate(CSOUND *csound)
{
return 0;
}
PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound)
{
int status =
csound->AppendOpcode(csound,
(char*)"ftsamplebank.k",
sizeof(kftsamplebank),
0,
3,
(char*)"k",
(char*)"Skkkkk",
(int(*)(CSOUND*,void*)) kftsamplebank::init_,
(int(*)(CSOUND*,void*)) kftsamplebank::kontrol_,
(int (*)(CSOUND*,void*)) 0);
status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank.i",
sizeof(iftsamplebank),
0,
1,
(char*)"i",
(char*)"Siiiii",
(int (*)(CSOUND*,void*)) iftsamplebank::init_,
(int (*)(CSOUND*,void*)) 0,
(int (*)(CSOUND*,void*)) 0);
/* status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank",
0xffff,
0,
0,
0,
0,
0,
0,
0); */
status |= csound->AppendOpcode(csound,
(char*)"directory",
sizeof(DIR_STRUCT),
0,
1,
(char*)"S[]",
(char*)"SN",
(int (*)(CSOUND*,void*)) directory,
(int (*)(CSOUND*,void*)) 0,
(int (*)(CSOUND*,void*)) 0);
return status;
}
PUBLIC int csoundModuleInit(CSOUND *csound)
{
return csoundModuleInit_ftsamplebank(csound);
}
PUBLIC int csoundModuleDestroy(CSOUND *csound)
{
return 0;
}
}
<commit_msg>coverity fixes (changes by Rory)<commit_after>/*
This file is part of Csound.
Copyright (C) 2014 Rory Walsh
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include "OpcodeBase.hpp"
#include <cmath>
#include <sys/types.h>
#include <dirent.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/* this function will load all samples of supported types into function
tables number 'index' and upwards.
It return the number of samples loaded */
int loadSamplesToTables(CSOUND *csound, int index, char* directory,
int skiptime, int format, int channel);
//-----------------------------------------------------------------
// i-rate class
//-----------------------------------------------------------------
class iftsamplebank : public OpcodeBase<iftsamplebank>
{
public:
// Outputs.
MYFLT* numberOfFiles;
// Inputs.
STRINGDAT* sDirectory;
MYFLT* index;
MYFLT* trigger;
MYFLT* skiptime;
MYFLT* format;
MYFLT* channel;
iftsamplebank()
{
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
}
//init-pass
int init(CSOUND *csound)
{
*numberOfFiles = loadSamplesToTables(csound, *index,
(char* )sDirectory->data,
*skiptime, *format, *channel);
return OK;
}
int noteoff(CSOUND *)
{
return OK;
}
};
//-----------------------------------------------------------------
// k-rate class
//-----------------------------------------------------------------
class kftsamplebank : public OpcodeBase<kftsamplebank>
{
public:
// Outputs.
MYFLT* numberOfFiles;
// Inputs.
STRINGDAT* sDirectory;
MYFLT* index;
MYFLT* trigger;
MYFLT* skiptime;
MYFLT* format;
MYFLT* channel;
int internalCounter;
kftsamplebank():internalCounter(0)
{
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
}
//init-pass
int init(CSOUND *csound)
{
*numberOfFiles = 0;
//loadSamplesToTables(csound, *index, fileNames,
// (char* )sDirectory->data, *skiptime, *format, *channel);
//csound->Message(csound, (char* )sDirectory->data);
*trigger=0;
return OK;
}
int noteoff(CSOUND *)
{
return OK;
}
int kontrol(CSOUND* csound)
{
//if directry changes update tables..
if (*trigger==1) {
*numberOfFiles = loadSamplesToTables(csound, *index,
(char* )sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
}
return OK;
}
};
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
int loadSamplesToTables(CSOUND *csound, int index, char* directory,
int skiptime, int format, int channel)
{
if (directory) {
DIR *dir = opendir(directory);
std::vector<std::string> fileNames;
std::vector<std::string> fileExtensions;
int noOfFiles = 0;
fileExtensions.push_back(".wav");
fileExtensions.push_back(".aiff");
fileExtensions.push_back(".ogg");
fileExtensions.push_back(".flac");
//check for valid path first
if(dir) {
struct dirent *ent;
while((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
//only use supported file types
for(int i=0;i<fileExtensions.size();i++)
{
std::string fname = ent->d_name;
if (fname.find(fileExtensions[i], (fname.length() - fileExtensions[i].length())) != std::string::npos)
{
if(strlen(directory)>2)
{
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end() );
// push statements to score, starting with table number 'index'
for(int y = 0; y < fileNames.size(); y++)
{
std::ostringstream statement;
statement << "f" << index+y << " 0 0 1 \"" << fileNames[y] <<
"\" " << skiptime << " " << format << " " << channel << "\n";
//csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());
csound->InputMessage(csound, statement.str().c_str());
}
}
else
{
csound->Message(csound,
Str("Cannot load file. Error opening directory: %s\n"),
directory);
}
closedir(dir);
//return number of files
return noOfFiles;
}
else
return 0;
}
typedef struct {
OPDS h;
ARRAYDAT* outArr;
STRINGDAT *directoryName;
MYFLT* extension;
} DIR_STRUCT;
/* this function will looks for files of a set type, in a particular directory */
std::vector<std::string> searchDir(CSOUND *csound,
char* directory, char* extension);
/* from Opcodes/arrays.c */
static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size)
{
if (p->data==NULL || p->dimensions == 0 ||
(p->dimensions==1 && p->sizes[0] < size)) {
size_t ss;
if (p->data == NULL) {
CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);
p->arrayMemberSize = var->memBlockSize;
}
ss = p->arrayMemberSize*size;
if (p->data==NULL) p->data = (MYFLT*)csound->Calloc(csound, ss);
else p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);
p->dimensions = 1;
p->sizes = (int*)csound->Malloc(csound, sizeof(int));
p->sizes[0] = size;
}
}
static int directory(CSOUND *csound, DIR_STRUCT* p)
{
int inArgCount = p->INOCOUNT;
char *extension, *file;
std::vector<std::string> fileNames;
if (inArgCount==0)
return
csound->InitError(csound,
Str("Error: you must pass a directory as a string."));
if(inArgCount==1)
{
fileNames = searchDir(csound, p->directoryName->data, (char *)"");
}
else if(inArgCount==2)
{
CS_TYPE* argType = csound->GetTypeForArg(p->extension);
if(strcmp("S", argType->varTypeName) == 0)
{
extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);
fileNames = searchDir(csound, p->directoryName->data, extension);
}
else
return csound->InitError(csound,
Str("Error: second parameter to directory"
" must be a string"));
}
int numberOfFiles = fileNames.size();
tabensure(csound, p->outArr, numberOfFiles);
STRINGDAT *strings = (STRINGDAT *) p->outArr->data;
for(int i=0; i < numberOfFiles; i++)
{
file = &fileNames[i][0u];
strings[i].size = strlen(file) + 1;
strings[i].data = csound->Strdup(csound, file);
}
fileNames.clear();
return OK;
}
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
std::vector<std::string> searchDir(CSOUND *csound, char* directory, char* extension)
{
std::vector<std::string> fileNames;
if(directory)
{
DIR *dir = opendir(directory);
std::string fileExtension(extension);
int noOfFiles = 0;
//check for valid path first
if(dir)
{
struct dirent *ent;
while((ent = readdir(dir)) != NULL)
{
std::ostringstream fullFileName;
if(std::string(ent->d_name).find(fileExtension)!=
std::string::npos && strlen(ent->d_name)>2)
{
if(strlen(directory)>2)
{
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end() );
}
else {
csound->Message(csound,
Str("Cannot find directory. "
"Error opening directory: %s\n"), directory);
}
closedir(dir);
}
return fileNames;
}
extern "C" {
PUBLIC int csoundModuleCreate(CSOUND *csound)
{
return 0;
}
PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound)
{
int status =
csound->AppendOpcode(csound,
(char*)"ftsamplebank.k",
sizeof(kftsamplebank),
0,
3,
(char*)"k",
(char*)"Skkkkk",
(int(*)(CSOUND*,void*)) kftsamplebank::init_,
(int(*)(CSOUND*,void*)) kftsamplebank::kontrol_,
(int (*)(CSOUND*,void*)) 0);
status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank.i",
sizeof(iftsamplebank),
0,
1,
(char*)"i",
(char*)"Siiiii",
(int (*)(CSOUND*,void*)) iftsamplebank::init_,
(int (*)(CSOUND*,void*)) 0,
(int (*)(CSOUND*,void*)) 0);
/* status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank",
0xffff,
0,
0,
0,
0,
0,
0,
0); */
status |= csound->AppendOpcode(csound,
(char*)"directory",
sizeof(DIR_STRUCT),
0,
1,
(char*)"S[]",
(char*)"SN",
(int (*)(CSOUND*,void*)) directory,
(int (*)(CSOUND*,void*)) 0,
(int (*)(CSOUND*,void*)) 0);
return status;
}
PUBLIC int csoundModuleInit(CSOUND *csound)
{
return csoundModuleInit_ftsamplebank(csound);
}
PUBLIC int csoundModuleDestroy(CSOUND *csound)
{
return 0;
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <time.h>
int __stdcall MOB_create();
void __stdcall MOB_open(int conId, const char *dns, const char *username, const char *password);
void __stdcall MOB_close(int conId);
void __stdcall MOB_execute(int conId, const char *sql);
int __stdcall MOB_getLastErrorNo(int conId);
char* __stdcall MOB_getLastErrorMesg(int conId);
int __stdcall MOB_prepareStatement(int conId, const char *sql);
int __stdcall MOB_executeWithTickData(int conId, int stmtId, int datetime, int millis, double *vals, int size);
int __stdcall MOB_executeWithCandleData(int conId, int stmtId, int datetime, double *vals, int size);
void checkError(int conId) {
int ret = MOB_getLastErrorNo(conId);
if (ret != 0) {
printf("ErrNo: %d, ErrMesg:\n%s\n", ret, MOB_getLastErrorMesg(conId));
}
}
int main(int argc, char *argv[])
{
int ret = 0;
int conId = 0;
int stmtId = 0;
time_t t;
printf("MT4-ODBC Bridge Test\n");
conId = MOB_create();
MOB_open(conId, "testhoge", "onagano", "password");
checkError(conId);
checkError(conId);
MOB_open(conId, "testmysql", "onagano", "password");
checkError(conId);
MOB_execute(conId, "insert into pet (name, owner) values ('aaa', 'hogefoobar')");
checkError(conId);
MOB_execute(conId, "insert into pet2 (name, owner) values ('aaa', 'hogefoobar')");
checkError(conId);
MOB_execute(conId, "create table if not exists ticks ("
"time datetime,"
"msec int,"
"open double,"
"high double,"
"low double,"
"close double,"
"vol double"
")");
checkError(conId);
MOB_execute(conId, "insert into ticks values ('2001-01-01 13:00:01', 333, 110.32, 111.55, 90.90, 101.01, 64)");
checkError(conId);
stmtId = MOB_prepareStatement(conId, "insert into ticks values (?, ?, ?, ?, ?, ?, ?)");
checkError(conId);
time(&t);
double vals1[5] = {111.32, 115.55, 70.90, 100.01, 44.24};
ret = MOB_executeWithTickData(conId, stmtId, (int) t, 123, vals1, 5);
checkError(conId);
MOB_execute(conId, "create table if not exists candles ("
"time datetime,"
"open double,"
"high double,"
"low double,"
"close double,"
"vol double"
")");
checkError(conId);
stmtId = MOB_prepareStatement(conId, "insert into candles values (?, ?, ?, ?, ?, ?)");
checkError(conId);
time(&t);
double vals2[5] = {1.3245, 1.5532, 0.9000, 1.0001, 1044.24};
ret = MOB_executeWithCandleData(conId, stmtId, (int) t, vals2, 5);
checkError(conId);
time(&t);
double vals3[5] = {1.11114, 1.11115, 0.999999, 0.000001, 1044.24};
ret = MOB_executeWithCandleData(conId, stmtId, (int) t, vals3, 5);
checkError(conId);
MOB_close(conId);
checkError(conId);
getchar();
return ret;
}
<commit_msg>Changed ticks table format<commit_after>#include <stdio.h>
#include <time.h>
int __stdcall MOB_create();
void __stdcall MOB_open(int conId, const char *dns, const char *username, const char *password);
void __stdcall MOB_close(int conId);
void __stdcall MOB_execute(int conId, const char *sql);
int __stdcall MOB_getLastErrorNo(int conId);
char* __stdcall MOB_getLastErrorMesg(int conId);
int __stdcall MOB_prepareStatement(int conId, const char *sql);
int __stdcall MOB_executeWithTickData(int conId, int stmtId, int datetime, int millis, double *vals, int size);
int __stdcall MOB_executeWithCandleData(int conId, int stmtId, int datetime, double *vals, int size);
void checkError(int conId) {
int ret = MOB_getLastErrorNo(conId);
if (ret != 0) {
printf("ErrNo: %d, ErrMesg:\n%s\n", ret, MOB_getLastErrorMesg(conId));
}
}
int main(int argc, char *argv[])
{
int ret = 0;
int conId = 0;
int stmtId = 0;
time_t t;
printf("MT4-ODBC Bridge Test\n");
conId = MOB_create();
MOB_open(conId, "testhoge", "onagano", "password");
checkError(conId);
checkError(conId);
MOB_open(conId, "testmysql", "onagano", "password");
checkError(conId);
MOB_execute(conId, "insert into pet (name, owner) values ('aaa', 'hogefoobar')");
checkError(conId);
MOB_execute(conId, "insert into pet2 (name, owner) values ('aaa', 'hogefoobar')");
checkError(conId);
MOB_execute(conId, "create table if not exists ticks ("
"time datetime,"
"msec int,"
"ask double,"
"bid double"
")");
checkError(conId);
MOB_execute(conId, "insert into ticks values ('2001-01-01 13:00:01', 333, 110.32, 111.55)");
checkError(conId);
stmtId = MOB_prepareStatement(conId, "insert into ticks values (?, ?, ?, ?)");
checkError(conId);
time(&t);
double vals1[2] = {111.32, 115.55};
ret = MOB_executeWithTickData(conId, stmtId, (int) t, 123, vals1, 2);
checkError(conId);
MOB_execute(conId, "create table if not exists candles ("
"time datetime,"
"open double,"
"high double,"
"low double,"
"close double,"
"vol double"
")");
checkError(conId);
stmtId = MOB_prepareStatement(conId, "insert into candles values (?, ?, ?, ?, ?, ?)");
checkError(conId);
time(&t);
double vals2[5] = {1.3245, 1.5532, 0.9000, 1.0001, 1044.24};
ret = MOB_executeWithCandleData(conId, stmtId, (int) t, vals2, 5);
checkError(conId);
time(&t);
double vals3[5] = {1.11114, 1.11115, 0.999999, 0.000001, 1044.24};
ret = MOB_executeWithCandleData(conId, stmtId, (int) t, vals3, 5);
checkError(conId);
MOB_close(conId);
checkError(conId);
getchar();
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkSGDraw.h"
#include "SkSGGeometryNode.h"
#include "SkSGInvalidationController.h"
#include "SkSGPaintNode.h"
namespace sksg {
Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint)
: fGeometry(std::move(geometry))
, fPaint(std::move(paint)) {
fGeometry->addInvalReceiver(this);
fPaint->addInvalReceiver(this);
}
Draw::~Draw() {
fGeometry->removeInvalReceiver(this);
fPaint->removeInvalReceiver(this);
}
void Draw::onRender(SkCanvas* canvas) const {
fGeometry->draw(canvas, fPaint->makePaint());
}
SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
SkASSERT(this->hasInval());
// TODO: adjust bounds for paint
const auto bounds = fGeometry->revalidate(ic, ctm);
fPaint->revalidate(ic, ctm);
return bounds;
}
} // namespace sksg
<commit_msg>[skotty] Adjust Draw node bounds for paint<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkSGDraw.h"
#include "SkSGGeometryNode.h"
#include "SkSGInvalidationController.h"
#include "SkSGPaintNode.h"
namespace sksg {
Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint)
: fGeometry(std::move(geometry))
, fPaint(std::move(paint)) {
fGeometry->addInvalReceiver(this);
fPaint->addInvalReceiver(this);
}
Draw::~Draw() {
fGeometry->removeInvalReceiver(this);
fPaint->removeInvalReceiver(this);
}
void Draw::onRender(SkCanvas* canvas) const {
fGeometry->draw(canvas, fPaint->makePaint());
}
SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
SkASSERT(this->hasInval());
auto bounds = fGeometry->revalidate(ic, ctm);
fPaint->revalidate(ic, ctm);
const auto& paint = fPaint->makePaint();
SkASSERT(paint.canComputeFastBounds());
return paint.computeFastBounds(bounds, &bounds);
}
} // namespace sksg
<|endoftext|> |
<commit_before>// @(#)root/hist:$Id$
// Author: Rene Brun 12/12/94
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TVirtualPad.h"
#include "TPolyMarker.h"
#include "TClass.h"
#include "TMath.h"
ClassImp(TPolyMarker)
//______________________________________________________________________________
//
// a PolyMarker is defined by an array on N points in a 2-D space.
// At each point x[i], y[i] a marker is drawn.
// Marker attributes are managed by TAttMarker.
// See TMarker for the list of possible marker types.
//
//______________________________________________________________________________
TPolyMarker::TPolyMarker(): TObject()
{
// Default constructor.
fN = 0;
fX = fY = 0;
fLastPoint = -1;
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Option_t *option)
:TObject(), TAttMarker()
{
// Constructor.
fOption = option;
SetBit(kCanDelete);
fLastPoint = -1;
if (n <= 0) {
fN = 0;
fLastPoint = -1;
fX = fY = 0;
return;
}
fN = n;
fX = new Double_t [fN];
fY = new Double_t [fN];
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
:TObject(), TAttMarker()
{
// Constructor.
fOption = option;
SetBit(kCanDelete);
fLastPoint = -1;
if (n <= 0) {
fN = 0;
fLastPoint = -1;
fX = fY = 0;
return;
}
fN = n;
fX = new Double_t [fN];
fY = new Double_t [fN];
if (!x || !y) return;
for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
fLastPoint = fN-1;
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
:TObject(), TAttMarker()
{
// Constructor.
fOption = option;
SetBit(kCanDelete);
fLastPoint = -1;
if (n <= 0) {
fN = 0;
fLastPoint = -1;
fX = fY = 0;
return;
}
fN = n;
fX = new Double_t [fN];
fY = new Double_t [fN];
if (!x || !y) return;
for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
fLastPoint = fN-1;
}
//______________________________________________________________________________
TPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)
{
//assignment operator
if(this!=&pm) {
TObject::operator=(pm);
TAttMarker::operator=(pm);
fN=pm.fN;
fLastPoint=pm.fLastPoint;
fX=pm.fX;
fY=pm.fY;
fOption=pm.fOption;
}
return *this;
}
//______________________________________________________________________________
TPolyMarker::~TPolyMarker()
{
// Desctructor.
if (fX) delete [] fX;
if (fY) delete [] fY;
fLastPoint = -1;
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(const TPolyMarker &polymarker) : TObject(polymarker), TAttMarker(polymarker)
{
// Copy constructor.
((TPolyMarker&)polymarker).Copy(*this);
}
//______________________________________________________________________________
void TPolyMarker::Copy(TObject &obj) const
{
// Copy.
TObject::Copy(obj);
TAttMarker::Copy(((TPolyMarker&)obj));
((TPolyMarker&)obj).fN = fN;
if (fN > 0) {
((TPolyMarker&)obj).fX = new Double_t [fN];
((TPolyMarker&)obj).fY = new Double_t [fN];
for (Int_t i=0; i<fN;i++) { ((TPolyMarker&)obj).fX[i] = fX[i], ((TPolyMarker&)obj).fY[i] = fY[i]; }
} else {
((TPolyMarker&)obj).fX = 0;
((TPolyMarker&)obj).fY = 0;
}
((TPolyMarker&)obj).fOption = fOption;
((TPolyMarker&)obj).fLastPoint = fLastPoint;
}
//______________________________________________________________________________
Int_t TPolyMarker::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to a polymarker.
//
// Compute the closest distance of approach from point px,py to each point
// of the polymarker.
// Returns when the distance found is below DistanceMaximum.
// The distance is computed in pixels units.
const Int_t big = 9999;
// check if point is near one of the points
Int_t i, pxp, pyp, d;
Int_t distance = big;
for (i=0;i<Size();i++) {
pxp = gPad->XtoAbsPixel(gPad->XtoPad(fX[i]));
pyp = gPad->YtoAbsPixel(gPad->YtoPad(fY[i]));
d = TMath::Abs(pxp-px) + TMath::Abs(pyp-py);
if (d < distance) distance = d;
}
return distance;
}
//______________________________________________________________________________
void TPolyMarker::Draw(Option_t *option)
{
// Draw.
AppendPad(option);
}
//______________________________________________________________________________
void TPolyMarker::DrawPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *)
{
// Draw polymarker.
TPolyMarker *newpolymarker = new TPolyMarker(n,x,y);
TAttMarker::Copy(*newpolymarker);
newpolymarker->fOption = fOption;
newpolymarker->SetBit(kCanDelete);
newpolymarker->AppendPad();
}
//______________________________________________________________________________
void TPolyMarker::ExecuteEvent(Int_t, Int_t, Int_t)
{
// Execute action corresponding to one event.
//
// This member function must be implemented to realize the action
// corresponding to the mouse click on the object in the window
}
//______________________________________________________________________________
void TPolyMarker::ls(Option_t *) const
{
// ls.
TROOT::IndentLevel();
printf("TPolyMarker N=%d\n",fN);
}
//______________________________________________________________________________
Int_t TPolyMarker::Merge(TCollection *li)
{
// Merge polymarkers in the collection in this polymarker.
if (!li) return 0;
TIter next(li);
//first loop to count the number of entries
TPolyMarker *pm;
Int_t npoints = 0;
while ((pm = (TPolyMarker*)next())) {
if (!pm->InheritsFrom(TPolyMarker::Class())) {
Error("Add","Attempt to add object of class: %s to a %s",pm->ClassName(),this->ClassName());
return -1;
}
npoints += pm->Size();
}
//extend this polymarker to hold npoints
pm->SetPoint(npoints-1,0,0);
//merge all polymarkers
next.Reset();
while ((pm = (TPolyMarker*)next())) {
Int_t np = pm->Size();
Double_t *x = pm->GetX();
Double_t *y = pm->GetY();
for (Int_t i=0;i<np;i++) {
SetPoint(i,x[i],y[i]);
}
}
return npoints;
}
//______________________________________________________________________________
void TPolyMarker::Paint(Option_t *option)
{
// Paint.
PaintPolyMarker(fLastPoint+1, fX, fY, option);
}
//______________________________________________________________________________
void TPolyMarker::PaintPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
// Paint polymarker.
if (n <= 0) return;
TAttMarker::Modify(); //Change marker attributes only if necessary
Double_t *xx = x;
Double_t *yy = y;
if (gPad->GetLogx()) {
xx = new Double_t[n];
for (Int_t ix=0;ix<n;ix++) xx[ix] = gPad->XtoPad(x[ix]);
}
if (gPad->GetLogy()) {
yy = new Double_t[n];
for (Int_t iy=0;iy<n;iy++) yy[iy] = gPad->YtoPad(y[iy]);
}
gPad->PaintPolyMarker(n,xx,yy,option);
if (x != xx) delete [] xx;
if (y != yy) delete [] yy;
}
//______________________________________________________________________________
void TPolyMarker::Print(Option_t *) const
{
// Print polymarker.
printf("TPolyMarker N=%d\n",fN);
}
//______________________________________________________________________________
void TPolyMarker::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out.
char quote = '"';
out<<" "<<endl;
out<<" Double_t *dum = 0;"<<endl;
if (gROOT->ClassSaved(TPolyMarker::Class())) {
out<<" ";
} else {
out<<" TPolyMarker *";
}
out<<"pmarker = new TPolyMarker("<<fN<<",dum,dum,"<<quote<<fOption<<quote<<");"<<endl;
SaveMarkerAttributes(out,"pmarker",1,1,1);
for (Int_t i=0;i<Size();i++) {
out<<" pmarker->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl;
}
out<<" pmarker->Draw("
<<quote<<option<<quote<<");"<<endl;
}
//______________________________________________________________________________
Int_t TPolyMarker::SetNextPoint(Double_t x, Double_t y)
{
// Set point following LastPoint to x, y.
// Returns index of the point (new last point).
fLastPoint++;
SetPoint(fLastPoint, x, y);
return fLastPoint;
}
//______________________________________________________________________________
void TPolyMarker::SetPoint(Int_t n, Double_t x, Double_t y)
{
// Set point number n.
// if n is greater than the current size, the arrays are automatically
// extended
if (n < 0) return;
if (!fX || !fY || n >= fN) {
// re-allocate the object
Int_t newN = TMath::Max(2*fN,n+1);
Double_t *savex = new Double_t [newN];
Double_t *savey = new Double_t [newN];
if (fX && fN){
memcpy(savex,fX,fN*sizeof(Double_t));
memset(&savex[fN],0,(newN-fN)*sizeof(Double_t));
delete [] fX;
}
if (fY && fN){
memcpy(savey,fY,fN*sizeof(Double_t));
memset(&savey[fN],0,(newN-fN)*sizeof(Double_t));
delete [] fY;
}
fX = savex;
fY = savey;
fN = newN;
}
fX[n] = x;
fY[n] = y;
fLastPoint = TMath::Max(fLastPoint,n);
}
//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n)
{
// If n <= 0 the current arrays of points are deleted.
if (n <= 0) {
fN = 0;
fLastPoint = -1;
delete [] fX;
delete [] fY;
fX = fY = 0;
return;
}
SetPoint(n-1,0,0);
}
//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
{
// If n <= 0 the current arrays of points are deleted.
if (n <= 0) {
fN = 0;
fLastPoint = -1;
delete [] fX;
delete [] fY;
fX = fY = 0;
return;
}
fN =n;
if (fX) delete [] fX;
if (fY) delete [] fY;
fX = new Double_t[fN];
fY = new Double_t[fN];
for (Int_t i=0; i<fN;i++) {
if (x) fX[i] = (Double_t)x[i];
if (y) fY[i] = (Double_t)y[i];
}
fOption = option;
fLastPoint = fN-1;
}
//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
// If n <= 0 the current arrays of points are deleted.
if (n <= 0) {
fN = 0;
fLastPoint = -1;
delete [] fX;
delete [] fY;
fX = fY = 0;
return;
}
fN =n;
if (fX) delete [] fX;
if (fY) delete [] fY;
fX = new Double_t[fN];
fY = new Double_t[fN];
for (Int_t i=0; i<fN;i++) {
if (x) fX[i] = x[i];
if (y) fY[i] = y[i];
}
fOption = option;
fLastPoint = fN-1;
}
//_______________________________________________________________________
void TPolyMarker::Streamer(TBuffer &R__b)
{
// Stream a class object.
if (R__b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
R__b.ReadClassBuffer(TPolyMarker::Class(), this, R__v, R__s, R__c);
return;
}
//====process old versions before automatic schema evolution
TObject::Streamer(R__b);
TAttMarker::Streamer(R__b);
R__b >> fN;
fX = new Double_t[fN];
fY = new Double_t[fN];
Int_t i;
Float_t xold,yold;
for (i=0;i<fN;i++) {R__b >> xold; fX[i] = xold;}
for (i=0;i<fN;i++) {R__b >> yold; fY[i] = yold;}
fOption.Streamer(R__b);
R__b.CheckByteCount(R__s, R__c, TPolyMarker::IsA());
//====end of old versions
} else {
R__b.WriteClassBuffer(TPolyMarker::Class(),this);
}
}
<commit_msg>- init missing (coverity)<commit_after>// @(#)root/hist:$Id$
// Author: Rene Brun 12/12/94
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TVirtualPad.h"
#include "TPolyMarker.h"
#include "TClass.h"
#include "TMath.h"
ClassImp(TPolyMarker)
//______________________________________________________________________________
//
// a PolyMarker is defined by an array on N points in a 2-D space.
// At each point x[i], y[i] a marker is drawn.
// Marker attributes are managed by TAttMarker.
// See TMarker for the list of possible marker types.
//
//______________________________________________________________________________
TPolyMarker::TPolyMarker(): TObject()
{
// Default constructor.
fN = 0;
fX = fY = 0;
fLastPoint = -1;
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Option_t *option)
:TObject(), TAttMarker()
{
// Constructor.
fOption = option;
SetBit(kCanDelete);
fLastPoint = -1;
if (n <= 0) {
fN = 0;
fLastPoint = -1;
fX = fY = 0;
return;
}
fN = n;
fX = new Double_t [fN];
fY = new Double_t [fN];
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
:TObject(), TAttMarker()
{
// Constructor.
fOption = option;
SetBit(kCanDelete);
fLastPoint = -1;
if (n <= 0) {
fN = 0;
fLastPoint = -1;
fX = fY = 0;
return;
}
fN = n;
fX = new Double_t [fN];
fY = new Double_t [fN];
if (!x || !y) return;
for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
fLastPoint = fN-1;
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
:TObject(), TAttMarker()
{
// Constructor.
fOption = option;
SetBit(kCanDelete);
fLastPoint = -1;
if (n <= 0) {
fN = 0;
fLastPoint = -1;
fX = fY = 0;
return;
}
fN = n;
fX = new Double_t [fN];
fY = new Double_t [fN];
if (!x || !y) return;
for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }
fLastPoint = fN-1;
}
//______________________________________________________________________________
TPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)
{
//assignment operator
if(this!=&pm) {
TObject::operator=(pm);
TAttMarker::operator=(pm);
fN=pm.fN;
fLastPoint=pm.fLastPoint;
fX=pm.fX;
fY=pm.fY;
fOption=pm.fOption;
}
return *this;
}
//______________________________________________________________________________
TPolyMarker::~TPolyMarker()
{
// Desctructor.
if (fX) delete [] fX;
if (fY) delete [] fY;
fLastPoint = -1;
}
//______________________________________________________________________________
TPolyMarker::TPolyMarker(const TPolyMarker &polymarker) : TObject(polymarker), TAttMarker(polymarker)
{
// Copy constructor.
fN = 0;
fLastPoint = -1;
((TPolyMarker&)polymarker).Copy(*this);
}
//______________________________________________________________________________
void TPolyMarker::Copy(TObject &obj) const
{
// Copy.
TObject::Copy(obj);
TAttMarker::Copy(((TPolyMarker&)obj));
((TPolyMarker&)obj).fN = fN;
if (fN > 0) {
((TPolyMarker&)obj).fX = new Double_t [fN];
((TPolyMarker&)obj).fY = new Double_t [fN];
for (Int_t i=0; i<fN;i++) { ((TPolyMarker&)obj).fX[i] = fX[i], ((TPolyMarker&)obj).fY[i] = fY[i]; }
} else {
((TPolyMarker&)obj).fX = 0;
((TPolyMarker&)obj).fY = 0;
}
((TPolyMarker&)obj).fOption = fOption;
((TPolyMarker&)obj).fLastPoint = fLastPoint;
}
//______________________________________________________________________________
Int_t TPolyMarker::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to a polymarker.
//
// Compute the closest distance of approach from point px,py to each point
// of the polymarker.
// Returns when the distance found is below DistanceMaximum.
// The distance is computed in pixels units.
const Int_t big = 9999;
// check if point is near one of the points
Int_t i, pxp, pyp, d;
Int_t distance = big;
for (i=0;i<Size();i++) {
pxp = gPad->XtoAbsPixel(gPad->XtoPad(fX[i]));
pyp = gPad->YtoAbsPixel(gPad->YtoPad(fY[i]));
d = TMath::Abs(pxp-px) + TMath::Abs(pyp-py);
if (d < distance) distance = d;
}
return distance;
}
//______________________________________________________________________________
void TPolyMarker::Draw(Option_t *option)
{
// Draw.
AppendPad(option);
}
//______________________________________________________________________________
void TPolyMarker::DrawPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *)
{
// Draw polymarker.
TPolyMarker *newpolymarker = new TPolyMarker(n,x,y);
TAttMarker::Copy(*newpolymarker);
newpolymarker->fOption = fOption;
newpolymarker->SetBit(kCanDelete);
newpolymarker->AppendPad();
}
//______________________________________________________________________________
void TPolyMarker::ExecuteEvent(Int_t, Int_t, Int_t)
{
// Execute action corresponding to one event.
//
// This member function must be implemented to realize the action
// corresponding to the mouse click on the object in the window
}
//______________________________________________________________________________
void TPolyMarker::ls(Option_t *) const
{
// ls.
TROOT::IndentLevel();
printf("TPolyMarker N=%d\n",fN);
}
//______________________________________________________________________________
Int_t TPolyMarker::Merge(TCollection *li)
{
// Merge polymarkers in the collection in this polymarker.
if (!li) return 0;
TIter next(li);
//first loop to count the number of entries
TPolyMarker *pm;
Int_t npoints = 0;
while ((pm = (TPolyMarker*)next())) {
if (!pm->InheritsFrom(TPolyMarker::Class())) {
Error("Add","Attempt to add object of class: %s to a %s",pm->ClassName(),this->ClassName());
return -1;
}
npoints += pm->Size();
}
//extend this polymarker to hold npoints
pm->SetPoint(npoints-1,0,0);
//merge all polymarkers
next.Reset();
while ((pm = (TPolyMarker*)next())) {
Int_t np = pm->Size();
Double_t *x = pm->GetX();
Double_t *y = pm->GetY();
for (Int_t i=0;i<np;i++) {
SetPoint(i,x[i],y[i]);
}
}
return npoints;
}
//______________________________________________________________________________
void TPolyMarker::Paint(Option_t *option)
{
// Paint.
PaintPolyMarker(fLastPoint+1, fX, fY, option);
}
//______________________________________________________________________________
void TPolyMarker::PaintPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
// Paint polymarker.
if (n <= 0) return;
TAttMarker::Modify(); //Change marker attributes only if necessary
Double_t *xx = x;
Double_t *yy = y;
if (gPad->GetLogx()) {
xx = new Double_t[n];
for (Int_t ix=0;ix<n;ix++) xx[ix] = gPad->XtoPad(x[ix]);
}
if (gPad->GetLogy()) {
yy = new Double_t[n];
for (Int_t iy=0;iy<n;iy++) yy[iy] = gPad->YtoPad(y[iy]);
}
gPad->PaintPolyMarker(n,xx,yy,option);
if (x != xx) delete [] xx;
if (y != yy) delete [] yy;
}
//______________________________________________________________________________
void TPolyMarker::Print(Option_t *) const
{
// Print polymarker.
printf("TPolyMarker N=%d\n",fN);
}
//______________________________________________________________________________
void TPolyMarker::SavePrimitive(ostream &out, Option_t *option /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out.
char quote = '"';
out<<" "<<endl;
out<<" Double_t *dum = 0;"<<endl;
if (gROOT->ClassSaved(TPolyMarker::Class())) {
out<<" ";
} else {
out<<" TPolyMarker *";
}
out<<"pmarker = new TPolyMarker("<<fN<<",dum,dum,"<<quote<<fOption<<quote<<");"<<endl;
SaveMarkerAttributes(out,"pmarker",1,1,1);
for (Int_t i=0;i<Size();i++) {
out<<" pmarker->SetPoint("<<i<<","<<fX[i]<<","<<fY[i]<<");"<<endl;
}
out<<" pmarker->Draw("
<<quote<<option<<quote<<");"<<endl;
}
//______________________________________________________________________________
Int_t TPolyMarker::SetNextPoint(Double_t x, Double_t y)
{
// Set point following LastPoint to x, y.
// Returns index of the point (new last point).
fLastPoint++;
SetPoint(fLastPoint, x, y);
return fLastPoint;
}
//______________________________________________________________________________
void TPolyMarker::SetPoint(Int_t n, Double_t x, Double_t y)
{
// Set point number n.
// if n is greater than the current size, the arrays are automatically
// extended
if (n < 0) return;
if (!fX || !fY || n >= fN) {
// re-allocate the object
Int_t newN = TMath::Max(2*fN,n+1);
Double_t *savex = new Double_t [newN];
Double_t *savey = new Double_t [newN];
if (fX && fN){
memcpy(savex,fX,fN*sizeof(Double_t));
memset(&savex[fN],0,(newN-fN)*sizeof(Double_t));
delete [] fX;
}
if (fY && fN){
memcpy(savey,fY,fN*sizeof(Double_t));
memset(&savey[fN],0,(newN-fN)*sizeof(Double_t));
delete [] fY;
}
fX = savex;
fY = savey;
fN = newN;
}
fX[n] = x;
fY[n] = y;
fLastPoint = TMath::Max(fLastPoint,n);
}
//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n)
{
// If n <= 0 the current arrays of points are deleted.
if (n <= 0) {
fN = 0;
fLastPoint = -1;
delete [] fX;
delete [] fY;
fX = fY = 0;
return;
}
SetPoint(n-1,0,0);
}
//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)
{
// If n <= 0 the current arrays of points are deleted.
if (n <= 0) {
fN = 0;
fLastPoint = -1;
delete [] fX;
delete [] fY;
fX = fY = 0;
return;
}
fN =n;
if (fX) delete [] fX;
if (fY) delete [] fY;
fX = new Double_t[fN];
fY = new Double_t[fN];
for (Int_t i=0; i<fN;i++) {
if (x) fX[i] = (Double_t)x[i];
if (y) fY[i] = (Double_t)y[i];
}
fOption = option;
fLastPoint = fN-1;
}
//______________________________________________________________________________
void TPolyMarker::SetPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)
{
// If n <= 0 the current arrays of points are deleted.
if (n <= 0) {
fN = 0;
fLastPoint = -1;
delete [] fX;
delete [] fY;
fX = fY = 0;
return;
}
fN =n;
if (fX) delete [] fX;
if (fY) delete [] fY;
fX = new Double_t[fN];
fY = new Double_t[fN];
for (Int_t i=0; i<fN;i++) {
if (x) fX[i] = x[i];
if (y) fY[i] = y[i];
}
fOption = option;
fLastPoint = fN-1;
}
//_______________________________________________________________________
void TPolyMarker::Streamer(TBuffer &R__b)
{
// Stream a class object.
if (R__b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
R__b.ReadClassBuffer(TPolyMarker::Class(), this, R__v, R__s, R__c);
return;
}
//====process old versions before automatic schema evolution
TObject::Streamer(R__b);
TAttMarker::Streamer(R__b);
R__b >> fN;
fX = new Double_t[fN];
fY = new Double_t[fN];
Int_t i;
Float_t xold,yold;
for (i=0;i<fN;i++) {R__b >> xold; fX[i] = xold;}
for (i=0;i<fN;i++) {R__b >> yold; fY[i] = yold;}
fOption.Streamer(R__b);
R__b.CheckByteCount(R__s, R__c, TPolyMarker::IsA());
//====end of old versions
} else {
R__b.WriteClassBuffer(TPolyMarker::Class(),this);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cluster.h"
#include "bucket.h"
#include "node.h"
#include <platform/dirutils.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <iostream>
#include <vector>
namespace cb {
namespace test {
Cluster::~Cluster() = default;
class ClusterImpl : public Cluster {
public:
ClusterImpl() = delete;
ClusterImpl(const ClusterImpl&) = delete;
ClusterImpl(std::vector<std::unique_ptr<Node>>& nodes, std::string dir)
: nodes(std::move(nodes)), directory(std::move(dir)) {
}
~ClusterImpl() override;
std::shared_ptr<Bucket> createBucket(
const std::string& name,
const nlohmann::json& attributes,
DcpPacketFilter packet_filter) override;
void deleteBucket(const std::string& name) override;
std::shared_ptr<Bucket> getBucket(const std::string& name) const override {
for (auto& bucket : buckets) {
if (bucket->getName() == name) {
return bucket;
}
}
return std::shared_ptr<Bucket>();
}
std::unique_ptr<MemcachedConnection> getConnection(
size_t node) const override {
if (node < nodes.size()) {
return nodes[node]->getConnection();
}
throw std::invalid_argument(
"ClusterImpl::getConnection: Invalid node number");
}
size_t size() const override;
protected:
std::vector<std::unique_ptr<Node>> nodes;
std::vector<std::shared_ptr<Bucket>> buckets;
const std::string directory;
};
std::shared_ptr<Bucket> ClusterImpl::createBucket(
const std::string& name,
const nlohmann::json& attributes,
DcpPacketFilter packet_filter) {
size_t vbuckets = 1024;
size_t replicas = std::min<size_t>(nodes.size() - 1, 3);
nlohmann::json json = {{"max_size", 67108864},
{"backend", "couchdb"},
{"couch_bucket", name},
{"max_vbuckets", vbuckets},
{"data_traffic_enabled", false},
{"max_num_workers", 3},
{"conflict_resolution_type", "seqno"},
{"bucket_type", "persistent"},
{"item_eviction_policy", "value_only"},
{"max_ttl", 0},
{"ht_locks", 47},
{"compression_mode", "off"},
{"failpartialwarmup", false}};
json.update(attributes);
auto iter = json.find("max_vbuckets");
if (iter != json.end()) {
vbuckets = iter->get<size_t>();
}
iter = json.find("replicas");
if (iter != json.end()) {
replicas = iter->get<size_t>();
// The underlying bucket don't know about replicas
json.erase(iter);
if (replicas > nodes.size() - 1) {
throw std::invalid_argument(
"ClusterImpl::createBucket: Not enough nodes in the "
"cluster for " +
std::to_string(replicas) + " replicas");
}
}
auto bucket = std::make_shared<Bucket>(
*this, name, vbuckets, replicas, packet_filter);
const auto& vbucketmap = bucket->getVbucketMap();
json["uuid"] = bucket->getUuid();
try {
// @todo I need at least the number of nodes to set active + n replicas
for (std::size_t node_idx = 0; node_idx < nodes.size(); ++node_idx) {
auto connection = nodes[node_idx]->getConnection();
connection->connect();
connection->authenticate("@admin", "password", "plain");
connection->setFeatures("cluster_testapp",
{{cb::mcbp::Feature::MUTATION_SEQNO,
cb::mcbp::Feature::XATTR,
cb::mcbp::Feature::XERROR,
cb::mcbp::Feature::SELECT_BUCKET,
cb::mcbp::Feature::JSON,
cb::mcbp::Feature::SNAPPY}});
std::string fname = nodes[node_idx]->directory + "/" + name;
std::replace(fname.begin(), fname.end(), '\\', '/');
json["dbname"] = fname;
fname = json["dbname"].get<std::string>() + "/access.log";
std::replace(fname.begin(), fname.end(), '\\', '/');
json["alog_path"] = fname;
std::string config;
for (auto it = json.begin(); it != json.end(); ++it) {
if (it.value().is_string()) {
config += it.key() + "=" + it.value().get<std::string>() +
";";
} else {
config += it.key() + "=" + it.value().dump() + ";";
}
}
connection->createBucket(name, config, BucketType::Couchbase);
connection->selectBucket(name);
// iterate over all of the vbuckets and find that node number and
// define the vbuckets
for (std::size_t vbucket = 0; vbucket < vbucketmap.size();
++vbucket) {
std::vector<std::string> chain;
for (int ii : vbucketmap[vbucket]) {
chain.emplace_back("n_" + std::to_string(ii));
}
nlohmann::json topology = {
{"topology", nlohmann::json::array({chain})}};
for (std::size_t ii = 0; ii < vbucketmap[vbucket].size();
++ii) {
if (vbucketmap[vbucket][ii] == int(node_idx)) {
// This is me
if (ii == 0) {
connection->setVbucket(Vbid{uint16_t(vbucket)},
vbucket_state_active,
topology);
} else {
connection->setVbucket(Vbid{uint16_t(vbucket)},
vbucket_state_replica,
{});
}
}
}
}
// Call enable traffic
const auto rsp = connection->execute(BinprotGenericCommand{
cb::mcbp::ClientOpcode::EnableTraffic});
if (!rsp.isSuccess()) {
throw ConnectionError("Failed to enable traffic",
rsp.getStatus());
}
}
bucket->setupReplication();
buckets.push_back(bucket);
return bucket;
} catch (const ConnectionError& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
for (auto& b : nodes) {
auto connection = b->getConnection();
connection->connect();
connection->authenticate("@admin", "password", "plain");
try {
connection->deleteBucket(name);
} catch (const std::exception&) {
}
}
}
return {};
}
void ClusterImpl::deleteBucket(const std::string& name) {
for (auto iter = buckets.begin(); iter != buckets.end(); ++iter) {
if ((*iter)->getName() == name) {
// The DCP replicators throws an exception if they get a
// read error (in the case of others holding a reference
// to the bucket class)...
(*iter)->shutdownReplication();
buckets.erase(iter);
break;
}
}
// I should wait for the bucket being closed on all nodes..
for (auto& n : nodes) {
auto connection = n->getConnection();
connection->connect();
connection->authenticate("@admin", "password", "plain");
connection->deleteBucket(name);
}
}
size_t ClusterImpl::size() const {
return nodes.size();
}
ClusterImpl::~ClusterImpl() {
buckets.clear();
bool cleanup = true;
for (auto& n : nodes) {
std::string minidump_dir = n->directory + "/crash";
cb::io::sanitizePath(minidump_dir);
if (cb::io::isDirectory(minidump_dir)) {
auto files = cb::io::findFilesWithPrefix(minidump_dir, "");
cleanup &= files.empty();
}
}
nodes.clear();
// @todo I should make this configurable?
if (cleanup && cb::io::isDirectory(directory)) {
cb::io::rmrf(directory);
}
}
std::unique_ptr<Cluster> Cluster::create(size_t num_nodes) {
auto pattern = cb::io::getcwd() + "/cluster_";
cb::io::sanitizePath(pattern);
auto clusterdir = cb::io::mkdtemp(pattern);
std::vector<std::unique_ptr<Node>> nodes;
for (size_t n = 0; n < num_nodes; ++n) {
const std::string id = "n_" + std::to_string(n);
std::string nodedir = clusterdir + "/" + id;
cb::io::sanitizePath(nodedir);
cb::io::mkdirp(nodedir);
nodes.emplace_back(Node::create(nodedir, id));
}
return std::make_unique<ClusterImpl>(nodes, clusterdir);
}
} // namespace test
} // namespace cb
<commit_msg>MB-35592: Fix hang situation in cluster_test<commit_after>/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cluster.h"
#include "bucket.h"
#include "node.h"
#include <platform/dirutils.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <iostream>
#include <vector>
namespace cb {
namespace test {
Cluster::~Cluster() = default;
class ClusterImpl : public Cluster {
public:
ClusterImpl() = delete;
ClusterImpl(const ClusterImpl&) = delete;
ClusterImpl(std::vector<std::unique_ptr<Node>>& nodes, std::string dir)
: nodes(std::move(nodes)), directory(std::move(dir)) {
}
~ClusterImpl() override;
std::shared_ptr<Bucket> createBucket(
const std::string& name,
const nlohmann::json& attributes,
DcpPacketFilter packet_filter) override;
void deleteBucket(const std::string& name) override;
std::shared_ptr<Bucket> getBucket(const std::string& name) const override {
for (auto& bucket : buckets) {
if (bucket->getName() == name) {
return bucket;
}
}
return std::shared_ptr<Bucket>();
}
std::unique_ptr<MemcachedConnection> getConnection(
size_t node) const override {
if (node < nodes.size()) {
return nodes[node]->getConnection();
}
throw std::invalid_argument(
"ClusterImpl::getConnection: Invalid node number");
}
size_t size() const override;
protected:
std::vector<std::unique_ptr<Node>> nodes;
std::vector<std::shared_ptr<Bucket>> buckets;
const std::string directory;
};
std::shared_ptr<Bucket> ClusterImpl::createBucket(
const std::string& name,
const nlohmann::json& attributes,
DcpPacketFilter packet_filter) {
size_t vbuckets = 1024;
size_t replicas = std::min<size_t>(nodes.size() - 1, 3);
nlohmann::json json = {{"max_size", 67108864},
{"backend", "couchdb"},
{"couch_bucket", name},
{"max_vbuckets", vbuckets},
{"data_traffic_enabled", false},
{"max_num_workers", 3},
{"conflict_resolution_type", "seqno"},
{"bucket_type", "persistent"},
{"item_eviction_policy", "value_only"},
{"max_ttl", 0},
{"ht_locks", 47},
{"compression_mode", "off"},
{"failpartialwarmup", false}};
json.update(attributes);
auto iter = json.find("max_vbuckets");
if (iter != json.end()) {
vbuckets = iter->get<size_t>();
}
iter = json.find("replicas");
if (iter != json.end()) {
replicas = iter->get<size_t>();
// The underlying bucket don't know about replicas
json.erase(iter);
if (replicas > nodes.size() - 1) {
throw std::invalid_argument(
"ClusterImpl::createBucket: Not enough nodes in the "
"cluster for " +
std::to_string(replicas) + " replicas");
}
}
auto bucket = std::make_shared<Bucket>(
*this, name, vbuckets, replicas, packet_filter);
const auto& vbucketmap = bucket->getVbucketMap();
json["uuid"] = bucket->getUuid();
try {
// @todo I need at least the number of nodes to set active + n replicas
for (std::size_t node_idx = 0; node_idx < nodes.size(); ++node_idx) {
auto connection = nodes[node_idx]->getConnection();
connection->connect();
connection->authenticate("@admin", "password", "plain");
connection->setFeatures("cluster_testapp",
{{cb::mcbp::Feature::MUTATION_SEQNO,
cb::mcbp::Feature::XATTR,
cb::mcbp::Feature::XERROR,
cb::mcbp::Feature::SELECT_BUCKET,
cb::mcbp::Feature::JSON,
cb::mcbp::Feature::SNAPPY}});
std::string fname = nodes[node_idx]->directory + "/" + name;
std::replace(fname.begin(), fname.end(), '\\', '/');
json["dbname"] = fname;
fname = json["dbname"].get<std::string>() + "/access.log";
std::replace(fname.begin(), fname.end(), '\\', '/');
json["alog_path"] = fname;
std::string config;
for (auto it = json.begin(); it != json.end(); ++it) {
if (it.value().is_string()) {
config += it.key() + "=" + it.value().get<std::string>() +
";";
} else {
config += it.key() + "=" + it.value().dump() + ";";
}
}
connection->createBucket(name, config, BucketType::Couchbase);
connection->selectBucket(name);
// iterate over all of the vbuckets and find that node number and
// define the vbuckets
for (std::size_t vbucket = 0; vbucket < vbucketmap.size();
++vbucket) {
std::vector<std::string> chain;
for (int ii : vbucketmap[vbucket]) {
chain.emplace_back("n_" + std::to_string(ii));
}
nlohmann::json topology = {
{"topology", nlohmann::json::array({chain})}};
for (std::size_t ii = 0; ii < vbucketmap[vbucket].size();
++ii) {
if (vbucketmap[vbucket][ii] == int(node_idx)) {
// This is me
if (ii == 0) {
connection->setVbucket(Vbid{uint16_t(vbucket)},
vbucket_state_active,
topology);
} else {
connection->setVbucket(Vbid{uint16_t(vbucket)},
vbucket_state_replica,
{});
}
}
}
}
// Call enable traffic
const auto rsp = connection->execute(BinprotGenericCommand{
cb::mcbp::ClientOpcode::EnableTraffic});
if (!rsp.isSuccess()) {
throw ConnectionError("Failed to enable traffic",
rsp.getStatus());
}
}
bucket->setupReplication();
buckets.push_back(bucket);
return bucket;
} catch (const ConnectionError& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
for (auto& b : nodes) {
auto connection = b->getConnection();
connection->connect();
connection->authenticate("@admin", "password", "plain");
try {
connection->deleteBucket(name);
} catch (const std::exception&) {
}
}
}
return {};
}
void ClusterImpl::deleteBucket(const std::string& name) {
for (auto iter = buckets.begin(); iter != buckets.end(); ++iter) {
if ((*iter)->getName() == name) {
// The DCP replicators throws an exception if they get a
// read error (in the case of others holding a reference
// to the bucket class)...
(*iter)->shutdownReplication();
buckets.erase(iter);
break;
}
}
// I should wait for the bucket being closed on all nodes..
for (auto& n : nodes) {
auto connection = n->getConnection();
connection->connect();
connection->authenticate("@admin", "password", "plain");
connection->deleteBucket(name);
// And nuke the files for the database on that node..
std::string bucketdir = n->directory + "/" + name;
cb::io::sanitizePath(bucketdir);
cb::io::rmrf(bucketdir);
}
}
size_t ClusterImpl::size() const {
return nodes.size();
}
ClusterImpl::~ClusterImpl() {
buckets.clear();
bool cleanup = true;
for (auto& n : nodes) {
std::string minidump_dir = n->directory + "/crash";
cb::io::sanitizePath(minidump_dir);
if (cb::io::isDirectory(minidump_dir)) {
auto files = cb::io::findFilesWithPrefix(minidump_dir, "");
cleanup &= files.empty();
}
}
nodes.clear();
// @todo I should make this configurable?
if (cleanup && cb::io::isDirectory(directory)) {
cb::io::rmrf(directory);
}
}
std::unique_ptr<Cluster> Cluster::create(size_t num_nodes) {
auto pattern = cb::io::getcwd() + "/cluster_";
cb::io::sanitizePath(pattern);
auto clusterdir = cb::io::mkdtemp(pattern);
std::vector<std::unique_ptr<Node>> nodes;
for (size_t n = 0; n < num_nodes; ++n) {
const std::string id = "n_" + std::to_string(n);
std::string nodedir = clusterdir + "/" + id;
cb::io::sanitizePath(nodedir);
cb::io::mkdirp(nodedir);
nodes.emplace_back(Node::create(nodedir, id));
}
return std::make_unique<ClusterImpl>(nodes, clusterdir);
}
} // namespace test
} // namespace cb
<|endoftext|> |
<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/UberShaderPreprocessor.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Renderer/OpenGL.hpp>
#include <algorithm>
#include <memory>
#include <Nazara/Renderer/Debug.hpp>
namespace Nz
{
UberShaderPreprocessor::~UberShaderPreprocessor()
{
OnUberShaderPreprocessorRelease(this);
}
UberShaderInstance* UberShaderPreprocessor::Get(const ParameterList& parameters) const
{
// Première étape, transformer les paramètres en un flag
UInt32 flags = 0;
for (auto it = m_flags.begin(); it != m_flags.end(); ++it)
{
if (parameters.HasParameter(it->first))
{
bool value;
if (parameters.GetBooleanParameter(it->first, &value) && value)
flags |= it->second;
}
}
// Le shader fait-il partie du cache ?
auto shaderIt = m_cache.find(flags);
// Si non, il nous faut le construire
if (shaderIt == m_cache.end())
{
try
{
// Une exception sera lancée à la moindre erreur et celle-ci ne sera pas enregistrée dans le log (car traitée dans le bloc catch)
ErrorFlags errFlags(ErrorFlag_Silent | ErrorFlag_ThrowException, true);
ShaderRef shader = Shader::New();
shader->Create();
for (unsigned int i = 0; i <= ShaderStageType_Max; ++i)
{
const CachedShader& shaderStage = m_shaders[i];
// Le shader stage est-il activé dans cette version du shader ?
if (shaderStage.present && (flags & shaderStage.requiredFlags) == shaderStage.requiredFlags)
{
UInt32 stageFlags = 0;
for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it)
{
if (parameters.HasParameter(it->first))
{
bool value;
if (parameters.GetBooleanParameter(it->first, &value) && value)
stageFlags |= it->second;
}
}
auto stageIt = shaderStage.cache.find(stageFlags);
if (stageIt == shaderStage.cache.end())
{
ShaderStage stage;
stage.Create(static_cast<ShaderStageType>(i));
unsigned int glslVersion = OpenGL::GetGLSLVersion();
StringStream code;
code << "#version " << glslVersion << "\n\n";
code << "#define GLSL_VERSION " << glslVersion << "\n\n";
code << "#define EARLY_FRAGMENT_TEST " << (glslVersion >= 420 || OpenGL::IsSupported(OpenGLExtension_Shader_ImageLoadStore)) << "\n\n";
for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it)
code << "#define " << it->first << ' ' << ((stageFlags & it->second) ? '1' : '0') << '\n';
code << "\n#line 1\n"; // Pour que les éventuelles erreurs du shader se réfèrent à la bonne ligne
code << shaderStage.source;
stage.SetSource(code);
stage.Compile();
stageIt = shaderStage.cache.emplace(flags, std::move(stage)).first;
}
shader->AttachStage(static_cast<ShaderStageType>(i), stageIt->second);
}
}
shader->Link();
// On construit l'instant
shaderIt = m_cache.emplace(flags, shader.Get()).first;
}
catch (const std::exception&)
{
ErrorFlags errFlags(ErrorFlag_ThrowExceptionDisabled);
NazaraError("Failed to build UberShader instance: " + Error::GetLastError());
throw;
}
}
return &shaderIt->second;
}
void UberShaderPreprocessor::SetShader(ShaderStageType stage, const String& source, const String& shaderFlags, const String& requiredFlags)
{
CachedShader& shader = m_shaders[stage];
shader.present = true;
shader.source = source;
// On extrait les flags de la chaîne
std::vector<String> flags;
shaderFlags.Split(flags, ' ');
for (String& flag : flags)
{
auto it = m_flags.find(flag);
if (it == m_flags.end())
m_flags[flag] = 1U << m_flags.size();
auto it2 = shader.flags.find(flag);
if (it2 == shader.flags.end())
shader.flags[flag] = 1U << shader.flags.size();
}
// On construit les flags requis pour l'activation du shader
shader.requiredFlags = 0;
flags.clear();
requiredFlags.Split(flags, ' ');
for (String& flag : flags)
{
UInt32 flagVal;
auto it = m_flags.find(flag);
if (it == m_flags.end())
{
flagVal = 1U << m_flags.size();
m_flags[flag] = flagVal;
}
else
flagVal = it->second;
shader.requiredFlags |= flagVal;
}
}
bool UberShaderPreprocessor::SetShaderFromFile(ShaderStageType stage, const String& filePath, const String& shaderFlags, const String& requiredFlags)
{
File file(filePath);
if (!file.Open(OpenMode_ReadOnly | OpenMode_Text))
{
NazaraError("Failed to open \"" + filePath + '"');
return false;
}
unsigned int length = static_cast<unsigned int>(file.GetSize());
String source(length, '\0');
if (file.Read(&source[0], length) != length)
{
NazaraError("Failed to read program file");
return false;
}
file.Close();
SetShader(stage, source, shaderFlags, requiredFlags);
return true;
}
bool UberShaderPreprocessor::IsSupported()
{
return true; // Forcément supporté
}
}
<commit_msg>Renderer/UberShaderPreprocessor: Fix compilation error with some drivers<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/UberShaderPreprocessor.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Renderer/OpenGL.hpp>
#include <algorithm>
#include <memory>
#include <Nazara/Renderer/Debug.hpp>
namespace Nz
{
UberShaderPreprocessor::~UberShaderPreprocessor()
{
OnUberShaderPreprocessorRelease(this);
}
UberShaderInstance* UberShaderPreprocessor::Get(const ParameterList& parameters) const
{
// Première étape, transformer les paramètres en un flag
UInt32 flags = 0;
for (auto it = m_flags.begin(); it != m_flags.end(); ++it)
{
if (parameters.HasParameter(it->first))
{
bool value;
if (parameters.GetBooleanParameter(it->first, &value) && value)
flags |= it->second;
}
}
// Le shader fait-il partie du cache ?
auto shaderIt = m_cache.find(flags);
// Si non, il nous faut le construire
if (shaderIt == m_cache.end())
{
try
{
// Une exception sera lancée à la moindre erreur et celle-ci ne sera pas enregistrée dans le log (car traitée dans le bloc catch)
ErrorFlags errFlags(ErrorFlag_Silent | ErrorFlag_ThrowException, true);
ShaderRef shader = Shader::New();
shader->Create();
for (unsigned int i = 0; i <= ShaderStageType_Max; ++i)
{
const CachedShader& shaderStage = m_shaders[i];
// Le shader stage est-il activé dans cette version du shader ?
if (shaderStage.present && (flags & shaderStage.requiredFlags) == shaderStage.requiredFlags)
{
UInt32 stageFlags = 0;
for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it)
{
if (parameters.HasParameter(it->first))
{
bool value;
if (parameters.GetBooleanParameter(it->first, &value) && value)
stageFlags |= it->second;
}
}
auto stageIt = shaderStage.cache.find(stageFlags);
if (stageIt == shaderStage.cache.end())
{
ShaderStage stage;
stage.Create(static_cast<ShaderStageType>(i));
unsigned int glslVersion = OpenGL::GetGLSLVersion();
StringStream code;
code << "#version " << glslVersion << "\n\n";
code << "#define GLSL_VERSION " << glslVersion << "\n\n";
code << "#define EARLY_FRAGMENT_TEST " << ((glslVersion >= 420 || OpenGL::IsSupported(OpenGLExtension_Shader_ImageLoadStore)) ? '1' : '0') << "\n\n";
for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it)
code << "#define " << it->first << ' ' << ((stageFlags & it->second) ? '1' : '0') << '\n';
code << "\n#line 1\n"; // Pour que les éventuelles erreurs du shader se réfèrent à la bonne ligne
code << shaderStage.source;
stage.SetSource(code);
stage.Compile();
stageIt = shaderStage.cache.emplace(flags, std::move(stage)).first;
}
shader->AttachStage(static_cast<ShaderStageType>(i), stageIt->second);
}
}
shader->Link();
// On construit l'instant
shaderIt = m_cache.emplace(flags, shader.Get()).first;
}
catch (const std::exception&)
{
ErrorFlags errFlags(ErrorFlag_ThrowExceptionDisabled);
NazaraError("Failed to build UberShader instance: " + Error::GetLastError());
throw;
}
}
return &shaderIt->second;
}
void UberShaderPreprocessor::SetShader(ShaderStageType stage, const String& source, const String& shaderFlags, const String& requiredFlags)
{
CachedShader& shader = m_shaders[stage];
shader.present = true;
shader.source = source;
// On extrait les flags de la chaîne
std::vector<String> flags;
shaderFlags.Split(flags, ' ');
for (String& flag : flags)
{
auto it = m_flags.find(flag);
if (it == m_flags.end())
m_flags[flag] = 1U << m_flags.size();
auto it2 = shader.flags.find(flag);
if (it2 == shader.flags.end())
shader.flags[flag] = 1U << shader.flags.size();
}
// On construit les flags requis pour l'activation du shader
shader.requiredFlags = 0;
flags.clear();
requiredFlags.Split(flags, ' ');
for (String& flag : flags)
{
UInt32 flagVal;
auto it = m_flags.find(flag);
if (it == m_flags.end())
{
flagVal = 1U << m_flags.size();
m_flags[flag] = flagVal;
}
else
flagVal = it->second;
shader.requiredFlags |= flagVal;
}
}
bool UberShaderPreprocessor::SetShaderFromFile(ShaderStageType stage, const String& filePath, const String& shaderFlags, const String& requiredFlags)
{
File file(filePath);
if (!file.Open(OpenMode_ReadOnly | OpenMode_Text))
{
NazaraError("Failed to open \"" + filePath + '"');
return false;
}
unsigned int length = static_cast<unsigned int>(file.GetSize());
String source(length, '\0');
if (file.Read(&source[0], length) != length)
{
NazaraError("Failed to read program file");
return false;
}
file.Close();
SetShader(stage, source, shaderFlags, requiredFlags);
return true;
}
bool UberShaderPreprocessor::IsSupported()
{
return true; // Forcément supporté
}
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_WATCHABLE_HPP_
#define CONCURRENCY_WATCHABLE_HPP_
#include <functional>
#include "errors.hpp"
#include <boost/function.hpp>
#include "concurrency/interruptor.hpp"
#include "concurrency/mutex_assertion.hpp"
#include "concurrency/pubsub.hpp"
#include "concurrency/signal.hpp"
#include "containers/clone_ptr.hpp"
#include "utils.hpp"
/* `watchable_t` represents a variable that you can get the value of and also
subscribe to further changes to the value. To get the value of a `watchable_t`,
just call `get()`. To subscribe to further changes to the value, construct a
`watchable_t::freeze_t` and then construct a `watchable_t::subscription_t`,
passing it the `watchable_t` and the `freeze_t`.
To create a `watchable_t`, construct a `watchable_variable_t` and then call its
`get_watchable()` method. You can change the value of the `watchable_t` by
calling `watchable_variable_t::set_value()`.
`watchable_t` has a home thread; it can only be accessed from that thread. If
you need to access it from another thread, consider using
`cross_thread_watchable_variable_t` to create a proxy-watchable with a different
home thread. */
template <class value_t> class watchable_t;
template <class value_t> class watchable_freeze_t;
template <class value_t>
class watchable_subscription_t {
public:
/* The `std::function<void()>` passed to the constructor is a callback
that will be called whenever the value changes. The callback must not
block, and it must not create or destroy `subscription_t` objects. */
explicit watchable_subscription_t(const std::function<void()> &f)
: subscription(f)
{ }
watchable_subscription_t(const std::function<void()> &f, const clone_ptr_t<watchable_t<value_t> > &watchable,
watchable_freeze_t<value_t> *freeze)
: subscription(f, watchable->get_publisher()) {
watchable->assert_thread();
freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion());
}
void reset() {
subscription.reset();
}
void reset(const clone_ptr_t<watchable_t<value_t> > &watchable, watchable_freeze_t<value_t> *freeze) {
watchable->assert_thread();
freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion());
subscription.reset(watchable->get_publisher());
}
private:
typename publisher_t<std::function<void()> >::subscription_t subscription;
DISABLE_COPYING(watchable_subscription_t);
};
/* The purpose of the `freeze_t` is to assert that the value of the
`watchable_t` doesn't change for as long as it exists. You should not block
while the `freeze_t` exists. It's kind of like `mutex_assertion_t`.
A common pattern is to construct a `freeze_t`, then call `get()` to
initialize some object or objects that mirrors the `watchable_t`'s value,
then construct a `subscription_t` to continually keep in sync with the
`watchable_t`, then destroy the `freeze_t`. If it weren't for the
`freeze_t`, a change might "slip through the cracks" if it happened after
`get()` but before constructing the `subscription_t`. If you constructed the
`subscription_t` before calling `get()`, then the callback might get run
before the objects were first initialized. */
template <class value_t>
class watchable_freeze_t {
public:
explicit watchable_freeze_t(const clone_ptr_t<watchable_t<value_t> > &watchable)
: rwi_lock_acquisition(watchable->get_rwi_lock_assertion())
{
watchable->assert_thread();
}
void assert_is_holding(const clone_ptr_t<watchable_t<value_t> > &watchable) {
rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion());
}
private:
friend class watchable_subscription_t<value_t>;
rwi_lock_assertion_t::read_acq_t rwi_lock_acquisition;
DISABLE_COPYING(watchable_freeze_t);
};
template <class value_t>
class watchable_t : public home_thread_mixin_t {
public:
typedef watchable_freeze_t<value_t> freeze_t;
typedef watchable_subscription_t<value_t> subscription_t;
virtual ~watchable_t() { }
virtual watchable_t *clone() const = 0;
virtual value_t get() = 0;
/* Applies `read` to the current value of the watchable. `read` must not block
and cannot change the value. */
virtual void apply_read(const std::function<void(const value_t*)> &read) = 0;
/* These are internal; the reason they're public is so that `subview()` and
similar things can be implemented. */
virtual publisher_t<std::function<void()> > *get_publisher() = 0;
virtual rwi_lock_assertion_t *get_rwi_lock_assertion() = 0;
/* `subview()` returns another `watchable_t` whose value is derived from
this one by calling `lens` on it. */
template<class callable_type>
clone_ptr_t<watchable_t<typename std::result_of<callable_type(value_t)>::type> > subview(const callable_type &lens);
/* `incremental_subview()` is like `subview()`. However it takes an incremental lens.
An incremental lens has the signature
`bool(const input_type &, result_type *current_out)`.
In contrast to a regular (non-incremental) lens it therefore has access to
the current value of the output value and can modify it in-place.
It should return true if `current_out` has been modified, and false otherwise.
We have two variants of this. The first one is a short-cut for incremental lenses
which contain a `result_type` typedef. In this case, result_type does not have
to be specified explicitly when calling `incremental_subview()`. Otherwise
the second variant must be used and `result_type` be specified as a template
parameter. */
template<class callable_type>
clone_ptr_t<watchable_t<typename callable_type::result_type> > incremental_subview(const callable_type &lens);
template<class result_type, class callable_type>
clone_ptr_t<watchable_t<result_type> > incremental_subview(const callable_type &lens);
/* `run_until_satisfied()` repeatedly calls `fun` on the current value of
`this` until either `fun` returns `true` or `interruptor` is pulsed. It's
efficient because it only retries `fun` when the value changes. */
template<class callable_type>
void run_until_satisfied(const callable_type &fun, signal_t *interruptor,
int64_t nap_before_retry_ms = 0) THROWS_ONLY(interrupted_exc_t);
protected:
watchable_t() { }
private:
DISABLE_COPYING(watchable_t);
};
/* `run_until_satisfied_2()` repeatedly calls `fun(a->get(), b->get())` until
`fun` returns `true` or `interruptor` is pulsed. It's efficient because it only
retries `fun` when the value of `a` or `b` changes. */
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2(
const clone_ptr_t<watchable_t<a_type> > &a,
const clone_ptr_t<watchable_t<b_type> > &b,
const callable_type &fun,
signal_t *interruptor,
int64_t nap_before_retry_ms = 0) THROWS_ONLY(interrupted_exc_t);
inline void call_function(const std::function<void()> &f) {
f();
}
template <class value_t>
class watchable_variable_t {
public:
explicit watchable_variable_t(const value_t &_value)
: value(_value), watchable(this)
{ }
clone_ptr_t<watchable_t<value_t> > get_watchable() {
return clone_ptr_t<watchable_t<value_t> >(watchable.clone());
}
void set_value(const value_t &_value) {
DEBUG_VAR rwi_lock_assertion_t::write_acq_t acquisition(&rwi_lock_assertion);
value = _value;
publisher_controller.publish(&call_function);
}
// Applies an atomic modification to the value.
// `op` must return true if the value was modified,
// and should return false otherwise.
void apply_atomic_op(const std::function<bool(value_t*)> &op) { // NOLINT(readability/casting)
DEBUG_VAR rwi_lock_assertion_t::write_acq_t acquisition(&rwi_lock_assertion);
bool was_modified;
{
ASSERT_NO_CORO_WAITING;
was_modified = op(&value);
}
if (was_modified) {
publisher_controller.publish(&call_function);
}
}
// This is similar to apply_atomic_op, except that the operation
// cannot modify the value.
void apply_read(const std::function<void(const value_t*)> &read) {
ASSERT_NO_CORO_WAITING;
read(&value);
}
private:
class w_t : public watchable_t<value_t> {
public:
explicit w_t(watchable_variable_t<value_t> *p) : parent(p) { }
w_t *clone() const {
return new w_t(parent);
}
value_t get() {
return parent->value;
}
publisher_t<std::function<void()> > *get_publisher() {
return parent->publisher_controller.get_publisher();
}
rwi_lock_assertion_t *get_rwi_lock_assertion() {
return &parent->rwi_lock_assertion;
}
void apply_read(const std::function<void(const value_t*)> &read) {
parent->apply_read(read);
}
watchable_variable_t<value_t> *parent;
};
publisher_controller_t<std::function<void()> > publisher_controller;
value_t value;
rwi_lock_assertion_t rwi_lock_assertion;
w_t watchable;
DISABLE_COPYING(watchable_variable_t);
};
#include "concurrency/watchable.tcc"
#endif /* CONCURRENCY_WATCHABLE_HPP_ */
<commit_msg>Removed boost/function.hpp from watchable.hpp.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_WATCHABLE_HPP_
#define CONCURRENCY_WATCHABLE_HPP_
#include <functional>
#include "concurrency/interruptor.hpp"
#include "concurrency/mutex_assertion.hpp"
#include "concurrency/pubsub.hpp"
#include "concurrency/signal.hpp"
#include "containers/clone_ptr.hpp"
#include "utils.hpp"
/* `watchable_t` represents a variable that you can get the value of and also
subscribe to further changes to the value. To get the value of a `watchable_t`,
just call `get()`. To subscribe to further changes to the value, construct a
`watchable_t::freeze_t` and then construct a `watchable_t::subscription_t`,
passing it the `watchable_t` and the `freeze_t`.
To create a `watchable_t`, construct a `watchable_variable_t` and then call its
`get_watchable()` method. You can change the value of the `watchable_t` by
calling `watchable_variable_t::set_value()`.
`watchable_t` has a home thread; it can only be accessed from that thread. If
you need to access it from another thread, consider using
`cross_thread_watchable_variable_t` to create a proxy-watchable with a different
home thread. */
template <class value_t> class watchable_t;
template <class value_t> class watchable_freeze_t;
template <class value_t>
class watchable_subscription_t {
public:
/* The `std::function<void()>` passed to the constructor is a callback
that will be called whenever the value changes. The callback must not
block, and it must not create or destroy `subscription_t` objects. */
explicit watchable_subscription_t(const std::function<void()> &f)
: subscription(f)
{ }
watchable_subscription_t(const std::function<void()> &f, const clone_ptr_t<watchable_t<value_t> > &watchable,
watchable_freeze_t<value_t> *freeze)
: subscription(f, watchable->get_publisher()) {
watchable->assert_thread();
freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion());
}
void reset() {
subscription.reset();
}
void reset(const clone_ptr_t<watchable_t<value_t> > &watchable, watchable_freeze_t<value_t> *freeze) {
watchable->assert_thread();
freeze->rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion());
subscription.reset(watchable->get_publisher());
}
private:
typename publisher_t<std::function<void()> >::subscription_t subscription;
DISABLE_COPYING(watchable_subscription_t);
};
/* The purpose of the `freeze_t` is to assert that the value of the
`watchable_t` doesn't change for as long as it exists. You should not block
while the `freeze_t` exists. It's kind of like `mutex_assertion_t`.
A common pattern is to construct a `freeze_t`, then call `get()` to
initialize some object or objects that mirrors the `watchable_t`'s value,
then construct a `subscription_t` to continually keep in sync with the
`watchable_t`, then destroy the `freeze_t`. If it weren't for the
`freeze_t`, a change might "slip through the cracks" if it happened after
`get()` but before constructing the `subscription_t`. If you constructed the
`subscription_t` before calling `get()`, then the callback might get run
before the objects were first initialized. */
template <class value_t>
class watchable_freeze_t {
public:
explicit watchable_freeze_t(const clone_ptr_t<watchable_t<value_t> > &watchable)
: rwi_lock_acquisition(watchable->get_rwi_lock_assertion())
{
watchable->assert_thread();
}
void assert_is_holding(const clone_ptr_t<watchable_t<value_t> > &watchable) {
rwi_lock_acquisition.assert_is_holding(watchable->get_rwi_lock_assertion());
}
private:
friend class watchable_subscription_t<value_t>;
rwi_lock_assertion_t::read_acq_t rwi_lock_acquisition;
DISABLE_COPYING(watchable_freeze_t);
};
template <class value_t>
class watchable_t : public home_thread_mixin_t {
public:
typedef watchable_freeze_t<value_t> freeze_t;
typedef watchable_subscription_t<value_t> subscription_t;
virtual ~watchable_t() { }
virtual watchable_t *clone() const = 0;
virtual value_t get() = 0;
/* Applies `read` to the current value of the watchable. `read` must not block
and cannot change the value. */
virtual void apply_read(const std::function<void(const value_t*)> &read) = 0;
/* These are internal; the reason they're public is so that `subview()` and
similar things can be implemented. */
virtual publisher_t<std::function<void()> > *get_publisher() = 0;
virtual rwi_lock_assertion_t *get_rwi_lock_assertion() = 0;
/* `subview()` returns another `watchable_t` whose value is derived from
this one by calling `lens` on it. */
template<class callable_type>
clone_ptr_t<watchable_t<typename std::result_of<callable_type(value_t)>::type> > subview(const callable_type &lens);
/* `incremental_subview()` is like `subview()`. However it takes an incremental lens.
An incremental lens has the signature
`bool(const input_type &, result_type *current_out)`.
In contrast to a regular (non-incremental) lens it therefore has access to
the current value of the output value and can modify it in-place.
It should return true if `current_out` has been modified, and false otherwise.
We have two variants of this. The first one is a short-cut for incremental lenses
which contain a `result_type` typedef. In this case, result_type does not have
to be specified explicitly when calling `incremental_subview()`. Otherwise
the second variant must be used and `result_type` be specified as a template
parameter. */
template<class callable_type>
clone_ptr_t<watchable_t<typename callable_type::result_type> > incremental_subview(const callable_type &lens);
template<class result_type, class callable_type>
clone_ptr_t<watchable_t<result_type> > incremental_subview(const callable_type &lens);
/* `run_until_satisfied()` repeatedly calls `fun` on the current value of
`this` until either `fun` returns `true` or `interruptor` is pulsed. It's
efficient because it only retries `fun` when the value changes. */
template<class callable_type>
void run_until_satisfied(const callable_type &fun, signal_t *interruptor,
int64_t nap_before_retry_ms = 0) THROWS_ONLY(interrupted_exc_t);
protected:
watchable_t() { }
private:
DISABLE_COPYING(watchable_t);
};
/* `run_until_satisfied_2()` repeatedly calls `fun(a->get(), b->get())` until
`fun` returns `true` or `interruptor` is pulsed. It's efficient because it only
retries `fun` when the value of `a` or `b` changes. */
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2(
const clone_ptr_t<watchable_t<a_type> > &a,
const clone_ptr_t<watchable_t<b_type> > &b,
const callable_type &fun,
signal_t *interruptor,
int64_t nap_before_retry_ms = 0) THROWS_ONLY(interrupted_exc_t);
inline void call_function(const std::function<void()> &f) {
f();
}
template <class value_t>
class watchable_variable_t {
public:
explicit watchable_variable_t(const value_t &_value)
: value(_value), watchable(this)
{ }
clone_ptr_t<watchable_t<value_t> > get_watchable() {
return clone_ptr_t<watchable_t<value_t> >(watchable.clone());
}
void set_value(const value_t &_value) {
DEBUG_VAR rwi_lock_assertion_t::write_acq_t acquisition(&rwi_lock_assertion);
value = _value;
publisher_controller.publish(&call_function);
}
// Applies an atomic modification to the value.
// `op` must return true if the value was modified,
// and should return false otherwise.
void apply_atomic_op(const std::function<bool(value_t*)> &op) { // NOLINT(readability/casting)
DEBUG_VAR rwi_lock_assertion_t::write_acq_t acquisition(&rwi_lock_assertion);
bool was_modified;
{
ASSERT_NO_CORO_WAITING;
was_modified = op(&value);
}
if (was_modified) {
publisher_controller.publish(&call_function);
}
}
// This is similar to apply_atomic_op, except that the operation
// cannot modify the value.
void apply_read(const std::function<void(const value_t*)> &read) {
ASSERT_NO_CORO_WAITING;
read(&value);
}
private:
class w_t : public watchable_t<value_t> {
public:
explicit w_t(watchable_variable_t<value_t> *p) : parent(p) { }
w_t *clone() const {
return new w_t(parent);
}
value_t get() {
return parent->value;
}
publisher_t<std::function<void()> > *get_publisher() {
return parent->publisher_controller.get_publisher();
}
rwi_lock_assertion_t *get_rwi_lock_assertion() {
return &parent->rwi_lock_assertion;
}
void apply_read(const std::function<void(const value_t*)> &read) {
parent->apply_read(read);
}
watchable_variable_t<value_t> *parent;
};
publisher_controller_t<std::function<void()> > publisher_controller;
value_t value;
rwi_lock_assertion_t rwi_lock_assertion;
w_t watchable;
DISABLE_COPYING(watchable_variable_t);
};
#include "concurrency/watchable.tcc"
#endif /* CONCURRENCY_WATCHABLE_HPP_ */
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "TiledMesh.h"
#include "Parser.h"
#include "InputParameters.h"
// libMesh includes
#include "libmesh/mesh_modification.h"
template<>
InputParameters validParams<TiledMesh>()
{
InputParameters params = validParams<MooseMesh>();
params.addParam<Real>("x_width", 0, "The tile width in the x direction");
params.addParam<Real>("y_width", 0, "The tile width in the y direction");
params.addParam<Real>("z_width", 0, "The tile width in the z direction");
params.addParam<BoundaryName>("left_boundary", "TODO");
params.addParam<BoundaryName>("right_boundary", "TODO");
params.addParam<BoundaryName>("top_boundary", "TODO");
params.addParam<BoundaryName>("bottom_boundary", "TODO");
params.addParam<BoundaryName>("front_boundary", "TODO");
params.addParam<BoundaryName>("back_boundary", "TODO");
params.addParam<unsigned int>("x_tiles", 1, "TODO");
params.addParam<unsigned int>("y_tiles", 1, "TODO");
params.addParam<unsigned int>("z_tiles", 1, "TODO");
return params;
}
TiledMesh::TiledMesh(const std::string & name, InputParameters parameters):
MooseMesh(name, parameters),
_x_width(getParam<Real>("x_width")),
_y_width(getParam<Real>("y_width")),
_z_width(getParam<Real>("z_width"))
{
// This class only works with SerialMesh
#ifndef LIBMESH_ENABLE_PARMESH
_mesh.read(getParam<MeshFileName>("file"));
BoundaryID left = getBoundaryID(getParam<BoundaryName>("left_boundary"));
BoundaryID right = getBoundaryID(getParam<BoundaryName>("right_boundary"));
BoundaryID top = getBoundaryID(getParam<BoundaryName>("top_boundary"));
BoundaryID bottom = getBoundaryID(getParam<BoundaryName>("bottom_boundary"));
BoundaryID front = getBoundaryID(getParam<BoundaryName>("front_boundary"));
BoundaryID back = getBoundaryID(getParam<BoundaryName>("back_boundary"));
{
AutoPtr<MeshBase> clone = _mesh.clone();
// Build X Tiles
for (unsigned int i=1; i<getParam<unsigned int>("x_tiles"); ++i)
{
MeshTools::Modification::translate(*clone, _x_width * i, 0, 0);
_mesh.stitch_meshes(dynamic_cast<SerialMesh &>(*clone), right, left, TOLERANCE, true);
}
}
{
AutoPtr<MeshBase> clone = _mesh.clone();
// Build Y Tiles
for (unsigned int i=1; i<getParam<unsigned int>("y_tiles"); ++i)
{
MeshTools::Modification::translate(*clone, 0, _y_width * i, 0);
_mesh.stitch_meshes(dynamic_cast<SerialMesh &>(*clone), top, bottom, TOLERANCE, true);
}
}
{
AutoPtr<MeshBase> clone = _mesh.clone();
// Build Y Tiles
for (unsigned int i=1; i<getParam<unsigned int>("z_tiles"); ++i)
{
MeshTools::Modification::translate(*clone, 0, 0, _z_width * i);
_mesh.stitch_meshes(dynamic_cast<SerialMesh &>(*clone), front, back, TOLERANCE, true);
}
}
#else
mooseError("TiledMesh cannot be used with --enable-parmesh");
#endif
}
<commit_msg>Minor bugfix to TiledMesh - refs #1729<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "TiledMesh.h"
#include "Parser.h"
#include "InputParameters.h"
// libMesh includes
#include "libmesh/mesh_modification.h"
template<>
InputParameters validParams<TiledMesh>()
{
InputParameters params = validParams<MooseMesh>();
params.addParam<Real>("x_width", 0, "The tile width in the x direction");
params.addParam<Real>("y_width", 0, "The tile width in the y direction");
params.addParam<Real>("z_width", 0, "The tile width in the z direction");
params.addParam<BoundaryName>("left_boundary", "TODO");
params.addParam<BoundaryName>("right_boundary", "TODO");
params.addParam<BoundaryName>("top_boundary", "TODO");
params.addParam<BoundaryName>("bottom_boundary", "TODO");
params.addParam<BoundaryName>("front_boundary", "TODO");
params.addParam<BoundaryName>("back_boundary", "TODO");
params.addParam<unsigned int>("x_tiles", 1, "TODO");
params.addParam<unsigned int>("y_tiles", 1, "TODO");
params.addParam<unsigned int>("z_tiles", 1, "TODO");
return params;
}
TiledMesh::TiledMesh(const std::string & name, InputParameters parameters):
MooseMesh(name, parameters),
_x_width(getParam<Real>("x_width")),
_y_width(getParam<Real>("y_width")),
_z_width(getParam<Real>("z_width"))
{
// This class only works with SerialMesh
#ifndef LIBMESH_ENABLE_PARMESH
_mesh.read(getParam<MeshFileName>("file"));
BoundaryID left = getBoundaryID(getParam<BoundaryName>("left_boundary"));
BoundaryID right = getBoundaryID(getParam<BoundaryName>("right_boundary"));
BoundaryID top = getBoundaryID(getParam<BoundaryName>("top_boundary"));
BoundaryID bottom = getBoundaryID(getParam<BoundaryName>("bottom_boundary"));
BoundaryID front = getBoundaryID(getParam<BoundaryName>("front_boundary"));
BoundaryID back = getBoundaryID(getParam<BoundaryName>("back_boundary"));
{
AutoPtr<MeshBase> clone = _mesh.clone();
// Build X Tiles
for (unsigned int i=1; i<getParam<unsigned int>("x_tiles"); ++i)
{
MeshTools::Modification::translate(*clone, _x_width, 0, 0);
_mesh.stitch_meshes(dynamic_cast<SerialMesh &>(*clone), right, left, TOLERANCE, true);
}
}
{
AutoPtr<MeshBase> clone = _mesh.clone();
// Build Y Tiles
for (unsigned int i=1; i<getParam<unsigned int>("y_tiles"); ++i)
{
MeshTools::Modification::translate(*clone, 0, _y_width, 0);
_mesh.stitch_meshes(dynamic_cast<SerialMesh &>(*clone), top, bottom, TOLERANCE, true);
}
}
{
AutoPtr<MeshBase> clone = _mesh.clone();
// Build Y Tiles
for (unsigned int i=1; i<getParam<unsigned int>("z_tiles"); ++i)
{
MeshTools::Modification::translate(*clone, 0, 0, _z_width);
_mesh.stitch_meshes(dynamic_cast<SerialMesh &>(*clone), front, back, TOLERANCE, true);
}
}
#else
mooseError("TiledMesh cannot be used with --enable-parmesh");
#endif
}
<|endoftext|> |
<commit_before>
#include "EventLogger.hpp"
using namespace std;
namespace YerFace {
EventLogger::EventLogger(json config, string myEventFile, OutputDriver *myOutputDriver, FrameDerivatives *myFrameDerivatives, double myFrom) {
eventTimestampAdjustment = config["YerFace"]["EventLogger"]["eventTimestampAdjustment"];
eventFilename = myEventFile;
outputDriver = myOutputDriver;
if(outputDriver == NULL) {
throw invalid_argument("outputDriver cannot be NULL");
}
frameDerivatives = myFrameDerivatives;
if(frameDerivatives == NULL) {
throw invalid_argument("frameDerivatives cannot be NULL");
}
from = myFrom;
logger = new Logger("EventLogger");
events = json::object();
eventReplay = false;
if(eventFilename.length() > 0) {
eventFilestream.open(eventFilename, ifstream::in | ifstream::binary);
if(eventFilestream.fail()) {
throw invalid_argument("could not open inEvents for reading");
}
nextPacket = json::object();
eventReplay = true;
}
logger->debug("EventLogger object constructed and ready to go!");
}
EventLogger::~EventLogger() {
logger->debug("EventLogger object destructing...");
delete logger;
}
void EventLogger::registerEventType(EventType eventType) {
if(eventType.name.length() < 1) {
throw invalid_argument("Event Type needs a name.");
}
for(EventType registered : registeredEventTypes) {
if(eventType.name == registered.name) {
throw invalid_argument("Event Types must have UNIQUE names");
}
}
registeredEventTypes.push_back(eventType);
}
void EventLogger::logEvent(string eventName, json payload, bool propagate, json sourcePacket) {
bool eventFound = false;
EventType event;
for(EventType registered : registeredEventTypes) {
if(eventName == registered.name) {
event = registered;
eventFound = true;
break;
}
}
if(!eventFound) {
logger->warn("Encountered unsupported event type [%s]! Are you using an old version of YerFace?", eventName.c_str());
return;
}
bool insertEventInCompletedFrameData = true;
if(propagate) {
insertEventInCompletedFrameData = event.replayCallback(eventName, payload, sourcePacket);
}
if(insertEventInCompletedFrameData) {
events[eventName] = payload;
}
}
void EventLogger::startNewFrame(void) {
if(eventReplay) {
eventReplayHold = false;
workingFrameTimestamps = frameDerivatives->getWorkingFrameTimestamps();
processNextPacket();
string line;
while(!eventReplayHold && getline(eventFilestream, line)) {
nextPacket = json::parse(line);
processNextPacket();
}
}
}
void EventLogger::handleCompletedFrame(void) {
if(!events.empty()) {
outputDriver->insertCompletedFrameData("events", events);
events = json::object();
}
}
void EventLogger::processNextPacket(void) {
if(nextPacket.size()) {
double frameStart = workingFrameTimestamps.startTimestamp - eventTimestampAdjustment;
double frameEnd = workingFrameTimestamps.estimatedEndTimestamp - eventTimestampAdjustment;
double packetTime = nextPacket["meta"]["startTime"];
if(from != -1.0 && from > 0.0) {
packetTime = packetTime - from;
nextPacket["meta"]["startTime"] = packetTime;
}
if(packetTime < frameEnd) {
if(packetTime >= 0.0 && packetTime < frameStart) {
logger->warn("==== EVENT REPLAY PACKET LATE! Processing anyway... ====");
}
json event;
try {
event = nextPacket.at("events");
} catch(nlohmann::detail::out_of_range &e) {
return;
}
for(json::iterator iter = event.begin(); iter != event.end(); ++iter) {
logEvent(iter.key(), iter.value(), true, nextPacket);
}
} else {
eventReplayHold = true;
}
}
}
} //namespace YerFace
<commit_msg>fix event replay issue when input events are shorter than input video<commit_after>
#include "EventLogger.hpp"
using namespace std;
namespace YerFace {
EventLogger::EventLogger(json config, string myEventFile, OutputDriver *myOutputDriver, FrameDerivatives *myFrameDerivatives, double myFrom) {
eventTimestampAdjustment = config["YerFace"]["EventLogger"]["eventTimestampAdjustment"];
eventFilename = myEventFile;
outputDriver = myOutputDriver;
if(outputDriver == NULL) {
throw invalid_argument("outputDriver cannot be NULL");
}
frameDerivatives = myFrameDerivatives;
if(frameDerivatives == NULL) {
throw invalid_argument("frameDerivatives cannot be NULL");
}
from = myFrom;
logger = new Logger("EventLogger");
events = json::object();
eventReplay = false;
if(eventFilename.length() > 0) {
eventFilestream.open(eventFilename, ifstream::in | ifstream::binary);
if(eventFilestream.fail()) {
throw invalid_argument("could not open inEvents for reading");
}
nextPacket = json::object();
eventReplay = true;
}
logger->debug("EventLogger object constructed and ready to go!");
}
EventLogger::~EventLogger() {
logger->debug("EventLogger object destructing...");
delete logger;
}
void EventLogger::registerEventType(EventType eventType) {
if(eventType.name.length() < 1) {
throw invalid_argument("Event Type needs a name.");
}
for(EventType registered : registeredEventTypes) {
if(eventType.name == registered.name) {
throw invalid_argument("Event Types must have UNIQUE names");
}
}
registeredEventTypes.push_back(eventType);
}
void EventLogger::logEvent(string eventName, json payload, bool propagate, json sourcePacket) {
bool eventFound = false;
EventType event;
for(EventType registered : registeredEventTypes) {
if(eventName == registered.name) {
event = registered;
eventFound = true;
break;
}
}
if(!eventFound) {
logger->warn("Encountered unsupported event type [%s]! Are you using an old version of YerFace?", eventName.c_str());
return;
}
bool insertEventInCompletedFrameData = true;
if(propagate) {
insertEventInCompletedFrameData = event.replayCallback(eventName, payload, sourcePacket);
}
if(insertEventInCompletedFrameData) {
events[eventName] = payload;
}
}
void EventLogger::startNewFrame(void) {
if(eventReplay) {
eventReplayHold = false;
workingFrameTimestamps = frameDerivatives->getWorkingFrameTimestamps();
processNextPacket();
string line;
while(!eventReplayHold && getline(eventFilestream, line)) {
nextPacket = json::parse(line);
processNextPacket();
}
}
}
void EventLogger::handleCompletedFrame(void) {
if(!events.empty()) {
outputDriver->insertCompletedFrameData("events", events);
events = json::object();
}
}
void EventLogger::processNextPacket(void) {
if(nextPacket.size()) {
double frameStart = workingFrameTimestamps.startTimestamp - eventTimestampAdjustment;
double frameEnd = workingFrameTimestamps.estimatedEndTimestamp - eventTimestampAdjustment;
double packetTime = nextPacket["meta"]["startTime"];
if(from != -1.0 && from > 0.0) {
packetTime = packetTime - from;
nextPacket["meta"]["startTime"] = packetTime;
}
if(packetTime < frameEnd) {
if(packetTime >= 0.0 && packetTime < frameStart) {
logger->warn("==== EVENT REPLAY PACKET LATE! Processing anyway... ====");
}
json event;
try {
event = nextPacket.at("events");
} catch(nlohmann::detail::out_of_range &e) {
return;
}
for(json::iterator iter = event.begin(); iter != event.end(); ++iter) {
logEvent(iter.key(), iter.value(), true, nextPacket);
nextPacket = json::object();
}
} else {
eventReplayHold = true;
}
}
}
} //namespace YerFace
<|endoftext|> |
<commit_before><commit_msg>prepare test code for next tests<commit_after><|endoftext|> |
<commit_before><commit_msg>CID#1038507 calm coverity nerves about a double free<commit_after><|endoftext|> |
<commit_before>/**
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: sbhklr
* @Last Modified time: 2020-05-01 23:34:07
**/
#include "FTDebouncer.h"
#define DEFAULT_DEBOUNCE_DELAY 40
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() : _debounceDelay(DEFAULT_DEBOUNCE_DELAY) {
}
FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
}
FTDebouncer::~FTDebouncer() {
this->end();
}
/* METHODS */
void FTDebouncer::addPin(uint8_t pinNumber, uint8_t restState, int pullMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = pinNumber;
debounceItem->restState = restState;
if (_firstDebounceItem == nullptr) {
_firstDebounceItem = debounceItem;
} else {
_lastDebounceItem->nextItem = debounceItem;
}
_lastDebounceItem = debounceItem;
pinMode(pinNumber, static_cast<uint8_t>(pullMode));
++_debouncedItemsCount;
}
void FTDebouncer::setPinEnabled(uint8_t pinNumber, bool enabled){
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if(debounceItem->pinNumber == pinNumber){
if(enabled) pinMode(debounceItem->pinNumber, debounceItem->pullMode);
debounceItem->enabled = enabled;
return;
}
}
}
void FTDebouncer::begin(){
unsigned long currentMilliseconds = millis();
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
debounceItem->enabled = true;
}
}
void FTDebouncer::init() {
this->begin();
}
void FTDebouncer::run() {
this->update();
}
void FTDebouncer::update(){
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
}
this->debouncePins();
this->checkStateChange();
}
void FTDebouncer::end(){
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
delete debounceItem;
}
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if (debounceItem->currentState != debounceItem->previousState) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
if (debounceItem->previousState == debounceItem->currentState) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
}
debounceItem->previousState = debounceItem->currentState;
}
}
void FTDebouncer::checkStateChange() {
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if(!debounceItem->enabled) continue;
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == debounceItem->restState) {
onPinDeactivated(static_cast<int>(debounceItem->pinNumber));
} else {
onPinActivated(static_cast<int>(debounceItem->pinNumber));
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
}
}
uint8_t FTDebouncer::getPinCount(){
return _debouncedItemsCount;
}
<commit_msg>Make debounce easier to understand<commit_after>/**
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: sbhklr
* @Last Modified time: 2020-05-01 23:34:07
**/
#include "FTDebouncer.h"
#define DEFAULT_DEBOUNCE_DELAY 40
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() : _debounceDelay(DEFAULT_DEBOUNCE_DELAY) {
}
FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
}
FTDebouncer::~FTDebouncer() {
this->end();
}
/* METHODS */
void FTDebouncer::addPin(uint8_t pinNumber, uint8_t restState, int pullMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = pinNumber;
debounceItem->restState = restState;
if (_firstDebounceItem == nullptr) {
_firstDebounceItem = debounceItem;
} else {
_lastDebounceItem->nextItem = debounceItem;
}
_lastDebounceItem = debounceItem;
pinMode(pinNumber, static_cast<uint8_t>(pullMode));
++_debouncedItemsCount;
}
void FTDebouncer::setPinEnabled(uint8_t pinNumber, bool enabled){
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if(debounceItem->pinNumber == pinNumber){
if(enabled) pinMode(debounceItem->pinNumber, debounceItem->pullMode);
debounceItem->enabled = enabled;
return;
}
}
}
void FTDebouncer::begin(){
unsigned long currentMilliseconds = millis();
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
debounceItem->enabled = true;
}
}
void FTDebouncer::init() {
this->begin();
}
void FTDebouncer::run() {
this->update();
}
void FTDebouncer::update(){
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
}
this->debouncePins();
this->checkStateChange();
}
void FTDebouncer::end(){
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
delete debounceItem;
}
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
bool stateHasChangedSinceLastCheck = debounceItem->currentState != debounceItem->previousState;
if (stateHasChangedSinceLastCheck) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
bool stateIsStable = currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay;
if (stateIsStable && !stateHasChangedSinceLastCheck) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
debounceItem->previousState = debounceItem->currentState;
}
}
void FTDebouncer::checkStateChange() {
for(DebounceItem *debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
if(!debounceItem->enabled) continue;
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == debounceItem->restState) {
onPinDeactivated(static_cast<int>(debounceItem->pinNumber));
} else {
onPinActivated(static_cast<int>(debounceItem->pinNumber));
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
}
}
uint8_t FTDebouncer::getPinCount(){
return _debouncedItemsCount;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkMacro.h"
#include "otbProlateInterpolateImageFunction.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include <fstream>
#include "otbImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "otbImageFileWriter.h"
#include "otbStreamingResampleImageFilter.h"
#include "otbWindowedSincInterpolateImageGaussianFunction.h"
#include "otbWindowedSincInterpolateImageHammingFunction.h"
#include "otbWindowedSincInterpolateImageCosineFunction.h"
#include "itkWindowedSincInterpolateImageFunction.h"
#include "itkDifferenceImageFilter.h"
int otbProlateInterpolateImageFunction(int argc, char * argv[])
{
const char * infname = argv[1];
const char * outfname = argv[2];
const char * cosfname = argv[3];
const char * itkcosfname = argv[4];
const char * profname = argv[5];
typedef otb::Image<double, 2> ImageType;
typedef otb::ProlateInterpolateImageFunction<ImageType> InterpolatorType;
typedef InterpolatorType::ContinuousIndexType ContinuousIndexType;
typedef otb::ImageFileReader<ImageType> ReaderType;
unsigned int i = 7;
std::vector<ContinuousIndexType> indicesList;
while (i < static_cast<unsigned int>(argc) && (i + 1) < static_cast<unsigned int>(argc))
{
ContinuousIndexType idx;
idx[0] = atof(argv[i]);
idx[1] = atof(argv[i + 1]);
indicesList.push_back(idx);
i += 2;
}
// Instantiating object
InterpolatorType::Pointer prolate = InterpolatorType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
reader->Update();
prolate->SetInputImage(reader->GetOutput());
prolate->SetRadius(atoi(argv[6]));
prolate->Initialize();
std::ofstream file;
file.open(outfname);
for (std::vector<ContinuousIndexType>::iterator it = indicesList.begin(); it != indicesList.end(); ++it)
{
file << (*it) << " -> " << prolate->EvaluateAtContinuousIndex((*it)) << std::endl;
}
file.close();
/**********************************************************/
//typedef otb::ImageFileWriter<ImageType> WriterType;
//typedef otb::StreamingResampleImageFilter<ImageType, ImageType, double> StreamingResampleImageFilterType;
typedef otb::ImageFileWriter<ImageType> WriterType;
typedef itk::ResampleImageFilter<ImageType, ImageType, double> StreamingResampleImageFilterType;
WriterType::Pointer prowriter = WriterType::New();
StreamingResampleImageFilterType::Pointer proresampler = StreamingResampleImageFilterType::New();
InterpolatorType::Pointer pro = InterpolatorType::New();
// Resampler connected to input image
proresampler->SetInput(reader->GetOutput());
pro->SetInputImage(reader->GetOutput());
pro->SetRadius(atoi(argv[6]));
pro->Initialize();
proresampler->SetInterpolator(pro);
StreamingResampleImageFilterType::SizeType size;
size[0] = 512;
size[1] = 512;
double tutu = 1;
proresampler->SetSize(size);
proresampler->SetOutputSpacing(tutu);
// Result of resampler is written
prowriter->SetInput(proresampler->GetOutput());
//prowriter->SetNumberOfDivisionsStrippedStreaming(1);
prowriter->SetFileName(profname);
prowriter->Update();
typedef otb::WindowedSincInterpolateImageCosineFunction<ImageType> CosInterpolatorType;
typedef itk::Function::CosineWindowFunction<1, double, double> itkCosType;
typedef itk::WindowedSincInterpolateImageFunction<ImageType, 1, itkCosType> itkCosInterpolatorType;
WriterType::Pointer itkcoswriter = WriterType::New();
WriterType::Pointer coswriter = WriterType::New();
StreamingResampleImageFilterType::Pointer cosresampler = StreamingResampleImageFilterType::New();
StreamingResampleImageFilterType::Pointer itkcosresampler = StreamingResampleImageFilterType::New();
CosInterpolatorType::Pointer cos = CosInterpolatorType::New();
itkCosInterpolatorType::Pointer itkcos = itkCosInterpolatorType::New();
cosresampler->SetSize(size);
cosresampler->SetOutputSpacing(tutu);
itkcosresampler->SetSize(size);
itkcosresampler->SetOutputSpacing(tutu);
cosresampler->SetInput(reader->GetOutput());
cos->SetInputImage(reader->GetOutput());
cos->SetRadius(atoi(argv[6]));
cos->Initialize();
cosresampler->SetInterpolator(cos);
itkcosresampler->SetInput(reader->GetOutput());
itkcosresampler->SetInterpolator(itkcos);
coswriter->SetInput(cosresampler->GetOutput());
coswriter->SetFileName(cosfname);
itkcoswriter->SetInput(itkcosresampler->GetOutput());
itkcoswriter->SetFileName(itkcosfname);
coswriter->Update();
itkcoswriter->Update();
return EXIT_SUCCESS;
}
<commit_msg>COMP: useless include have been removed.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkMacro.h"
#include "otbProlateInterpolateImageFunction.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include <fstream>
#include "otbImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "otbImageFileWriter.h"
#include "otbStreamingResampleImageFilter.h"
#include "otbWindowedSincInterpolateImageGaussianFunction.h"
#include "otbWindowedSincInterpolateImageHammingFunction.h"
#include "otbWindowedSincInterpolateImageCosineFunction.h"
#include "itkWindowedSincInterpolateImageFunction.h"
int otbProlateInterpolateImageFunction(int argc, char * argv[])
{
const char * infname = argv[1];
const char * outfname = argv[2];
const char * cosfname = argv[3];
const char * itkcosfname = argv[4];
const char * profname = argv[5];
typedef otb::Image<double, 2> ImageType;
typedef otb::ProlateInterpolateImageFunction<ImageType> InterpolatorType;
typedef InterpolatorType::ContinuousIndexType ContinuousIndexType;
typedef otb::ImageFileReader<ImageType> ReaderType;
unsigned int i = 7;
std::vector<ContinuousIndexType> indicesList;
while (i < static_cast<unsigned int>(argc) && (i + 1) < static_cast<unsigned int>(argc))
{
ContinuousIndexType idx;
idx[0] = atof(argv[i]);
idx[1] = atof(argv[i + 1]);
indicesList.push_back(idx);
i += 2;
}
// Instantiating object
InterpolatorType::Pointer prolate = InterpolatorType::New();
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(infname);
reader->Update();
prolate->SetInputImage(reader->GetOutput());
prolate->SetRadius(atoi(argv[6]));
prolate->Initialize();
std::ofstream file;
file.open(outfname);
for (std::vector<ContinuousIndexType>::iterator it = indicesList.begin(); it != indicesList.end(); ++it)
{
file << (*it) << " -> " << prolate->EvaluateAtContinuousIndex((*it)) << std::endl;
}
file.close();
/**********************************************************/
//typedef otb::ImageFileWriter<ImageType> WriterType;
//typedef otb::StreamingResampleImageFilter<ImageType, ImageType, double> StreamingResampleImageFilterType;
typedef otb::ImageFileWriter<ImageType> WriterType;
typedef itk::ResampleImageFilter<ImageType, ImageType, double> StreamingResampleImageFilterType;
WriterType::Pointer prowriter = WriterType::New();
StreamingResampleImageFilterType::Pointer proresampler = StreamingResampleImageFilterType::New();
InterpolatorType::Pointer pro = InterpolatorType::New();
// Resampler connected to input image
proresampler->SetInput(reader->GetOutput());
pro->SetInputImage(reader->GetOutput());
pro->SetRadius(atoi(argv[6]));
pro->Initialize();
proresampler->SetInterpolator(pro);
StreamingResampleImageFilterType::SizeType size;
size[0] = 512;
size[1] = 512;
double tutu = 1;
proresampler->SetSize(size);
proresampler->SetOutputSpacing(tutu);
// Result of resampler is written
prowriter->SetInput(proresampler->GetOutput());
//prowriter->SetNumberOfDivisionsStrippedStreaming(1);
prowriter->SetFileName(profname);
prowriter->Update();
typedef otb::WindowedSincInterpolateImageCosineFunction<ImageType> CosInterpolatorType;
typedef itk::Function::CosineWindowFunction<1, double, double> itkCosType;
typedef itk::WindowedSincInterpolateImageFunction<ImageType, 1, itkCosType> itkCosInterpolatorType;
WriterType::Pointer itkcoswriter = WriterType::New();
WriterType::Pointer coswriter = WriterType::New();
StreamingResampleImageFilterType::Pointer cosresampler = StreamingResampleImageFilterType::New();
StreamingResampleImageFilterType::Pointer itkcosresampler = StreamingResampleImageFilterType::New();
CosInterpolatorType::Pointer cos = CosInterpolatorType::New();
itkCosInterpolatorType::Pointer itkcos = itkCosInterpolatorType::New();
cosresampler->SetSize(size);
cosresampler->SetOutputSpacing(tutu);
itkcosresampler->SetSize(size);
itkcosresampler->SetOutputSpacing(tutu);
cosresampler->SetInput(reader->GetOutput());
cos->SetInputImage(reader->GetOutput());
cos->SetRadius(atoi(argv[6]));
cos->Initialize();
cosresampler->SetInterpolator(cos);
itkcosresampler->SetInput(reader->GetOutput());
itkcosresampler->SetInterpolator(itkcos);
coswriter->SetInput(cosresampler->GetOutput());
coswriter->SetFileName(cosfname);
itkcoswriter->SetInput(itkcosresampler->GetOutput());
itkcoswriter->SetFileName(itkcosfname);
coswriter->Update();
itkcoswriter->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlrowi.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:11:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_XMLROWI_HXX
#define SC_XMLROWI_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
class ScXMLImport;
class ScXMLTableRowContext : public SvXMLImportContext
{
rtl::OUString sStyleName;
rtl::OUString sVisibility;
sal_Int32 nRepeatedRows;
sal_Bool bHasCell;
const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }
public:
ScXMLTableRowContext( ScXMLImport& rImport, USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual ~ScXMLTableRowContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
};
class ScXMLTableRowsContext : public SvXMLImportContext
{
sal_Int32 nHeaderStartRow;
sal_Int32 nHeaderEndRow;
sal_Int32 nGroupStartRow;
sal_Int32 nGroupEndRow;
sal_Bool bHeader;
sal_Bool bGroup;
sal_Bool bGroupDisplay;
const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }
public:
ScXMLTableRowsContext( ScXMLImport& rImport, USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
const sal_Bool bHeader, const sal_Bool bGroup);
virtual ~ScXMLTableRowsContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.7.700); FILE MERGED 2008/04/01 15:30:32 thb 1.7.700.2: #i85898# Stripping all external header guards 2008/03/31 17:14:58 rt 1.7.700.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlrowi.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_XMLROWI_HXX
#define SC_XMLROWI_HXX
#include <xmloff/xmlictxt.hxx>
#include <xmloff/xmlimp.hxx>
class ScXMLImport;
class ScXMLTableRowContext : public SvXMLImportContext
{
rtl::OUString sStyleName;
rtl::OUString sVisibility;
sal_Int32 nRepeatedRows;
sal_Bool bHasCell;
const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }
public:
ScXMLTableRowContext( ScXMLImport& rImport, USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual ~ScXMLTableRowContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
};
class ScXMLTableRowsContext : public SvXMLImportContext
{
sal_Int32 nHeaderStartRow;
sal_Int32 nHeaderEndRow;
sal_Int32 nGroupStartRow;
sal_Int32 nGroupEndRow;
sal_Bool bHeader;
sal_Bool bGroup;
sal_Bool bGroupDisplay;
const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }
public:
ScXMLTableRowsContext( ScXMLImport& rImport, USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
const sal_Bool bHeader, const sal_Bool bGroup);
virtual ~ScXMLTableRowsContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
};
#endif
<|endoftext|> |
<commit_before>#include "pch.h"
#include "Missile.h"
#include "MissileManager.h"
#include "MissilePlayerMelee.h"
#include "GameManager.h"
#include "ComponentManager.h"
#include "StageManager.h"
bool Arthas::MissileManager::init()
{
//ѹ ٲ
m_Missiles.reserve(50);
for (int i = 0; i < 20; ++i)
{
Missile* PlayerMeleeMissile = GET_COMPONENT_MANAGER()->createComponent<MissilePlayerMelee>();
PlayerMeleeMissile->initMissile();
m_Missiles.push_back(PlayerMeleeMissile);
}
return true;
}
Arthas::Missile* Arthas::MissileManager::getMissile(Arthas::ComponentType missileType, cocos2d::Point pos,
Arthas::Direction attackDir,
float damage, cocos2d::Vec2 velocity)
{
for (auto pMissile : m_Missiles)
{
if (pMissile->getType() == missileType && pMissile->isUsable())
{
pMissile->setAttribute(pos, attackDir, damage, velocity);
GET_STAGE_MANAGER()->addObject(pMissile, GET_STAGE_MANAGER()->getRoomNum(), pos, GAME_OBJECT);
return pMissile;
}
}
return createMissile(missileType);
}
Arthas::Missile* Arthas::MissileManager::createMissile(ComponentType missileType)
{
Missile* tmpMissile;
switch (missileType)
{
case Arthas::OT_MISSILE_PLAYER_MELEE:
tmpMissile = GET_COMPONENT_MANAGER()->createComponent<MissilePlayerMelee>();
break;
default:
tmpMissile = nullptr;
break;
}
if (tmpMissile == nullptr)
{
return tmpMissile;
}
else
{
tmpMissile->initMissile();
m_Missiles.push_back(tmpMissile);
return tmpMissile;
}
}
<commit_msg>getMissile 에서 launchMissile로<commit_after>#include "pch.h"
#include "Missile.h"
#include "MissileManager.h"
#include "MissilePlayerMelee.h"
#include "GameManager.h"
#include "ComponentManager.h"
#include "StageManager.h"
bool Arthas::MissileManager::init()
{
//ѹ ٲ
m_Missiles.reserve(50);
for (int i = 0; i < 20; ++i)
{
Missile* PlayerMeleeMissile = GET_COMPONENT_MANAGER()->createComponent<MissilePlayerMelee>();
PlayerMeleeMissile->initMissile();
m_Missiles.push_back(PlayerMeleeMissile);
}
return true;
}
Arthas::Missile* Arthas::MissileManager::launchMissile(Arthas::ComponentType missileType, cocos2d::Point pos,
Arthas::Direction attackDir,
float damage, cocos2d::Vec2 velocity)
{
for (auto pMissile : m_Missiles)
{
if (pMissile->getType() == missileType && pMissile->isUsable())
{
pMissile->setAttribute(pos, attackDir, damage, velocity);
GET_STAGE_MANAGER()->addObject(pMissile, GET_STAGE_MANAGER()->getRoomNum(), pos, GAME_OBJECT);
return pMissile;
}
}
return createMissile(missileType);
}
Arthas::Missile* Arthas::MissileManager::createMissile(ComponentType missileType)
{
Missile* tmpMissile;
switch (missileType)
{
case Arthas::OT_MISSILE_PLAYER_MELEE:
tmpMissile = GET_COMPONENT_MANAGER()->createComponent<MissilePlayerMelee>();
break;
default:
tmpMissile = nullptr;
break;
}
if (tmpMissile == nullptr)
{
return tmpMissile;
}
else
{
tmpMissile->initMissile();
m_Missiles.push_back(tmpMissile);
return tmpMissile;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "../util.hpp"
/*
template <typename Weight>
struct Edge{
int from, to; Weight cost;
Edge(int s, int t, Weight c) : from(s), to(t), cost(c) {}
};
*/
using Flow = int;
template <typename Weight>
struct Edge{
int from, to;
Flow cap; int rev;
Weight cost;
Edge(int t) : to(t) {}
Edge(int s, int t) : from(s), to(t) {}
Edge(int s, int t, Weight c) : from(s), to(t), cost(c) {}
Edge(int s, int t, Flow f, int r) :
from(s), to(t), cap(f), rev(r) {}
Edge(int s, int t, Flow f, int r, Weight c) :
from(s), to(t), cap(f), rev(r), cost(c) {}
};
template <typename Weight> using Edges = vector<Edge<Weight>>;
template <typename Weight> using Graph = vector<Edges<Weight>>;
template <typename Weight> using Array = vector<Weight>;
/*
template <typename Weight>
void add_edge(Graph<Weight> &g, int from, int to) {
g[from].push_back(Edge<Weight>(to));
}
*/
template <typename Weight>
void add_edge(Graph<Weight> &g, int from, int to) {
g[from].push_back(Edge<Weight>(from, to));
}
template <typename Weight>
void add_edge(Graph<Weight> &g, int from, int to, Weight cost) {
g[from].push_back(Edge<Weight>(from, to, cost));
}
template <typename Weight>
void add_edge(Graph<Weight> &g, int from, int to, Flow cap) {
g[from].emplace_back(from, to, cap, (int)g[to].size());
g[to].emplace_back(to, from, 0, (int)g[from].size() - 1);
}
template <typename Weight>
void add_edge(Graph<Weight> &g, int from, int to, Flow cap, Weight cost) {
g[from].push_back(Edge<Weight>(from, to, cap, (int)g[to].size(), cost));
g[to].push_back(Edge<Weight>(to, from, 0, (int)g[from].size() - 1, -cost));
}
<commit_msg>modify graph definition<commit_after>#pragma once
#include "../util.hpp"
struct Edge {
int to;
Edge(int t) : to(t) {}
};
using Graph = vector<vector<Edge>>;
void add_edge(Graph &g, int from, int to) {
g[from].push_back(to);
}
struct Edge2 {
int from, to;
Edge2(int s, int t) : from(s), to(t) {}
};
using Graph2 = vector<vector<Edge2>>;
void add_edge(Graph2 &g, int from, int to) {
g[from].emplace_back(from, to);
}
template <typename Cost>
struct CEdge {
int from, to;
Cost cost;
CEdge(int s, int t, Cost c) : from(s), to(t), cost(c) {}
};
template<typename Cost> using CGraph = vector<vector<CEdge<Cost>>>;
template <typename Cost>
void add_edge(CGraph<Cost> &g, int from, int to, Cost cost) {
g[from].emplace_back(from, to, cost);
}
template <typename Flow>
struct FEdge {
int from, to;
Flow cap; int rev;
FEdge(int s, int t, Flow f, int r) : from(s), to(t), cap(f), rev(r) {}
};
template<typename Flow> using FGraph = vector<vector<FEdge<Flow>>>;
template <typename Flow>
void add_edge(FGraph<Flow> &g, int from, int to, Flow cap) {
g[from].emplace_back(from, to, cap, (int)g[to].size());
g[to].emplace_back(to, from, 0, (int)g[from].size() - 1);
}
template <typename Flow, typename Cost>
struct FCEdge {
int from, to;
Flow cap; int rev;
Cost cost;
FCEdge(int s, int t, Flow f, int r, Cost c) :
from(s), to(t), cap(f), rev(r), cost(c) {}
};
template<typename Flow, typename Cost>
using FCGraph = vector<vector<FCEdge<Flow, Cost>>>;
template <typename Flow, typename Cost>
void add_edge(FCGraph<Flow, Cost> &g, int from, int to, Flow cap, Cost cost) {
g[from].emplace_back(from, to, cap, (int)g[to].size(), cost);
g[to].emplace_back(to, from, 0, (int)g[from].size() - 1, -cost);
}
<|endoftext|> |
<commit_before>
#include <GraphLoader.hpp>
#include <algorithm>
#include <istream>
#include <iomanip>
#include <sstream>
#include <limits>
#include <vector>
#include <unordered_map>
namespace kn
{
Graph* GraphLoader::loadAdjacencyMatrix(char delim, bool directed)
{
Graph* g = new Graph();
std::string line;
std::size_t numVertices = 0;
std::size_t row = 0;
while (std::getline(stream, line))
{
std::stringstream lstream(line);
std::string entry;
std::size_t column = 0;
bool none = true;
while (std::getline(lstream, entry, delim))
{
none = false;
if (column == numVertices)
{
g->addVertex(0);
numVertices++;
}
int value = std::stoi(entry);
if (value != 0)
{
if (directed)
g->addArc(row, column, 0);
else
if (!g->hasEdge(row, column))
{
g->addEdge(row, column, 0);
}
}
column++;
}
if (none) break;
row++;
}
return g;
}
Graph* GraphLoader::loadAdjacencyList(char delim, bool directed)
{
Graph* g = new Graph();
std::string line;
std::size_t numVertices = 0;
while (std::getline(stream, line))
{
std::stringstream lstream(line);
std::string entry;
if (std::getline(lstream, entry, delim))
{
std::size_t source = (std::size_t) std::stoi(entry) - 1;
while (source >= numVertices)
{
g->addVertex(0);
numVertices++;
}
while (std::getline(lstream, entry, delim))
{
std::size_t dest = (std::size_t) std::stoi(entry) - 1;
while (dest >= numVertices)
{
g->addVertex(0);
numVertices++;
}
if (directed)
g->addArc(source, dest, 0);
else
if (!g->hasEdge(source, dest))
{
g->addEdge(source, dest, 0);
}
}
}
else
break;
}
return g;
}
Graph* GraphLoader::loadDIMACS()
{
Graph* g = new Graph();
std::string line;
while (std::getline(stream, line))
{
std::stringstream lstream(line);
std::string key = "";
std::size_t numVertices = 0;
lstream >> key;
if (key != "")
{
if (key == "e")
{
std::size_t source, dest;
lstream >> source;
lstream >> dest;
source--;
dest--;
while (source >= numVertices)
{
g->addVertex(0);
numVertices++;
}
while (dest >= numVertices)
{
g->addVertex(0);
numVertices++;
}
if (!g->hasEdge(source, dest))
{
g->addEdge(source, dest, 0);
}
}
else
{
// Discard the line
std::string ignore;
std::getline(stream, ignore);
}
}
else
break;
}
return g;
}
}
<commit_msg>Fixed DIMACS loading<commit_after>
#include <GraphLoader.hpp>
#include <algorithm>
#include <istream>
#include <iomanip>
#include <sstream>
#include <limits>
#include <vector>
#include <unordered_map>
namespace kn
{
Graph* GraphLoader::loadAdjacencyMatrix(char delim, bool directed)
{
Graph* g = new Graph();
std::string line;
std::size_t numVertices = 0;
std::size_t row = 0;
while (std::getline(stream, line))
{
std::stringstream lstream(line);
std::string entry;
std::size_t column = 0;
bool none = true;
while (std::getline(lstream, entry, delim))
{
none = false;
if (column == numVertices)
{
g->addVertex(0);
numVertices++;
}
int value = std::stoi(entry);
if (value != 0)
{
if (directed)
g->addArc(row, column, 0);
else
if (!g->hasEdge(row, column))
{
g->addEdge(row, column, 0);
}
}
column++;
}
if (none) break;
row++;
}
return g;
}
Graph* GraphLoader::loadAdjacencyList(char delim, bool directed)
{
Graph* g = new Graph();
std::string line;
std::size_t numVertices = 0;
while (std::getline(stream, line))
{
std::stringstream lstream(line);
std::string entry;
if (std::getline(lstream, entry, delim))
{
std::size_t source = (std::size_t) std::stoi(entry) - 1;
while (source >= numVertices)
{
g->addVertex(0);
numVertices++;
}
while (std::getline(lstream, entry, delim))
{
std::size_t dest = (std::size_t) std::stoi(entry) - 1;
while (dest >= numVertices)
{
g->addVertex(0);
numVertices++;
}
if (directed)
g->addArc(source, dest, 0);
else
if (!g->hasEdge(source, dest))
{
g->addEdge(source, dest, 0);
}
}
}
else
break;
}
return g;
}
Graph* GraphLoader::loadDIMACS()
{
Graph* g = new Graph();
std::string line;
std::size_t numVertices = 0;
while (std::getline(stream, line))
{
std::stringstream lstream(line);
std::string key = "";
lstream >> key;
if (key != "")
{
if (key == "e")
{
std::size_t source, dest;
lstream >> source;
lstream >> dest;
source--;
dest--;
while (source >= numVertices)
{
g->addVertex(0);
numVertices++;
}
while (dest >= numVertices)
{
g->addVertex(0);
numVertices++;
}
if (!g->hasEdge(source, dest))
{
g->addEdge(source, dest, 0);
}
}
}
else
break;
}
return g;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: multistratumbackend.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-05-20 15:43:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_MULTISTRATUMBACKEND_HXX_
#define CONFIGMGR_BACKEND_MULTISTRATUMBACKEND_HXX_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_
#include <com/sun/star/configuration/backend/XBackend.hpp>
#endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDENTITIES_HPP_
#include <com/sun/star/configuration/backend/XBackendEntities.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XVERSIONEDSCHEMASUPPLIER_HPP_
#include <com/sun/star/configuration/backend/XVersionedSchemaSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif // _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_BACKENDSETUPEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/BackendSetupException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESNOTIFIER_HPP_
#include <com/sun/star/configuration/backend/XBackendChangesNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESLISTENER_HPP_
#include <com/sun/star/configuration/backend/XBackendChangesListener.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE7_HXX_
#include <cppuhelper/compbase7.hxx>
#endif // _CPPUHELPER_COMPBASE7_HXX_
#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif
namespace configmgr { namespace backend {
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backenduno = css::configuration::backend ;
typedef cppu::WeakComponentImplHelper7< backenduno::XBackend,
backenduno::XBackendEntities,
backenduno::XVersionedSchemaSupplier,
backenduno::XBackendChangesNotifier,
backenduno::XBackendChangesListener,
lang::XInitialization,
lang::XServiceInfo> BackendBase ;
/**
Class implementing the Backend service for multibackend access.
It creates the required backends and coordinates access to them.
*/
class MultiStratumBackend : public BackendBase {
public :
/**
Service constructor from a service factory.
@param xContext component context
*/
explicit
MultiStratumBackend(
const uno::Reference<uno::XComponentContext>& xContext) ;
/** Destructor */
~MultiStratumBackend() ;
// XInitialize
virtual void SAL_CALL initialize(
const uno::Sequence<uno::Any>& aParameters)
throw (uno::RuntimeException, uno::Exception,
css::configuration::InvalidBootstrapFileException,
backenduno::BackendSetupException) ;
// XVersionedSchemaSupplier
virtual rtl::OUString
SAL_CALL getSchemaVersion(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XSchemaSupplier
virtual uno::Reference<backenduno::XSchema>
SAL_CALL getComponentSchema(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XBackend
virtual uno::Sequence<uno::Reference<backenduno::XLayer> >
SAL_CALL listOwnLayers(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backenduno::XUpdateHandler>
SAL_CALL getOwnUpdateHandler(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
lang::NoSupportException,
uno::RuntimeException) ;
virtual uno::Sequence<uno::Reference<backenduno::XLayer> > SAL_CALL
listLayers(const rtl::OUString& aComponent,
const rtl::OUString& aEntity)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backenduno::XUpdateHandler> SAL_CALL
getUpdateHandler(const rtl::OUString& aComponent,
const rtl::OUString& aEntity)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
lang::NoSupportException,
uno::RuntimeException) ;
// XBackendEntities
virtual rtl::OUString SAL_CALL
getOwnerEntity( )
throw (uno::RuntimeException);
virtual rtl::OUString SAL_CALL
getAdminEntity( )
throw (uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsEntity( const rtl::OUString& aEntity )
throw (backenduno::BackendAccessException, uno::RuntimeException);
virtual sal_Bool SAL_CALL
isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity )
throw ( backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName()
throw (uno::RuntimeException) ;
virtual sal_Bool SAL_CALL supportsService(
const rtl::OUString& aServiceName)
throw (uno::RuntimeException) ;
virtual uno::Sequence<rtl::OUString> SAL_CALL
getSupportedServiceNames(void) throw (uno::RuntimeException) ;
// XBackendChangesNotifier
virtual void SAL_CALL addChangesListener( const uno::Reference<backenduno::XBackendChangesListener>& xListner,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangesListener( const uno::Reference<backenduno::XBackendChangesListener>& xListner,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
// XBackendChangesListener
virtual void SAL_CALL componentDataChanged(const backenduno::ComponentChangeEvent& aEvent)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing( lang::EventObject const & rSource )
throw (uno::RuntimeException);
void notifyListeners(const backenduno::ComponentChangeEvent& aEvent) const;
protected:
// ComponentHelper
virtual void SAL_CALL disposing();
private :
/** Initialize the schema supplier backend
*/
void initializeSchemaSupplier(const uno::Reference<uno::XComponentContext>& aContext);
/** Initialize strata(SingleLayer or MultiLayer) backend
*/
void initializeBackendStrata(const uno::Reference<uno::XComponentContext>& aContext);
/** Get Layers from Backend Strata
*/
uno::Sequence<uno::Reference<backenduno::XLayer> >
searchSupportingStrata(sal_Int32 nNumLayer,
rtl::OUString aEntity,
const rtl::OUString& aComponent) ;
/** Find the Stratum that supports the specified Entity
* @return Number of Supported Strata
*/
sal_Int32 findSupportingStratum(const rtl::OUString& aEntity) ;
/**
Check state of MultiStratumBackend -
@return true if not disposed/uninitialized
*/
bool checkOkState();
/** Service factory */
uno::Reference<lang::XMultiServiceFactory> mFactory ;
/** Mutex for resource protection */
osl::Mutex mMutex ;
typedef std::vector< uno::Reference <uno::XInterface> > BackendStrata;
uno::Reference<backenduno::XSchemaSupplier> mSchemaSupplier ;
/** list of all backends */
BackendStrata mBackendStrata;
rtl::OUString mOwnerEntity;
/** Helper object that listens to the Strata Backends */
typedef uno::Reference<backenduno::XBackendChangesListener> ListenerRef;
ListenerRef mStrataListener;
/** List of higher level listeners */
typedef std::multimap<rtl::OUString, ListenerRef> ListenerList;
ListenerList mListenerList;
} ;
} } // configmgr.backend
#endif // CONFIGMGR_BACKEND_MULTISTRATUMBACKEND_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.18); FILE MERGED 2005/09/05 17:04:04 rt 1.4.18.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: multistratumbackend.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:33:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_MULTISTRATUMBACKEND_HXX_
#define CONFIGMGR_BACKEND_MULTISTRATUMBACKEND_HXX_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_
#include <com/sun/star/configuration/backend/XBackend.hpp>
#endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDENTITIES_HPP_
#include <com/sun/star/configuration/backend/XBackendEntities.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XVERSIONEDSCHEMASUPPLIER_HPP_
#include <com/sun/star/configuration/backend/XVersionedSchemaSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif // _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_BACKENDSETUPEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/BackendSetupException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESNOTIFIER_HPP_
#include <com/sun/star/configuration/backend/XBackendChangesNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESLISTENER_HPP_
#include <com/sun/star/configuration/backend/XBackendChangesListener.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE7_HXX_
#include <cppuhelper/compbase7.hxx>
#endif // _CPPUHELPER_COMPBASE7_HXX_
#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif
namespace configmgr { namespace backend {
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backenduno = css::configuration::backend ;
typedef cppu::WeakComponentImplHelper7< backenduno::XBackend,
backenduno::XBackendEntities,
backenduno::XVersionedSchemaSupplier,
backenduno::XBackendChangesNotifier,
backenduno::XBackendChangesListener,
lang::XInitialization,
lang::XServiceInfo> BackendBase ;
/**
Class implementing the Backend service for multibackend access.
It creates the required backends and coordinates access to them.
*/
class MultiStratumBackend : public BackendBase {
public :
/**
Service constructor from a service factory.
@param xContext component context
*/
explicit
MultiStratumBackend(
const uno::Reference<uno::XComponentContext>& xContext) ;
/** Destructor */
~MultiStratumBackend() ;
// XInitialize
virtual void SAL_CALL initialize(
const uno::Sequence<uno::Any>& aParameters)
throw (uno::RuntimeException, uno::Exception,
css::configuration::InvalidBootstrapFileException,
backenduno::BackendSetupException) ;
// XVersionedSchemaSupplier
virtual rtl::OUString
SAL_CALL getSchemaVersion(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XSchemaSupplier
virtual uno::Reference<backenduno::XSchema>
SAL_CALL getComponentSchema(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XBackend
virtual uno::Sequence<uno::Reference<backenduno::XLayer> >
SAL_CALL listOwnLayers(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backenduno::XUpdateHandler>
SAL_CALL getOwnUpdateHandler(const rtl::OUString& aComponent)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
lang::NoSupportException,
uno::RuntimeException) ;
virtual uno::Sequence<uno::Reference<backenduno::XLayer> > SAL_CALL
listLayers(const rtl::OUString& aComponent,
const rtl::OUString& aEntity)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backenduno::XUpdateHandler> SAL_CALL
getUpdateHandler(const rtl::OUString& aComponent,
const rtl::OUString& aEntity)
throw (backenduno::BackendAccessException,
lang::IllegalArgumentException,
lang::NoSupportException,
uno::RuntimeException) ;
// XBackendEntities
virtual rtl::OUString SAL_CALL
getOwnerEntity( )
throw (uno::RuntimeException);
virtual rtl::OUString SAL_CALL
getAdminEntity( )
throw (uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsEntity( const rtl::OUString& aEntity )
throw (backenduno::BackendAccessException, uno::RuntimeException);
virtual sal_Bool SAL_CALL
isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity )
throw ( backenduno::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName()
throw (uno::RuntimeException) ;
virtual sal_Bool SAL_CALL supportsService(
const rtl::OUString& aServiceName)
throw (uno::RuntimeException) ;
virtual uno::Sequence<rtl::OUString> SAL_CALL
getSupportedServiceNames(void) throw (uno::RuntimeException) ;
// XBackendChangesNotifier
virtual void SAL_CALL addChangesListener( const uno::Reference<backenduno::XBackendChangesListener>& xListner,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangesListener( const uno::Reference<backenduno::XBackendChangesListener>& xListner,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
// XBackendChangesListener
virtual void SAL_CALL componentDataChanged(const backenduno::ComponentChangeEvent& aEvent)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL disposing( lang::EventObject const & rSource )
throw (uno::RuntimeException);
void notifyListeners(const backenduno::ComponentChangeEvent& aEvent) const;
protected:
// ComponentHelper
virtual void SAL_CALL disposing();
private :
/** Initialize the schema supplier backend
*/
void initializeSchemaSupplier(const uno::Reference<uno::XComponentContext>& aContext);
/** Initialize strata(SingleLayer or MultiLayer) backend
*/
void initializeBackendStrata(const uno::Reference<uno::XComponentContext>& aContext);
/** Get Layers from Backend Strata
*/
uno::Sequence<uno::Reference<backenduno::XLayer> >
searchSupportingStrata(sal_Int32 nNumLayer,
rtl::OUString aEntity,
const rtl::OUString& aComponent) ;
/** Find the Stratum that supports the specified Entity
* @return Number of Supported Strata
*/
sal_Int32 findSupportingStratum(const rtl::OUString& aEntity) ;
/**
Check state of MultiStratumBackend -
@return true if not disposed/uninitialized
*/
bool checkOkState();
/** Service factory */
uno::Reference<lang::XMultiServiceFactory> mFactory ;
/** Mutex for resource protection */
osl::Mutex mMutex ;
typedef std::vector< uno::Reference <uno::XInterface> > BackendStrata;
uno::Reference<backenduno::XSchemaSupplier> mSchemaSupplier ;
/** list of all backends */
BackendStrata mBackendStrata;
rtl::OUString mOwnerEntity;
/** Helper object that listens to the Strata Backends */
typedef uno::Reference<backenduno::XBackendChangesListener> ListenerRef;
ListenerRef mStrataListener;
/** List of higher level listeners */
typedef std::multimap<rtl::OUString, ListenerRef> ListenerList;
ListenerList mListenerList;
} ;
} } // configmgr.backend
#endif // CONFIGMGR_BACKEND_MULTISTRATUMBACKEND_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: predicateinput.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:01:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONNECTIVITY_PREDICATEINPUT_HXX
#define CONNECTIVITY_PREDICATEINPUT_HXX
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XLOCALEDATA_HPP_
#include <com/sun/star/i18n/XLocaleData.hpp>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
//.........................................................................
namespace dbtools
{
//.........................................................................
//=====================================================================
//= OPredicateInputController
//=====================================================================
/** A class which allows input of an SQL predicate for a row set column
into a edit field.
*/
class OPredicateInputController
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
m_xORB;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
m_xConnection;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >
m_xFormatter;
::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData >
m_xLocaleData;
::connectivity::OSQLParser
m_aParser;
public:
OPredicateInputController(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const ::connectivity::IParseContext* _pParseContext = NULL
);
/** transforms a "raw" predicate value (usually obtained from a user input) into a valid predicate for the given column
@param _rPredicateValue
The text to normalize.
@param _rxField
The field for which the text should be a predicate value.
@param _pErrorMessage
If not <NULL/>, and a parsing error occurs, the error message will be copied to the string the argument
points to.
*/
sal_Bool normalizePredicateString(
::rtl::OUString& _rPredicateValue,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField,
::rtl::OUString* _pErrorMessage = NULL
) const;
/** get's a value of the predicate which can be used in a WHERE clause.
@param _rPredicateValue
the value which has been normalized using normalizePredicateString
@param _rxField
is the field for which a predicate is to be entered
@param _bForStatementUse
If <TRUE/>, the returned value can be used in an SQL statement. If <FALSE/>, it can be used
for instance for setting parameter values.
@param _pErrorMessage
If not <NULL/>, and a parsing error occurs, the error message will be copied to the string the argument
points to.
@see normalizePredicateString
*/
::rtl::OUString getPredicateValue(
const ::rtl::OUString& _rPredicateValue,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & _rxField,
sal_Bool _bForStatementUse,
::rtl::OUString* _pErrorMessage = NULL
) const;
private:
::connectivity::OSQLParseNode* implPredicateTree(
::rtl::OUString& _rErrorMessage,
const ::rtl::OUString& _rStatement,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & _rxField
) const;
sal_Bool getSeparatorChars(
const ::com::sun::star::lang::Locale& _rLocale,
sal_Unicode& _rDecSep,
sal_Unicode& _rThdSep
) const;
};
//.........................................................................
} // namespace dbtools
//.........................................................................
#endif // CONNECTIVITY_PREDICATEINPUT_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.372); FILE MERGED 2008/04/01 10:52:41 thb 1.5.372.2: #i85898# Stripping all external header guards 2008/03/28 15:23:15 rt 1.5.372.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: predicateinput.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CONNECTIVITY_PREDICATEINPUT_HXX
#define CONNECTIVITY_PREDICATEINPUT_HXX
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <com/sun/star/util/XNumberFormatter.hpp>
#include <com/sun/star/i18n/XLocaleData.hpp>
#include <connectivity/sqlparse.hxx>
//.........................................................................
namespace dbtools
{
//.........................................................................
//=====================================================================
//= OPredicateInputController
//=====================================================================
/** A class which allows input of an SQL predicate for a row set column
into a edit field.
*/
class OPredicateInputController
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
m_xORB;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
m_xConnection;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >
m_xFormatter;
::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData >
m_xLocaleData;
::connectivity::OSQLParser
m_aParser;
public:
OPredicateInputController(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const ::connectivity::IParseContext* _pParseContext = NULL
);
/** transforms a "raw" predicate value (usually obtained from a user input) into a valid predicate for the given column
@param _rPredicateValue
The text to normalize.
@param _rxField
The field for which the text should be a predicate value.
@param _pErrorMessage
If not <NULL/>, and a parsing error occurs, the error message will be copied to the string the argument
points to.
*/
sal_Bool normalizePredicateString(
::rtl::OUString& _rPredicateValue,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField,
::rtl::OUString* _pErrorMessage = NULL
) const;
/** get's a value of the predicate which can be used in a WHERE clause.
@param _rPredicateValue
the value which has been normalized using normalizePredicateString
@param _rxField
is the field for which a predicate is to be entered
@param _bForStatementUse
If <TRUE/>, the returned value can be used in an SQL statement. If <FALSE/>, it can be used
for instance for setting parameter values.
@param _pErrorMessage
If not <NULL/>, and a parsing error occurs, the error message will be copied to the string the argument
points to.
@see normalizePredicateString
*/
::rtl::OUString getPredicateValue(
const ::rtl::OUString& _rPredicateValue,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & _rxField,
sal_Bool _bForStatementUse,
::rtl::OUString* _pErrorMessage = NULL
) const;
private:
::connectivity::OSQLParseNode* implPredicateTree(
::rtl::OUString& _rErrorMessage,
const ::rtl::OUString& _rStatement,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & _rxField
) const;
sal_Bool getSeparatorChars(
const ::com::sun::star::lang::Locale& _rLocale,
sal_Unicode& _rDecSep,
sal_Unicode& _rThdSep
) const;
};
//.........................................................................
} // namespace dbtools
//.........................................................................
#endif // CONNECTIVITY_PREDICATEINPUT_HXX
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Offline Analysis Database Container and Service Class
// Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------
#include "AliOADBContainer.h"
#include "AliLog.h"
#include <TObjArray.h>
#include <TArrayI.h>
#include <TFile.h>
#include <TList.h>
#include <TBrowser.h>
#include <TSystem.h>
#include <TError.h>
ClassImp(AliOADBContainer);
//______________________________________________________________________________
AliOADBContainer::AliOADBContainer() :
TNamed(),
fArray(0),
fDefaultList(0),
fLowerLimits(),
fUpperLimits(),
fEntries(0)
{
// Default constructor
}
AliOADBContainer::AliOADBContainer(const char* name) :
TNamed(name, "OADBContainer"),
fArray(new TObjArray(100)),
fDefaultList(new TList()),
fLowerLimits(),
fUpperLimits(),
fEntries(0)
{
// Constructor
}
//______________________________________________________________________________
AliOADBContainer::~AliOADBContainer()
{
// destructor
}
//______________________________________________________________________________
AliOADBContainer::AliOADBContainer(const AliOADBContainer& cont) :
TNamed(cont),
fArray(cont.fArray),
fDefaultList(cont.fDefaultList),
fLowerLimits(cont.fLowerLimits),
fUpperLimits(cont.fUpperLimits),
fEntries(cont.fEntries)
{
// Copy constructor.
}
//______________________________________________________________________________
AliOADBContainer& AliOADBContainer::operator=(const AliOADBContainer& cont)
{
//
// Assignment operator
// Copy objects related to run ranges
if(this!=&cont) {
TNamed::operator=(cont);
fEntries = cont.fEntries;
fLowerLimits.Set(fEntries);
fUpperLimits.Set(fEntries);
for (Int_t i = 0; i < fEntries; i++) {
fLowerLimits[i] = cont.fLowerLimits[i];
fUpperLimits[i] = cont.fUpperLimits[i];
fArray->AddAt(cont.fArray->At(i), i);
}
}
//
// Copy default objects
TList* list = cont.GetDefaultList();
TIter next(list);
TObject* obj;
while((obj = next())) fDefaultList->Add(obj);
//
return *this;
}
void AliOADBContainer::AppendObject(TObject* obj, Int_t lower, Int_t upper)
{
//
// Append a new object to the list
//
// Check that there is no overlap with existing run ranges
Int_t index = HasOverlap(lower, upper);
if (index != -1) {
AliFatal(Form("Ambiguos validity range (%5d, %5.5d-%5.5d) !\n", index,lower,upper));
return;
}
//
// Adjust arrays
fEntries++;
fLowerLimits.Set(fEntries);
fUpperLimits.Set(fEntries);
// Add the object
fLowerLimits[fEntries - 1] = lower;
fUpperLimits[fEntries - 1] = upper;
fArray->Add(obj);
}
void AliOADBContainer::RemoveObject(Int_t idx)
{
//
// Remove object from the list
//
// Check that index is inside range
if (idx < 0 || idx >= fEntries)
{
AliError(Form("Index out of Range %5d >= %5d", idx, fEntries));
return;
}
//
// Remove the object
TObject* obj = fArray->RemoveAt(idx);
delete obj;
//
// Adjust the run ranges and shrink the array
for (Int_t i = idx; i < (fEntries-1); i++) {
fLowerLimits[i] = fLowerLimits[i + 1];
fUpperLimits[i] = fUpperLimits[i + 1];
fArray->AddAt(fArray->At(i+1), i);
}
fArray->RemoveAt(fEntries - 1);
fEntries--;
}
void AliOADBContainer::UpdateObject(Int_t idx, TObject* obj, Int_t lower, Int_t upper)
{
//
// Update an existing object, at a given position
// Check that index is inside range
if (idx < 0 || idx >= fEntries)
{
AliError(Form("Index out of Range %5d >= %5d", idx, fEntries));
return;
}
//
// Remove the old object and reset the range
// TObject* obj2 =
fArray->RemoveAt(idx);
// don't delete it: if you are updating it may be pointing to the same location of obj...
// delete obj2;
fLowerLimits[idx] = -1;
fUpperLimits[idx] = -1;
// Check that there is no overlap with existing run ranges
Int_t index = HasOverlap(lower, upper);
if (index != -1) {
AliFatal(Form("Ambiguos validity range (%5d, %5.5d-%5.5d) !\n", index,lower,upper));
return;
}
//
// Add object at the same position
//printf("idx %d obj %llx\n", idx, obj);
fLowerLimits[idx] = lower;
fUpperLimits[idx] = upper;
fArray->AddAt(obj, idx);
}
void AliOADBContainer::AddDefaultObject(TObject* obj)
{
// Add a default object
fDefaultList->Add(obj);
}
void AliOADBContainer::CleanDefaultList()
{
// Clean default list
fDefaultList->Delete();
}
Int_t AliOADBContainer::GetIndexForRun(Int_t run) const
{
//
// Find the index for a given run
Int_t found = 0;
Int_t index = -1;
for (Int_t i = 0; i < fEntries; i++)
{
if (run >= fLowerLimits[i] && run <= fUpperLimits[i])
{
found++;
index = i;
}
}
if (found > 1) {
AliError(Form("More than one (%5d) object found; return last (%5d) !\n", found, index));
} else if (index == -1) {
AliWarning(Form("No object found for run %5d !\n", run));
}
return index;
}
TObject* AliOADBContainer::GetObject(Int_t run, const char* def) const
{
// Return object for given run or default if not found
TObject* obj = 0;
Int_t idx = GetIndexForRun(run);
if (idx == -1) {
// no object found, try default
obj = fDefaultList->FindObject(def);
if (!obj) {
AliError("Default Object not found !\n");
return (0);
} else {
return (obj);
}
} else {
return (fArray->At(idx));
}
}
TObject* AliOADBContainer::GetObjectByIndex(Int_t run) const
{
// Return object for given index
return (fArray->At(run));
}
void AliOADBContainer::WriteToFile(const char* fname) const
{
//
// Write object to file
TFile* f = new TFile(fname, "update");
Write();
f->Purge();
f->Close();
}
Int_t AliOADBContainer::InitFromFile(const char* fname, const char* key)
{
//
// Initialize object from file
TFile* file = TFile::Open(fname);
if (!file) return (1);
AliOADBContainer* cont = 0;
file->GetObject(key, cont);
if (!cont)
{
AliError("Object not found in file \n");
return 1;
}
SetName(cont->GetName());
SetTitle(cont->GetTitle());
fEntries = cont->GetNumberOfEntries();
fLowerLimits.Set(fEntries);
fUpperLimits.Set(fEntries);
if(fEntries > fArray->GetSize()) fArray->Expand(fEntries);
for (Int_t i = 0; i < fEntries; i++) {
fLowerLimits[i] = cont->LowerLimit(i);
fUpperLimits[i] = cont->UpperLimit(i);
fArray->AddAt(cont->GetObjectByIndex(i), i);
}
if (!fDefaultList) fDefaultList = new TList();
TIter next(cont->GetDefaultList());
TObject* obj;
while((obj = next())) fDefaultList->Add(obj);
return 0;
}
void AliOADBContainer::List()
{
//
// List Objects
printf("Entries %d\n", fEntries);
for (Int_t i = 0; i < fEntries; i++) {
printf("Lower %5d Upper %5d \n", fLowerLimits[i], fUpperLimits[i]);
(fArray->At(i))->Dump();
}
TIter next(fDefaultList);
TObject* obj;
while((obj = next())) obj->Dump();
}
Int_t AliOADBContainer::HasOverlap(Int_t lower, Int_t upper) const
{
//
// Checks for overlpapping validity regions
for (Int_t i = 0; i < fEntries; i++) {
if ((lower >= fLowerLimits[i] && lower <= fUpperLimits[i]) ||
(upper >= fLowerLimits[i] && upper <= fUpperLimits[i]))
{
return (i);
}
}
return (-1);
}
void AliOADBContainer::Browse(TBrowser *b)
{
// Browse this object.
// If b=0, there is no Browse call TObject::Browse(0) instead.
// This means TObject::Inspect() will be invoked indirectly
if (b) {
for (Int_t i = 0; i < fEntries; i++) {
b->Add(fArray->At(i),Form("%9.9d - %9.9d", fLowerLimits[i], fUpperLimits[i]));
}
TIter next(fDefaultList);
TObject* obj;
while((obj = next())) b->Add(obj);
}
else
TObject::Browse(b);
}
//______________________________________________________________________________
const char* AliOADBContainer::GetOADBPath()
{
// returns the path of the OADB
// this static function just depends on environment variables
static TString oadbPath;
if (gSystem->Getenv("OADB_PATH"))
oadbPath = gSystem->Getenv("OADB_PATH");
else if (gSystem->Getenv("ALICE_ROOT"))
oadbPath.Form("%s/OADB", gSystem->Getenv("ALICE_ROOT"));
else
::Fatal("AliAnalysisManager::GetOADBPath", "Cannot figure out AODB path. Define ALICE_ROOT or OADB_PATH!");
return oadbPath;
}
<commit_msg>Patch that prints the name of the OADB object in case it was missing so that it is easier to debug in case OADB warnings appears. Constantin<commit_after>/**************************************************************************
* Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Offline Analysis Database Container and Service Class
// Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------
#include "AliOADBContainer.h"
#include "AliLog.h"
#include <TObjArray.h>
#include <TArrayI.h>
#include <TFile.h>
#include <TList.h>
#include <TBrowser.h>
#include <TSystem.h>
#include <TError.h>
ClassImp(AliOADBContainer);
//______________________________________________________________________________
AliOADBContainer::AliOADBContainer() :
TNamed(),
fArray(0),
fDefaultList(0),
fLowerLimits(),
fUpperLimits(),
fEntries(0)
{
// Default constructor
}
AliOADBContainer::AliOADBContainer(const char* name) :
TNamed(name, "OADBContainer"),
fArray(new TObjArray(100)),
fDefaultList(new TList()),
fLowerLimits(),
fUpperLimits(),
fEntries(0)
{
// Constructor
}
//______________________________________________________________________________
AliOADBContainer::~AliOADBContainer()
{
// destructor
}
//______________________________________________________________________________
AliOADBContainer::AliOADBContainer(const AliOADBContainer& cont) :
TNamed(cont),
fArray(cont.fArray),
fDefaultList(cont.fDefaultList),
fLowerLimits(cont.fLowerLimits),
fUpperLimits(cont.fUpperLimits),
fEntries(cont.fEntries)
{
// Copy constructor.
}
//______________________________________________________________________________
AliOADBContainer& AliOADBContainer::operator=(const AliOADBContainer& cont)
{
//
// Assignment operator
// Copy objects related to run ranges
if(this!=&cont) {
TNamed::operator=(cont);
fEntries = cont.fEntries;
fLowerLimits.Set(fEntries);
fUpperLimits.Set(fEntries);
for (Int_t i = 0; i < fEntries; i++) {
fLowerLimits[i] = cont.fLowerLimits[i];
fUpperLimits[i] = cont.fUpperLimits[i];
fArray->AddAt(cont.fArray->At(i), i);
}
}
//
// Copy default objects
TList* list = cont.GetDefaultList();
TIter next(list);
TObject* obj;
while((obj = next())) fDefaultList->Add(obj);
//
return *this;
}
void AliOADBContainer::AppendObject(TObject* obj, Int_t lower, Int_t upper)
{
//
// Append a new object to the list
//
// Check that there is no overlap with existing run ranges
Int_t index = HasOverlap(lower, upper);
if (index != -1) {
AliFatal(Form("Ambiguos validity range (%5d, %5.5d-%5.5d) !\n", index,lower,upper));
return;
}
//
// Adjust arrays
fEntries++;
fLowerLimits.Set(fEntries);
fUpperLimits.Set(fEntries);
// Add the object
fLowerLimits[fEntries - 1] = lower;
fUpperLimits[fEntries - 1] = upper;
fArray->Add(obj);
}
void AliOADBContainer::RemoveObject(Int_t idx)
{
//
// Remove object from the list
//
// Check that index is inside range
if (idx < 0 || idx >= fEntries)
{
AliError(Form("Index out of Range %5d >= %5d", idx, fEntries));
return;
}
//
// Remove the object
TObject* obj = fArray->RemoveAt(idx);
delete obj;
//
// Adjust the run ranges and shrink the array
for (Int_t i = idx; i < (fEntries-1); i++) {
fLowerLimits[i] = fLowerLimits[i + 1];
fUpperLimits[i] = fUpperLimits[i + 1];
fArray->AddAt(fArray->At(i+1), i);
}
fArray->RemoveAt(fEntries - 1);
fEntries--;
}
void AliOADBContainer::UpdateObject(Int_t idx, TObject* obj, Int_t lower, Int_t upper)
{
//
// Update an existing object, at a given position
// Check that index is inside range
if (idx < 0 || idx >= fEntries)
{
AliError(Form("Index out of Range %5d >= %5d", idx, fEntries));
return;
}
//
// Remove the old object and reset the range
// TObject* obj2 =
fArray->RemoveAt(idx);
// don't delete it: if you are updating it may be pointing to the same location of obj...
// delete obj2;
fLowerLimits[idx] = -1;
fUpperLimits[idx] = -1;
// Check that there is no overlap with existing run ranges
Int_t index = HasOverlap(lower, upper);
if (index != -1) {
AliFatal(Form("Ambiguos validity range (%5d, %5.5d-%5.5d) !\n", index,lower,upper));
return;
}
//
// Add object at the same position
//printf("idx %d obj %llx\n", idx, obj);
fLowerLimits[idx] = lower;
fUpperLimits[idx] = upper;
fArray->AddAt(obj, idx);
}
void AliOADBContainer::AddDefaultObject(TObject* obj)
{
// Add a default object
fDefaultList->Add(obj);
}
void AliOADBContainer::CleanDefaultList()
{
// Clean default list
fDefaultList->Delete();
}
Int_t AliOADBContainer::GetIndexForRun(Int_t run) const
{
//
// Find the index for a given run
Int_t found = 0;
Int_t index = -1;
for (Int_t i = 0; i < fEntries; i++)
{
if (run >= fLowerLimits[i] && run <= fUpperLimits[i])
{
found++;
index = i;
}
}
if (found > 1) {
AliError(Form("More than one (%5d) object found; return last (%5d) !\n", found, index));
} else if (index == -1) {
AliWarning(Form("No object (%s) found for run %5d !\n", GetName(), run));
}
return index;
}
TObject* AliOADBContainer::GetObject(Int_t run, const char* def) const
{
// Return object for given run or default if not found
TObject* obj = 0;
Int_t idx = GetIndexForRun(run);
if (idx == -1) {
// no object found, try default
obj = fDefaultList->FindObject(def);
if (!obj) {
AliError(Form("Default Object (%s) not found !\n", GetName()));
return (0);
} else {
return (obj);
}
} else {
return (fArray->At(idx));
}
}
TObject* AliOADBContainer::GetObjectByIndex(Int_t run) const
{
// Return object for given index
return (fArray->At(run));
}
void AliOADBContainer::WriteToFile(const char* fname) const
{
//
// Write object to file
TFile* f = new TFile(fname, "update");
Write();
f->Purge();
f->Close();
}
Int_t AliOADBContainer::InitFromFile(const char* fname, const char* key)
{
//
// Initialize object from file
TFile* file = TFile::Open(fname);
if (!file) return (1);
AliOADBContainer* cont = 0;
file->GetObject(key, cont);
if (!cont)
{
AliError(Form("Object (%s) not found in file \n", GetName()));
return 1;
}
SetName(cont->GetName());
SetTitle(cont->GetTitle());
fEntries = cont->GetNumberOfEntries();
fLowerLimits.Set(fEntries);
fUpperLimits.Set(fEntries);
if(fEntries > fArray->GetSize()) fArray->Expand(fEntries);
for (Int_t i = 0; i < fEntries; i++) {
fLowerLimits[i] = cont->LowerLimit(i);
fUpperLimits[i] = cont->UpperLimit(i);
fArray->AddAt(cont->GetObjectByIndex(i), i);
}
if (!fDefaultList) fDefaultList = new TList();
TIter next(cont->GetDefaultList());
TObject* obj;
while((obj = next())) fDefaultList->Add(obj);
return 0;
}
void AliOADBContainer::List()
{
//
// List Objects
printf("Entries %d\n", fEntries);
for (Int_t i = 0; i < fEntries; i++) {
printf("Lower %5d Upper %5d \n", fLowerLimits[i], fUpperLimits[i]);
(fArray->At(i))->Dump();
}
TIter next(fDefaultList);
TObject* obj;
while((obj = next())) obj->Dump();
}
Int_t AliOADBContainer::HasOverlap(Int_t lower, Int_t upper) const
{
//
// Checks for overlpapping validity regions
for (Int_t i = 0; i < fEntries; i++) {
if ((lower >= fLowerLimits[i] && lower <= fUpperLimits[i]) ||
(upper >= fLowerLimits[i] && upper <= fUpperLimits[i]))
{
return (i);
}
}
return (-1);
}
void AliOADBContainer::Browse(TBrowser *b)
{
// Browse this object.
// If b=0, there is no Browse call TObject::Browse(0) instead.
// This means TObject::Inspect() will be invoked indirectly
if (b) {
for (Int_t i = 0; i < fEntries; i++) {
b->Add(fArray->At(i),Form("%9.9d - %9.9d", fLowerLimits[i], fUpperLimits[i]));
}
TIter next(fDefaultList);
TObject* obj;
while((obj = next())) b->Add(obj);
}
else
TObject::Browse(b);
}
//______________________________________________________________________________
const char* AliOADBContainer::GetOADBPath()
{
// returns the path of the OADB
// this static function just depends on environment variables
static TString oadbPath;
if (gSystem->Getenv("OADB_PATH"))
oadbPath = gSystem->Getenv("OADB_PATH");
else if (gSystem->Getenv("ALICE_ROOT"))
oadbPath.Form("%s/OADB", gSystem->Getenv("ALICE_ROOT"));
else
::Fatal("AliAnalysisManager::GetOADBPath", "Cannot figure out AODB path. Define ALICE_ROOT or OADB_PATH!");
return oadbPath;
}
<|endoftext|> |
<commit_before>#include "Hearthstone.h"
#include <QFile>
#include <QDesktopServices>
#include <QSettings>
#include <QTextStream>
#include <QRegExp>
#include <QJsonDocument>
#include <QJsonObject>
#ifdef Q_OS_MAC
#include "OSXWindowCapture.h"
#elif defined Q_OS_WIN
#include "WinWindowCapture.h"
#include "Shlobj.h"
#endif
DEFINE_SINGLETON_SCOPE( Hearthstone )
Hearthstone::Hearthstone()
: mCapture( NULL ), mGameRunning( false )
{
#ifdef Q_OS_MAC
mCapture = new OSXWindowCapture( WindowName() );
#elif defined Q_OS_WIN
mCapture = new WinWindowCapture( WindowName() );
#endif
// On OS X, WindowFound is quite CPU intensive
// Starting time for HS is also long
// So just check only once in a while
mTimer = new QTimer( this );
connect( mTimer, &QTimer::timeout, this, &Hearthstone::Update );
#ifdef Q_OS_MAC
mTimer->start( 5000 );
#else
mTimer->start( 250 );
#endif
}
Hearthstone::~Hearthstone() {
if( mCapture != NULL )
delete mCapture;
}
void Hearthstone::Update() {
bool isRunning = mCapture->WindowFound();
if( isRunning ) {
static int lastLeft = 0, lastTop = 0, lastWidth = 0, lastHeight = 0;
if( lastLeft != mCapture->Left() || lastTop != mCapture->Top() ||
lastWidth != mCapture->Width() || lastHeight != mCapture->Height() )
{
lastLeft = mCapture->Left(),
lastTop = mCapture->Top(),
lastWidth = mCapture->Width(),
lastHeight = mCapture->Height();
DBG( "HS window changed %d %d %d %d", lastLeft, lastTop, lastWidth, lastHeight );
emit GameWindowChanged( lastLeft, lastTop, lastWidth, lastHeight );
}
}
if( mGameRunning != isRunning ) {
mGameRunning = isRunning;
if( isRunning ) {
LOG( "Hearthstone is running" );
emit GameStarted();
} else {
LOG( "Hearthstone stopped" );
emit GameStopped();
}
}
}
QString Hearthstone::ReadAgentAttribute( const char *attributeName ) const {
#ifdef Q_OS_MAC
QString path = "/Users/Shared/Battle.net/Agent/agent.db";
#elif defined Q_OS_WIN
wchar_t buffer[ MAX_PATH ];
SHGetSpecialFolderPathW( NULL, buffer, CSIDL_COMMON_APPDATA, FALSE );
QString programData = QString::fromWCharArray( buffer );
QString path = programData + "\\Battle.net\\Agent\\agent.db";
#endif
QFile file( path );
if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) {
DBG( "Couldn't open %s (%d)", qt2cstr( path ), file.error() );
return "";
}
QString contents = file.readAll();
QJsonDocument doc = QJsonDocument::fromJson( contents.toUtf8() );
QJsonObject root = doc.object();
QJsonObject hs = root["/game/hs_beta"].toObject()["resource"].toObject()["game"].toObject();
return hs[ QString( attributeName ) ].toString();
}
bool Hearthstone::GameRunning() const {
return mGameRunning;
}
#ifdef Q_OS_WIN
inline float roundf( float x ) {
return x >= 0.0f ? floorf( x + 0.5f ) : ceilf( x - 0.5f );
}
#endif
bool Hearthstone::CaptureWholeScreen( QPixmap *screen ) {
*screen = mCapture->Capture( 0, 0, Width(), Height() );
return true;
}
QPixmap Hearthstone::Capture( int canvasWidth, int canvasHeight, int cx, int cy, int cw, int ch )
{
UNUSED_ARG( canvasWidth );
int x, y, w, h;
int windowHeight = mCapture->Height();
float scale = windowHeight / float( canvasHeight );
x = roundf( cx * scale );
y = roundf( cy * scale );
w = roundf( cw * scale );
h = roundf( ch * scale );
return mCapture->Capture( x, y, w, h );
}
void Hearthstone::SetWindowCapture( WindowCapture *windowCapture ) {
if( mCapture != NULL )
delete mCapture;
mCapture = windowCapture;
}
void Hearthstone::EnableLogging() {
QString path = LogConfigPath();
QFile file( path );
bool logModified = false;
// Read file contents
QString contents;
if( file.exists() ) {
file.open( QIODevice::ReadOnly | QIODevice::Text );
QTextStream in( &file );
contents = in.readAll();
file.close();
}
// Check what modules we have to activate
QStringList modulesToActivate;
for( int i = 0; i < NUM_LOG_MODULES; i++ ) {
const char *moduleName = LOG_MODULE_NAMES[ i ];
QString moduleLine = QString( "[%1]" ).arg( moduleName ) ;
if( !contents.contains( moduleLine ) ) {
contents += "\n";
contents += moduleLine + "\n";
contents += "LogLevel=1\n";
contents += "FilePrinting=true\n";
DBG( "Activate module %s", moduleName );
logModified = true;
}
}
QRegExp regexEnabledConsolePrinting( "ConsolePrinting\\s*=\\s*true",
Qt::CaseInsensitive );
QRegExp regexDisabledFilePrinting( "FilePrinting\\s*=\\s*false",
Qt::CaseInsensitive );
if( contents.contains( regexEnabledConsolePrinting ) ||
contents.contains( regexDisabledFilePrinting ) )
{
contents.replace( regexEnabledConsolePrinting, "FilePrinting=true" );
contents.replace( regexDisabledFilePrinting, "FilePrinting=true" );
DBG( "FilePrinting enabled" );
logModified = true;
}
// Finally write updated log.config
if( logModified ) {
DBG( "Log modified. Write new version" );
if( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) {
ERR( "Couldn't create file %s", qt2cstr( path ) );
} else {
QTextStream out( &file );
out << contents;
}
}
// Notify about restart if game is running
Update();
if( GameRunning() && logModified ) {
emit GameRequiresRestart();
}
}
void Hearthstone::DisableLogging() {
QFile file( LogConfigPath() );
if( file.exists() ) {
file.remove();
LOG( "Ingame log deactivated." );
}
}
QString Hearthstone::LogConfigPath() const {
#ifdef Q_OS_MAC
QString homeLocation = QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first();
QString configPath = homeLocation + "/Library/Preferences/Blizzard/Hearthstone/log.config";
#elif defined Q_OS_WIN
wchar_t buffer[ MAX_PATH ];
SHGetSpecialFolderPathW( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE );
QString localAppData = QString::fromWCharArray( buffer );
QString configPath = localAppData + "/Blizzard/Hearthstone/log.config";
#endif
return configPath;
}
QString Hearthstone::DetectHearthstonePath() const {
static QString hsPath;
if( hsPath.isEmpty() ) {
#ifdef Q_OS_WIN
QString hsPathByAgent = ReadAgentAttribute( "install_dir" );
QSettings hsKey( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hearthstone", QSettings::NativeFormat );
QString hsPathByRegistry = hsKey.value( "InstallLocation" ).toString();
if( hsPathByAgent.isEmpty() && hsPathByRegistry.isEmpty() ) {
LOG( "Game folder not found. Fall back to default game path for now. You should set the path manually in the settings!" );
hsPath = QString( getenv("PROGRAMFILES") ) + "/Hearthstone";
} else if( !hsPathByRegistry.isEmpty() ) {
hsPath = hsPathByRegistry;
} else {
hsPath = hsPathByAgent;
}
#elif defined Q_OS_MAC
hsPath = ReadAgentAttribute( "install_dir" );
if( hsPath.isEmpty() ) {
LOG( "Fall back to default game path. You should set the path manually in the settings!" );
hsPath = QStandardPaths::standardLocations( QStandardPaths::ApplicationsLocation ).first() + "/Hearthstone";
}
#endif
}
return hsPath;
}
QString Hearthstone::WindowName() const {
QString locale = ReadAgentAttribute( "selected_locale" );
QString windowName = "Hearthstone";
#ifdef Q_OS_MAC
// Under mac the window name is not localized
return windowName;
#endif
if( locale == "zhCN" ) {
windowName = QString::fromWCharArray( L"炉石传说" );
} else if( locale == "zhTW" ) {
windowName = QString::fromWCharArray( L"《爐石戰記》" );
} else if( locale == "koKR") {
windowName = QString::fromWCharArray( L"하스스톤" );
}
QFile file("C:\\tmp\\out.txt");
file.open(QIODevice::Text | QIODevice::WriteOnly );
QTextStream out(&file);
out << windowName << "\n";
file.close();
return windowName;
}
int Hearthstone::Width() const {
return mCapture->Width();
}
int Hearthstone::Height() const {
return mCapture->Height();
}
<commit_msg>Remove debug stuff<commit_after>#include "Hearthstone.h"
#include <QFile>
#include <QDesktopServices>
#include <QSettings>
#include <QTextStream>
#include <QRegExp>
#include <QJsonDocument>
#include <QJsonObject>
#ifdef Q_OS_MAC
#include "OSXWindowCapture.h"
#elif defined Q_OS_WIN
#include "WinWindowCapture.h"
#include "Shlobj.h"
#endif
DEFINE_SINGLETON_SCOPE( Hearthstone )
Hearthstone::Hearthstone()
: mCapture( NULL ), mGameRunning( false )
{
#ifdef Q_OS_MAC
mCapture = new OSXWindowCapture( WindowName() );
#elif defined Q_OS_WIN
mCapture = new WinWindowCapture( WindowName() );
#endif
// On OS X, WindowFound is quite CPU intensive
// Starting time for HS is also long
// So just check only once in a while
mTimer = new QTimer( this );
connect( mTimer, &QTimer::timeout, this, &Hearthstone::Update );
#ifdef Q_OS_MAC
mTimer->start( 5000 );
#else
mTimer->start( 250 );
#endif
}
Hearthstone::~Hearthstone() {
if( mCapture != NULL )
delete mCapture;
}
void Hearthstone::Update() {
bool isRunning = mCapture->WindowFound();
if( isRunning ) {
static int lastLeft = 0, lastTop = 0, lastWidth = 0, lastHeight = 0;
if( lastLeft != mCapture->Left() || lastTop != mCapture->Top() ||
lastWidth != mCapture->Width() || lastHeight != mCapture->Height() )
{
lastLeft = mCapture->Left(),
lastTop = mCapture->Top(),
lastWidth = mCapture->Width(),
lastHeight = mCapture->Height();
DBG( "HS window changed %d %d %d %d", lastLeft, lastTop, lastWidth, lastHeight );
emit GameWindowChanged( lastLeft, lastTop, lastWidth, lastHeight );
}
}
if( mGameRunning != isRunning ) {
mGameRunning = isRunning;
if( isRunning ) {
LOG( "Hearthstone is running" );
emit GameStarted();
} else {
LOG( "Hearthstone stopped" );
emit GameStopped();
}
}
}
QString Hearthstone::ReadAgentAttribute( const char *attributeName ) const {
#ifdef Q_OS_MAC
QString path = "/Users/Shared/Battle.net/Agent/agent.db";
#elif defined Q_OS_WIN
wchar_t buffer[ MAX_PATH ];
SHGetSpecialFolderPathW( NULL, buffer, CSIDL_COMMON_APPDATA, FALSE );
QString programData = QString::fromWCharArray( buffer );
QString path = programData + "\\Battle.net\\Agent\\agent.db";
#endif
QFile file( path );
if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) {
DBG( "Couldn't open %s (%d)", qt2cstr( path ), file.error() );
return "";
}
QString contents = file.readAll();
QJsonDocument doc = QJsonDocument::fromJson( contents.toUtf8() );
QJsonObject root = doc.object();
QJsonObject hs = root["/game/hs_beta"].toObject()["resource"].toObject()["game"].toObject();
return hs[ QString( attributeName ) ].toString();
}
bool Hearthstone::GameRunning() const {
return mGameRunning;
}
#ifdef Q_OS_WIN
inline float roundf( float x ) {
return x >= 0.0f ? floorf( x + 0.5f ) : ceilf( x - 0.5f );
}
#endif
bool Hearthstone::CaptureWholeScreen( QPixmap *screen ) {
*screen = mCapture->Capture( 0, 0, Width(), Height() );
return true;
}
QPixmap Hearthstone::Capture( int canvasWidth, int canvasHeight, int cx, int cy, int cw, int ch )
{
UNUSED_ARG( canvasWidth );
int x, y, w, h;
int windowHeight = mCapture->Height();
float scale = windowHeight / float( canvasHeight );
x = roundf( cx * scale );
y = roundf( cy * scale );
w = roundf( cw * scale );
h = roundf( ch * scale );
return mCapture->Capture( x, y, w, h );
}
void Hearthstone::SetWindowCapture( WindowCapture *windowCapture ) {
if( mCapture != NULL )
delete mCapture;
mCapture = windowCapture;
}
void Hearthstone::EnableLogging() {
QString path = LogConfigPath();
QFile file( path );
bool logModified = false;
// Read file contents
QString contents;
if( file.exists() ) {
file.open( QIODevice::ReadOnly | QIODevice::Text );
QTextStream in( &file );
contents = in.readAll();
file.close();
}
// Check what modules we have to activate
QStringList modulesToActivate;
for( int i = 0; i < NUM_LOG_MODULES; i++ ) {
const char *moduleName = LOG_MODULE_NAMES[ i ];
QString moduleLine = QString( "[%1]" ).arg( moduleName ) ;
if( !contents.contains( moduleLine ) ) {
contents += "\n";
contents += moduleLine + "\n";
contents += "LogLevel=1\n";
contents += "FilePrinting=true\n";
DBG( "Activate module %s", moduleName );
logModified = true;
}
}
QRegExp regexEnabledConsolePrinting( "ConsolePrinting\\s*=\\s*true",
Qt::CaseInsensitive );
QRegExp regexDisabledFilePrinting( "FilePrinting\\s*=\\s*false",
Qt::CaseInsensitive );
if( contents.contains( regexEnabledConsolePrinting ) ||
contents.contains( regexDisabledFilePrinting ) )
{
contents.replace( regexEnabledConsolePrinting, "FilePrinting=true" );
contents.replace( regexDisabledFilePrinting, "FilePrinting=true" );
DBG( "FilePrinting enabled" );
logModified = true;
}
// Finally write updated log.config
if( logModified ) {
DBG( "Log modified. Write new version" );
if( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) {
ERR( "Couldn't create file %s", qt2cstr( path ) );
} else {
QTextStream out( &file );
out << contents;
}
}
// Notify about restart if game is running
Update();
if( GameRunning() && logModified ) {
emit GameRequiresRestart();
}
}
void Hearthstone::DisableLogging() {
QFile file( LogConfigPath() );
if( file.exists() ) {
file.remove();
LOG( "Ingame log deactivated." );
}
}
QString Hearthstone::LogConfigPath() const {
#ifdef Q_OS_MAC
QString homeLocation = QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first();
QString configPath = homeLocation + "/Library/Preferences/Blizzard/Hearthstone/log.config";
#elif defined Q_OS_WIN
wchar_t buffer[ MAX_PATH ];
SHGetSpecialFolderPathW( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE );
QString localAppData = QString::fromWCharArray( buffer );
QString configPath = localAppData + "/Blizzard/Hearthstone/log.config";
#endif
return configPath;
}
QString Hearthstone::DetectHearthstonePath() const {
static QString hsPath;
if( hsPath.isEmpty() ) {
#ifdef Q_OS_WIN
QString hsPathByAgent = ReadAgentAttribute( "install_dir" );
QSettings hsKey( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hearthstone", QSettings::NativeFormat );
QString hsPathByRegistry = hsKey.value( "InstallLocation" ).toString();
if( hsPathByAgent.isEmpty() && hsPathByRegistry.isEmpty() ) {
LOG( "Game folder not found. Fall back to default game path for now. You should set the path manually in the settings!" );
hsPath = QString( getenv("PROGRAMFILES") ) + "/Hearthstone";
} else if( !hsPathByRegistry.isEmpty() ) {
hsPath = hsPathByRegistry;
} else {
hsPath = hsPathByAgent;
}
#elif defined Q_OS_MAC
hsPath = ReadAgentAttribute( "install_dir" );
if( hsPath.isEmpty() ) {
LOG( "Fall back to default game path. You should set the path manually in the settings!" );
hsPath = QStandardPaths::standardLocations( QStandardPaths::ApplicationsLocation ).first() + "/Hearthstone";
}
#endif
}
return hsPath;
}
QString Hearthstone::WindowName() const {
QString locale = ReadAgentAttribute( "selected_locale" );
QString windowName = "Hearthstone";
#ifdef Q_OS_MAC
// Under mac the window name is not localized
return windowName;
#endif
if( locale == "zhCN" ) {
windowName = QString::fromWCharArray( L"炉石传说" );
} else if( locale == "zhTW" ) {
windowName = QString::fromWCharArray( L"《爐石戰記》" );
} else if( locale == "koKR") {
windowName = QString::fromWCharArray( L"하스스톤" );
}
return windowName;
}
int Hearthstone::Width() const {
return mCapture->Width();
}
int Hearthstone::Height() const {
return mCapture->Height();
}
<|endoftext|> |
<commit_before>#include "yyltype.h"
#include "ast.h"
#include "bitvariable.h"
#include "generator.h" // Todo refactor away
#include <llvm/IR/Type.h>
#include <llvm/IR/Value.h>
llvm::Value* CExchange::codeGen(CodeGenContext& context)
{
BitVariable lhsVar, rhsVar;
if (!context.LookupBitVariable(lhsVar, lhs.module, lhs.name, lhs.modLoc, lhs.nameLoc))
{
return nullptr;
}
if (!context.LookupBitVariable(rhsVar, rhs.module, rhs.name, rhs.modLoc, rhs.nameLoc))
{
return nullptr;
}
if (lhsVar.value->getType()->isPointerTy() && rhsVar.value->getType()->isPointerTy())
{
// Both sides must be identifiers
llvm::Value* left = lhs.codeGen(context);
llvm::Value* right = rhs.codeGen(context);
if (left->getType()->isIntegerTy() && right->getType()->isIntegerTy())
{
const llvm::IntegerType* leftType = llvm::cast<llvm::IntegerType>(left->getType());
const llvm::IntegerType* rightType = llvm::cast<llvm::IntegerType>(right->getType());
if (leftType->getBitWidth() != rightType->getBitWidth())
{
return context.gContext.ReportError(nullptr, EC_ErrorAtLocation, operatorLoc, "Both operands to exchange must be same size");
}
CAssignment::generateAssignment(lhsVar, lhs, right, context);
CAssignment::generateAssignment(rhsVar, rhs, left, context);
}
return nullptr;
}
return context.gContext.ReportError(nullptr, EC_ErrorAtLocation, operatorLoc, "Illegal operands to exchange (must both be assignable)");
}
<commit_msg>Bug Fix: MAPPINGs can now be used as inputs/outputs to <-> operator (if appropriate)<commit_after>#include "yyltype.h"
#include "ast.h"
#include "bitvariable.h"
#include "generator.h" // Todo refactor away
#include <llvm/IR/Type.h>
#include <llvm/IR/Value.h>
llvm::Value* CExchange::codeGen(CodeGenContext& context)
{
BitVariable lhsVar, rhsVar;
if (!context.LookupBitVariable(lhsVar, lhs.module, lhs.name, lhs.modLoc, lhs.nameLoc))
{
return nullptr;
}
if (!context.LookupBitVariable(rhsVar, rhs.module, rhs.name, rhs.modLoc, rhs.nameLoc))
{
return nullptr;
}
if ((lhsVar.mappingRef || lhsVar.value->getType()->isPointerTy()) && (rhsVar.mappingRef || rhsVar.value->getType()->isPointerTy()))
{
// Both sides must be identifiers/valid mappingReferences
llvm::Value* left = nullptr;
llvm::Value* right = nullptr;
if (lhsVar.mappingRef)
{
left = lhsVar.mapping->generateCallGetByMapping(context, lhs.modLoc, lhs.nameLoc);
}
else
{
left = lhs.codeGen(context);
}
if (rhsVar.mappingRef)
{
right = rhsVar.mapping->generateCallGetByMapping(context, rhs.modLoc, rhs.nameLoc);
}
else
{
right = rhs.codeGen(context);
}
if (left->getType()->isIntegerTy() && right->getType()->isIntegerTy())
{
const llvm::IntegerType* leftType = llvm::cast<llvm::IntegerType>(left->getType());
const llvm::IntegerType* rightType = llvm::cast<llvm::IntegerType>(right->getType());
if (leftType->getBitWidth() != rightType->getBitWidth())
{
return context.gContext.ReportError(nullptr, EC_ErrorAtLocation, operatorLoc, "Both operands to exchange must be same size");
}
if (lhsVar.mappingRef)
{
lhsVar.mapping->generateCallSetByMapping(context, lhs.modLoc, lhs.nameLoc, right);
}
else
{
CAssignment::generateAssignment(lhsVar, lhs, right, context);
}
if (rhsVar.mappingRef)
{
rhsVar.mapping->generateCallSetByMapping(context, rhs.modLoc, rhs.nameLoc, left);
}
else
{
CAssignment::generateAssignment(rhsVar, rhs, left, context);
}
return nullptr;
}
}
return context.gContext.ReportError(nullptr, EC_ErrorAtLocation, operatorLoc, "Illegal operands to exchange (must both be assignable)");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "content/browser/android/content_startup_flags.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "cc/base/switches.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "ui/base/ui_base_switches.h"
namespace content {
void SetContentCommandLineFlags(int max_render_process_count,
const std::string& plugin_descriptor) {
// May be called multiple times, to cover all possible program entry points.
static bool already_initialized = false;
if (already_initialized)
return;
already_initialized = true;
CommandLine* parsed_command_line = CommandLine::ForCurrentProcess();
if (parsed_command_line->HasSwitch(switches::kRendererProcessLimit)) {
std::string limit = parsed_command_line->GetSwitchValueASCII(
switches::kRendererProcessLimit);
int value;
if (base::StringToInt(limit, &value))
max_render_process_count = value;
}
if (max_render_process_count <= 0) {
// Need to ensure the command line flag is consistent as a lot of chrome
// internal code checks this directly, but it wouldn't normally get set when
// we are implementing an embedded WebView.
parsed_command_line->AppendSwitch(switches::kSingleProcess);
} else {
max_render_process_count =
std::min(max_render_process_count,
static_cast<int>(content::kMaxRendererProcessCount));
content::RenderProcessHost::SetMaxRendererProcessCount(
max_render_process_count);
}
parsed_command_line->AppendSwitch(switches::kForceCompositingMode);
parsed_command_line->AppendSwitch(switches::kAllowWebUICompositing);
parsed_command_line->AppendSwitch(switches::kEnableThreadedCompositing);
parsed_command_line->AppendSwitch(
switches::kEnableCompositingForFixedPosition);
parsed_command_line->AppendSwitch(switches::kEnableAcceleratedOverflowScroll);
parsed_command_line->AppendSwitch(
switches::kEnableAcceleratedScrollableFrames);
parsed_command_line->AppendSwitch(
switches::kEnableCompositedScrollingForFrames);
parsed_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);
parsed_command_line->AppendSwitch(switches::kEnablePinch);
parsed_command_line->AppendSwitch(switches::kEnableOverscrollNotifications);
// Run the GPU service as a thread in the browser instead of as a
// standalone process.
parsed_command_line->AppendSwitch(switches::kInProcessGPU);
parsed_command_line->AppendSwitch(switches::kDisableGpuShaderDiskCache);
// Always use fixed layout and viewport tag.
parsed_command_line->AppendSwitch(switches::kEnableFixedLayout);
parsed_command_line->AppendSwitch(switches::kEnableViewport);
if (!plugin_descriptor.empty()) {
parsed_command_line->AppendSwitchNative(
switches::kRegisterPepperPlugins, plugin_descriptor);
}
}
} // namespace content
<commit_msg>android: Enable BeginFrame scheduling by default<commit_after>// Copyright (c) 2012 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 "content/browser/android/content_startup_flags.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "cc/base/switches.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "ui/base/ui_base_switches.h"
namespace content {
void SetContentCommandLineFlags(int max_render_process_count,
const std::string& plugin_descriptor) {
// May be called multiple times, to cover all possible program entry points.
static bool already_initialized = false;
if (already_initialized)
return;
already_initialized = true;
CommandLine* parsed_command_line = CommandLine::ForCurrentProcess();
if (parsed_command_line->HasSwitch(switches::kRendererProcessLimit)) {
std::string limit = parsed_command_line->GetSwitchValueASCII(
switches::kRendererProcessLimit);
int value;
if (base::StringToInt(limit, &value))
max_render_process_count = value;
}
if (max_render_process_count <= 0) {
// Need to ensure the command line flag is consistent as a lot of chrome
// internal code checks this directly, but it wouldn't normally get set when
// we are implementing an embedded WebView.
parsed_command_line->AppendSwitch(switches::kSingleProcess);
} else {
max_render_process_count =
std::min(max_render_process_count,
static_cast<int>(content::kMaxRendererProcessCount));
content::RenderProcessHost::SetMaxRendererProcessCount(
max_render_process_count);
}
parsed_command_line->AppendSwitch(switches::kForceCompositingMode);
parsed_command_line->AppendSwitch(switches::kAllowWebUICompositing);
parsed_command_line->AppendSwitch(switches::kEnableThreadedCompositing);
parsed_command_line->AppendSwitch(
switches::kEnableCompositingForFixedPosition);
parsed_command_line->AppendSwitch(switches::kEnableAcceleratedOverflowScroll);
parsed_command_line->AppendSwitch(
switches::kEnableAcceleratedScrollableFrames);
parsed_command_line->AppendSwitch(
switches::kEnableCompositedScrollingForFrames);
parsed_command_line->AppendSwitch(switches::kEnableBeginFrameScheduling);
parsed_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);
parsed_command_line->AppendSwitch(switches::kEnablePinch);
parsed_command_line->AppendSwitch(switches::kEnableOverscrollNotifications);
// Run the GPU service as a thread in the browser instead of as a
// standalone process.
parsed_command_line->AppendSwitch(switches::kInProcessGPU);
parsed_command_line->AppendSwitch(switches::kDisableGpuShaderDiskCache);
// Always use fixed layout and viewport tag.
parsed_command_line->AppendSwitch(switches::kEnableFixedLayout);
parsed_command_line->AppendSwitch(switches::kEnableViewport);
if (!plugin_descriptor.empty()) {
parsed_command_line->AppendSwitchNative(
switches::kRegisterPepperPlugins, plugin_descriptor);
}
}
} // namespace content
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015-2016, The Kovri I2P Router Project
*
* 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.
*/
#include "Signature.h"
#include "cryptopp_impl.h"
#include "Rand.h"
#include <memory>
#include "util/Log.h"
namespace i2p {
namespace crypto {
DSAVerifier::DSAVerifier(const uint8_t * signingKey) : m_Impl(new DSAVerifier_Pimpl(signingKey)) {}
DSAVerifier::~DSAVerifier() {
delete m_Impl;
}
bool DSAVerifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
DSASigner::DSASigner(const uint8_t* signingPrivateKey) : m_Impl(new DSASigner_Pimpl(signingPrivateKey)) {}
DSASigner::~DSASigner() { delete m_Impl; }
void DSASigner::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
DSASigner_Pimpl::DSASigner_Pimpl(const uint8_t* signingPrivateKey) {
m_PrivateKey.Initialize(
dsap,
dsaq,
dsag,
CryptoPP::Integer(
signingPrivateKey,
DSA_PRIVATE_KEY_LENGTH));
}
void DSASigner_Pimpl::Sign(
const uint8_t* buf,
size_t len,
uint8_t* signature) const {
i2p::crypto::PRNG & rnd = i2p::crypto::GetPRNG();
CryptoPP::DSA::Signer signer(m_PrivateKey);
signer.SignMessage(rnd, buf, len, signature);
}
void CreateDSARandomKeys(
uint8_t* signingPrivateKey,
uint8_t* signingPublicKey) {
uint8_t keybuff[DSA_PRIVATE_KEY_LENGTH];
i2p::crypto::RandBytes(keybuff, DSA_PRIVATE_KEY_LENGTH);
CryptoPP::Integer dsax(keybuff, DSA_PRIVATE_KEY_LENGTH);
CryptoPP::DSA::PrivateKey privateKey;
CryptoPP::DSA::PublicKey publicKey;
privateKey.Initialize(dsap, dsaq, dsag, dsax);
privateKey.MakePublicKey(publicKey);
privateKey.GetPrivateExponent().Encode(
signingPrivateKey,
DSA_PRIVATE_KEY_LENGTH);
publicKey.GetPublicElement().Encode(
signingPublicKey,
DSA_PUBLIC_KEY_LENGTH);
}
DSAVerifier_Pimpl::DSAVerifier_Pimpl(const uint8_t* signingKey) {
m_PublicKey.Initialize(
dsap,
dsaq,
dsag,
CryptoPP::Integer(
signingKey,
DSA_PUBLIC_KEY_LENGTH));
}
bool DSAVerifier_Pimpl::Verify(
const uint8_t* buf,
size_t len,
const uint8_t* signature) const {
CryptoPP::DSA::Verifier verifier(m_PublicKey);
return verifier.VerifyMessage(buf, len, signature, DSA_SIGNATURE_LENGTH);
}
ECDSAP256Verifier::ECDSAP256Verifier(const uint8_t* signingKey) : m_Impl(new ECDSAP256Verifier_Pimpl(signingKey)) {}
ECDSAP256Verifier::~ECDSAP256Verifier() { delete m_Impl; }
bool ECDSAP256Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
ECDSAP256Signer::ECDSAP256Signer(const uint8_t* signingPrivateKey) : m_Impl(new ECDSAP256Signer_Pimpl(signingPrivateKey)) {}
ECDSAP256Signer::~ECDSAP256Signer() { delete m_Impl; }
void ECDSAP256Signer::Sign(const uint8_t* buf, size_t len, uint8_t * signature) const {
m_Impl->Sign(buf, len, signature);
}
ECDSAP384Verifier::ECDSAP384Verifier(const uint8_t* signingKey) : m_Impl(new ECDSAP384Verifier_Pimpl(signingKey)) {}
ECDSAP384Verifier::~ECDSAP384Verifier() { delete m_Impl; }
bool ECDSAP384Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
ECDSAP384Signer::ECDSAP384Signer(const uint8_t* signingPrivateKey) : m_Impl(new ECDSAP384Signer_Pimpl(signingPrivateKey)) {}
ECDSAP384Signer::~ECDSAP384Signer() { delete m_Impl; }
void ECDSAP384Signer::Sign(const uint8_t* buf, size_t len, uint8_t * signature) const {
m_Impl->Sign(buf, len, signature);
}
ECDSAP521Verifier::ECDSAP521Verifier(const uint8_t* signingKey) : m_Impl(new ECDSAP521Verifier_Pimpl(signingKey)) {}
ECDSAP521Verifier::~ECDSAP521Verifier() { delete m_Impl; }
bool ECDSAP521Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
ECDSAP521Signer::ECDSAP521Signer(const uint8_t* signingPrivateKey) : m_Impl(new ECDSAP521Signer_Pimpl(signingPrivateKey)) {}
ECDSAP521Signer::~ECDSAP521Signer() { delete m_Impl; }
void ECDSAP521Signer::Sign(const uint8_t* buf, size_t len, uint8_t * signature) const {
m_Impl->Sign(buf, len, signature);
}
void CreateECDSAP256RandomKeys(uint8_t* signingPrivateKey, uint8_t* signingPublicKey) {
CreateECDSARandomKeys<CryptoPP::SHA256>(
CryptoPP::ASN1::secp256r1(),
ECDSAP256_KEY_LENGTH,
signingPrivateKey,
signingPublicKey);
}
void CreateECDSAP384RandomKeys(uint8_t* signingPrivateKey, uint8_t* signingPublicKey) {
CreateECDSARandomKeys<CryptoPP::SHA384>(
CryptoPP::ASN1::secp384r1(),
ECDSAP384_KEY_LENGTH,
signingPrivateKey,
signingPublicKey);
}
void CreateECDSAP521RandomKeys(uint8_t* signingPrivateKey, uint8_t* signingPublicKey) {
CreateECDSARandomKeys<CryptoPP::SHA512>(
CryptoPP::ASN1::secp256r1(),
ECDSAP521_KEY_LENGTH,
signingPrivateKey,
signingPublicKey);
}
void CreateRSARandomKeys(size_t publicKeyLen,
uint8_t* signingPrivateKey,
uint8_t* signingPublicKey) {
CryptoPP::RSA::PrivateKey privateKey;
PRNG & rnd = GetPRNG();
privateKey.Initialize(rnd,
publicKeyLen * 8,
rsae);
privateKey.GetModulus().Encode(signingPrivateKey,
publicKeyLen);
privateKey.GetPrivateExponent().Encode(
signingPrivateKey + publicKeyLen,
publicKeyLen);
privateKey.GetModulus().Encode(
signingPublicKey,
publicKeyLen);
}
RSASHA2562048Signer::RSASHA2562048Signer(const uint8_t* privateKey) : m_Impl(new RSASHA2562048Signer_Pimpl(privateKey)) {}
RSASHA2562048Signer::~RSASHA2562048Signer() { delete m_Impl; }
void RSASHA2562048Signer::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
RSASHA3843072Signer::RSASHA3843072Signer(const uint8_t* privateKey) : m_Impl(new RSASHA3843072Signer_Pimpl(privateKey)) {}
RSASHA3843072Signer::~RSASHA3843072Signer() { delete m_Impl; }
void RSASHA3843072Signer::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
RSASHA5124096Signer::RSASHA5124096Signer(const uint8_t* privateKey) : m_Impl(new RSASHA5124096Signer_Pimpl(privateKey)) {}
RSASHA5124096Signer::~RSASHA5124096Signer() { delete m_Impl; }
void RSASHA5124096Signer::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
RSASHA2562048Verifier::RSASHA2562048Verifier(const uint8_t* pubKey) : m_Impl(new RSASHA2562048Verifier_Pimpl(pubKey)) {}
RSASHA2562048Verifier::~RSASHA2562048Verifier() { delete m_Impl; }
bool RSASHA2562048Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
RSASHA3843072Verifier::RSASHA3843072Verifier(const uint8_t* pubKey) : m_Impl(new RSASHA3843072Verifier_Pimpl(pubKey)) {}
RSASHA3843072Verifier::~RSASHA3843072Verifier() { delete m_Impl; }
bool RSASHA3843072Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
RSASHA5124096Verifier::RSASHA5124096Verifier(const uint8_t* pubKey) : m_Impl(new RSASHA5124096Verifier_Pimpl(pubKey)) {}
RSASHA5124096Verifier::~RSASHA5124096Verifier() { delete m_Impl; }
bool RSASHA5124096Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
RSASHA5124096RawVerifier::RSASHA5124096RawVerifier(const uint8_t* signingKey) : m_Impl(new RSASHA5124096RawVerifier_Pimpl(signingKey)) {}
RSASHA5124096RawVerifier::~RSASHA5124096RawVerifier() { delete m_Impl; }
void RSASHA5124096RawVerifier::Update(const uint8_t* buf, size_t len) {
m_Impl->Update(buf, len);
}
bool RSASHA5124096RawVerifier::Verify(const uint8_t* signature) {
return m_Impl->Verify(signature);
}
} // namespace crypto
} // namespace i2p
<commit_msg>fix typo<commit_after>/**
* Copyright (c) 2015-2016, The Kovri I2P Router Project
*
* 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.
*/
#include "Signature.h"
#include "cryptopp_impl.h"
#include "Rand.h"
#include <memory>
#include "util/Log.h"
namespace i2p {
namespace crypto {
DSAVerifier::DSAVerifier(const uint8_t * signingKey) : m_Impl(new DSAVerifier_Pimpl(signingKey)) {}
DSAVerifier::~DSAVerifier() {
delete m_Impl;
}
bool DSAVerifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
DSASigner::DSASigner(const uint8_t* signingPrivateKey) : m_Impl(new DSASigner_Pimpl(signingPrivateKey)) {}
DSASigner::~DSASigner() { delete m_Impl; }
void DSASigner::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
DSASigner_Pimpl::DSASigner_Pimpl(const uint8_t* signingPrivateKey) {
m_PrivateKey.Initialize(
dsap,
dsaq,
dsag,
CryptoPP::Integer(
signingPrivateKey,
DSA_PRIVATE_KEY_LENGTH));
}
void DSASigner_Pimpl::Sign(
const uint8_t* buf,
size_t len,
uint8_t* signature) const {
i2p::crypto::PRNG & rnd = i2p::crypto::GetPRNG();
CryptoPP::DSA::Signer signer(m_PrivateKey);
signer.SignMessage(rnd, buf, len, signature);
}
void CreateDSARandomKeys(
uint8_t* signingPrivateKey,
uint8_t* signingPublicKey) {
uint8_t keybuff[DSA_PRIVATE_KEY_LENGTH];
i2p::crypto::RandBytes(keybuff, DSA_PRIVATE_KEY_LENGTH);
CryptoPP::Integer dsax(keybuff, DSA_PRIVATE_KEY_LENGTH);
CryptoPP::DSA::PrivateKey privateKey;
CryptoPP::DSA::PublicKey publicKey;
privateKey.Initialize(dsap, dsaq, dsag, dsax);
privateKey.MakePublicKey(publicKey);
privateKey.GetPrivateExponent().Encode(
signingPrivateKey,
DSA_PRIVATE_KEY_LENGTH);
publicKey.GetPublicElement().Encode(
signingPublicKey,
DSA_PUBLIC_KEY_LENGTH);
}
DSAVerifier_Pimpl::DSAVerifier_Pimpl(const uint8_t* signingKey) {
m_PublicKey.Initialize(
dsap,
dsaq,
dsag,
CryptoPP::Integer(
signingKey,
DSA_PUBLIC_KEY_LENGTH));
}
bool DSAVerifier_Pimpl::Verify(
const uint8_t* buf,
size_t len,
const uint8_t* signature) const {
CryptoPP::DSA::Verifier verifier(m_PublicKey);
return verifier.VerifyMessage(buf, len, signature, DSA_SIGNATURE_LENGTH);
}
ECDSAP256Verifier::ECDSAP256Verifier(const uint8_t* signingKey) : m_Impl(new ECDSAP256Verifier_Pimpl(signingKey)) {}
ECDSAP256Verifier::~ECDSAP256Verifier() { delete m_Impl; }
bool ECDSAP256Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
ECDSAP256Signer::ECDSAP256Signer(const uint8_t* signingPrivateKey) : m_Impl(new ECDSAP256Signer_Pimpl(signingPrivateKey)) {}
ECDSAP256Signer::~ECDSAP256Signer() { delete m_Impl; }
void ECDSAP256Signer::Sign(const uint8_t* buf, size_t len, uint8_t * signature) const {
m_Impl->Sign(buf, len, signature);
}
ECDSAP384Verifier::ECDSAP384Verifier(const uint8_t* signingKey) : m_Impl(new ECDSAP384Verifier_Pimpl(signingKey)) {}
ECDSAP384Verifier::~ECDSAP384Verifier() { delete m_Impl; }
bool ECDSAP384Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
ECDSAP384Signer::ECDSAP384Signer(const uint8_t* signingPrivateKey) : m_Impl(new ECDSAP384Signer_Pimpl(signingPrivateKey)) {}
ECDSAP384Signer::~ECDSAP384Signer() { delete m_Impl; }
void ECDSAP384Signer::Sign(const uint8_t* buf, size_t len, uint8_t * signature) const {
m_Impl->Sign(buf, len, signature);
}
ECDSAP521Verifier::ECDSAP521Verifier(const uint8_t* signingKey) : m_Impl(new ECDSAP521Verifier_Pimpl(signingKey)) {}
ECDSAP521Verifier::~ECDSAP521Verifier() { delete m_Impl; }
bool ECDSAP521Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
ECDSAP521Signer::ECDSAP521Signer(const uint8_t* signingPrivateKey) : m_Impl(new ECDSAP521Signer_Pimpl(signingPrivateKey)) {}
ECDSAP521Signer::~ECDSAP521Signer() { delete m_Impl; }
void ECDSAP521Signer::Sign(const uint8_t* buf, size_t len, uint8_t * signature) const {
m_Impl->Sign(buf, len, signature);
}
void CreateECDSAP256RandomKeys(uint8_t* signingPrivateKey, uint8_t* signingPublicKey) {
CreateECDSARandomKeys<CryptoPP::SHA256>(
CryptoPP::ASN1::secp256r1(),
ECDSAP256_KEY_LENGTH,
signingPrivateKey,
signingPublicKey);
}
void CreateECDSAP384RandomKeys(uint8_t* signingPrivateKey, uint8_t* signingPublicKey) {
CreateECDSARandomKeys<CryptoPP::SHA384>(
CryptoPP::ASN1::secp384r1(),
ECDSAP384_KEY_LENGTH,
signingPrivateKey,
signingPublicKey);
}
void CreateECDSAP521RandomKeys(uint8_t* signingPrivateKey, uint8_t* signingPublicKey) {
CreateECDSARandomKeys<CryptoPP::SHA512>(
CryptoPP::ASN1::secp521r1(),
ECDSAP521_KEY_LENGTH,
signingPrivateKey,
signingPublicKey);
}
void CreateRSARandomKeys(size_t publicKeyLen,
uint8_t* signingPrivateKey,
uint8_t* signingPublicKey) {
CryptoPP::RSA::PrivateKey privateKey;
PRNG & rnd = GetPRNG();
privateKey.Initialize(rnd,
publicKeyLen * 8,
rsae);
privateKey.GetModulus().Encode(signingPrivateKey,
publicKeyLen);
privateKey.GetPrivateExponent().Encode(
signingPrivateKey + publicKeyLen,
publicKeyLen);
privateKey.GetModulus().Encode(
signingPublicKey,
publicKeyLen);
}
RSASHA2562048Signer::RSASHA2562048Signer(const uint8_t* privateKey) : m_Impl(new RSASHA2562048Signer_Pimpl(privateKey)) {}
RSASHA2562048Signer::~RSASHA2562048Signer() { delete m_Impl; }
void RSASHA2562048Signer::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
RSASHA3843072Signer::RSASHA3843072Signer(const uint8_t* privateKey) : m_Impl(new RSASHA3843072Signer_Pimpl(privateKey)) {}
RSASHA3843072Signer::~RSASHA3843072Signer() { delete m_Impl; }
void RSASHA3843072Signer::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
RSASHA5124096Signer::RSASHA5124096Signer(const uint8_t* privateKey) : m_Impl(new RSASHA5124096Signer_Pimpl(privateKey)) {}
RSASHA5124096Signer::~RSASHA5124096Signer() { delete m_Impl; }
void RSASHA5124096Signer::Sign(const uint8_t* buf, size_t len, uint8_t* signature) const {
m_Impl->Sign(buf, len, signature);
}
RSASHA2562048Verifier::RSASHA2562048Verifier(const uint8_t* pubKey) : m_Impl(new RSASHA2562048Verifier_Pimpl(pubKey)) {}
RSASHA2562048Verifier::~RSASHA2562048Verifier() { delete m_Impl; }
bool RSASHA2562048Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
RSASHA3843072Verifier::RSASHA3843072Verifier(const uint8_t* pubKey) : m_Impl(new RSASHA3843072Verifier_Pimpl(pubKey)) {}
RSASHA3843072Verifier::~RSASHA3843072Verifier() { delete m_Impl; }
bool RSASHA3843072Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
RSASHA5124096Verifier::RSASHA5124096Verifier(const uint8_t* pubKey) : m_Impl(new RSASHA5124096Verifier_Pimpl(pubKey)) {}
RSASHA5124096Verifier::~RSASHA5124096Verifier() { delete m_Impl; }
bool RSASHA5124096Verifier::Verify(const uint8_t* buf, size_t len, const uint8_t* signature) const {
return m_Impl->Verify(buf, len, signature);
}
RSASHA5124096RawVerifier::RSASHA5124096RawVerifier(const uint8_t* signingKey) : m_Impl(new RSASHA5124096RawVerifier_Pimpl(signingKey)) {}
RSASHA5124096RawVerifier::~RSASHA5124096RawVerifier() { delete m_Impl; }
void RSASHA5124096RawVerifier::Update(const uint8_t* buf, size_t len) {
m_Impl->Update(buf, len);
}
bool RSASHA5124096RawVerifier::Verify(const uint8_t* signature) {
return m_Impl->Verify(signature);
}
} // namespace crypto
} // namespace i2p
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include "Stroika/Foundation/DataExchange/OptionsFile.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/ModuleGetterSetter.h"
#include "Stroika/Foundation/Execution/WaitableEvent.h"
#include "Stroika/Foundation/Time/Duration.h"
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Time;
namespace {
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
/*
* MyData_Storage_IMPL_ is a 'traits' object, defining a GET and SET method to save/restore
* MyData_.
*
* This need not worry about thread safety:
* o in the constructor because C++ guarantees this for statically constructed objects
* o and in the Get/Set methods because ModuleGetterSetter manages this locking
*
* A user COULD either choose NOT to persist the data (in which case the logic with fOptionsFile_
* would be removed/unneeded). Or could perist another way.
*
* But this example shows using OptionsFile to persist the data to a local JSON file, using
* the ObjectVariantMapper to serialize/deserialize C++ data structures.
*/
struct MyData_Storage_IMPL_ {
MyData_Storage_IMPL_ ()
: fOptionsFile_{
/*
* Any module name will do. This will map (by default) to a MyModule.json file in XXX.
* If you require a single configuration file 'Main" might be a better module name.
* But if you have multiple modules with configuration data, pick a name that matches that module,
* and they will all be stored under a folder for all your apps configuration.
*/
L"MyModule"sv,
/*
* C++ doesn't have intrinsically enough metadata to effectively serialize deserialize data, but its close.
* You have to give it class mappings, and other non-builtin types mappings, so that it can serialize.
*
* Note - this serializing logic is VERY widely useful outside of configuration - for example it can be used
* to provide WebService/REST interfaces, or for debugging/logging output.
*/
[]() -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (MyData_, fEnabled)},
{L"Last-Synchronized-At", Stroika_Foundation_DataExchange_StructFieldMetaInfo (MyData_, fLastSynchronizedAt)},
});
return mapper;
}(),
/*
* Hooks for versioning, to manage as your application evolves and the configuration data changes
*/
OptionsFile::kDefaultUpgrader,
/*
* Hook to decide the folder (and filename pattern) where the configuration data will be stored.
*
* This defaults to
* FileSystem::WellKnownLocations::GetApplicationData () + appName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + suffix
* or folder:
* L"/var/opt/Put-Your-App-Name-Here" or "C:\ProgramData\Put-Your-App-Name-Here"
* and this module configuration file would be:
* L"/var/opt/Put-Your-App-Name-Here/MyModule.json" OR
* L"C:/ProgramData/Put-Your-App-Name-Here/MyModule.json" OR
*
* \note - this function does NOT create the 'Put-Your-App-Name-Here' folder first, and will NOT persist
* files if this folder does not exist.
*
* Callers can easily repalce the default function provided in OptionsFile::mkFilenameMapper - just
* dont call that and provide your own lambda - to create the folder.
*
* But a better pattern is to create the folder in your application installer, typically.
*/
OptionsFile::mkFilenameMapper (L"Put-Your-App-Name-Here")}
, fActualCurrentConfigData_ (fOptionsFile_.Read<MyData_> (MyData_{}))
{
Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date
}
MyData_ Get () const
{
// no locking required here for thread safety.
// This is always done inside of a read or a full lock by ModuleGetterSetter
return fActualCurrentConfigData_;
}
void Set (const MyData_& v)
{
// no locking required here for thread safety.
// This is always done inside of a write lock by ModuleGetterSetter
fActualCurrentConfigData_ = v;
fOptionsFile_.Write (v);
}
private:
OptionsFile fOptionsFile_;
MyData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized
};
}
namespace {
ModuleGetterSetter<MyData_, MyData_Storage_IMPL_> sModuleConfiguration_;
WaitableEvent sWaitableEvent_; // some thread could be waiting on this, and perform some reactive task when the module settings change
void TestUse1_ ()
{
// This will be by far the most common use pattern - just read some field of the configuraiton object
if (sModuleConfiguration_.Get ().fEnabled) {
// do something
}
}
void TestUse2_ ()
{
// or read several fields all guaranteed within this same snapshot (not holding a lock duing the action)
auto d = sModuleConfiguration_.Get ();
// lock not held here so configuration could change but this code remains safe and crash free
if (d.fEnabled and d.fLastSynchronizedAt) {
// do something
}
}
void TestUse3_ ()
{
if (sModuleConfiguration_.Get ().fEnabled) {
// a non-atomic update of the entire MyData_ object
auto n = sModuleConfiguration_.Get ();
n.fEnabled = false; // change something in 'n' here
sModuleConfiguration_.Set (n);
}
}
void TestUse4_ ()
{
// Use Update () to atomically update data
// Use the return value to tell if a real change was made (so you can invoke some sort of notication/action)
static const Duration kMinTime_ = 2min;
if (sModuleConfiguration_.Update ([](const MyData_& data) -> optional<MyData_> { if (data.fLastSynchronizedAt && *data.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { MyData_ result = data; result.fLastSynchronizedAt = DateTime::Now (); return result; } return {}; })) {
sWaitableEvent_.Set (); // e.g. trigger someone to wakeup and used changes? - no global lock held here...
}
}
}
int main (int argc, const char* argv[])
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())};
TestUse1_ ();
TestUse2_ ();
TestUse3_ ();
TestUse4_ ();
return EXIT_SUCCESS;
}
<commit_msg>cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include "Stroika/Foundation/DataExchange/OptionsFile.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/ModuleGetterSetter.h"
#include "Stroika/Foundation/Execution/WaitableEvent.h"
#include "Stroika/Foundation/Time/Duration.h"
using namespace std;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Time;
namespace {
struct MyData_ {
bool fEnabled = false;
optional<DateTime> fLastSynchronizedAt;
};
/*
* MyData_Storage_IMPL_ is a 'traits' object, defining a GET and SET method to save/restore
* MyData_.
*
* This need not worry about thread safety:
* o in the constructor because C++ guarantees this for statically constructed objects
* o and in the Get/Set methods because ModuleGetterSetter manages this locking
*
* A user COULD either choose NOT to persist the data (in which case the logic with fOptionsFile_
* would be removed/unneeded). Or could perist another way.
*
* But this example shows using OptionsFile to persist the data to a local JSON file, using
* the ObjectVariantMapper to serialize/deserialize C++ data structures.
*/
struct MyData_Storage_IMPL_ {
MyData_Storage_IMPL_ ()
: fOptionsFile_{
/*
* Any module name will do. This will map (by default) to a MyModule.json file in XXX.
* If you require a single configuration file 'Main" might be a better module name.
* But if you have multiple modules with configuration data, pick a name that matches that module,
* and they will all be stored under a folder for all your apps configuration.
*/
L"MyModule"sv,
/*
* C++ doesn't have intrinsically enough metadata to effectively serialize deserialize data, but its close.
* You have to give it class mappings, and other non-builtin types mappings, so that it can serialize.
*
* Note - this serializing logic is VERY widely useful outside of configuration - for example it can be used
* to provide WebService/REST interfaces, or for debugging/logging output.
*/
[]() -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddClass<MyData_> (initializer_list<ObjectVariantMapper::StructFieldInfo>{
{L"Enabled", Stroika_Foundation_DataExchange_StructFieldMetaInfo (MyData_, fEnabled)},
{L"Last-Synchronized-At", Stroika_Foundation_DataExchange_StructFieldMetaInfo (MyData_, fLastSynchronizedAt)},
});
return mapper;
}(),
/*
* Hooks for versioning, to manage as your application evolves and the configuration data changes
*/
OptionsFile::kDefaultUpgrader,
/*
* Hook to decide the folder (and filename pattern) where the configuration data will be stored.
*
* This defaults to
* FileSystem::WellKnownLocations::GetApplicationData () + appName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + suffix
* or folder:
* L"/var/opt/Put-Your-App-Name-Here" or "C:\ProgramData\Put-Your-App-Name-Here"
* and this module configuration file would be:
* L"/var/opt/Put-Your-App-Name-Here/MyModule.json" OR
* L"C:/ProgramData/Put-Your-App-Name-Here/MyModule.json" OR
*
* \note - this function does NOT create the 'Put-Your-App-Name-Here' folder first, and will NOT persist
* files if this folder does not exist.
*
* Callers can easily repalce the default function provided in OptionsFile::mkFilenameMapper - just
* dont call that and provide your own lambda - to create the folder.
*
* But a better pattern is to create the folder in your application installer, typically.
*/
OptionsFile::mkFilenameMapper (L"Put-Your-App-Name-Here")}
, fActualCurrentConfigData_ (fOptionsFile_.Read<MyData_> (MyData_{}))
{
Set (fActualCurrentConfigData_); // assure derived data (and changed fields etc) up to date
}
MyData_ Get () const
{
// no locking required here for thread safety.
// This is always done inside of a read or a full lock by ModuleGetterSetter
return fActualCurrentConfigData_;
}
void Set (const MyData_& v)
{
// no locking required here for thread safety.
// This is always done inside of a write lock by ModuleGetterSetter
fActualCurrentConfigData_ = v;
fOptionsFile_.Write (v);
}
private:
OptionsFile fOptionsFile_;
MyData_ fActualCurrentConfigData_; // automatically initialized just in time, and externally synchronized
};
}
namespace {
ModuleGetterSetter<MyData_, MyData_Storage_IMPL_> sModuleConfiguration_;
WaitableEvent sWaitableEvent_; // some thread could be waiting on this, and perform some reactive task when the module settings change
void TestUse1_ ()
{
// This will be by far the most common use pattern - just read some field of the configuraiton object
if (sModuleConfiguration_.Get ().fEnabled) {
// do something
}
}
void TestUse2_ ()
{
// or read several fields all guaranteed within this same snapshot (not holding a lock duing the action)
auto d = sModuleConfiguration_.Get ();
// lock not held here so configuration could change but this code remains safe and crash free
if (d.fEnabled and d.fLastSynchronizedAt) {
// do something
}
}
void TestUse3_ ()
{
if (sModuleConfiguration_.Get ().fEnabled) {
// a non-atomic update of the entire MyData_ object
auto n = sModuleConfiguration_.Get ();
n.fEnabled = false; // change something in 'n' here
sModuleConfiguration_.Set (n);
}
}
void TestUse4_ ()
{
// Use Update () to atomically update data
// Use the return value to tell if a real change was made (so you can invoke some sort of notication/action)
static const Duration kMinTime_ = 2min;
if (sModuleConfiguration_.Update ([](const MyData_& data) -> optional<MyData_> { if (data.fLastSynchronizedAt && *data.fLastSynchronizedAt + kMinTime_ > DateTime::Now ()) { MyData_ result = data; result.fLastSynchronizedAt = DateTime::Now (); return result; } return {}; })) {
sWaitableEvent_.Set (); // e.g. trigger someone to wakeup and used changes? - no global lock held here...
}
}
}
int main (int argc, const char* argv[])
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())};
TestUse1_ ();
TestUse2_ ();
TestUse3_ ();
TestUse4_ ();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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.
// This file looks like a unit test, but it contains benchmarks and test
// utilities intended for manual evaluation of the scalers in
// gl_helper*. These tests produce output in the form of files and printouts,
// but cannot really "fail". There is no point in making these tests part
// of any test automation run.
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2extchromium.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/strings/stringprintf.h"
#include "base/time.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/gl_helper_scaling.h"
#include "content/public/test/unittest_test_suite.h"
#include "content/test/content_test_suite.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkTypes.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gl/gl_surface.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#if defined(TOOLKIT_GTK)
#include "ui/gfx/gtk_util.h"
#endif
namespace content {
using WebKit::WebGLId;
using WebKit::WebGraphicsContext3D;
content::GLHelper::ScalerQuality kQualities[] = {
content::GLHelper::SCALER_QUALITY_BEST,
content::GLHelper::SCALER_QUALITY_GOOD,
content::GLHelper::SCALER_QUALITY_FAST,
};
const char *kQualityNames[] = {
"best",
"good",
"fast",
};
class GLHelperTest : public testing::Test {
protected:
virtual void SetUp() {
WebGraphicsContext3D::Attributes attributes;
context_.reset(
webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl::
CreateOffscreenContext(attributes));
context_->makeContextCurrent();
helper_.reset(new content::GLHelper(context_.get()));
helper_scaling_.reset(new content::GLHelperScaling(
context_.get(),
helper_.get()));
}
virtual void TearDown() {
helper_scaling_.reset(NULL);
helper_.reset(NULL);
context_.reset(NULL);
}
void LoadPngFileToSkBitmap(const base::FilePath& filename,
SkBitmap* bitmap) {
std::string compressed;
file_util::ReadFileToString(base::MakeAbsoluteFilePath(filename),
&compressed);
ASSERT_TRUE(compressed.size());
ASSERT_TRUE(gfx::PNGCodec::Decode(
reinterpret_cast<const unsigned char*>(compressed.data()),
compressed.size(), bitmap));
}
// Save the image to a png file. Used to create the initial test files.
void SaveToFile(SkBitmap* bitmap, const base::FilePath& filename) {
std::vector<unsigned char> compressed;
ASSERT_TRUE(gfx::PNGCodec::Encode(
static_cast<unsigned char*>(bitmap->getPixels()),
gfx::PNGCodec::FORMAT_BGRA,
gfx::Size(bitmap->width(), bitmap->height()),
static_cast<int>(bitmap->rowBytes()),
true,
std::vector<gfx::PNGCodec::Comment>(),
&compressed));
ASSERT_TRUE(compressed.size());
FILE* f = file_util::OpenFile(filename, "wb");
ASSERT_TRUE(f);
ASSERT_EQ(fwrite(&*compressed.begin(), 1, compressed.size(), f),
compressed.size());
file_util::CloseFile(f);
}
scoped_ptr<WebKit::WebGraphicsContext3D> context_;
scoped_ptr<content::GLHelper> helper_;
scoped_ptr<content::GLHelperScaling> helper_scaling_;
std::deque<GLHelperScaling::ScaleOp> x_ops_, y_ops_;
};
TEST_F(GLHelperTest, ScaleBenchmark) {
int output_sizes[] = { 1920, 1080,
1249, 720, // Output size on pixel
256, 144 };
int input_sizes[] = { 3200, 2040,
2560, 1476, // Pixel tab size
1920, 1080,
1280, 720,
800, 480,
256, 144 };
for (size_t q = 0; q < arraysize(kQualities); q++) {
for (size_t outsize = 0;
outsize < arraysize(output_sizes);
outsize += 2) {
for (size_t insize = 0;
insize < arraysize(input_sizes);
insize += 2) {
WebGLId src_texture = context_->createTexture();
WebGLId dst_texture = context_->createTexture();
WebGLId framebuffer = context_->createFramebuffer();
const gfx::Size src_size(input_sizes[insize],
input_sizes[insize + 1]);
const gfx::Size dst_size(output_sizes[outsize],
output_sizes[outsize + 1]);
SkBitmap input;
input.setConfig(SkBitmap::kARGB_8888_Config,
src_size.width(),
src_size.height());
input.allocPixels();
SkAutoLockPixels lock(input);
SkBitmap output_pixels;
input.setConfig(SkBitmap::kARGB_8888_Config,
dst_size.width(),
dst_size.height());
output_pixels.allocPixels();
SkAutoLockPixels output_lock(output_pixels);
context_->bindFramebuffer(GL_FRAMEBUFFER, framebuffer);
context_->bindTexture(GL_TEXTURE_2D, dst_texture);
context_->texImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
dst_size.width(),
dst_size.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
0);
context_->bindTexture(GL_TEXTURE_2D, src_texture);
context_->texImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
src_size.width(),
src_size.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
input.getPixels());
gfx::Rect src_subrect(0, 0,
src_size.width(), src_size.height());
scoped_ptr<content::GLHelper::ScalerInterface> scaler(
helper_->CreateScaler(kQualities[q],
src_size,
src_subrect,
dst_size,
false,
false));
// Scale once beforehand before we start measuring.
scaler->Scale(src_texture, dst_texture);
context_->finish();
base::TimeTicks start_time = base::TimeTicks::Now();
int iterations = 0;
base::TimeTicks end_time;
while (true) {
for (int i = 0; i < 50; i++) {
iterations++;
scaler->Scale(src_texture, dst_texture);
context_->flush();
}
context_->finish();
if (iterations > 2000) {
break;
}
end_time = base::TimeTicks::Now();
if ((end_time - start_time).InMillisecondsF() > 1000) {
break;
}
}
context_->deleteTexture(dst_texture);
context_->deleteTexture(src_texture);
context_->deleteFramebuffer(framebuffer);
std::string name;
name = base::StringPrintf("scale_%dx%d_to_%dx%d_%s",
src_size.width(),
src_size.height(),
dst_size.width(),
dst_size.height(),
kQualityNames[q]);
float ms = (end_time - start_time).InMillisecondsF() / iterations;
printf("*RESULT gpu_scale_time: %s=%.2f ms\n", name.c_str(), ms);
}
}
}
}
// This is more of a test utility than a test.
// Put an PNG image called "testimage.png" in your
// current directory, then run this test. It will
// create testoutput_Q_P.png, where Q is the scaling
// mode and P is the scaling percentage taken from
// the table below.
TEST_F(GLHelperTest, DISABLED_ScaleTestImage) {
int percents[] = {
230,
180,
150,
110,
90,
70,
50,
49,
40,
20,
10,
};
SkBitmap input;
LoadPngFileToSkBitmap(base::FilePath(
FILE_PATH_LITERAL("testimage.png")), &input);
WebGLId framebuffer = context_->createFramebuffer();
WebGLId src_texture = context_->createTexture();
const gfx::Size src_size(input.width(), input.height());
context_->bindFramebuffer(GL_FRAMEBUFFER, framebuffer);
context_->bindTexture(GL_TEXTURE_2D, src_texture);
context_->texImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
src_size.width(),
src_size.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
input.getPixels());
for (size_t q = 0; q < arraysize(kQualities); q++) {
for (size_t p = 0; p < arraysize(percents); p++) {
const gfx::Size dst_size(input.width() * percents[p] / 100,
input.height() * percents[p] / 100);
WebGLId dst_texture = helper_->CopyAndScaleTexture(
src_texture,
src_size,
dst_size,
false,
kQualities[q]);
SkBitmap output_pixels;
input.setConfig(SkBitmap::kARGB_8888_Config,
dst_size.width(),
dst_size.height());
output_pixels.allocPixels();
SkAutoLockPixels lock(output_pixels);
helper_->ReadbackTextureSync(
dst_texture,
gfx::Rect(0, 0,
dst_size.width(),
dst_size.height()),
static_cast<unsigned char *>(output_pixels.getPixels()));
context_->deleteTexture(dst_texture);
std::string filename = base::StringPrintf("testoutput_%s_%d.ppm",
kQualityNames[q],
percents[p]);
LOG(INFO) << "Writing " << filename;
SaveToFile(&output_pixels, base::FilePath::FromUTF8Unsafe(filename));
}
}
context_->deleteTexture(src_texture);
context_->deleteFramebuffer(framebuffer);
}
} // namespace
// These tests needs to run against a proper GL environment, so we
// need to set it up before we can run the tests.
int main(int argc, char** argv) {
CommandLine::Init(argc, argv);
base::TestSuite* suite = new content::ContentTestSuite(argc, argv);
#if defined(OS_MACOSX)
base::mac::ScopedNSAutoreleasePool pool;
#endif
#if defined(TOOLKIT_GTK)
gfx::GtkInitFromCommandLine(*CommandLine::ForCurrentProcess());
#endif
gfx::GLSurface::InitializeOneOff();
return content::UnitTestTestSuite(suite).Run();
}
<commit_msg>gl_helper_benchmark: fix measurement bug.<commit_after>// Copyright (c) 2012 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.
// This file looks like a unit test, but it contains benchmarks and test
// utilities intended for manual evaluation of the scalers in
// gl_helper*. These tests produce output in the form of files and printouts,
// but cannot really "fail". There is no point in making these tests part
// of any test automation run.
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2extchromium.h>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/strings/stringprintf.h"
#include "base/time.h"
#include "content/common/gpu/client/gl_helper.h"
#include "content/common/gpu/client/gl_helper_scaling.h"
#include "content/public/test/unittest_test_suite.h"
#include "content/test/content_test_suite.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkTypes.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gl/gl_surface.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#if defined(TOOLKIT_GTK)
#include "ui/gfx/gtk_util.h"
#endif
namespace content {
using WebKit::WebGLId;
using WebKit::WebGraphicsContext3D;
content::GLHelper::ScalerQuality kQualities[] = {
content::GLHelper::SCALER_QUALITY_BEST,
content::GLHelper::SCALER_QUALITY_GOOD,
content::GLHelper::SCALER_QUALITY_FAST,
};
const char *kQualityNames[] = {
"best",
"good",
"fast",
};
class GLHelperTest : public testing::Test {
protected:
virtual void SetUp() {
WebGraphicsContext3D::Attributes attributes;
context_.reset(
webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl::
CreateOffscreenContext(attributes));
context_->makeContextCurrent();
helper_.reset(new content::GLHelper(context_.get()));
helper_scaling_.reset(new content::GLHelperScaling(
context_.get(),
helper_.get()));
}
virtual void TearDown() {
helper_scaling_.reset(NULL);
helper_.reset(NULL);
context_.reset(NULL);
}
void LoadPngFileToSkBitmap(const base::FilePath& filename,
SkBitmap* bitmap) {
std::string compressed;
file_util::ReadFileToString(base::MakeAbsoluteFilePath(filename),
&compressed);
ASSERT_TRUE(compressed.size());
ASSERT_TRUE(gfx::PNGCodec::Decode(
reinterpret_cast<const unsigned char*>(compressed.data()),
compressed.size(), bitmap));
}
// Save the image to a png file. Used to create the initial test files.
void SaveToFile(SkBitmap* bitmap, const base::FilePath& filename) {
std::vector<unsigned char> compressed;
ASSERT_TRUE(gfx::PNGCodec::Encode(
static_cast<unsigned char*>(bitmap->getPixels()),
gfx::PNGCodec::FORMAT_BGRA,
gfx::Size(bitmap->width(), bitmap->height()),
static_cast<int>(bitmap->rowBytes()),
true,
std::vector<gfx::PNGCodec::Comment>(),
&compressed));
ASSERT_TRUE(compressed.size());
FILE* f = file_util::OpenFile(filename, "wb");
ASSERT_TRUE(f);
ASSERT_EQ(fwrite(&*compressed.begin(), 1, compressed.size(), f),
compressed.size());
file_util::CloseFile(f);
}
scoped_ptr<WebKit::WebGraphicsContext3D> context_;
scoped_ptr<content::GLHelper> helper_;
scoped_ptr<content::GLHelperScaling> helper_scaling_;
std::deque<GLHelperScaling::ScaleOp> x_ops_, y_ops_;
};
TEST_F(GLHelperTest, ScaleBenchmark) {
int output_sizes[] = { 1920, 1080,
1249, 720, // Output size on pixel
256, 144 };
int input_sizes[] = { 3200, 2040,
2560, 1476, // Pixel tab size
1920, 1080,
1280, 720,
800, 480,
256, 144 };
for (size_t q = 0; q < arraysize(kQualities); q++) {
for (size_t outsize = 0;
outsize < arraysize(output_sizes);
outsize += 2) {
for (size_t insize = 0;
insize < arraysize(input_sizes);
insize += 2) {
WebGLId src_texture = context_->createTexture();
WebGLId dst_texture = context_->createTexture();
WebGLId framebuffer = context_->createFramebuffer();
const gfx::Size src_size(input_sizes[insize],
input_sizes[insize + 1]);
const gfx::Size dst_size(output_sizes[outsize],
output_sizes[outsize + 1]);
SkBitmap input;
input.setConfig(SkBitmap::kARGB_8888_Config,
src_size.width(),
src_size.height());
input.allocPixels();
SkAutoLockPixels lock(input);
SkBitmap output_pixels;
input.setConfig(SkBitmap::kARGB_8888_Config,
dst_size.width(),
dst_size.height());
output_pixels.allocPixels();
SkAutoLockPixels output_lock(output_pixels);
context_->bindFramebuffer(GL_FRAMEBUFFER, framebuffer);
context_->bindTexture(GL_TEXTURE_2D, dst_texture);
context_->texImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
dst_size.width(),
dst_size.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
0);
context_->bindTexture(GL_TEXTURE_2D, src_texture);
context_->texImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
src_size.width(),
src_size.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
input.getPixels());
gfx::Rect src_subrect(0, 0,
src_size.width(), src_size.height());
scoped_ptr<content::GLHelper::ScalerInterface> scaler(
helper_->CreateScaler(kQualities[q],
src_size,
src_subrect,
dst_size,
false,
false));
// Scale once beforehand before we start measuring.
scaler->Scale(src_texture, dst_texture);
context_->finish();
base::TimeTicks start_time = base::TimeTicks::Now();
int iterations = 0;
base::TimeTicks end_time;
while (true) {
for (int i = 0; i < 50; i++) {
iterations++;
scaler->Scale(src_texture, dst_texture);
context_->flush();
}
context_->finish();
end_time = base::TimeTicks::Now();
if (iterations > 2000) {
break;
}
if ((end_time - start_time).InMillisecondsF() > 1000) {
break;
}
}
context_->deleteTexture(dst_texture);
context_->deleteTexture(src_texture);
context_->deleteFramebuffer(framebuffer);
std::string name;
name = base::StringPrintf("scale_%dx%d_to_%dx%d_%s",
src_size.width(),
src_size.height(),
dst_size.width(),
dst_size.height(),
kQualityNames[q]);
float ms = (end_time - start_time).InMillisecondsF() / iterations;
printf("*RESULT gpu_scale_time: %s=%.2f ms\n", name.c_str(), ms);
}
}
}
}
// This is more of a test utility than a test.
// Put an PNG image called "testimage.png" in your
// current directory, then run this test. It will
// create testoutput_Q_P.png, where Q is the scaling
// mode and P is the scaling percentage taken from
// the table below.
TEST_F(GLHelperTest, DISABLED_ScaleTestImage) {
int percents[] = {
230,
180,
150,
110,
90,
70,
50,
49,
40,
20,
10,
};
SkBitmap input;
LoadPngFileToSkBitmap(base::FilePath(
FILE_PATH_LITERAL("testimage.png")), &input);
WebGLId framebuffer = context_->createFramebuffer();
WebGLId src_texture = context_->createTexture();
const gfx::Size src_size(input.width(), input.height());
context_->bindFramebuffer(GL_FRAMEBUFFER, framebuffer);
context_->bindTexture(GL_TEXTURE_2D, src_texture);
context_->texImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
src_size.width(),
src_size.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
input.getPixels());
for (size_t q = 0; q < arraysize(kQualities); q++) {
for (size_t p = 0; p < arraysize(percents); p++) {
const gfx::Size dst_size(input.width() * percents[p] / 100,
input.height() * percents[p] / 100);
WebGLId dst_texture = helper_->CopyAndScaleTexture(
src_texture,
src_size,
dst_size,
false,
kQualities[q]);
SkBitmap output_pixels;
input.setConfig(SkBitmap::kARGB_8888_Config,
dst_size.width(),
dst_size.height());
output_pixels.allocPixels();
SkAutoLockPixels lock(output_pixels);
helper_->ReadbackTextureSync(
dst_texture,
gfx::Rect(0, 0,
dst_size.width(),
dst_size.height()),
static_cast<unsigned char *>(output_pixels.getPixels()));
context_->deleteTexture(dst_texture);
std::string filename = base::StringPrintf("testoutput_%s_%d.ppm",
kQualityNames[q],
percents[p]);
LOG(INFO) << "Writing " << filename;
SaveToFile(&output_pixels, base::FilePath::FromUTF8Unsafe(filename));
}
}
context_->deleteTexture(src_texture);
context_->deleteFramebuffer(framebuffer);
}
} // namespace
// These tests needs to run against a proper GL environment, so we
// need to set it up before we can run the tests.
int main(int argc, char** argv) {
CommandLine::Init(argc, argv);
base::TestSuite* suite = new content::ContentTestSuite(argc, argv);
#if defined(OS_MACOSX)
base::mac::ScopedNSAutoreleasePool pool;
#endif
#if defined(TOOLKIT_GTK)
gfx::GtkInitFromCommandLine(*CommandLine::ForCurrentProcess());
#endif
gfx::GLSurface::InitializeOneOff();
return content::UnitTestTestSuite(suite).Run();
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2019 musikcube team
//
// 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 author nor the names of other 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 OWNER 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 "pch.hpp"
#include "Playback.h"
#include <core/library/query/local/PersistedPlayQueueQuery.h>
#include <core/sdk/constants.h>
#include <core/support/PreferenceKeys.h>
#include <cmath>
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::db::local;
using namespace musik::core::sdk;
namespace keys = musik::core::prefs::keys;
using Prefs = std::shared_ptr<Preferences>;
namespace musik {
namespace core {
namespace playback {
void PauseOrResume(ITransport& transport) {
int state = transport.GetPlaybackState();
if (state == PlaybackPaused || state == PlaybackPrepared) {
transport.Resume();
}
else if (state == PlaybackPlaying) {
transport.Pause();
}
}
void VolumeUp(ITransport& transport) {
double delta = round(transport.Volume() * 100.0) >= 10.0 ? 0.05 : 0.01;
transport.SetVolume(transport.Volume() + delta);
}
void VolumeDown(ITransport& transport) {
double delta = round(transport.Volume() * 100.0) > 10.0 ? 0.05 : 0.01;
transport.SetVolume(transport.Volume() - delta);
}
void SeekForward(IPlaybackService& playback) {
playback.SetPosition(playback.GetPosition() + 10.0f);
}
void SeekBack(IPlaybackService& playback) {
playback.SetPosition(playback.GetPosition() - 10.0f);
}
void SeekForwardProportional(IPlaybackService& playback) {
double moveBy = 0.05f * playback.GetDuration();
playback.SetPosition(playback.GetPosition() + moveBy);
}
void SeekBackProportional(IPlaybackService& playback) {
double moveBy = 0.05f * playback.GetDuration();
playback.SetPosition(playback.GetPosition() - moveBy);
}
void LoadPlaybackContext(Prefs prefs, ILibraryPtr library, PlaybackService& playback) {
if (prefs->GetBool(keys::SaveSessionOnExit, true)) {
auto query = std::shared_ptr<PersistedPlayQueueQuery>(
PersistedPlayQueueQuery::Restore(library, playback));
library->Enqueue(query, ILibrary::QuerySynchronous);
int index = prefs->GetInt(keys::LastPlayQueueIndex, -1);
if (index >= 0) {
double time = prefs->GetDouble(keys::LastPlayQueueTime, 0.0f);
playback.Prepare(index, time);
}
}
}
void SavePlaybackContext(Prefs prefs, ILibraryPtr library, PlaybackService& playback) {
if (prefs->GetBool(keys::SaveSessionOnExit, true)) {
if (playback.GetPlaybackState() != sdk::PlaybackStopped) {
prefs->SetInt(keys::LastPlayQueueIndex, (int)playback.GetIndex());
prefs->SetDouble(keys::LastPlayQueueTime, playback.GetPosition());
}
else {
prefs->SetInt(keys::LastPlayQueueIndex, -1);
prefs->SetDouble(keys::LastPlayQueueTime, 0.0f);
}
auto query = std::shared_ptr<PersistedPlayQueueQuery>(
PersistedPlayQueueQuery::Save(library, playback));
library->Enqueue(query, ILibrary::QuerySynchronous);
}
}
}
}
}
<commit_msg>Don't cache playback position for streams of indeterminate length.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2019 musikcube team
//
// 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 author nor the names of other 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 OWNER 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 "pch.hpp"
#include "Playback.h"
#include <core/library/query/local/PersistedPlayQueueQuery.h>
#include <core/sdk/constants.h>
#include <core/support/PreferenceKeys.h>
#include <cmath>
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::db::local;
using namespace musik::core::sdk;
namespace keys = musik::core::prefs::keys;
using Prefs = std::shared_ptr<Preferences>;
namespace musik {
namespace core {
namespace playback {
void PauseOrResume(ITransport& transport) {
int state = transport.GetPlaybackState();
if (state == PlaybackPaused || state == PlaybackPrepared) {
transport.Resume();
}
else if (state == PlaybackPlaying) {
transport.Pause();
}
}
void VolumeUp(ITransport& transport) {
double delta = round(transport.Volume() * 100.0) >= 10.0 ? 0.05 : 0.01;
transport.SetVolume(transport.Volume() + delta);
}
void VolumeDown(ITransport& transport) {
double delta = round(transport.Volume() * 100.0) > 10.0 ? 0.05 : 0.01;
transport.SetVolume(transport.Volume() - delta);
}
void SeekForward(IPlaybackService& playback) {
playback.SetPosition(playback.GetPosition() + 10.0f);
}
void SeekBack(IPlaybackService& playback) {
playback.SetPosition(playback.GetPosition() - 10.0f);
}
void SeekForwardProportional(IPlaybackService& playback) {
double moveBy = 0.05f * playback.GetDuration();
playback.SetPosition(playback.GetPosition() + moveBy);
}
void SeekBackProportional(IPlaybackService& playback) {
double moveBy = 0.05f * playback.GetDuration();
playback.SetPosition(playback.GetPosition() - moveBy);
}
void LoadPlaybackContext(Prefs prefs, ILibraryPtr library, PlaybackService& playback) {
if (prefs->GetBool(keys::SaveSessionOnExit, true)) {
auto query = std::shared_ptr<PersistedPlayQueueQuery>(
PersistedPlayQueueQuery::Restore(library, playback));
library->Enqueue(query, ILibrary::QuerySynchronous);
int index = prefs->GetInt(keys::LastPlayQueueIndex, -1);
if (index >= 0) {
double time = prefs->GetDouble(keys::LastPlayQueueTime, 0.0f);
playback.Prepare(index, time);
}
}
}
void SavePlaybackContext(Prefs prefs, ILibraryPtr library, PlaybackService& playback) {
if (prefs->GetBool(keys::SaveSessionOnExit, true)) {
if (playback.GetPlaybackState() != sdk::PlaybackStopped) {
prefs->SetInt(keys::LastPlayQueueIndex, (int)playback.GetIndex());
/* streams with a negative duration are of indeterminate length,
and may be infinite, so don't cache the playback position */
double offset = playback.GetDuration() > 0.0 ? playback.GetPosition() : 0.0;
prefs->SetDouble(keys::LastPlayQueueTime, offset);
}
else {
prefs->SetInt(keys::LastPlayQueueIndex, -1);
prefs->SetDouble(keys::LastPlayQueueTime, 0.0f);
}
auto query = std::shared_ptr<PersistedPlayQueueQuery>(
PersistedPlayQueueQuery::Save(library, playback));
library->Enqueue(query, ILibrary::QuerySynchronous);
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Utils/CardSetUtils.hpp>
#include <hspp/Actions/Generic.hpp>
#include <hspp/Cards/Cards.hpp>
using namespace Hearthstonepp;
using namespace PlayerTasks;
using namespace SimpleTasks;
TEST(CoreCardsGen, EX1_066)
{
GameAgent agent(CardClass::WARRIOR, CardClass::ROGUE, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
const auto card1 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
const auto card2 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), true);
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2));
EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), false);
}
TEST(CoreCardsGen, EX1_306)
{
GameAgent agent(CardClass::WARLOCK, CardClass::WARRIOR,
PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
const auto card1 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Succubus"));
Generic::DrawCard(currentPlayer,
Cards::GetInstance().FindCardByName("Stonetusk Boar"));
const auto card2 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Generic::DrawCard(opponentPlayer,
Cards::GetInstance().FindCardByName("Fiery War Axe"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
EXPECT_EQ(currentPlayer.GetHand().size(), 0u);
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2));
EXPECT_EQ(opponentPlayer.GetHand().size(), 1u);
}
TEST(CoreCardsGen, CS2_041)
{
GameAgent agent(CardClass::SHAMAN, CardClass::ROGUE, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
const auto card1 = Generic::DrawCard(
currentPlayer,
Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card2 = Generic::DrawCard(
currentPlayer,
Cards::GetInstance().FindCardByName("Ancestral Healing"));
const auto card3 = Generic::DrawCard(
opponentPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card3));
GameAgent::RunTask(opponentPlayer, CombatTask(taskAgent, card3, card1));
EXPECT_EQ(currentPlayer.GetField()[0]->health, 1);
EXPECT_EQ(opponentPlayer.GetField().size(), 0u);
GameAgent::RunTask(currentPlayer,
PlayCardTask(taskAgent, card2, -1, card1));
EXPECT_EQ(currentPlayer.GetField()[0]->health, 2);
EXPECT_EQ(currentPlayer.GetField()[0]->GetGameTag(GameTag::TAUNT), 1);
}
TEST(CoreCardsGen, CS2_088)
{
GameAgent agent(CardClass::DRUID, CardClass::PALADIN, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
opponentPlayer.GetHero()->health = 24;
const auto card1 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Guardian of Kings"));
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card1));
EXPECT_EQ(opponentPlayer.GetHero()->maxHealth,
opponentPlayer.GetHero()->health);
}<commit_msg>test: Add unit test for 'CS1_112' card<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Utils/CardSetUtils.hpp>
#include <hspp/Actions/Generic.hpp>
#include <hspp/Cards/Cards.hpp>
using namespace Hearthstonepp;
using namespace PlayerTasks;
using namespace SimpleTasks;
TEST(CoreCardsGen, EX1_066)
{
GameAgent agent(CardClass::WARRIOR, CardClass::ROGUE, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
const auto card1 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
const auto card2 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), true);
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2));
EXPECT_EQ(currentPlayer.GetHero()->HasWeapon(), false);
}
TEST(CoreCardsGen, EX1_306)
{
GameAgent agent(CardClass::WARLOCK, CardClass::WARRIOR,
PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
const auto card1 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Succubus"));
Generic::DrawCard(currentPlayer,
Cards::GetInstance().FindCardByName("Stonetusk Boar"));
const auto card2 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Generic::DrawCard(opponentPlayer,
Cards::GetInstance().FindCardByName("Fiery War Axe"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
EXPECT_EQ(currentPlayer.GetHand().size(), 0u);
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card2));
EXPECT_EQ(opponentPlayer.GetHand().size(), 1u);
}
TEST(CoreCardsGen, CS2_041)
{
GameAgent agent(CardClass::SHAMAN, CardClass::ROGUE, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
const auto card1 = Generic::DrawCard(
currentPlayer,
Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card2 = Generic::DrawCard(
currentPlayer,
Cards::GetInstance().FindCardByName("Ancestral Healing"));
const auto card3 = Generic::DrawCard(
opponentPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card3));
GameAgent::RunTask(opponentPlayer, CombatTask(taskAgent, card3, card1));
EXPECT_EQ(currentPlayer.GetField()[0]->health, 1);
EXPECT_EQ(opponentPlayer.GetField().size(), 0u);
GameAgent::RunTask(currentPlayer,
PlayCardTask(taskAgent, card2, -1, card1));
EXPECT_EQ(currentPlayer.GetField()[0]->health, 2);
EXPECT_EQ(currentPlayer.GetField()[0]->GetGameTag(GameTag::TAUNT), 1);
}
TEST(CoreCardsGen, CS2_088)
{
GameAgent agent(CardClass::DRUID, CardClass::PALADIN, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
opponentPlayer.GetHero()->health = 24;
const auto card1 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Guardian of Kings"));
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card1));
EXPECT_EQ(opponentPlayer.GetHero()->maxHealth,
opponentPlayer.GetHero()->health);
}
TEST(CoreCardsGen, CS1_112)
{
GameAgent agent(CardClass::PRIEST, CardClass::PALADIN, PlayerType::PLAYER1);
TaskAgent& taskAgent = agent.GetTaskAgent();
Player& currentPlayer = agent.GetCurrentPlayer();
Player& opponentPlayer = agent.GetCurrentPlayer().GetOpponent();
currentPlayer.SetMaximumMana(10);
currentPlayer.SetAvailableMana(10);
opponentPlayer.SetMaximumMana(10);
opponentPlayer.SetAvailableMana(10);
currentPlayer.GetHero()->health = 26;
const auto card1 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
currentPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
const auto card4 = Generic::DrawCard(
opponentPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
const auto card5 = Generic::DrawCard(
opponentPlayer,
Cards::GetInstance().FindCardByName("Worgen Infiltrator"));
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card1));
currentPlayer.SetAvailableMana(10);
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card2));
currentPlayer.SetAvailableMana(10);
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card4));
GameAgent::RunTask(opponentPlayer, PlayCardTask(taskAgent, card5));
GameAgent::RunTask(currentPlayer, InitAttackCountTask());
GameAgent::RunTask(currentPlayer, CombatTask(taskAgent, card1, card4));
EXPECT_EQ(currentPlayer.GetField()[0]->health, 4);
EXPECT_EQ(opponentPlayer.GetField()[0]->GetGameTag(GameTag::DIVINE_SHIELD),
0);
GameAgent::RunTask(currentPlayer, PlayCardTask(taskAgent, card3));
EXPECT_EQ(currentPlayer.GetHero()->health, 28);
EXPECT_EQ(opponentPlayer.GetHero()->health, 28);
EXPECT_EQ(currentPlayer.GetField()[0]->health, 5);
EXPECT_EQ(currentPlayer.GetField()[1]->health, 7);
EXPECT_EQ(opponentPlayer.GetField().size(), 0u);
}<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Utils/CardSetUtils.hpp>
#include <hspp/Actions/Draw.hpp>
#include <hspp/Cards/Cards.hpp>
using namespace Hearthstonepp;
using namespace PlayerTasks;
using namespace SimpleTasks;
TEST(CoreCardsGen, EX1_066)
{
GameConfig config;
config.player1Class = CardClass::WARRIOR;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Task::Run(curPlayer, PlayCardTask(card1));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), true);
Task::Run(opPlayer, PlayCardTask(card2));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), false);
}
TEST(CoreCardsGen, EX1_306)
{
GameConfig config;
config.player1Class = CardClass::WARLOCK;
config.player2Class = CardClass::WARRIOR;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Succubus"));
Generic::DrawCard(curPlayer,
Cards::GetInstance().FindCardByName("Stonetusk Boar"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Generic::DrawCard(opPlayer,
Cards::GetInstance().FindCardByName("Fiery War Axe"));
Task::Run(curPlayer, PlayCardTask(card1));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 0u);
Task::Run(opPlayer, PlayCardTask(card2));
EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 1u);
}
TEST(CoreCardsGen, CS2_041)
{
GameConfig config;
config.player1Class = CardClass::SHAMAN;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing"));
const auto card3 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));
Task::Run(curPlayer, PlayCardTask(card1));
Task::Run(opPlayer, PlayCardTask(card3));
Task::Run(opPlayer, CombatTask(card3, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 1);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
Task::Run(curPlayer, PlayCardTask(card2, -1, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 2);
EXPECT_EQ(curField.GetMinion(0)->GetGameTag(GameTag::TAUNT), 1);
}
TEST(CoreCardsGen, CS2_088)
{
GameConfig config;
config.player1Class = CardClass::DRUID;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 24;
const auto card1 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings"));
Task::Run(opPlayer, PlayCardTask(card1));
EXPECT_EQ(opPlayer.GetHero()->maxHealth, opPlayer.GetHero()->health);
}
TEST(CoreCardsGen, CS1_112)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
curPlayer.GetHero()->health = 26;
auto& curField = curPlayer.GetField();
auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
const auto card5 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator"));
Task::Run(curPlayer, PlayCardTask(card1));
curPlayer.currentMana = 10;
Task::Run(curPlayer, PlayCardTask(card2));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask(card4));
Task::Run(opPlayer, PlayCardTask(card5));
Task::Run(curPlayer, InitAttackCountTask());
Task::Run(curPlayer, CombatTask(card1, card4));
EXPECT_EQ(curField.GetMinion(0)->health, 4);
EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::DIVINE_SHIELD), 0);
Task::Run(curPlayer, PlayCardTask(card3));
EXPECT_EQ(curPlayer.GetHero()->health, 28);
EXPECT_EQ(opPlayer.GetHero()->health, 28);
EXPECT_EQ(curField.GetMinion(0)->health, 5);
EXPECT_EQ(curField.GetMinion(1)->health, 7);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
}
TEST(CoreCardsGen, CS1_113)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
Task::Run(curPlayer, PlayCardTask(card1));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask(card2));
EXPECT_EQ(curField.GetNumOfMinions(), 1u);
EXPECT_EQ(opField.GetNumOfMinions(), 1u);
Task::Run(curPlayer, PlayCardTask(card3, -1, card2));
EXPECT_EQ(curField.GetNumOfMinions(), 2u);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
opPlayer.currentMana = 10;
auto result =
Task::Run(opPlayer, PlayCardTask(card4, -1, curPlayer.GetHero()));
EXPECT_EQ(result, TaskStatus::PLAY_CARD_INVALID_TARGET);
}<commit_msg>[ci skip] feat(game-state): Call StartGame() method to start game<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Utils/CardSetUtils.hpp>
#include <hspp/Actions/Draw.hpp>
#include <hspp/Cards/Cards.hpp>
using namespace Hearthstonepp;
using namespace PlayerTasks;
using namespace SimpleTasks;
TEST(CoreCardsGen, EX1_066)
{
GameConfig config;
config.player1Class = CardClass::WARRIOR;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Fiery War Axe"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Task::Run(curPlayer, PlayCardTask(card1));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), true);
Task::Run(opPlayer, PlayCardTask(card2));
EXPECT_EQ(curPlayer.GetHero()->HasWeapon(), false);
}
TEST(CoreCardsGen, EX1_306)
{
GameConfig config;
config.player1Class = CardClass::WARLOCK;
config.player2Class = CardClass::WARRIOR;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Succubus"));
Generic::DrawCard(curPlayer,
Cards::GetInstance().FindCardByName("Stonetusk Boar"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
Generic::DrawCard(opPlayer,
Cards::GetInstance().FindCardByName("Fiery War Axe"));
Task::Run(curPlayer, PlayCardTask(card1));
EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 0u);
Task::Run(opPlayer, PlayCardTask(card2));
EXPECT_EQ(opPlayer.GetHand().GetNumOfCards(), 1u);
}
TEST(CoreCardsGen, CS2_041)
{
GameConfig config;
config.player1Class = CardClass::SHAMAN;
config.player2Class = CardClass::ROGUE;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Ancestral Healing"));
const auto card3 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Stonetusk Boar"));
Task::Run(curPlayer, PlayCardTask(card1));
Task::Run(opPlayer, PlayCardTask(card3));
Task::Run(opPlayer, CombatTask(card3, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 1);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
Task::Run(curPlayer, PlayCardTask(card2, -1, card1));
EXPECT_EQ(curField.GetMinion(0)->health, 2);
EXPECT_EQ(curField.GetMinion(0)->GetGameTag(GameTag::TAUNT), 1);
}
TEST(CoreCardsGen, CS2_088)
{
GameConfig config;
config.player1Class = CardClass::DRUID;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
opPlayer.GetHero()->health = 24;
const auto card1 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Guardian of Kings"));
Task::Run(opPlayer, PlayCardTask(card1));
EXPECT_EQ(opPlayer.GetHero()->maxHealth, opPlayer.GetHero()->health);
}
TEST(CoreCardsGen, CS1_112)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
curPlayer.GetHero()->health = 26;
auto& curField = curPlayer.GetField();
auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Holy Nova"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Argent Squire"));
const auto card5 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Worgen Infiltrator"));
Task::Run(curPlayer, PlayCardTask(card1));
curPlayer.currentMana = 10;
Task::Run(curPlayer, PlayCardTask(card2));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask(card4));
Task::Run(opPlayer, PlayCardTask(card5));
Task::Run(curPlayer, InitAttackCountTask());
Task::Run(curPlayer, CombatTask(card1, card4));
EXPECT_EQ(curField.GetMinion(0)->health, 4);
EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::DIVINE_SHIELD), 0);
Task::Run(curPlayer, PlayCardTask(card3));
EXPECT_EQ(curPlayer.GetHero()->health, 28);
EXPECT_EQ(opPlayer.GetHero()->health, 28);
EXPECT_EQ(curField.GetMinion(0)->health, 5);
EXPECT_EQ(curField.GetMinion(1)->health, 7);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
}
TEST(CoreCardsGen, CS1_113)
{
GameConfig config;
config.player1Class = CardClass::PRIEST;
config.player2Class = CardClass::PALADIN;
config.startPlayer = PlayerType::PLAYER1;
Game game(config);
game.StartGame();
Player& curPlayer = game.GetCurrentPlayer();
Player& opPlayer = game.GetCurrentPlayer().GetOpponent();
curPlayer.maximumMana = 10;
curPlayer.currentMana = 10;
opPlayer.maximumMana = 10;
opPlayer.currentMana = 10;
const auto& curField = curPlayer.GetField();
const auto& opField = opPlayer.GetField();
const auto card1 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Windfury Harpy"));
const auto card2 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
const auto card3 = Generic::DrawCard(
curPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
const auto card4 = Generic::DrawCard(
opPlayer, Cards::GetInstance().FindCardByName("Mind Control"));
Task::Run(curPlayer, PlayCardTask(card1));
curPlayer.currentMana = 10;
Task::Run(opPlayer, PlayCardTask(card2));
EXPECT_EQ(curField.GetNumOfMinions(), 1u);
EXPECT_EQ(opField.GetNumOfMinions(), 1u);
Task::Run(curPlayer, PlayCardTask(card3, -1, card2));
EXPECT_EQ(curField.GetNumOfMinions(), 2u);
EXPECT_EQ(opField.GetNumOfMinions(), 0u);
opPlayer.currentMana = 10;
auto result =
Task::Run(opPlayer, PlayCardTask(card4, -1, curPlayer.GetHero()));
EXPECT_EQ(result, TaskStatus::PLAY_CARD_INVALID_TARGET);
}<|endoftext|> |
<commit_before>/* ecpp.cpp
* Copyright (C) 2003-2005 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <tnt/ecpp.h>
#include <tnt/urlmapper.h>
#include <tnt/comploader.h>
#include <tnt/httperror.h>
#include <tnt/httprequest.h>
#include <cxxtools/log.h>
log_define("tntnet.ecpp")
namespace tnt
{
//////////////////////////////////////////////////////////////////////
// Subcompident
//
inline std::ostream& operator<< (std::ostream& out, const Subcompident& comp)
{ return out << comp.toString(); }
Subcompident::Subcompident(const std::string& ident)
: tnt::Compident(ident)
{
std::string::size_type pos = compname.find('.');
if (pos != std::string::npos)
{
subname = compname.substr(pos + 1);
compname = compname.substr(0, pos);
}
}
std::string Subcompident::toString() const
{
std::string ret = tnt::Compident::toString();
if (!subname.empty())
{
ret += '.';
ret += subname;
}
return ret;
}
//////////////////////////////////////////////////////////////////////
// EcppComponent
//
cxxtools::RWLock equivMonitor;
EcppComponent::EcppComponent(const Compident& ci, const Urlmapper& um,
Comploader& cl)
: myident(ci),
rootmapper(um),
loader(cl)
{ }
EcppComponent::~EcppComponent()
{ }
void EcppComponent::registerSubComp(const std::string& name, EcppSubComponent* comp)
{
log_debug(getCompident() << ": registerSubComp " << name);
subcomps_type::const_iterator it = getSubcomps().find(name);
if (it != getSubcomps().end())
log_error("duplicate subcomp " << name);
else
getSubcomps().insert(subcomps_type::value_type(name, comp));
}
Component& EcppComponent::fetchComp(const std::string& url) const
{
log_debug("fetchComp(\"" << url << "\")");
Subcompident ci(url);
if (ci.libname.empty())
ci.libname = myident.libname;
if (ci.compname.empty())
ci.compname = myident.compname;
Component* comp;
// fetch component by name
comp = &loader.fetchComp(ci, rootmapper);
// if there is a subcomponent, fetch it
if (!ci.subname.empty())
{
try
{
EcppComponent& e = dynamic_cast<EcppComponent&>(*comp);
comp = &e.fetchSubComp(ci.subname);
}
catch (const NotFoundException&)
{
throw;
}
catch (const std::exception&)
{
throw NotFoundException(ci.toString());
}
}
return *comp;
}
Component& EcppComponent::fetchComp(const Compident& ci) const
{
if (ci.libname.empty())
{
Compident cii(ci);
cii.libname = myident.libname;
return loader.fetchComp(cii, rootmapper);
}
else
return loader.fetchComp(ci, rootmapper);
}
Component* EcppComponent::createComp(const Compident& ci) const
{
log_debug("createComp(" << ci << ")");
if (ci.libname.empty())
{
Compident cii(ci);
cii.libname = myident.libname;
return loader.createComp(cii, rootmapper);
}
else
return loader.createComp(ci, rootmapper);
}
EcppSubComponent& EcppComponent::fetchSubComp(const std::string& sub) const
{
log_debug(getCompident() << ": fetchSubComp(\"" << sub << "\")");
subcomps_type::const_iterator it = getSubcomps().find(sub);
if (it == getSubcomps().end())
throw NotFoundException(Subcompident(getCompident(), sub).toString());
return *it->second;
}
const char* EcppComponent::getData(const HttpRequest& request, const char* def) const
{
std::string lang = request.getLang();
if (!lang.empty())
{
const char* data = loader.getLangData(myident, lang);
if (data)
return data;
}
return def;
}
///////////////////////////////////////////////////////////////////////
// ecppSubComponent
//
void EcppSubComponent::drop()
{ }
}
<commit_msg>remove unused mutex instance<commit_after>/* ecpp.cpp
* Copyright (C) 2003-2005 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <tnt/ecpp.h>
#include <tnt/urlmapper.h>
#include <tnt/comploader.h>
#include <tnt/httperror.h>
#include <tnt/httprequest.h>
#include <cxxtools/log.h>
log_define("tntnet.ecpp")
namespace tnt
{
//////////////////////////////////////////////////////////////////////
// Subcompident
//
inline std::ostream& operator<< (std::ostream& out, const Subcompident& comp)
{ return out << comp.toString(); }
Subcompident::Subcompident(const std::string& ident)
: tnt::Compident(ident)
{
std::string::size_type pos = compname.find('.');
if (pos != std::string::npos)
{
subname = compname.substr(pos + 1);
compname = compname.substr(0, pos);
}
}
std::string Subcompident::toString() const
{
std::string ret = tnt::Compident::toString();
if (!subname.empty())
{
ret += '.';
ret += subname;
}
return ret;
}
//////////////////////////////////////////////////////////////////////
// EcppComponent
//
EcppComponent::EcppComponent(const Compident& ci, const Urlmapper& um,
Comploader& cl)
: myident(ci),
rootmapper(um),
loader(cl)
{ }
EcppComponent::~EcppComponent()
{ }
void EcppComponent::registerSubComp(const std::string& name, EcppSubComponent* comp)
{
log_debug(getCompident() << ": registerSubComp " << name);
subcomps_type::const_iterator it = getSubcomps().find(name);
if (it != getSubcomps().end())
log_error("duplicate subcomp " << name);
else
getSubcomps().insert(subcomps_type::value_type(name, comp));
}
Component& EcppComponent::fetchComp(const std::string& url) const
{
log_debug("fetchComp(\"" << url << "\")");
Subcompident ci(url);
if (ci.libname.empty())
ci.libname = myident.libname;
if (ci.compname.empty())
ci.compname = myident.compname;
Component* comp;
// fetch component by name
comp = &loader.fetchComp(ci, rootmapper);
// if there is a subcomponent, fetch it
if (!ci.subname.empty())
{
try
{
EcppComponent& e = dynamic_cast<EcppComponent&>(*comp);
comp = &e.fetchSubComp(ci.subname);
}
catch (const NotFoundException&)
{
throw;
}
catch (const std::exception&)
{
throw NotFoundException(ci.toString());
}
}
return *comp;
}
Component& EcppComponent::fetchComp(const Compident& ci) const
{
if (ci.libname.empty())
{
Compident cii(ci);
cii.libname = myident.libname;
return loader.fetchComp(cii, rootmapper);
}
else
return loader.fetchComp(ci, rootmapper);
}
Component* EcppComponent::createComp(const Compident& ci) const
{
log_debug("createComp(" << ci << ")");
if (ci.libname.empty())
{
Compident cii(ci);
cii.libname = myident.libname;
return loader.createComp(cii, rootmapper);
}
else
return loader.createComp(ci, rootmapper);
}
EcppSubComponent& EcppComponent::fetchSubComp(const std::string& sub) const
{
log_debug(getCompident() << ": fetchSubComp(\"" << sub << "\")");
subcomps_type::const_iterator it = getSubcomps().find(sub);
if (it == getSubcomps().end())
throw NotFoundException(Subcompident(getCompident(), sub).toString());
return *it->second;
}
const char* EcppComponent::getData(const HttpRequest& request, const char* def) const
{
std::string lang = request.getLang();
if (!lang.empty())
{
const char* data = loader.getLangData(myident, lang);
if (data)
return data;
}
return def;
}
///////////////////////////////////////////////////////////////////////
// ecppSubComponent
//
void EcppSubComponent::drop()
{ }
}
<|endoftext|> |
<commit_before>#include "tensor.h"
#include "text/table.h"
#include "text/cmdline.h"
#include "math/random.hpp"
#include "tensor/numeric.hpp"
#include "cortex/measure.hpp"
#include "text/table_row_mark.h"
#include <iostream>
namespace
{
using namespace nano;
nano::random_t<scalar_t> rng(scalar_t(-1e-3), scalar_t(+1e-3));
const std::size_t trials = 16;
tensor_size_t measure_dot(const tensor_size_t dims)
{
vector_t x(dims);
vector_t y(dims);
tensor::set_random(rng, x, y);
scalar_t z = 0;
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x.dot(y);
}, trials);
NANO_UNUSED1(z);
return nano::mflops(2 * dims, duration);
}
tensor_size_t measure_sumv1(const tensor_size_t dims)
{
vector_t x(dims);
vector_t z(dims);
tensor::set_random(rng, x);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x * scalar_t(0.5);
}, trials);
NANO_UNUSED1(z);
return nano::mflops(2 * dims, duration);
}
tensor_size_t measure_sumv2(const tensor_size_t dims)
{
vector_t x(dims);
vector_t y(dims);
vector_t z(dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x * scalar_t(0.5) + y * scalar_t(0.3);
}, trials);
NANO_UNUSED1(z);
return nano::mflops(4 * dims, duration);
}
tensor_size_t measure_mulv(const tensor_size_t dims)
{
matrix_t x(dims, dims);
vector_t y(dims);
vector_t z(dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x * y;
}, trials);
NANO_UNUSED1(z);
return nano::mflops(dims * dims + dims, duration);
}
tensor_size_t measure_mulm(const tensor_size_t dims)
{
matrix_t x(dims, dims);
matrix_t y(dims, dims);
matrix_t z(dims, dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x * y;
}, trials);
NANO_UNUSED1(z);
return nano::mflops(dims * dims * dims + dims * dims, duration);
}
tensor_size_t measure_outv(const tensor_size_t dims)
{
vector_t x(dims);
vector_t y(dims);
matrix_t z(dims, dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x * y.transpose();
}, trials);
NANO_UNUSED1(z);
return nano::mflops(2 * dims * dims, duration);
}
}
int main(int, const char* [])
{
using namespace nano;
const auto min_dims = tensor_size_t(8);
const auto max_dims = tensor_size_t(1024);
const auto foreach_dims = [&] (const auto& op)
{
for (tensor_size_t dims = min_dims; dims <= max_dims; dims *= 2)
{
op(dims);
}
};
const auto fillrow = [&] (auto&& row, const auto& op)
{
foreach_dims([&] (const auto dims) { row << op(dims); });
};
table_t table("operation\\dimensions [MFLOPS]");
foreach_dims([&] (const auto dims) { table.header() << to_string(dims); });
fillrow(table.append("z += x.dot(y)"), measure_dot);
fillrow(table.append("z += x * 0.5"), measure_sumv1);
fillrow(table.append("z += x * 0.5 + y * 0.3"), measure_sumv2);
fillrow(table.append("z += X * y"), measure_mulv);
fillrow(table.append("Z += X * Y"), measure_mulm);
fillrow(table.append("Z += x * y^t"), measure_outv);
table.mark(nano::make_table_mark_maximum_percentage_cols<size_t>(10));
table.print(std::cout);
return EXIT_SUCCESS;
}
<commit_msg>more efficient linear operations<commit_after>#include "tensor.h"
#include "text/table.h"
#include "text/cmdline.h"
#include "math/random.hpp"
#include "tensor/numeric.hpp"
#include "cortex/measure.hpp"
#include "text/table_row_mark.h"
#include <iostream>
namespace
{
using namespace nano;
nano::random_t<scalar_t> rng(scalar_t(-1e-3), scalar_t(+1e-3));
const std::size_t trials = 16;
tensor_size_t measure_dot(const tensor_size_t dims)
{
vector_t x(dims);
vector_t y(dims);
tensor::set_random(rng, x, y);
scalar_t z = 0;
const auto duration = nano::measure_robustly_nsec([&] ()
{
z += x.dot(y);
}, trials);
NANO_UNUSED1(z);
return nano::mflops(2 * dims, duration);
}
tensor_size_t measure_sumv1(const tensor_size_t dims)
{
vector_t x(dims);
vector_t z(dims);
tensor::set_random(rng, x);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z.noalias() += x * scalar_t(0.5);
}, trials);
NANO_UNUSED1(z);
return nano::mflops(2 * dims, duration);
}
tensor_size_t measure_sumv2(const tensor_size_t dims)
{
vector_t x(dims);
vector_t y(dims);
vector_t z(dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z.noalias() += x * scalar_t(0.5) + y * scalar_t(0.3);
}, trials);
NANO_UNUSED1(z);
return nano::mflops(4 * dims, duration);
}
tensor_size_t measure_mulv(const tensor_size_t dims)
{
matrix_t x(dims, dims);
vector_t y(dims);
vector_t z(dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z.noalias() += x * y;
}, trials);
NANO_UNUSED1(z);
return nano::mflops(dims * dims + dims, duration);
}
tensor_size_t measure_mulm(const tensor_size_t dims)
{
matrix_t x(dims, dims);
matrix_t y(dims, dims);
matrix_t z(dims, dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z.noalias() += x * y;
}, trials);
NANO_UNUSED1(z);
return nano::mflops(dims * dims * dims + dims * dims, duration);
}
tensor_size_t measure_outv(const tensor_size_t dims)
{
vector_t x(dims);
vector_t y(dims);
matrix_t z(dims, dims);
tensor::set_random(rng, x, y);
z.setZero();
const auto duration = nano::measure_robustly_nsec([&] ()
{
z.noalias() += x * y.transpose();
}, trials);
NANO_UNUSED1(z);
return nano::mflops(2 * dims * dims, duration);
}
}
int main(int, const char* [])
{
using namespace nano;
const auto min_dims = tensor_size_t(8);
const auto max_dims = tensor_size_t(1024);
const auto foreach_dims = [&] (const auto& op)
{
for (tensor_size_t dims = min_dims; dims <= max_dims; dims *= 2)
{
op(dims);
}
};
const auto fillrow = [&] (auto&& row, const auto& op)
{
foreach_dims([&] (const auto dims) { row << op(dims); });
};
table_t table("operation\\dimensions [MFLOPS]");
foreach_dims([&] (const auto dims) { table.header() << to_string(dims); });
fillrow(table.append("z += x.dot(y)"), measure_dot);
fillrow(table.append("z += x * 0.5"), measure_sumv1);
fillrow(table.append("z += x * 0.5 + y * 0.3"), measure_sumv2);
fillrow(table.append("z += X * y"), measure_mulv);
fillrow(table.append("Z += X * Y"), measure_mulm);
fillrow(table.append("Z += x * y^t"), measure_outv);
table.mark(nano::make_table_mark_maximum_percentage_cols<size_t>(10));
table.print(std::cout);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------
// @author Toby D. Young
//
// Copyright 2014 nil 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.
//
// THIS SOFTWARE IS PROVIDED BY THE NAMEPSACE EWALENA AUTHORS ``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
// NAMESPACE EWALENA AUTHORS 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.
//
// The views and conclusions contained in the software and
// documentation are those of the authors and should not be
// interpreted as representing official policies, either expressed or
// implied, of the namespace ewalena authors.
// -------------------------------------------------------------------
// deal.II headers
#include <deal.II/base/logstream.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/tensor.h>
// Library-based headers.
#include "group_symmetry.h"
#include "piezoelectric_tensor.h"
// Application-base headers.
#include "command_line.h"
#include <fstream>
#include <iostream>
template <int dim, typename ValueType = double>
class Step0
{
public:
// First, are the usual class constructors and destructors.
Step0 ();
~Step0 ();
void run ();
// Coefficients are held in a parameter file, so it will be
// necessary to read in a file from the command line.
nil::CommandLine command_line;
private:
// First is a list of functions that belong to this class (they are
// explained later on).
void setup_problem ();
void get_parameters ();
// Following that we have a list of the tensors that will be used in
// this calculation. They are, first- and second-order piezoelectric
// tensors, a first-order strain tensor, and a tensor of first-order
// displacement
nil::PiezoelectricTensor<1, ValueType> first_order_piezoelectric_tensor;
nil::PiezoelectricTensor<2, ValueType> second_order_piezoelectric_tensor;
dealii::Tensor<1, dim> first_order_displacement;
dealii::Tensor<1, dim> first_order_strain;
// Additionally, lists of coefficients are needed for those tensors
// that are tensors of empirical moduli.
std::vector<ValueType> first_order_piezoelectric_coefficients;
std::vector<ValueType> second_order_piezoelectric_coefficients;
// Then we need an object to hold various run-time parameters that
// are specified in an "prm file".
dealii::ParameterHandler parameters;
};
// The constructor is typically borning...
template <int dim, typename ValueType>
Step0<dim, ValueType>::Step0 ()
{}
// as is the destructor.
template <int dim, typename ValueType>
Step0<dim, ValueType>::~Step0 ()
{}
template <int dim, typename ValueType>
void
Step0<dim, ValueType>::setup_problem ()
{
// Initialise the first- and second-order piezoelectric tensors...
first_order_piezoelectric_tensor.reinit (nil::GroupSymmetry::Wurtzite);
second_order_piezoelectric_tensor.reinit (nil::GroupSymmetry::Wurtzite);
// and then the strain tensor.
first_order_strain.reinit ();
}
// The next step is to obtain a complete list of the coefficients
// needed for this calculation. First comes a declaration of the
// entries expected to be find in the parameter file and then they are
// read into the object parameters.
template <int dim, typename ValueType>
void
Step0<dim, ValueType>::get_parameters ()
{
// First declare the parameters that are expected to be found.
parameters.declare_entry ("First-order piezoelectric constants",
"-0.230",
dealii::Patterns::List (dealii::Patterns::Double (), 1),
"A list of the first-order piezoelectric constants. "
"Default is zinc-blende GaAs. "
"See: PRL 96, 187602 (2006). ");
parameters.declare_entry ("Second-order piezoelectric constants",
"-0.439, -3.765, -0.492",
dealii::Patterns::List (dealii::Patterns::Double (), 1),
"A list of the second-order piezoelectric constants. "
"Default is zinc-blende GaAs. "
"See: PRL 96, 187602 (2006). ");
parameters.read_input (command_line.get_prm_file ());
first_order_piezoelectric_coefficients =
dealii::Utilities::string_to_double
(dealii::Utilities::split_string_list (parameters.get ("First-order piezoelectric constants")));
second_order_piezoelectric_coefficients =
dealii::Utilities::string_to_double
(dealii::Utilities::split_string_list (parameters.get ("Second-order piezoelectric constants")));
}
template <int dim, typename ValueType>
void
Step0<dim, ValueType>::run ()
{
// First find the parameters need for this calculation
get_parameters ();
// First up, fill the piezoelectric tensors with coefficent
// values. Starting with first-order coefficients...
// first_order_piezoelectric_tensor
// .distribute_coefficients (first_order_piezoelectric_coefficients);
distribute_first_order_coefficients (first_order_piezoelectric_tensor,
first_order_piezoelectric_coefficients);
// and then second-order coefficients.
distribute_second_order_coefficients (second_order_piezoelectric_tensor,
second_order_piezoelectric_coefficients);
// Having done that now we want to start applying an incremental
// strain pattern. This is done
}
int main (int argc, char **argv)
{
try
{
// Set deal.II's logger depth.
dealii::deallog.depth_console (0);
// Initialise the problem.
Step0<3, double> problem;
// Parse the command line and input file.
problem.command_line.parse_command_line (argc, argv);
// Run the problem.
problem.run ();
}
// ...and if this should fail, try to gather as much information as
// possible. Specifically, if the exception that was thrown is an
// object of a class that is derived from the C++ standard class
// <code>exception</code>.
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
// If the exception that was thrown somewhere was not an object of a
// class derived from the standard <code>exception</code> class,
// then nothing cane be done at all - simply print an error message
// and exit.
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
// At this point, the application performed as was expected - return
// without error.
return 0;
}
<commit_msg>We decided to use Green's strain in step-0, so we call the object green_strain.<commit_after>// -------------------------------------------------------------------
// @author Toby D. Young
//
// Copyright 2014 nil 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.
//
// THIS SOFTWARE IS PROVIDED BY THE NAMEPSACE EWALENA AUTHORS ``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
// NAMESPACE EWALENA AUTHORS 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.
//
// The views and conclusions contained in the software and
// documentation are those of the authors and should not be
// interpreted as representing official policies, either expressed or
// implied, of the namespace ewalena authors.
// -------------------------------------------------------------------
// deal.II headers
#include <deal.II/base/logstream.h>
#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/tensor.h>
// Library-based headers.
#include "group_symmetry.h"
#include "piezoelectric_tensor.h"
// Application-base headers.
#include "command_line.h"
#include <fstream>
#include <iostream>
template <int dim, typename ValueType = double>
class Step0
{
public:
// First, are the usual class constructors and destructors.
Step0 ();
~Step0 ();
void run ();
// Coefficients are held in a parameter file, so it will be
// necessary to read in a file from the command line.
nil::CommandLine command_line;
private:
// First is a list of functions that belong to this class (they are
// explained later on).
void setup_problem ();
void get_parameters ();
// Following that we have a list of the tensors that will be used in
// this calculation. They are, first- and second-order piezoelectric
// tensors, and a Green strain tensor.
nil::PiezoelectricTensor<1, ValueType> first_order_piezoelectric_tensor;
nil::PiezoelectricTensor<2, ValueType> second_order_piezoelectric_tensor;
dealii::Tensor<1, dim> green_strain;
// Additionally, lists of coefficients are needed for those tensors
// that are tensors of empirical moduli.
std::vector<ValueType> first_order_piezoelectric_coefficients;
std::vector<ValueType> second_order_piezoelectric_coefficients;
// Then we need an object to hold various run-time parameters that
// are specified in an "prm file".
dealii::ParameterHandler parameters;
};
// The constructor is typically borning...
template <int dim, typename ValueType>
Step0<dim, ValueType>::Step0 ()
{}
// as is the destructor.
template <int dim, typename ValueType>
Step0<dim, ValueType>::~Step0 ()
{}
// The first step is to initialise all of the objects we are goinf to
// use. This is done in a single function.
template <int dim, typename ValueType>
void
Step0<dim, ValueType>::setup_problem ()
{
// Initialise the first- and second-order piezoelectric tensors...
first_order_piezoelectric_tensor.reinit (nil::GroupSymmetry::Wurtzite);
second_order_piezoelectric_tensor.reinit (nil::GroupSymmetry::Wurtzite);
// and then the strain tensor.
green_strain.reinit ();
}
// The next step is to obtain a complete list of the coefficients
// needed for this calculation. First comes a declaration of the
// entries expected to be find in the parameter file and then they are
// read into the object parameters.
template <int dim, typename ValueType>
void
Step0<dim, ValueType>::get_parameters ()
{
// First declare the parameters that are expected to be found.
parameters.declare_entry ("First-order piezoelectric constants",
"-0.230",
dealii::Patterns::List (dealii::Patterns::Double (), 1),
"A list of the first-order piezoelectric constants. "
"Default is zinc-blende GaAs. "
"See: PRL 96, 187602 (2006). ");
parameters.declare_entry ("Second-order piezoelectric constants",
"-0.439, -3.765, -0.492",
dealii::Patterns::List (dealii::Patterns::Double (), 1),
"A list of the second-order piezoelectric constants. "
"Default is zinc-blende GaAs. "
"See: PRL 96, 187602 (2006). ");
parameters.read_input (command_line.get_prm_file ());
first_order_piezoelectric_coefficients =
dealii::Utilities::string_to_double
(dealii::Utilities::split_string_list (parameters.get ("First-order piezoelectric constants")));
second_order_piezoelectric_coefficients =
dealii::Utilities::string_to_double
(dealii::Utilities::split_string_list (parameters.get ("Second-order piezoelectric constants")));
}
template <int dim, typename ValueType>
void
Step0<dim, ValueType>::run ()
{
// First find the parameters need for this calculation
get_parameters ();
// First up, fill the piezoelectric tensors with coefficent
// values. Starting with first-order coefficients...
// first_order_piezoelectric_tensor
// .distribute_coefficients (first_order_piezoelectric_coefficients);
distribute_first_order_coefficients (first_order_piezoelectric_tensor,
first_order_piezoelectric_coefficients);
// and then second-order coefficients.
distribute_second_order_coefficients (second_order_piezoelectric_tensor,
second_order_piezoelectric_coefficients);
// Having done that now we want to start applying an incremental
// strain pattern. This is done
}
int main (int argc, char **argv)
{
try
{
// Set deal.II's logger depth.
dealii::deallog.depth_console (0);
// Initialise the problem.
Step0<3, double> problem;
// Parse the command line and input file.
problem.command_line.parse_command_line (argc, argv);
// Run the problem.
problem.run ();
}
// ...and if this should fail, try to gather as much information as
// possible. Specifically, if the exception that was thrown is an
// object of a class that is derived from the C++ standard class
// <code>exception</code>.
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
// If the exception that was thrown somewhere was not an object of a
// class derived from the standard <code>exception</code> class,
// then nothing cane be done at all - simply print an error message
// and exit.
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
// At this point, the application performed as was expected - return
// without error.
return 0;
}
<|endoftext|> |
<commit_before>// Source file for the mesh to grid conversion program
// Include files
namespace gaps {}
using namespace gaps;
#include "R3Shapes/R3Shapes.h"
// Program variables
static char *mesh_name = NULL;
static char *grid_name = NULL;
static int min_resolution = 16;
static int max_resolution = 512;
static double grid_spacing = 0.1;
static int sdf = 0;
static int print_verbose = 0;
static R3Mesh *
ReadMesh(char *mesh_name)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Allocate mesh
R3Mesh *mesh = new R3Mesh();
assert(mesh);
// Read mesh from file
if (!mesh->ReadFile(mesh_name)) {
delete mesh;
return NULL;
}
// Print statistics
if (print_verbose) {
printf("Read mesh ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Faces = %d\n", mesh->NFaces());
printf(" # Edges = %d\n", mesh->NEdges());
printf(" # Vertices = %d\n", mesh->NVertices());
fflush(stdout);
}
// Return success
return mesh;
}
static RNLength
ShortestEdgeLength(R3Mesh *mesh, R3MeshFace *face)
{
// Return shortest edge on face
RNLength d0 = mesh->EdgeLength(mesh->EdgeOnFace(face, 0));
RNLength d1 = mesh->EdgeLength(mesh->EdgeOnFace(face, 1));
RNLength d2 = mesh->EdgeLength(mesh->EdgeOnFace(face, 2));
RNLength d = FLT_MAX;
if (d0 < d) d = d0;
if (d1 < d) d = d1;
if (d2 < d) d = d2;
return d;
}
static R3Grid *
CreateGrid(R3Mesh *mesh)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Allocate grid
R3Grid *grid = new R3Grid(mesh->BBox(), grid_spacing, min_resolution, max_resolution);
if (!grid) {
RNFail("Unable to allocate grid\n");
exit(-1);
}
// Rasterize each triangle into grid
for (int i = 0; i < mesh->NFaces(); i++) {
R3MeshFace *face = mesh->Face(i);
const R3Point& p0 = mesh->VertexPosition(mesh->VertexOnFace(face, 0));
const R3Point& p1 = mesh->VertexPosition(mesh->VertexOnFace(face, 1));
const R3Point& p2 = mesh->VertexPosition(mesh->VertexOnFace(face, 2));
grid->RasterizeWorldTriangle(p0, p1, p2, 1.0);
}
// Make binary (in case triangles overlap)
grid->Threshold(0.5, 0, 1);
// Check if should compute sdf
if (sdf) {
// Compute distance grid
grid->SquaredDistanceTransform();
grid->Sqrt();
grid->Multiply(grid->GridToWorldScaleFactor());
// Allocate temmporary memory
int *votes = new int [ grid->NEntries() ];
int *components = new int [ grid->NEntries() ];
for (int i = 0; i < grid->NEntries(); i++) votes[i] = 0;
for (int i = 0; i < grid->NEntries(); i++) components[i] = 0;
// Vote for signs by connected component
R3Grid signs(*grid);
signs.Clear(0);
for (int i = 0; i < mesh->NFaces(); i++) {
R3MeshFace *face = mesh->Face(i);
RNLength e = ShortestEdgeLength(mesh, face);
if (e > grid_spacing) e = grid_spacing;
R3Point p = mesh->FaceCentroid(face);
R3Point p1 = p + e * mesh->FaceNormal(face);
R3Point p2 = p - e * mesh->FaceNormal(face);
signs.RasterizeWorldPoint(p1, 1.0);
signs.RasterizeWorldPoint(p2, -1.0);
}
// Vote for connected components
int ncomponents = grid->ConnectedComponents(0, grid->NEntries(), NULL, NULL, components);
if (ncomponents > 0) {
for (int i = 0; i < grid->NEntries(); i++) {
int component = components[i];
if (component < 0) continue;
votes[component] += signs.GridValue(i);
}
// Set signs by votes on connected components
for (int i = 0; i < grid->NEntries(); i++) {
int component = components[i];
if (component < 0) continue;
if (votes[component] < 0) {
RNScalar d = grid->GridValue(i);
grid->SetGridValue(i, -d);
}
}
}
// Delete temporary memory
delete [] components;
delete [] votes;
}
// Print statistics
if (print_verbose) {
printf("Created grid ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" Resolution = %d %d %d\n", grid->XResolution(), grid->YResolution(), grid->ZResolution());
printf(" Spacing = %g\n", grid->GridToWorldScaleFactor());
printf(" Cardinality = %d\n", grid->Cardinality());
printf(" Volume = %g\n", grid->Volume());
RNInterval grid_range = grid->Range();
printf(" Minimum = %g\n", grid_range.Min());
printf(" Maximum = %g\n", grid_range.Max());
printf(" L1Norm = %g\n", grid->L1Norm());
printf(" L2Norm = %g\n", grid->L2Norm());
fflush(stdout);
}
// Return grid
return grid;
}
static int
WriteGrid(R3Grid *grid, const char *grid_name)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Write grid
int status = grid->WriteFile(grid_name);
// Print statistics
if (print_verbose) {
printf("Wrote grid ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Bytes = %d\n", status * (int) sizeof(RNScalar));
fflush(stdout);
}
// Return status
return status;
}
static int
ParseArgs(int argc, char **argv)
{
// Parse arguments
argc--; argv++;
while (argc > 0) {
if ((*argv)[0] == '-') {
if (!strcmp(*argv, "-v")) print_verbose = 1;
else if (!strcmp(*argv, "-sdf")) sdf = 1;
else if (!strcmp(*argv, "-spacing")) { argc--; argv++; grid_spacing = atof(*argv); }
else if (!strcmp(*argv, "-min_resolution")) { argc--; argv++; min_resolution = atoi(*argv); }
else if (!strcmp(*argv, "-max_resolution")) { argc--; argv++; max_resolution = atoi(*argv); }
else { RNFail("Invalid program argument: %s", *argv); exit(1); }
}
else {
if (!mesh_name) mesh_name = *argv;
else if (!grid_name) grid_name = *argv;
else { RNFail("Invalid program argument: %s", *argv); exit(1); }
}
argv++; argc--;
}
// Check mesh filename
if (!mesh_name || !grid_name) {
RNFail("Usage: msh2grd mesh grid [options]\n");
return 0;
}
// Return OK status
return 1;
}
int
main(int argc, char **argv)
{
// Parse program arguments
if (!ParseArgs(argc, argv)) exit(-1);
// Read mesh file
R3Mesh *mesh = ReadMesh(mesh_name);
if (!mesh) exit(-1);
// Create grid from mesh
R3Grid *grid = CreateGrid(mesh);
if (!grid) exit(-1);
// Write grid
int status = WriteGrid(grid, grid_name);
if (!status) exit(-1);
// Return success
return 0;
}
<commit_msg>msh2grd<commit_after>// Source file for the mesh to grid conversion program
// Include files
namespace gaps {}
using namespace gaps;
#include "R3Shapes/R3Shapes.h"
// Program variables
static char *mesh_name = NULL;
static char *grid_name = NULL;
static int min_resolution = 16;
static int max_resolution = 512;
static double grid_spacing = 0.1;
static int sdf = 0;
static int print_verbose = 0;
static R3Mesh *
ReadMesh(char *mesh_name)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Allocate mesh
R3Mesh *mesh = new R3Mesh();
assert(mesh);
// Read mesh from file
if (!mesh->ReadFile(mesh_name)) {
delete mesh;
return NULL;
}
// Print statistics
if (print_verbose) {
printf("Read mesh ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Faces = %d\n", mesh->NFaces());
printf(" # Edges = %d\n", mesh->NEdges());
printf(" # Vertices = %d\n", mesh->NVertices());
fflush(stdout);
}
// Return success
return mesh;
}
static RNLength
ShortestEdgeLength(R3Mesh *mesh, R3MeshFace *face)
{
// Return shortest edge on face
RNLength d0 = mesh->EdgeLength(mesh->EdgeOnFace(face, 0));
RNLength d1 = mesh->EdgeLength(mesh->EdgeOnFace(face, 1));
RNLength d2 = mesh->EdgeLength(mesh->EdgeOnFace(face, 2));
RNLength d = FLT_MAX;
if (d0 < d) d = d0;
if (d1 < d) d = d1;
if (d2 < d) d = d2;
return d;
}
static R3Grid *
CreateGrid(R3Mesh *mesh)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Allocate grid
R3Grid *grid = new R3Grid(mesh->BBox(), grid_spacing, min_resolution, max_resolution);
if (!grid) {
RNFail("Unable to allocate grid\n");
exit(-1);
}
// Rasterize mesh
if (mesh->NFaces() == 0) {
// Rasterize each vertex into grid
for (int i = 0; i < mesh->NVertices(); i++) {
R3MeshVertex *vertex = mesh->Vertex(i);
const R3Point& p = mesh->VertexPosition(vertex);
grid->RasterizeWorldPoint(p, 1.0);
}
}
else {
// Rasterize each triangle into grid
for (int i = 0; i < mesh->NFaces(); i++) {
R3MeshFace *face = mesh->Face(i);
const R3Point& p0 = mesh->VertexPosition(mesh->VertexOnFace(face, 0));
const R3Point& p1 = mesh->VertexPosition(mesh->VertexOnFace(face, 1));
const R3Point& p2 = mesh->VertexPosition(mesh->VertexOnFace(face, 2));
grid->RasterizeWorldTriangle(p0, p1, p2, 1.0);
}
}
// Make binary (in case triangles overlap)
grid->Threshold(0.5, 0, 1);
// Check if should compute sdf
if (sdf) {
// Compute distance grid
grid->SquaredDistanceTransform();
grid->Sqrt();
grid->Multiply(grid->GridToWorldScaleFactor());
// Allocate temmporary memory
int *votes = new int [ grid->NEntries() ];
int *components = new int [ grid->NEntries() ];
for (int i = 0; i < grid->NEntries(); i++) votes[i] = 0;
for (int i = 0; i < grid->NEntries(); i++) components[i] = 0;
// Vote for signs by connected component
R3Grid signs(*grid);
signs.Clear(0);
for (int i = 0; i < mesh->NFaces(); i++) {
R3MeshFace *face = mesh->Face(i);
RNLength e = ShortestEdgeLength(mesh, face);
if (e > grid_spacing) e = grid_spacing;
R3Point p = mesh->FaceCentroid(face);
R3Point p1 = p + e * mesh->FaceNormal(face);
R3Point p2 = p - e * mesh->FaceNormal(face);
signs.RasterizeWorldPoint(p1, 1.0);
signs.RasterizeWorldPoint(p2, -1.0);
}
// Vote for connected components
int ncomponents = grid->ConnectedComponents(0, grid->NEntries(), NULL, NULL, components);
if (ncomponents > 0) {
for (int i = 0; i < grid->NEntries(); i++) {
int component = components[i];
if (component < 0) continue;
votes[component] += signs.GridValue(i);
}
// Set signs by votes on connected components
for (int i = 0; i < grid->NEntries(); i++) {
int component = components[i];
if (component < 0) continue;
if (votes[component] < 0) {
RNScalar d = grid->GridValue(i);
grid->SetGridValue(i, -d);
}
}
}
// Delete temporary memory
delete [] components;
delete [] votes;
}
// Print statistics
if (print_verbose) {
printf("Created grid ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" Resolution = %d %d %d\n", grid->XResolution(), grid->YResolution(), grid->ZResolution());
printf(" Spacing = %g\n", grid->GridToWorldScaleFactor());
printf(" Cardinality = %d\n", grid->Cardinality());
printf(" Volume = %g\n", grid->Volume());
RNInterval grid_range = grid->Range();
printf(" Minimum = %g\n", grid_range.Min());
printf(" Maximum = %g\n", grid_range.Max());
printf(" L1Norm = %g\n", grid->L1Norm());
printf(" L2Norm = %g\n", grid->L2Norm());
fflush(stdout);
}
// Return grid
return grid;
}
static int
WriteGrid(R3Grid *grid, const char *grid_name)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Write grid
int status = grid->WriteFile(grid_name);
// Print statistics
if (print_verbose) {
printf("Wrote grid ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Bytes = %d\n", status * (int) sizeof(RNScalar));
fflush(stdout);
}
// Return status
return status;
}
static int
ParseArgs(int argc, char **argv)
{
// Parse arguments
argc--; argv++;
while (argc > 0) {
if ((*argv)[0] == '-') {
if (!strcmp(*argv, "-v")) print_verbose = 1;
else if (!strcmp(*argv, "-sdf")) sdf = 1;
else if (!strcmp(*argv, "-spacing")) { argc--; argv++; grid_spacing = atof(*argv); }
else if (!strcmp(*argv, "-min_resolution")) { argc--; argv++; min_resolution = atoi(*argv); }
else if (!strcmp(*argv, "-max_resolution")) { argc--; argv++; max_resolution = atoi(*argv); }
else { RNFail("Invalid program argument: %s", *argv); exit(1); }
}
else {
if (!mesh_name) mesh_name = *argv;
else if (!grid_name) grid_name = *argv;
else { RNFail("Invalid program argument: %s", *argv); exit(1); }
}
argv++; argc--;
}
// Check mesh filename
if (!mesh_name || !grid_name) {
RNFail("Usage: msh2grd mesh grid [options]\n");
return 0;
}
// Return OK status
return 1;
}
int
main(int argc, char **argv)
{
// Parse program arguments
if (!ParseArgs(argc, argv)) exit(-1);
// Read mesh file
R3Mesh *mesh = ReadMesh(mesh_name);
if (!mesh) exit(-1);
// Create grid from mesh
R3Grid *grid = CreateGrid(mesh);
if (!grid) exit(-1);
// Write grid
int status = WriteGrid(grid, grid_name);
if (!status) exit(-1);
// Return success
return 0;
}
<|endoftext|> |
<commit_before>#include "Scene.h"
#include "MaterialElement.h"
#include <iostream>
//**************************************************************************************
//-----------------------------------SCENE------------------------------------
//Constructors and destructor
Scene::Scene()
{
}
Scene::~Scene()
{
for (auto it = S.begin(); it != S.end(); it++)
{
delete *it;
}
}
//Accessors
MaterialElement *Scene::getElement(unsigned int i)
{
MaterialElement *M = NULL;
if (i < S.size())
{
M = S[i];
}
else
{
std::cout << "No element" << '\n';
}
return M;
}
double Scene::getTime()
{
return Time;
}
//Display
void Scene::consoleShow()
{
if (0 < S.size())
{
for (unsigned int i = 0; i < S.size(); i++)
{
std::cout << "element " << i + 1 << ": " << '\n'; //from 1 to number of elements
S[i]->consoleShow();
}
}
else { std::cout << "empty scene " << '\n'; }
}
//Modifier
void Scene::setForce(Vect F, unsigned int place) // add force to element i
{
S[place]->setResultant(F);
}
void Scene::update(double dt)
{
//std::vector<MaterialElement*>::iterator it;
for (auto it = S.begin(); it != S.end(); it++)
{
(*it)->update(dt);
}
}
void Scene::simulate(double step, double duration)
{
double t = 0;
while (t < duration)
{
update(step);
t = t + step;
}
Time += t;
}
//----------Model interface-----------------------
void Scene::addMatPoint()
{
MaterialPoint *Mp = new MaterialPoint;
S.push_back(Mp);
}
void Scene::addMatPoint(double x, double y, double z, double mass, double charge)
{
MaterialPoint *Mp = new MaterialPoint;
Mp->setPosition(x, y, z);
Mp->setMass(mass);
Mp->setCharge(charge);
Mp->setMass(mass);
Mp->setPosition(x, y, z);
S.push_back(Mp);
}
<commit_msg>External actions integration<commit_after>#include "Scene.h"
#include "MaterialElement.h"
#include <iostream>
//**************************************************************************************
//-----------------------------------SCENE------------------------------------
//Constructors and destructor
Scene::Scene()
{
}
Scene::~Scene()
{
for (auto it = S.begin(); it != S.end(); it++)
{
delete *it;
}
}
//Accessors
MaterialElement *Scene::getElement(unsigned int i)
{
MaterialElement *M = nullptr;
if (i < S.size())
{
M = S[i];
}
else
{
std::cout << "No element" << '\n';
}
return M;
}
double Scene::getTime()
{
return Time;
}
//Display
void Scene::consoleShow()
{
if (0 < S.size())
{
for (unsigned int i = 0; i < S.size(); i++)
{
std::cout << "element " << i + 1 << ": " << '\n'; //from 1 to number of elements
S[i]->consoleShow();
}
}
else { std::cout << "empty scene " << '\n'; }
}
//Modifier
void Scene::addExternalAction(Vect F, unsigned int place) // add force to element i
{
S[place]->addExternalAction(F);
}
void Scene::update(double dt)
{
for (auto it = S.begin(); it != S.end(); it++)
{
(*it)->update(dt);
}
}
void Scene::simulate(double step, double duration)
{
double t = 0;
while (t < duration)
{
update(step);
t = t + step;
}
Time += t;
}
//----------Model interface-----------------------
void Scene::addMatPoint()
{
MaterialPoint *Mp = new MaterialPoint;
S.push_back(Mp);
}
void Scene::addMatPoint(double x, double y, double z, double mass, double charge)
{
MaterialPoint *Mp = new MaterialPoint;
Mp->place(x, y, z);
Mp->setMass(mass);
Mp->setCharge(charge);
Mp->setMass(mass);
Mp->place(x, y, z);
S.push_back(Mp);
}
<|endoftext|> |
<commit_before>#include <LD30/Engine.hpp>
#include <LD30/MainMenuState.hpp>
#include <SFML/Window/Event.hpp>
namespace
{
sf::RenderWindow* openWindow(sf::RenderWindow* ptr)
{
int x = ld::Settings::getInt("iResolutionX", 1024);
int y = ld::Settings::getInt("iResolutionY", 600);
std::string title = ld::Settings::getString("sWindowTitle", "You haven't set the window title :(");
sf::RenderWindow* wndw = nullptr;
if (!ptr)
{
wndw = new sf::RenderWindow(sf::VideoMode(x, y),
title, sf::Style::Close);
}
else
{
ptr->~RenderWindow();
wndw = new (ptr) sf::RenderWindow(sf::VideoMode(x, y),
title, sf::Style::Close);
}
sf::Vector2f wsize(1920.f, 1080.f);
wndw->setView(sf::View(wsize / 2.f, wsize));
return wndw;
}
}
ld::Engine::Engine()
: m_currentState (nullptr),
m_nextState (nullptr),
m_window (nullptr),
m_paused (false),
m_shouldExit (false)
{
}
ld::Engine::~Engine()
{
}
ld::Engine& ld::Engine::getInstance()
{
static Engine eng;
return eng;
}
bool ld::Engine::init()
{
ld::Settings::init(ld::Misc::getHomeDir("LD30") + "settings.json");
m_window.reset(openWindow(nullptr));
m_currentState.reset(new MainMenuState(*m_window));
m_currentState->init();
return (m_window->isOpen() && m_currentState);
}
bool ld::Engine::mainLoop()
{
sf::Clock frameClock;
while (!m_shouldExit && m_currentState)
{
// If changeState has been called, the current state will be removed & deleted and replaced with the new one.
if (m_nextState)
{
m_currentState.reset(m_nextState.release());
m_currentState->init();
}
// Call update.
m_currentState->update(m_paused ? 0.f : frameClock.restart().asSeconds());
// Draw
m_window->clear();
m_currentState->draw();
m_window->display();
// Poll events
sf::Event e;
while (m_window->pollEvent(e))
{
if (e.type == sf::Event::Closed)
m_shouldExit = true;
}
}
if (m_currentState)
m_currentState.reset(nullptr);
ld::Settings::writeSettings();
return true;
}
void ld::Engine::changeState(GameState* state)
{
m_nextState.reset(state);
}
void ld::Engine::setShouldExit(const bool exit)
{
m_shouldExit = exit;
}
bool ld::Engine::isPaused()
{
return m_paused;
}
void ld::Engine::setPaused(const bool paused)
{
m_paused = paused;
}
<commit_msg>added debug functionality to change framerate<commit_after>#include <LD30/Engine.hpp>
#include <LD30/MainMenuState.hpp>
#include <SFML/Window/Event.hpp>
namespace
{
sf::RenderWindow* openWindow(sf::RenderWindow* ptr)
{
int x = ld::Settings::getInt("iResolutionX", 1024);
int y = ld::Settings::getInt("iResolutionY", 600);
std::string title = ld::Settings::getString("sWindowTitle", "You haven't set the window title :(");
sf::RenderWindow* wndw = nullptr;
if (!ptr)
{
wndw = new sf::RenderWindow(sf::VideoMode(x, y),
title, sf::Style::Close);
}
else
{
ptr->~RenderWindow();
wndw = new (ptr) sf::RenderWindow(sf::VideoMode(x, y),
title, sf::Style::Close);
}
sf::Vector2f wsize(1920.f, 1080.f);
wndw->setView(sf::View(wsize / 2.f, wsize));
return wndw;
}
}
ld::Engine::Engine()
: m_currentState (nullptr),
m_nextState (nullptr),
m_window (nullptr),
m_paused (false),
m_shouldExit (false)
{
}
ld::Engine::~Engine()
{
}
ld::Engine& ld::Engine::getInstance()
{
static Engine eng;
return eng;
}
bool ld::Engine::init()
{
ld::Settings::init(ld::Misc::getHomeDir("LD30") + "settings.json");
m_window.reset(openWindow(nullptr));
m_currentState.reset(new MainMenuState(*m_window));
m_currentState->init();
return (m_window->isOpen() && m_currentState);
}
bool ld::Engine::mainLoop()
{
sf::Clock frameClock;
float timer = 0;
while (!m_shouldExit && m_currentState)
{
// If changeState has been called, the current state will be removed & deleted and replaced with the new one.
if (m_nextState)
{
m_currentState.reset(m_nextState.release());
m_currentState->init();
}
// Call update.
timer += frameClock.restart().asSeconds();
if (timer > (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) ? 0.05f : 0.00015f))
{
m_currentState->update(m_paused ? 0.f : timer);
timer = 0;
}
// Draw
m_window->clear();
m_currentState->draw();
m_window->display();
// Poll events
sf::Event e;
while (m_window->pollEvent(e))
{
if (e.type == sf::Event::Closed)
m_shouldExit = true;
}
}
if (m_currentState)
m_currentState.reset(nullptr);
ld::Settings::writeSettings();
return true;
}
void ld::Engine::changeState(GameState* state)
{
m_nextState.reset(state);
}
void ld::Engine::setShouldExit(const bool exit)
{
m_shouldExit = exit;
}
bool ld::Engine::isPaused()
{
return m_paused;
}
void ld::Engine::setPaused(const bool paused)
{
m_paused = paused;
}
<|endoftext|> |
<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include <iostream>
#include <fstream>
namespace Halide {
llvm::raw_fd_ostream *new_raw_fd_ostream(const std::string &filename) {
std::string error_string;
#if LLVM_VERSION < 35
llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string);
#elif LLVM_VERSION == 35
llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string, llvm::sys::fs::F_None);
#else // llvm 3.6
std::error_code err;
llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), err, llvm::sys::fs::F_None);
if (err) error_string = err.message();
#endif
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
namespace Internal {
bool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {
#if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(value);
#else
llvm::ConstantAsMetadata *cam = llvm::cast<llvm::ConstantAsMetadata>(value);
llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(cam->getValue());
#endif
if (c) {
result = !c->isZero();
return true;
}
return false;
}
bool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {
#if LLVM_VERSION < 36
if (llvm::dyn_cast<llvm::ConstantAggregateZero>(value)) {
result = "";
return true;
}
llvm::ConstantDataArray *c = llvm::cast<llvm::ConstantDataArray>(value);
if (c) {
result = c->getAsCString();
return true;
}
#else
llvm::MDString *c = llvm::dyn_cast<llvm::MDString>(value);
if (c) {
result = c->getString();
return true;
}
#endif
return false;
}
}
void get_target_options(const llvm::Module &module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {
bool use_soft_float_abi = false;
Internal::get_md_bool(module.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi);
Internal::get_md_string(module.getModuleFlag("halide_mcpu"), mcpu);
Internal::get_md_string(module.getModuleFlag("halide_mattrs"), mattrs);
options = llvm::TargetOptions();
options.LessPreciseFPMADOption = true;
options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
options.UnsafeFPMath = true;
options.NoInfsFPMath = true;
options.NoNaNsFPMath = true;
options.HonorSignDependentRoundingFPMathOption = false;
#if LLVM_VERSION < 37
options.NoFramePointerElim = false;
options.UseSoftFloat = false;
#endif
options.NoZerosInBSS = false;
options.GuaranteedTailCallOpt = false;
#if LLVM_VERSION < 37
options.DisableTailCalls = false;
#endif
options.StackAlignmentOverride = 0;
#if LLVM_VERSION < 37
options.TrapFuncName = "";
#endif
options.PositionIndependentExecutable = true;
options.FunctionSections = true;
#ifdef WITH_NATIVE_CLIENT
options.UseInitArray = true;
#else
options.UseInitArray = false;
#endif
options.FloatABIType =
use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;
}
void clone_target_options(const llvm::Module &from, llvm::Module &to) {
to.setTargetTriple(from.getTargetTriple());
llvm::LLVMContext &context = to.getContext();
bool use_soft_float_abi = false;
if (Internal::get_md_bool(from.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi))
to.addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi ? 1 : 0);
std::string mcpu;
if (Internal::get_md_string(from.getModuleFlag("halide_mcpu"), mcpu)) {
#if LLVM_VERSION < 36
to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::ConstantDataArray::getString(context, mcpu));
#else
to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::MDString::get(context, mcpu));
#endif
}
std::string mattrs;
if (Internal::get_md_string(from.getModuleFlag("halide_mattrs"), mattrs)) {
#if LLVM_VERSION < 36
to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::ConstantDataArray::getString(context, mattrs));
#else
to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::MDString::get(context, mattrs));
#endif
}
}
llvm::TargetMachine *get_target_machine(const llvm::Module &module) {
std::string error_string;
const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module.getTargetTriple(), error_string);
if (!target) {
std::cout << error_string << std::endl;
llvm::TargetRegistry::printRegisteredTargetsForVersion();
}
internal_assert(target) << "Could not create target for " << module.getTargetTriple() << "\n";
llvm::TargetOptions options;
std::string mcpu = "";
std::string mattrs = "";
get_target_options(module, options, mcpu, mattrs);
return target->createTargetMachine(module.getTargetTriple(),
mcpu, mattrs,
options,
llvm::Reloc::PIC_,
llvm::CodeModel::Default,
llvm::CodeGenOpt::Aggressive);
}
#if LLVM_VERSION < 37
void emit_file_legacy(llvm::Module &module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file_legacy.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
llvm::TargetMachine *target_machine = get_target_machine(module);
internal_assert(target_machine) << "Could not allocate target machine!\n";
// Build up all of the passes that we want to do to the module.
llvm::PassManager pass_manager;
// Add an appropriate TargetLibraryInfo pass for the module's triple.
pass_manager.add(new llvm::TargetLibraryInfo(llvm::Triple(module.getTargetTriple())));
#if LLVM_VERSION < 33
pass_manager.add(new llvm::TargetTransformInfo(target_machine->getScalarTargetTransformInfo(),
target_machine->getVectorTargetTransformInfo()));
#else
target_machine->addAnalysisPasses(pass_manager);
#endif
#if LLVM_VERSION < 35
llvm::DataLayout *layout = new llvm::DataLayout(module.get());
Internal::debug(2) << "Data layout: " << layout->getStringRepresentation();
pass_manager.add(layout);
#endif
// Make sure things marked as always-inline get inlined
pass_manager.add(llvm::createAlwaysInlinerPass());
// Override default to generate verbose assembly.
target_machine->setAsmVerbosityDefault(true);
llvm::raw_fd_ostream *raw_out = new_raw_fd_ostream(filename);
llvm::formatted_raw_ostream *out = new llvm::formatted_raw_ostream(*raw_out);
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, *out, file_type);
pass_manager.run(module);
delete out;
delete raw_out;
delete target_machine;
}
#endif
void emit_file(llvm::Module &module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {
#if LLVM_VERSION < 37
emit_file_legacy(module, filename, file_type);
#else
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
llvm::TargetMachine *target_machine = get_target_machine(module);
internal_assert(target_machine) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
std::unique_ptr<llvm::raw_fd_ostream> out(new_raw_fd_ostream(filename));
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
pass_manager.add(llvm::createAlwaysInlinerPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, *out, file_type);
pass_manager.run(module);
delete target_machine;
#endif
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, const std::string &filename) {
emit_file(module, filename, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, const std::string &filename) {
emit_file(module, filename, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_native(llvm::Module &module,
const std::string &object_filename,
const std::string &assembly_filename) {
emit_file(module, object_filename, llvm::TargetMachine::CGFT_ObjectFile);
emit_file(module, assembly_filename, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, const std::string &filename) {
llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
WriteBitcodeToFile(&module, *file);
delete file;
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, const std::string &filename) {
llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
module.print(*file, nullptr);
delete file;
}
} // namespace Halide
<commit_msg>use PIC, not PIE<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include <iostream>
#include <fstream>
namespace Halide {
llvm::raw_fd_ostream *new_raw_fd_ostream(const std::string &filename) {
std::string error_string;
#if LLVM_VERSION < 35
llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string);
#elif LLVM_VERSION == 35
llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string, llvm::sys::fs::F_None);
#else // llvm 3.6
std::error_code err;
llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), err, llvm::sys::fs::F_None);
if (err) error_string = err.message();
#endif
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
namespace Internal {
bool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {
#if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(value);
#else
llvm::ConstantAsMetadata *cam = llvm::cast<llvm::ConstantAsMetadata>(value);
llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(cam->getValue());
#endif
if (c) {
result = !c->isZero();
return true;
}
return false;
}
bool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {
#if LLVM_VERSION < 36
if (llvm::dyn_cast<llvm::ConstantAggregateZero>(value)) {
result = "";
return true;
}
llvm::ConstantDataArray *c = llvm::cast<llvm::ConstantDataArray>(value);
if (c) {
result = c->getAsCString();
return true;
}
#else
llvm::MDString *c = llvm::dyn_cast<llvm::MDString>(value);
if (c) {
result = c->getString();
return true;
}
#endif
return false;
}
}
void get_target_options(const llvm::Module &module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {
bool use_soft_float_abi = false;
Internal::get_md_bool(module.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi);
Internal::get_md_string(module.getModuleFlag("halide_mcpu"), mcpu);
Internal::get_md_string(module.getModuleFlag("halide_mattrs"), mattrs);
options = llvm::TargetOptions();
options.LessPreciseFPMADOption = true;
options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
options.UnsafeFPMath = true;
options.NoInfsFPMath = true;
options.NoNaNsFPMath = true;
options.HonorSignDependentRoundingFPMathOption = false;
#if LLVM_VERSION < 37
options.NoFramePointerElim = false;
options.UseSoftFloat = false;
#endif
options.NoZerosInBSS = false;
options.GuaranteedTailCallOpt = false;
#if LLVM_VERSION < 37
options.DisableTailCalls = false;
#endif
options.StackAlignmentOverride = 0;
#if LLVM_VERSION < 37
options.TrapFuncName = "";
#endif
options.FunctionSections = true;
#ifdef WITH_NATIVE_CLIENT
options.UseInitArray = true;
#else
options.UseInitArray = false;
#endif
options.FloatABIType =
use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;
}
void clone_target_options(const llvm::Module &from, llvm::Module &to) {
to.setTargetTriple(from.getTargetTriple());
llvm::LLVMContext &context = to.getContext();
bool use_soft_float_abi = false;
if (Internal::get_md_bool(from.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi))
to.addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi ? 1 : 0);
std::string mcpu;
if (Internal::get_md_string(from.getModuleFlag("halide_mcpu"), mcpu)) {
#if LLVM_VERSION < 36
to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::ConstantDataArray::getString(context, mcpu));
#else
to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::MDString::get(context, mcpu));
#endif
}
std::string mattrs;
if (Internal::get_md_string(from.getModuleFlag("halide_mattrs"), mattrs)) {
#if LLVM_VERSION < 36
to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::ConstantDataArray::getString(context, mattrs));
#else
to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::MDString::get(context, mattrs));
#endif
}
}
llvm::TargetMachine *get_target_machine(const llvm::Module &module) {
std::string error_string;
const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module.getTargetTriple(), error_string);
if (!target) {
std::cout << error_string << std::endl;
llvm::TargetRegistry::printRegisteredTargetsForVersion();
}
internal_assert(target) << "Could not create target for " << module.getTargetTriple() << "\n";
llvm::TargetOptions options;
std::string mcpu = "";
std::string mattrs = "";
get_target_options(module, options, mcpu, mattrs);
return target->createTargetMachine(module.getTargetTriple(),
mcpu, mattrs,
options,
llvm::Reloc::PIC_,
llvm::CodeModel::Default,
llvm::CodeGenOpt::Aggressive);
}
#if LLVM_VERSION < 37
void emit_file_legacy(llvm::Module &module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file_legacy.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
llvm::TargetMachine *target_machine = get_target_machine(module);
internal_assert(target_machine) << "Could not allocate target machine!\n";
// Build up all of the passes that we want to do to the module.
llvm::PassManager pass_manager;
// Add an appropriate TargetLibraryInfo pass for the module's triple.
pass_manager.add(new llvm::TargetLibraryInfo(llvm::Triple(module.getTargetTriple())));
#if LLVM_VERSION < 33
pass_manager.add(new llvm::TargetTransformInfo(target_machine->getScalarTargetTransformInfo(),
target_machine->getVectorTargetTransformInfo()));
#else
target_machine->addAnalysisPasses(pass_manager);
#endif
#if LLVM_VERSION < 35
llvm::DataLayout *layout = new llvm::DataLayout(module.get());
Internal::debug(2) << "Data layout: " << layout->getStringRepresentation();
pass_manager.add(layout);
#endif
// Make sure things marked as always-inline get inlined
pass_manager.add(llvm::createAlwaysInlinerPass());
// Override default to generate verbose assembly.
target_machine->setAsmVerbosityDefault(true);
llvm::raw_fd_ostream *raw_out = new_raw_fd_ostream(filename);
llvm::formatted_raw_ostream *out = new llvm::formatted_raw_ostream(*raw_out);
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, *out, file_type);
pass_manager.run(module);
delete out;
delete raw_out;
delete target_machine;
}
#endif
void emit_file(llvm::Module &module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {
#if LLVM_VERSION < 37
emit_file_legacy(module, filename, file_type);
#else
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
llvm::TargetMachine *target_machine = get_target_machine(module);
internal_assert(target_machine) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
std::unique_ptr<llvm::raw_fd_ostream> out(new_raw_fd_ostream(filename));
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
pass_manager.add(llvm::createAlwaysInlinerPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, *out, file_type);
pass_manager.run(module);
delete target_machine;
#endif
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, const std::string &filename) {
emit_file(module, filename, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, const std::string &filename) {
emit_file(module, filename, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_native(llvm::Module &module,
const std::string &object_filename,
const std::string &assembly_filename) {
emit_file(module, object_filename, llvm::TargetMachine::CGFT_ObjectFile);
emit_file(module, assembly_filename, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, const std::string &filename) {
llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
WriteBitcodeToFile(&module, *file);
delete file;
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, const std::string &filename) {
llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
module.print(*file, nullptr);
delete file;
}
} // namespace Halide
<|endoftext|> |
<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = path.size() >= 1 && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<commit_msg>Check for UNC paths on Windows<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
// Note that passing null for the first arg isn't strictly POSIX, but is
// supported everywhere we currently build.
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = path.size() >= 1 && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
} else if (path.size() > 2 && path[0] == '\\' && path[1] == '\\') {
// Also allow for UNC-style paths beginning with double-backslash
is_absolute = true;
sep = path[0];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<|endoftext|> |
<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
void create_static_library(const std::vector<std::string> &src_files, const Target &target,
const std::string &dst_file, bool deterministic) {
internal_assert(!src_files.empty());
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<commit_msg>Ensure that LLVM-created .a files don't contain absolute paths<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret == 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file, bool deterministic) {
internal_assert(!src_files_in.empty());
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliRICHRawCluster.h"
#include <iostream.h>
ClassImp(AliRICHRawCluster)
//__________________________________________________________________________________________________
AliRICHRawCluster :: AliRICHRawCluster()
{//default ctor
fTracks[0]=fTracks[1]=fTracks[2]=-1;
fX=fY=0;
fQ=fMultiplicity=0;
for (int k=0;k<50;k++) {
fIndexMap[k]=-1;
fContMap[k]=0;
fPhysicsMap[k]=-1;
fCtype=-1;
}
fNcluster[0]=fNcluster[1]=-1;
}//ctor
//__________________________________________________________________________________________________
Int_t AliRICHRawCluster::Compare(const TObject *obj) const
{//Compare two clusters
AliRICHRawCluster *raw=(AliRICHRawCluster *)obj;
Float_t y=fY;
Float_t yo=raw->fY;
if(y>yo) return 1;
else if(y<yo) return -1;
else return 0;
}//Compare()
//__________________________________________________________________________________________________
Int_t AliRICHRawCluster::PhysicsContribution()
{//Type of physics processes
Int_t iPhys=0;
Int_t iBg=0;
Int_t iMixed=0;
for (Int_t i=0; i<fMultiplicity; i++){
if(fPhysicsMap[i]==2) iPhys++;
if(fPhysicsMap[i]==1) iMixed++;
if(fPhysicsMap[i]==0) iBg++;
}
if(iMixed==0 && iBg==0) return 2;
else if((iPhys != 0 && iBg !=0) || iMixed != 0) return 1;
else return 0;
}//PhysicsContribution
//__________________________________________________________________________________________________
void AliRICHRawCluster::Print(Option_t*)const
{
Info("","X=%7.2f, Y=%7.2f, Qdc=%4i, Peak=%4i, Multip=%2i, T0=%5i T1=%5i T2=%5i",
fX, fY, fQ, fPeakSignal,fMultiplicity, fTracks[0], fTracks[1], fTracks[2]);
for(int i=0;i<fMultiplicity;i++)
cout<<"D"<<i<<"="<<fIndexMap[i]<<" C="<<fContMap[i]<<endl;
}//void AliRICHRawCluster::Print(Option_t *option)const
<commit_msg>Using Riostream.h instead of iostream.h<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliRICHRawCluster.h"
#include <Riostream.h>
ClassImp(AliRICHRawCluster)
//__________________________________________________________________________________________________
AliRICHRawCluster :: AliRICHRawCluster()
{//default ctor
fTracks[0]=fTracks[1]=fTracks[2]=-1;
fX=fY=0;
fQ=fMultiplicity=0;
for (int k=0;k<50;k++) {
fIndexMap[k]=-1;
fContMap[k]=0;
fPhysicsMap[k]=-1;
fCtype=-1;
}
fNcluster[0]=fNcluster[1]=-1;
}//ctor
//__________________________________________________________________________________________________
Int_t AliRICHRawCluster::Compare(const TObject *obj) const
{//Compare two clusters
AliRICHRawCluster *raw=(AliRICHRawCluster *)obj;
Float_t y=fY;
Float_t yo=raw->fY;
if(y>yo) return 1;
else if(y<yo) return -1;
else return 0;
}//Compare()
//__________________________________________________________________________________________________
Int_t AliRICHRawCluster::PhysicsContribution()
{//Type of physics processes
Int_t iPhys=0;
Int_t iBg=0;
Int_t iMixed=0;
for (Int_t i=0; i<fMultiplicity; i++){
if(fPhysicsMap[i]==2) iPhys++;
if(fPhysicsMap[i]==1) iMixed++;
if(fPhysicsMap[i]==0) iBg++;
}
if(iMixed==0 && iBg==0) return 2;
else if((iPhys != 0 && iBg !=0) || iMixed != 0) return 1;
else return 0;
}//PhysicsContribution
//__________________________________________________________________________________________________
void AliRICHRawCluster::Print(Option_t*)const
{
Info("","X=%7.2f, Y=%7.2f, Qdc=%4i, Peak=%4i, Multip=%2i, T0=%5i T1=%5i T2=%5i",
fX, fY, fQ, fPeakSignal,fMultiplicity, fTracks[0], fTracks[1], fTracks[2]);
for(int i=0;i<fMultiplicity;i++)
cout<<"D"<<i<<"="<<fIndexMap[i]<<" C="<<fContMap[i]<<endl;
}//void AliRICHRawCluster::Print(Option_t *option)const
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/V8Initializer.h"
#include "V8DOMException.h"
#include "V8ErrorEvent.h"
#include "V8History.h"
#include "V8Location.h"
#include "V8Window.h"
#include "bindings/v8/DOMWrapperWorld.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptProfiler.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ErrorHandler.h"
#include "bindings/v8/V8GCController.h"
#include "bindings/v8/V8PerContextData.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/frame/ConsoleTypes.h"
#include "core/frame/ContentSecurityPolicy.h"
#include "core/frame/DOMWindow.h"
#include "core/frame/Frame.h"
#include "public/platform/Platform.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
#include <v8-debug.h>
namespace WebCore {
static Frame* findFrame(v8::Local<v8::Object> host, v8::Local<v8::Value> data, v8::Isolate* isolate)
{
const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);
if (V8Window::wrapperTypeInfo.equals(type)) {
v8::Handle<v8::Object> windowWrapper = host->FindInstanceInPrototypeChain(V8Window::domTemplate(isolate, worldTypeInMainThread(isolate)));
if (windowWrapper.IsEmpty())
return 0;
return V8Window::toNative(windowWrapper)->frame();
}
if (V8History::wrapperTypeInfo.equals(type))
return V8History::toNative(host)->frame();
if (V8Location::wrapperTypeInfo.equals(type))
return V8Location::toNative(host)->frame();
// This function can handle only those types listed above.
ASSERT_NOT_REACHED();
return 0;
}
static void reportFatalErrorInMainThread(const char* location, const char* message)
{
int memoryUsageMB = blink::Platform::current()->actualMemoryUsageMB();
printf("V8 error: %s (%s). Current memory usage: %d MB\n", message, location, memoryUsageMB);
CRASH();
}
static void messageHandlerInMainThread(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// If called during context initialization, there will be no entered context.
v8::Handle<v8::Context> enteredContext = isolate->GetEnteredContext();
if (enteredContext.IsEmpty())
return;
DOMWindow* firstWindow = toDOMWindow(enteredContext);
if (!firstWindow->isCurrentlyDisplayedInFrame())
return;
String errorMessage = toCoreString(message->Get());
v8::Handle<v8::StackTrace> stackTrace = message->GetStackTrace();
RefPtr<ScriptCallStack> callStack;
// Currently stack trace is only collected when inspector is open.
if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool shouldUseDocumentURL = resourceName.IsEmpty() || !resourceName->IsString();
String resource = shouldUseDocumentURL ? firstWindow->document()->url() : toCoreString(resourceName.As<v8::String>());
AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
DOMWrapperWorld* world = DOMWrapperWorld::current(isolate);
RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, world);
if (V8DOMWrapper::isDOMWrapper(data)) {
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(data);
const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
DOMException* exception = V8DOMException::toNative(obj);
if (exception && !exception->messageForConsole().isEmpty())
event->setUnsanitizedMessage("Uncaught " + exception->toStringForConsole());
}
}
// This method might be called while we're creating a new context. In this case, we
// avoid storing the exception object, as we can't create a wrapper during context creation.
// FIXME: Can we even get here during initialization now that we bail out when GetEntered returns an empty handle?
Frame* frame = firstWindow->document()->frame();
if (world && frame && frame->script().existingWindowShell(world))
V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, v8::Isolate::GetCurrent());
firstWindow->document()->reportException(event.release(), callStack, corsStatus);
}
static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Frame* target = findFrame(host, data, isolate);
if (!target)
return;
DOMWindow* targetWindow = target->domWindow();
ExceptionState exceptionState(v8::Handle<v8::Object>(), isolate);
exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(activeDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(activeDOMWindow(isolate)));
exceptionState.throwIfNeeded();
}
static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
{
if (ExecutionContext* executionContext = toExecutionContext(context)) {
if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
return policy->allowEval(ScriptState::forContext(context));
}
return false;
}
static void initializeV8Common(v8::Isolate* isolate)
{
v8::ResourceConstraints constraints;
constraints.ConfigureDefaults(static_cast<uint64_t>(blink::Platform::current()->physicalMemoryMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->numberOfProcessors()));
v8::SetResourceConstraints(isolate, &constraints);
v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);
v8::V8::IgnoreOutOfMemoryException();
v8::Debug::SetLiveEditEnabled(false);
}
void V8Initializer::initializeMainThreadIfNeeded(v8::Isolate* isolate)
{
ASSERT(isMainThread());
static bool initialized = false;
if (initialized)
return;
initialized = true;
initializeV8Common(isolate);
v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
v8::V8::AddMessageListener(messageHandlerInMainThread);
v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);
ScriptProfiler::initialize();
V8PerIsolateData::ensureInitialized(isolate);
}
static void reportFatalErrorInWorker(const char* location, const char* message)
{
// FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
CRASH();
}
static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
static bool isReportingException = false;
// Exceptions that occur in error handler should be ignored since in that case
// WorkerGlobalScope::reportException will send the exception to the worker object.
if (isReportingException)
return;
isReportingException = true;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// During the frame teardown, there may not be a valid context.
if (ExecutionContext* context = currentExecutionContext(isolate)) {
String errorMessage = toCoreString(message->Get());
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, sourceURL, message->GetScriptResourceName());
RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, DOMWrapperWorld::current(isolate));
AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, isolate);
context->reportException(event.release(), 0, corsStatus);
}
isReportingException = false;
}
static const int kWorkerMaxStackSize = 500 * 1024;
void V8Initializer::initializeWorker(v8::Isolate* isolate)
{
initializeV8Common(isolate);
v8::V8::AddMessageListener(messageHandlerInWorker);
v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);
v8::ResourceConstraints resourceConstraints;
uint32_t here;
resourceConstraints.set_stack_limit(&here - kWorkerMaxStackSize / sizeof(uint32_t*));
v8::SetResourceConstraints(isolate, &resourceConstraints);
}
} // namespace WebCore
<commit_msg>Move V8PerIsolateData initialization before calling AddMessageListener<commit_after>/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/V8Initializer.h"
#include "V8DOMException.h"
#include "V8ErrorEvent.h"
#include "V8History.h"
#include "V8Location.h"
#include "V8Window.h"
#include "bindings/v8/DOMWrapperWorld.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptProfiler.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ErrorHandler.h"
#include "bindings/v8/V8GCController.h"
#include "bindings/v8/V8PerContextData.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/frame/ConsoleTypes.h"
#include "core/frame/ContentSecurityPolicy.h"
#include "core/frame/DOMWindow.h"
#include "core/frame/Frame.h"
#include "public/platform/Platform.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
#include <v8-debug.h>
namespace WebCore {
static Frame* findFrame(v8::Local<v8::Object> host, v8::Local<v8::Value> data, v8::Isolate* isolate)
{
const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);
if (V8Window::wrapperTypeInfo.equals(type)) {
v8::Handle<v8::Object> windowWrapper = host->FindInstanceInPrototypeChain(V8Window::domTemplate(isolate, worldTypeInMainThread(isolate)));
if (windowWrapper.IsEmpty())
return 0;
return V8Window::toNative(windowWrapper)->frame();
}
if (V8History::wrapperTypeInfo.equals(type))
return V8History::toNative(host)->frame();
if (V8Location::wrapperTypeInfo.equals(type))
return V8Location::toNative(host)->frame();
// This function can handle only those types listed above.
ASSERT_NOT_REACHED();
return 0;
}
static void reportFatalErrorInMainThread(const char* location, const char* message)
{
int memoryUsageMB = blink::Platform::current()->actualMemoryUsageMB();
printf("V8 error: %s (%s). Current memory usage: %d MB\n", message, location, memoryUsageMB);
CRASH();
}
static void messageHandlerInMainThread(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// If called during context initialization, there will be no entered context.
v8::Handle<v8::Context> enteredContext = isolate->GetEnteredContext();
if (enteredContext.IsEmpty())
return;
DOMWindow* firstWindow = toDOMWindow(enteredContext);
if (!firstWindow->isCurrentlyDisplayedInFrame())
return;
String errorMessage = toCoreString(message->Get());
v8::Handle<v8::StackTrace> stackTrace = message->GetStackTrace();
RefPtr<ScriptCallStack> callStack;
// Currently stack trace is only collected when inspector is open.
if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
bool shouldUseDocumentURL = resourceName.IsEmpty() || !resourceName->IsString();
String resource = shouldUseDocumentURL ? firstWindow->document()->url() : toCoreString(resourceName.As<v8::String>());
AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
DOMWrapperWorld* world = DOMWrapperWorld::current(isolate);
RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, world);
if (V8DOMWrapper::isDOMWrapper(data)) {
v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(data);
const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
DOMException* exception = V8DOMException::toNative(obj);
if (exception && !exception->messageForConsole().isEmpty())
event->setUnsanitizedMessage("Uncaught " + exception->toStringForConsole());
}
}
// This method might be called while we're creating a new context. In this case, we
// avoid storing the exception object, as we can't create a wrapper during context creation.
// FIXME: Can we even get here during initialization now that we bail out when GetEntered returns an empty handle?
Frame* frame = firstWindow->document()->frame();
if (world && frame && frame->script().existingWindowShell(world))
V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, v8::Isolate::GetCurrent());
firstWindow->document()->reportException(event.release(), callStack, corsStatus);
}
static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Frame* target = findFrame(host, data, isolate);
if (!target)
return;
DOMWindow* targetWindow = target->domWindow();
ExceptionState exceptionState(v8::Handle<v8::Object>(), isolate);
exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(activeDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(activeDOMWindow(isolate)));
exceptionState.throwIfNeeded();
}
static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
{
if (ExecutionContext* executionContext = toExecutionContext(context)) {
if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
return policy->allowEval(ScriptState::forContext(context));
}
return false;
}
static void initializeV8Common(v8::Isolate* isolate)
{
v8::ResourceConstraints constraints;
constraints.ConfigureDefaults(static_cast<uint64_t>(blink::Platform::current()->physicalMemoryMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->numberOfProcessors()));
v8::SetResourceConstraints(isolate, &constraints);
v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);
v8::V8::IgnoreOutOfMemoryException();
v8::Debug::SetLiveEditEnabled(false);
}
void V8Initializer::initializeMainThreadIfNeeded(v8::Isolate* isolate)
{
ASSERT(isMainThread());
static bool initialized = false;
if (initialized)
return;
initialized = true;
initializeV8Common(isolate);
v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
V8PerIsolateData::ensureInitialized(isolate);
v8::V8::AddMessageListener(messageHandlerInMainThread);
v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);
ScriptProfiler::initialize();
}
static void reportFatalErrorInWorker(const char* location, const char* message)
{
// FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
CRASH();
}
static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
{
static bool isReportingException = false;
// Exceptions that occur in error handler should be ignored since in that case
// WorkerGlobalScope::reportException will send the exception to the worker object.
if (isReportingException)
return;
isReportingException = true;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// During the frame teardown, there may not be a valid context.
if (ExecutionContext* context = currentExecutionContext(isolate)) {
String errorMessage = toCoreString(message->Get());
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, sourceURL, message->GetScriptResourceName());
RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, DOMWrapperWorld::current(isolate));
AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, isolate);
context->reportException(event.release(), 0, corsStatus);
}
isReportingException = false;
}
static const int kWorkerMaxStackSize = 500 * 1024;
void V8Initializer::initializeWorker(v8::Isolate* isolate)
{
initializeV8Common(isolate);
v8::V8::AddMessageListener(messageHandlerInWorker);
v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);
v8::ResourceConstraints resourceConstraints;
uint32_t here;
resourceConstraints.set_stack_limit(&here - kWorkerMaxStackSize / sizeof(uint32_t*));
v8::SetResourceConstraints(isolate, &resourceConstraints);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>#include<unistd.h>
#include "../include/QueueLock.h"
QueueLock GlobalQueueLock;
void *thread_getlock_start(void *arg1)
{
GlobalQueueLock.GetLock();
cout<<"Lock acquired by"<<" "<<(char*)arg1<<endl;
usleep(1);
GlobalQueueLock.ReleaseLock();
}
int main()
{
int data_value = 5;
QueueLock lock1;
pthread_t tid1;
pthread_t tid2;
pthread_t tid3;
pthread_t tid4;
pthread_t tid5;
pthread_t tid6;
pthread_t tid7;
char name1[] = "thread1";
char name2[] = "thread2";
char name3[] = "thread3";
char name4[] = "thread4";
char name5[] = "thread5";
pthread_create(&tid1,NULL,thread_getlock_start,(void*)(name1));
pthread_create(&tid2,NULL,thread_getlock_start,(void*)(name2));
pthread_create(&tid3,NULL,thread_getlock_start,(void*)(name3));
pthread_create(&tid4,NULL,thread_getlock_start,(void*)(name4));
pthread_create(&tid5,NULL,thread_getlock_start,(void*)(name5));
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
pthread_join(tid5,NULL);
}
<commit_msg>CONCERTED-17:Update QueueLockTest to pass name as parameter<commit_after>#include<unistd.h>
#include "../include/QueueLock.h"
QueueLock GlobalQueueLock;
void *thread_getlock_start(void *arg1)
{
GlobalQueueLock.GetLock((char*)arg1);
cout<<"Lock acquired by"<<" "<<(char*)arg1<<endl;
usleep(1);
GlobalQueueLock.ReleaseLock((char*)arg1);
}
int main()
{
int data_value = 5;
QueueLock lock1;
pthread_t tid1;
pthread_t tid2;
pthread_t tid3;
pthread_t tid4;
pthread_t tid5;
pthread_t tid6;
pthread_t tid7;
char name1[] = "thread1";
char name2[] = "thread2";
char name3[] = "thread3";
char name4[] = "thread4";
char name5[] = "thread5";
pthread_create(&tid1,NULL,thread_getlock_start,(void*)(name1));
pthread_create(&tid2,NULL,thread_getlock_start,(void*)(name2));
pthread_create(&tid3,NULL,thread_getlock_start,(void*)(name3));
pthread_create(&tid4,NULL,thread_getlock_start,(void*)(name4));
pthread_create(&tid5,NULL,thread_getlock_start,(void*)(name5));
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
pthread_join(tid5,NULL);
}
<|endoftext|> |
<commit_before>#include <functional>
#include <future>
#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geos/geom/CoordinateArraySequence.h"
#include "geos/geom/LinearRing.h"
#include "geos/geom/Polygon.h"
#include "geos/geom/GeometryFactory.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
//#include "commandhandler.h"
#include "gridding.h"
using namespace Ilwis;
using namespace FeatureOperations;
Gridding::Gridding()
{
}
Gridding::Gridding(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}
bool Gridding::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx, symTable)) != sPREPARED)
return false;
for(int fx=0; fx < _xsize; ++fx) {
for(int fy=0; fy < _ysize; ++fy) {
Coordinate c1(_top + std::vector<double>{_cellXSize * fx, _cellYSize * fy });
Coordinate c2(_top +std::vector<double>{_cellXSize * (fx+1), _cellYSize * fy });
Coordinate c3(_top + std::vector<double>{_cellXSize * (fx+1), _cellYSize * (fy+1) });
Coordinate c4(_top + std::vector<double>{_cellXSize * fx, _cellYSize * (fy+1) });
geos::geom::CoordinateSequence *coords = new geos::geom::CoordinateArraySequence();
coords->add(c1);
coords->add(c2);
coords->add(c3);
coords->add(c4);
coords->add(c1);
geos::geom::LinearRing *outer = _outfeatures->geomfactory()->createLinearRing(coords);
geos::geom::Geometry *pol = _outfeatures->geomfactory()->createPolygon(outer, 0);
_outfeatures->newFeature(pol);
}
}
if ( ctx != 0) {
QVariant value;
value.setValue<IFeatureCoverage>(_outfeatures);
ctx->setOutput(symTable, value, _outfeatures->name(), itFEATURE,_outfeatures->source());
}
return true;
}
OperationImplementation *Gridding::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new Gridding(metaid, expr) ;
}
quint64 Gridding::createMetadata()
{
QString url = QString("ilwis://operations/gridding");
Resource resource(QUrl(url), itOPERATIONMETADATA);
resource.addProperty("namespace","ilwis");
resource.addProperty("longname","gridding");
resource.addProperty("syntax","gridding(coordinatesyste,top-coordinate,x-cell-size, y-cell-size, horizontal-cells, vertical-cells)");
resource.addProperty("description",TR("generates a new featurecoverage(polygons) were the polygons form a rectangular grid"));
resource.addProperty("inparameters","6");
resource.addProperty("pin_1_type", itCOORDSYSTEM);
resource.addProperty("pin_1_name", TR("coordinate-syste,"));
resource.addProperty("pin_1_desc",TR("The coordinate system of the to be created polygon coverage"));
resource.addProperty("pin_2_type", itCOORDINATE);
resource.addProperty("pin_2_name", TR("top corner"));
resource.addProperty("pin_2_desc",TR("The top corner of the polygonmap expressed in coordinates of the coordinate system"));
resource.addProperty("pin_3_type", itDOUBLE);
resource.addProperty("pin_3_name", TR("X cell size"));
resource.addProperty("pin_3_desc",TR("Size in the x direction of a cell in the grid expressed in untis of the coordinate system"));
resource.addProperty("pin_4_type", itDOUBLE);
resource.addProperty("pin_4_name", TR("Y cell size"));
resource.addProperty("pin_4_desc",TR("Size in the y direction of a cell in the grid expressed in untis of the coordinate system"));
resource.addProperty("pin_5_type", itINTEGER);
resource.addProperty("pin_5_name", TR("Horizontal cells"));
resource.addProperty("pin_5_desc",TR("Number of cells in the x directions"));
resource.addProperty("pin_6_type", itINTEGER);
resource.addProperty("pin_6_name", TR("Vertical cells"));
resource.addProperty("pin_6_desc",TR("Number of cells in the y directions"));
resource.addProperty("outparameters",1);
resource.addProperty("pout_1_type", itPOLYGON);
resource.addProperty("pout_1_name", TR("output polygon coverage"));
resource.addProperty("pout_1_desc",TR("output polygon coverage"));
resource.prepare();
url += "=" + QString::number(resource.id());
resource.setUrl(url);
mastercatalog()->addItems({resource});
return resource.id();
}
OperationImplementation::State Gridding::prepare(ExecutionContext *ctx, const SymbolTable &symTable)
{
QString csyName = _expression.parm(0).value();
if (!_csy.prepare(csyName)) {
ERROR2(ERR_COULD_NOT_LOAD_2,csyName,"" );
return sPREPAREFAILED;
}
QString name = _expression.parm(1).value();
QVariant var = symTable.getValue(name);
_top = var.value<Coordinate>();
if (!_top.isValid() || _top.is0()) {
_top = var.value<Coordinate>();
}
if (!_top.isValid() || _top.is0()) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value",name);
return sPREPAREFAILED;
}
bool ok;
_cellXSize = _expression.parm(2).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","3");
return sPREPAREFAILED;
}
_cellYSize = _expression.parm(3).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","4");
return sPREPAREFAILED;
}
_xsize = _expression.parm(4).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","5");
return sPREPAREFAILED;
}
_ysize = _expression.parm(5).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","6");
return sPREPAREFAILED;
}
QString outputName = _expression.parm(0,false).value();
Resource resource = outputName != sUNDEF ? Resource("ilwis://internalcatalog/" + outputName, itFLATTABLE) : Resource(itFLATTABLE);
_attTable.prepare(resource);
IDomain covdom;
if (!covdom.prepare("count")){
return sPREPAREFAILED;
}
_attTable->addColumn(FEATUREIDCOLUMN,covdom);
_outfeatures.prepare();
_outfeatures->setCoordinateSystem(_csy);
_outfeatures->attributeTable(_attTable);
Envelope env(_top, _top + std::vector<double>{_cellXSize * _xsize, _cellYSize * _ysize });
_outfeatures->envelope(env);
return sPREPARED;
}
<commit_msg>the setcoordinatesystem renamed to coordinatesystem( ...), this is consistent with the naming of other setters<commit_after>#include <functional>
#include <future>
#include "kernel.h"
#include "coverage.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geos/geom/CoordinateArraySequence.h"
#include "geos/geom/LinearRing.h"
#include "geos/geom/Polygon.h"
#include "geos/geom/GeometryFactory.h"
#include "feature.h"
#include "factory.h"
#include "abstractfactory.h"
#include "featurefactory.h"
#include "featurecoverage.h"
#include "featureiterator.h"
#include "symboltable.h"
#include "OperationExpression.h"
#include "operationmetadata.h"
#include "operation.h"
//#include "commandhandler.h"
#include "gridding.h"
using namespace Ilwis;
using namespace FeatureOperations;
Gridding::Gridding()
{
}
Gridding::Gridding(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}
bool Gridding::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx, symTable)) != sPREPARED)
return false;
for(int fx=0; fx < _xsize; ++fx) {
for(int fy=0; fy < _ysize; ++fy) {
Coordinate c1(_top + std::vector<double>{_cellXSize * fx, _cellYSize * fy });
Coordinate c2(_top +std::vector<double>{_cellXSize * (fx+1), _cellYSize * fy });
Coordinate c3(_top + std::vector<double>{_cellXSize * (fx+1), _cellYSize * (fy+1) });
Coordinate c4(_top + std::vector<double>{_cellXSize * fx, _cellYSize * (fy+1) });
geos::geom::CoordinateSequence *coords = new geos::geom::CoordinateArraySequence();
coords->add(c1);
coords->add(c2);
coords->add(c3);
coords->add(c4);
coords->add(c1);
geos::geom::LinearRing *outer = _outfeatures->geomfactory()->createLinearRing(coords);
geos::geom::Geometry *pol = _outfeatures->geomfactory()->createPolygon(outer, 0);
_outfeatures->newFeature(pol);
}
}
if ( ctx != 0) {
QVariant value;
value.setValue<IFeatureCoverage>(_outfeatures);
ctx->setOutput(symTable, value, _outfeatures->name(), itFEATURE,_outfeatures->source());
}
return true;
}
OperationImplementation *Gridding::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new Gridding(metaid, expr) ;
}
quint64 Gridding::createMetadata()
{
QString url = QString("ilwis://operations/gridding");
Resource resource(QUrl(url), itOPERATIONMETADATA);
resource.addProperty("namespace","ilwis");
resource.addProperty("longname","gridding");
resource.addProperty("syntax","gridding(coordinatesyste,top-coordinate,x-cell-size, y-cell-size, horizontal-cells, vertical-cells)");
resource.addProperty("description",TR("generates a new featurecoverage(polygons) were the polygons form a rectangular grid"));
resource.addProperty("inparameters","6");
resource.addProperty("pin_1_type", itCOORDSYSTEM);
resource.addProperty("pin_1_name", TR("coordinate-syste,"));
resource.addProperty("pin_1_desc",TR("The coordinate system of the to be created polygon coverage"));
resource.addProperty("pin_2_type", itCOORDINATE);
resource.addProperty("pin_2_name", TR("top corner"));
resource.addProperty("pin_2_desc",TR("The top corner of the polygonmap expressed in coordinates of the coordinate system"));
resource.addProperty("pin_3_type", itDOUBLE);
resource.addProperty("pin_3_name", TR("X cell size"));
resource.addProperty("pin_3_desc",TR("Size in the x direction of a cell in the grid expressed in untis of the coordinate system"));
resource.addProperty("pin_4_type", itDOUBLE);
resource.addProperty("pin_4_name", TR("Y cell size"));
resource.addProperty("pin_4_desc",TR("Size in the y direction of a cell in the grid expressed in untis of the coordinate system"));
resource.addProperty("pin_5_type", itINTEGER);
resource.addProperty("pin_5_name", TR("Horizontal cells"));
resource.addProperty("pin_5_desc",TR("Number of cells in the x directions"));
resource.addProperty("pin_6_type", itINTEGER);
resource.addProperty("pin_6_name", TR("Vertical cells"));
resource.addProperty("pin_6_desc",TR("Number of cells in the y directions"));
resource.addProperty("outparameters",1);
resource.addProperty("pout_1_type", itPOLYGON);
resource.addProperty("pout_1_name", TR("output polygon coverage"));
resource.addProperty("pout_1_desc",TR("output polygon coverage"));
resource.prepare();
url += "=" + QString::number(resource.id());
resource.setUrl(url);
mastercatalog()->addItems({resource});
return resource.id();
}
OperationImplementation::State Gridding::prepare(ExecutionContext *ctx, const SymbolTable &symTable)
{
QString csyName = _expression.parm(0).value();
if (!_csy.prepare(csyName)) {
ERROR2(ERR_COULD_NOT_LOAD_2,csyName,"" );
return sPREPAREFAILED;
}
QString name = _expression.parm(1).value();
QVariant var = symTable.getValue(name);
_top = var.value<Coordinate>();
if (!_top.isValid() || _top.is0()) {
_top = var.value<Coordinate>();
}
if (!_top.isValid() || _top.is0()) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value",name);
return sPREPAREFAILED;
}
bool ok;
_cellXSize = _expression.parm(2).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","3");
return sPREPAREFAILED;
}
_cellYSize = _expression.parm(3).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","4");
return sPREPAREFAILED;
}
_xsize = _expression.parm(4).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","5");
return sPREPAREFAILED;
}
_ysize = _expression.parm(5).value().toDouble(&ok);
if ( !ok ) {
ERROR2(ERR_ILLEGAL_VALUE_2,"parameter value","6");
return sPREPAREFAILED;
}
QString outputName = _expression.parm(0,false).value();
Resource resource = outputName != sUNDEF ? Resource("ilwis://internalcatalog/" + outputName, itFLATTABLE) : Resource(itFLATTABLE);
_attTable.prepare(resource);
IDomain covdom;
if (!covdom.prepare("count")){
return sPREPAREFAILED;
}
_attTable->addColumn(FEATUREIDCOLUMN,covdom);
_outfeatures.prepare();
_outfeatures->coordinateSystem(_csy);
_outfeatures->attributeTable(_attTable);
Envelope env(_top, _top + std::vector<double>{_cellXSize * _xsize, _cellYSize * _ysize });
_outfeatures->envelope(env);
return sPREPARED;
}
<|endoftext|> |
<commit_before><commit_msg>WaE: pesky gcc 4.0.1<commit_after><|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "gtest/gtest.h"
#include "Common.h"
#include "Statistics.h"
//////////////////////////////// StatsWindow /////////////////////////////////
TEST(StatsWindow, clear) {
int windowSize = 60;
for (int j = 0; j < 10; j++) {
StatsWindow<int64> sw(windowSize);
ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0);
int64 val = 3;
for (int i = 0; i < windowSize; i++) {
sw.insert(i, val);
}
ASSERT_EQ(sw.sum(windowSize - 1, windowSize), windowSize * val);
sw.clear();
ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0);
}
}
TEST(StatsWindow, sum01) {
int windowSize = 60;
StatsWindow<int64> sw(windowSize);
int64 val = 5;
for (int i = 0; i < windowSize; i++) {
sw.insert(i, val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(i, 1), val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(windowSize - 1, i), i * val);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, 1), 0);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val);
}
for (int i = windowSize*2; i < windowSize*3; i++) {
ASSERT_EQ(sw.sum(i, windowSize), 0);
}
}
TEST(StatsWindow, sum02) {
int windowSize = 60;
StatsWindow<int64> sw(windowSize);
int64 val = 5;
for (int i = windowSize - 1; i >= 0; i--) {
sw.insert(i, val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(i, 1), val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(windowSize - 1, i), i * val);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, 1), 0);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val);
}
for (int i = windowSize*2; i < windowSize*3; i++) {
ASSERT_EQ(sw.sum(i, windowSize), 0);
}
}
TEST(StatsWindow, sum03) {
StatsWindow<int64> sw(5);
sw.insert(0, 1);
ASSERT_EQ(sw.sum(0, 1), 1);
sw.clear();
ASSERT_EQ(sw.sum(0, 1), 0);
sw.insert(0, 1);
sw.insert(5, 5);
ASSERT_EQ(sw.sum(5, 1), 5);
ASSERT_EQ(sw.sum(5, 5), 5);
sw.clear();
sw.insert(0, 1);
sw.insert(1, 2);
sw.insert(2, 3);
sw.insert(3, 4);
sw.insert(4, 5);
ASSERT_EQ(sw.sum(4, 1), 5);
ASSERT_EQ(sw.sum(4, 2), 9);
ASSERT_EQ(sw.sum(4, 3), 12);
ASSERT_EQ(sw.sum(4, 4), 14);
ASSERT_EQ(sw.sum(4, 5), 15);
sw.insert(8, 9);
ASSERT_EQ(sw.sum(8, 5), 14);
sw.insert(7, 8);
ASSERT_EQ(sw.sum(8, 5), 22);
sw.insert(6, 7);
ASSERT_EQ(sw.sum(8, 5), 29);
sw.insert(5, 6);
ASSERT_EQ(sw.sum(8, 5), 35);
}
TEST(StatsWindow, map) {
int windowSize = 10;
StatsWindow<int64> sw(windowSize);
for (int i = 0; i < windowSize; i++) {
sw.insert(i, i * 2);
}
ASSERT_EQ(sw.sum(windowSize-1), sw.sum(windowSize-1, windowSize));
int64 sum = sw.sum(windowSize-1, windowSize);
sw.mapDivide(2);
int64 sum2 = sw.sum(windowSize-1, windowSize);
ASSERT_EQ(sum/2, sum2);
sw.mapMultiply(2);
int64 sum3 = sw.sum(windowSize-1, windowSize);
ASSERT_EQ(sum, sum3);
}
//////////////////////////////// ShareStatsDay ///////////////////////////////
TEST(ShareStatsDay, ShareStatsDay) {
// using mainnet
SelectParams(CBaseChainParams::MAIN);
// 1
{
ShareStatsDay stats;
Share share;
share.height_ = 504031;
share.result_ = Share::ACCEPT;
uint64_t shareValue = 1ll;
// share -> socre = 1 : 1
// https://btc.com/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
share.blkBits_ = 0x1d00ffffu;
// accept
for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23]
share.share_ = shareValue;
stats.processShare(i, share);
}
// reject
share.result_ = Share::REJECT;
for (uint32_t i = 0; i < 24; i++) {
share.share_ = shareValue;
stats.processShare(i, share);
}
ShareStats ss;
for (uint32_t i = 0; i < 24; i++) {
stats.getShareStatsHour(i, &ss);
ASSERT_EQ(ss.shareAccept_, shareValue);
ASSERT_EQ(ss.shareReject_, shareValue);
ASSERT_EQ(ss.earn_, 1 * BLOCK_REWARD);
}
stats.getShareStatsDay(&ss);
ASSERT_EQ(ss.shareAccept_, shareValue * 24);
ASSERT_EQ(ss.shareReject_, shareValue * 24);
ASSERT_EQ(ss.earn_, 1 * 24 * BLOCK_REWARD);
}
// UINT32_MAX
{
ShareStatsDay stats;
Share share;
share.height_ = 504031;
share.result_ = Share::ACCEPT;
uint64_t shareValue = UINT32_MAX;
// share -> socre = UINT32_MAX : 0.0197582875516673
// https://btc.com/00000000000000000015f613f161b431acc6bbcb34533d2ca47d3cde4ec58b76
share.blkBits_ = 0x18050edcu;
// accept
for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23]
share.share_ = shareValue;
stats.processShare(i, share);
// LOG(INFO) << score2Str(share.score());
}
// reject
share.result_ = Share::REJECT;
for (uint32_t i = 0; i < 24; i++) {
share.share_ = shareValue;
stats.processShare(i, share);
}
ShareStats ss;
for (uint32_t i = 0; i < 24; i++) {
stats.getShareStatsHour(i, &ss);
ASSERT_EQ(ss.shareAccept_, shareValue);
ASSERT_EQ(ss.shareReject_, shareValue);
ASSERT_EQ(ss.earn_, 24697859); // satoshi
}
stats.getShareStatsDay(&ss);
ASSERT_EQ(ss.shareAccept_, shareValue * 24);
ASSERT_EQ(ss.shareReject_, shareValue * 24);
ASSERT_EQ(ss.earn_, 592748626); // satoshi
}
}
<commit_msg>fix testutil build failure.<commit_after>/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "gtest/gtest.h"
#include "Common.h"
#include "Statistics.h"
#include "BitcoinUtils.h"
//////////////////////////////// StatsWindow /////////////////////////////////
TEST(StatsWindow, clear) {
int windowSize = 60;
for (int j = 0; j < 10; j++) {
StatsWindow<int64> sw(windowSize);
ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0);
int64 val = 3;
for (int i = 0; i < windowSize; i++) {
sw.insert(i, val);
}
ASSERT_EQ(sw.sum(windowSize - 1, windowSize), windowSize * val);
sw.clear();
ASSERT_EQ(sw.sum(windowSize - 1, windowSize), 0);
}
}
TEST(StatsWindow, sum01) {
int windowSize = 60;
StatsWindow<int64> sw(windowSize);
int64 val = 5;
for (int i = 0; i < windowSize; i++) {
sw.insert(i, val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(i, 1), val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(windowSize - 1, i), i * val);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, 1), 0);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val);
}
for (int i = windowSize*2; i < windowSize*3; i++) {
ASSERT_EQ(sw.sum(i, windowSize), 0);
}
}
TEST(StatsWindow, sum02) {
int windowSize = 60;
StatsWindow<int64> sw(windowSize);
int64 val = 5;
for (int i = windowSize - 1; i >= 0; i--) {
sw.insert(i, val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(i, 1), val);
}
for (int i = 0; i < windowSize; i++) {
ASSERT_EQ(sw.sum(windowSize - 1, i), i * val);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, 1), 0);
}
for (int i = windowSize; i < windowSize*2; i++) {
ASSERT_EQ(sw.sum(i, windowSize), (windowSize - (i % windowSize + 1)) * val);
}
for (int i = windowSize*2; i < windowSize*3; i++) {
ASSERT_EQ(sw.sum(i, windowSize), 0);
}
}
TEST(StatsWindow, sum03) {
StatsWindow<int64> sw(5);
sw.insert(0, 1);
ASSERT_EQ(sw.sum(0, 1), 1);
sw.clear();
ASSERT_EQ(sw.sum(0, 1), 0);
sw.insert(0, 1);
sw.insert(5, 5);
ASSERT_EQ(sw.sum(5, 1), 5);
ASSERT_EQ(sw.sum(5, 5), 5);
sw.clear();
sw.insert(0, 1);
sw.insert(1, 2);
sw.insert(2, 3);
sw.insert(3, 4);
sw.insert(4, 5);
ASSERT_EQ(sw.sum(4, 1), 5);
ASSERT_EQ(sw.sum(4, 2), 9);
ASSERT_EQ(sw.sum(4, 3), 12);
ASSERT_EQ(sw.sum(4, 4), 14);
ASSERT_EQ(sw.sum(4, 5), 15);
sw.insert(8, 9);
ASSERT_EQ(sw.sum(8, 5), 14);
sw.insert(7, 8);
ASSERT_EQ(sw.sum(8, 5), 22);
sw.insert(6, 7);
ASSERT_EQ(sw.sum(8, 5), 29);
sw.insert(5, 6);
ASSERT_EQ(sw.sum(8, 5), 35);
}
TEST(StatsWindow, map) {
int windowSize = 10;
StatsWindow<int64> sw(windowSize);
for (int i = 0; i < windowSize; i++) {
sw.insert(i, i * 2);
}
ASSERT_EQ(sw.sum(windowSize-1), sw.sum(windowSize-1, windowSize));
int64 sum = sw.sum(windowSize-1, windowSize);
sw.mapDivide(2);
int64 sum2 = sw.sum(windowSize-1, windowSize);
ASSERT_EQ(sum/2, sum2);
sw.mapMultiply(2);
int64 sum3 = sw.sum(windowSize-1, windowSize);
ASSERT_EQ(sum, sum3);
}
//////////////////////////////// ShareStatsDay ///////////////////////////////
TEST(ShareStatsDay, ShareStatsDay) {
// using mainnet
SelectParams(CBaseChainParams::MAIN);
// 1
{
ShareStatsDay stats;
Share share;
share.height_ = 504031;
share.result_ = Share::ACCEPT;
uint64_t shareValue = 1ll;
auto reward = GetBlockSubsidy(share.height_, Params().GetConsensus());
// share -> socre = 1 : 1
// https://btc.com/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
share.blkBits_ = 0x1d00ffffu;
// accept
for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23]
share.share_ = shareValue;
stats.processShare(i, share);
}
// reject
share.result_ = Share::REJECT;
for (uint32_t i = 0; i < 24; i++) {
share.share_ = shareValue;
stats.processShare(i, share);
}
ShareStats ss;
for (uint32_t i = 0; i < 24; i++) {
stats.getShareStatsHour(i, &ss);
ASSERT_EQ(ss.shareAccept_, shareValue);
ASSERT_EQ(ss.shareReject_, shareValue);
ASSERT_EQ(ss.earn_, 1 * reward);
}
stats.getShareStatsDay(&ss);
ASSERT_EQ(ss.shareAccept_, shareValue * 24);
ASSERT_EQ(ss.shareReject_, shareValue * 24);
ASSERT_EQ(ss.earn_, 1 * 24 * reward);
}
// UINT32_MAX
{
ShareStatsDay stats;
Share share;
share.height_ = 504031;
share.result_ = Share::ACCEPT;
uint64_t shareValue = UINT32_MAX;
// share -> socre = UINT32_MAX : 0.0197582875516673
// https://btc.com/00000000000000000015f613f161b431acc6bbcb34533d2ca47d3cde4ec58b76
share.blkBits_ = 0x18050edcu;
// accept
for (uint32_t i = 0; i < 24; i++) { // hour idx range: [0, 23]
share.share_ = shareValue;
stats.processShare(i, share);
// LOG(INFO) << score2Str(share.score());
}
// reject
share.result_ = Share::REJECT;
for (uint32_t i = 0; i < 24; i++) {
share.share_ = shareValue;
stats.processShare(i, share);
}
ShareStats ss;
for (uint32_t i = 0; i < 24; i++) {
stats.getShareStatsHour(i, &ss);
ASSERT_EQ(ss.shareAccept_, shareValue);
ASSERT_EQ(ss.shareReject_, shareValue);
ASSERT_EQ(ss.earn_, 24697859); // satoshi
}
stats.getShareStatsDay(&ss);
ASSERT_EQ(ss.shareAccept_, shareValue * 24);
ASSERT_EQ(ss.shareReject_, shareValue * 24);
ASSERT_EQ(ss.earn_, 592748626); // satoshi
}
}
<|endoftext|> |
<commit_before>#include "tagview.h"
using namespace AhoViewer::Booru;
#include "settings.h"
// {{{ Favorite Icons
/**
* These icons are from http://raphaeljs.com/icons
*
* Copyright © 2008 Dmitry Baranovskiy
*
* 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.
**/
const std::string TagView::StarSVG = "<?xml version=\"1.0\" standalone=\"no\"?>\
<svg width=\"16px\" height=\"16px\" viewBox=\"-2 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\
<path fill=\"%1\" d=\"M22.441,28.181c-0.419,0-0.835-0.132-1.189-0.392l-5.751-4.247L9.75,\
27.789c-0.354,0.26-0.771,0.392-1.189,0.392c-0.412,\
0-0.824-0.128-1.175-0.384c-0.707-0.511-1-1.422-0.723-2.25l2.26-6.783l-5.815-4.158c-0.71-0.509-1.009-1.416-0.74-2.246c0.268-0.826,\
1.037-1.382,1.904-1.382c0.004,0,0.01,0,0.014,0l7.15,0.056l2.157-6.816c0.262-0.831,1.035-1.397,\
1.906-1.397s1.645,0.566,1.906,1.397l2.155,6.816l7.15-0.056c0.004,0,\
0.01,0,0.015,0c0.867,0,1.636,0.556,1.903,1.382c0.271,0.831-0.028,\
1.737-0.739,2.246l-5.815,4.158l2.263,6.783c0.276,0.826-0.017,1.737-0.721,\
2.25C23.268,28.053,22.854,28.181,22.441,28.181L22.441,28.181z\"/>\
</svg>";
const std::string TagView::StarOutlineSVG = "<?xml version=\"1.0\" standalone=\"no\"?>\
<svg width=\"16px\" height=\"16px\" viewBox=\"-2 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\
<path fill=\"%1\" d=\"M28.631,12.359c-0.268-0.826-1.036-1.382-1.903-1.382h-0.015l-7.15,\
0.056l-2.155-6.816c-0.262-0.831-1.035-1.397-1.906-1.397s-1.645,0.566-1.906,1.397l-2.157,\
6.816l-7.15-0.056H4.273c-0.868,0-1.636,0.556-1.904,1.382c-0.27,0.831,0.029,1.737,0.74,\
2.246l5.815,4.158l-2.26,6.783c-0.276,0.828,0.017,1.739,0.723,2.25c0.351,0.256,0.763,0.384,\
1.175,0.384c0.418,0,0.834-0.132,1.189-0.392l5.751-4.247l5.751,4.247c0.354,0.26,0.771,0.392,\
1.189,0.392c0.412,0,0.826-0.128,1.177-0.384c0.704-0.513,0.997-1.424,\
0.721-2.25l-2.263-6.783l5.815-4.158C28.603,14.097,28.901,13.19,28.631,12.359zM19.712,\
17.996l2.729,8.184l-6.94-5.125L8.56,26.18l2.729-8.184l-7.019-5.018l8.627,0.066L15.5,\
4.82l2.603,8.225l8.627-0.066L19.712,17.996z\"/>\
</svg>";
// }}}
TagView::TagView(BaseObjectType *cobj, const Glib::RefPtr<Gtk::Builder> &bldr)
: Gtk::TreeView(cobj)
{
bldr->get_widget_derived("Booru::Browser::TagEntry", m_TagEntry);
m_ListStore = Gtk::ListStore::create(m_Columns);
set_model(m_ListStore);
Gtk::CellRendererPixbuf *fcell = Gtk::manage(new Gtk::CellRendererPixbuf());
append_column("Favorite", *fcell);
Gtk::CellRendererToggle *cell = Gtk::manage(new Gtk::CellRendererToggle());
append_column("Toggle", *cell);
append_column("Tag", m_Columns.tag);
get_column(0)->set_cell_data_func(*fcell, sigc::mem_fun(*this, &TagView::on_favorite_cell_data));
get_column(1)->set_cell_data_func(*cell, sigc::mem_fun(*this, &TagView::on_toggle_cell_data));
m_FavoriteTags = &Settings.get_favorite_tags();
show_favorite_tags();
}
void TagView::set_tags(const std::set<std::string> &tags)
{
clear();
for (const std::string &tag : tags)
m_ListStore->append()->set_value(m_Columns.tag, tag);
}
void TagView::on_style_changed(const Glib::RefPtr<Gtk::Style> &s)
{
Gtk::TreeView::on_style_changed(s);
m_PrevColor = m_Color;
m_Color = get_style()->get_bg(Gtk::STATE_SELECTED);
if (m_PrevColor != m_Color)
update_favorite_icons();
}
bool TagView::on_button_press_event(GdkEventButton *e)
{
if (e->button == 1)
{
Gtk::TreePath path;
get_path_at_pos(e->x, e->y, path);
if (path)
{
std::string tag = m_ListStore->get_iter(path)->get_value(m_Columns.tag);
// The favorite column was clicked
if (e->x < get_column(0)->get_width())
{
if (m_FavoriteTags->find(tag) != m_FavoriteTags->end())
Settings.remove_favorite_tag(tag);
else
Settings.add_favorite_tag(tag);
}
else
{
// Open tag alone in new tab
if ((e->state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK)
{
m_SignalNewTabTag(tag);
}
else
{
std::istringstream ss(m_TagEntry->get_text());
std::set<std::string> tags = { std::istream_iterator<std::string>(ss),
std::istream_iterator<std::string>() };
if (tags.find(tag) != tags.end())
tags.erase(tag);
else
tags.insert(tags.end(), tag);
std::ostringstream oss;
std::copy(tags.begin(), tags.end(), std::ostream_iterator<std::string>(oss, " "));
m_TagEntry->set_text(oss.str());
}
}
queue_draw();
}
}
return true;
}
void TagView::on_favorite_cell_data(Gtk::CellRenderer *c, const Gtk::TreeIter &iter)
{
Gtk::CellRendererPixbuf *cell = static_cast<Gtk::CellRendererPixbuf*>(c);
std::string tag = iter->get_value(m_Columns.tag);
if (m_FavoriteTags->find(tag) != m_FavoriteTags->end())
cell->property_pixbuf().set_value(m_StarPixbuf);
else
cell->property_pixbuf().set_value(m_StarOutlinePixbuf);
}
void TagView::on_toggle_cell_data(Gtk::CellRenderer *c, const Gtk::TreeIter &iter)
{
Gtk::CellRendererToggle *cell = static_cast<Gtk::CellRendererToggle*>(c);
std::istringstream ss(m_TagEntry->get_text());
std::set<std::string> tags = { std::istream_iterator<std::string>(ss),
std::istream_iterator<std::string>() };
std::string tag = iter->get_value(m_Columns.tag);
cell->set_active(std::find(tags.begin(), tags.end(), tag) != tags.end());
}
void TagView::update_favorite_icons()
{
Glib::RefPtr<Gdk::PixbufLoader> loader;
Glib::ustring vgdata;
gchar *color = g_strdup_printf("#%02x%02x%02x", (m_Color.get_red() >> 8) & 0xff,
(m_Color.get_green() >> 8) & 0xff,
(m_Color.get_blue() >> 8) & 0xff);
loader = Gdk::PixbufLoader::create("svg");
vgdata = Glib::ustring::compose(StarSVG, color);
loader->write(reinterpret_cast<const unsigned char*>(vgdata.c_str()), vgdata.size());
loader->close();
m_StarPixbuf = loader->get_pixbuf();
loader = Gdk::PixbufLoader::create("svg");
vgdata = Glib::ustring::compose(StarOutlineSVG, color);
loader->write(reinterpret_cast<const unsigned char*>(vgdata.c_str()), vgdata.size());
loader->close();
m_StarOutlinePixbuf = loader->get_pixbuf();
g_free(color);
}
<commit_msg>booru/tagview: Move cursor to end of entry after adding/removing tag<commit_after>#include "tagview.h"
using namespace AhoViewer::Booru;
#include "settings.h"
// {{{ Favorite Icons
/**
* These icons are from http://raphaeljs.com/icons
*
* Copyright © 2008 Dmitry Baranovskiy
*
* 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.
**/
const std::string TagView::StarSVG = "<?xml version=\"1.0\" standalone=\"no\"?>\
<svg width=\"16px\" height=\"16px\" viewBox=\"-2 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\
<path fill=\"%1\" d=\"M22.441,28.181c-0.419,0-0.835-0.132-1.189-0.392l-5.751-4.247L9.75,\
27.789c-0.354,0.26-0.771,0.392-1.189,0.392c-0.412,\
0-0.824-0.128-1.175-0.384c-0.707-0.511-1-1.422-0.723-2.25l2.26-6.783l-5.815-4.158c-0.71-0.509-1.009-1.416-0.74-2.246c0.268-0.826,\
1.037-1.382,1.904-1.382c0.004,0,0.01,0,0.014,0l7.15,0.056l2.157-6.816c0.262-0.831,1.035-1.397,\
1.906-1.397s1.645,0.566,1.906,1.397l2.155,6.816l7.15-0.056c0.004,0,\
0.01,0,0.015,0c0.867,0,1.636,0.556,1.903,1.382c0.271,0.831-0.028,\
1.737-0.739,2.246l-5.815,4.158l2.263,6.783c0.276,0.826-0.017,1.737-0.721,\
2.25C23.268,28.053,22.854,28.181,22.441,28.181L22.441,28.181z\"/>\
</svg>";
const std::string TagView::StarOutlineSVG = "<?xml version=\"1.0\" standalone=\"no\"?>\
<svg width=\"16px\" height=\"16px\" viewBox=\"-2 0 32 32\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\
<path fill=\"%1\" d=\"M28.631,12.359c-0.268-0.826-1.036-1.382-1.903-1.382h-0.015l-7.15,\
0.056l-2.155-6.816c-0.262-0.831-1.035-1.397-1.906-1.397s-1.645,0.566-1.906,1.397l-2.157,\
6.816l-7.15-0.056H4.273c-0.868,0-1.636,0.556-1.904,1.382c-0.27,0.831,0.029,1.737,0.74,\
2.246l5.815,4.158l-2.26,6.783c-0.276,0.828,0.017,1.739,0.723,2.25c0.351,0.256,0.763,0.384,\
1.175,0.384c0.418,0,0.834-0.132,1.189-0.392l5.751-4.247l5.751,4.247c0.354,0.26,0.771,0.392,\
1.189,0.392c0.412,0,0.826-0.128,1.177-0.384c0.704-0.513,0.997-1.424,\
0.721-2.25l-2.263-6.783l5.815-4.158C28.603,14.097,28.901,13.19,28.631,12.359zM19.712,\
17.996l2.729,8.184l-6.94-5.125L8.56,26.18l2.729-8.184l-7.019-5.018l8.627,0.066L15.5,\
4.82l2.603,8.225l8.627-0.066L19.712,17.996z\"/>\
</svg>";
// }}}
TagView::TagView(BaseObjectType *cobj, const Glib::RefPtr<Gtk::Builder> &bldr)
: Gtk::TreeView(cobj)
{
bldr->get_widget_derived("Booru::Browser::TagEntry", m_TagEntry);
m_ListStore = Gtk::ListStore::create(m_Columns);
set_model(m_ListStore);
Gtk::CellRendererPixbuf *fcell = Gtk::manage(new Gtk::CellRendererPixbuf());
append_column("Favorite", *fcell);
Gtk::CellRendererToggle *cell = Gtk::manage(new Gtk::CellRendererToggle());
append_column("Toggle", *cell);
append_column("Tag", m_Columns.tag);
get_column(0)->set_cell_data_func(*fcell, sigc::mem_fun(*this, &TagView::on_favorite_cell_data));
get_column(1)->set_cell_data_func(*cell, sigc::mem_fun(*this, &TagView::on_toggle_cell_data));
m_FavoriteTags = &Settings.get_favorite_tags();
show_favorite_tags();
}
void TagView::set_tags(const std::set<std::string> &tags)
{
clear();
for (const std::string &tag : tags)
m_ListStore->append()->set_value(m_Columns.tag, tag);
}
void TagView::on_style_changed(const Glib::RefPtr<Gtk::Style> &s)
{
Gtk::TreeView::on_style_changed(s);
m_PrevColor = m_Color;
m_Color = get_style()->get_bg(Gtk::STATE_SELECTED);
if (m_PrevColor != m_Color)
update_favorite_icons();
}
bool TagView::on_button_press_event(GdkEventButton *e)
{
if (e->button == 1)
{
Gtk::TreePath path;
get_path_at_pos(e->x, e->y, path);
if (path)
{
std::string tag = m_ListStore->get_iter(path)->get_value(m_Columns.tag);
// The favorite column was clicked
if (e->x < get_column(0)->get_width())
{
if (m_FavoriteTags->find(tag) != m_FavoriteTags->end())
Settings.remove_favorite_tag(tag);
else
Settings.add_favorite_tag(tag);
}
else
{
// Open tag alone in new tab
if ((e->state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK)
{
m_SignalNewTabTag(tag);
}
else
{
std::istringstream ss(m_TagEntry->get_text());
std::set<std::string> tags = { std::istream_iterator<std::string>(ss),
std::istream_iterator<std::string>() };
if (tags.find(tag) != tags.end())
tags.erase(tag);
else
tags.insert(tags.end(), tag);
std::ostringstream oss;
std::copy(tags.begin(), tags.end(), std::ostream_iterator<std::string>(oss, " "));
m_TagEntry->set_text(oss.str());
m_TagEntry->set_position(-1);
}
}
queue_draw();
}
}
return true;
}
void TagView::on_favorite_cell_data(Gtk::CellRenderer *c, const Gtk::TreeIter &iter)
{
Gtk::CellRendererPixbuf *cell = static_cast<Gtk::CellRendererPixbuf*>(c);
std::string tag = iter->get_value(m_Columns.tag);
if (m_FavoriteTags->find(tag) != m_FavoriteTags->end())
cell->property_pixbuf().set_value(m_StarPixbuf);
else
cell->property_pixbuf().set_value(m_StarOutlinePixbuf);
}
void TagView::on_toggle_cell_data(Gtk::CellRenderer *c, const Gtk::TreeIter &iter)
{
Gtk::CellRendererToggle *cell = static_cast<Gtk::CellRendererToggle*>(c);
std::istringstream ss(m_TagEntry->get_text());
std::set<std::string> tags = { std::istream_iterator<std::string>(ss),
std::istream_iterator<std::string>() };
std::string tag = iter->get_value(m_Columns.tag);
cell->set_active(std::find(tags.begin(), tags.end(), tag) != tags.end());
}
void TagView::update_favorite_icons()
{
Glib::RefPtr<Gdk::PixbufLoader> loader;
Glib::ustring vgdata;
gchar *color = g_strdup_printf("#%02x%02x%02x", (m_Color.get_red() >> 8) & 0xff,
(m_Color.get_green() >> 8) & 0xff,
(m_Color.get_blue() >> 8) & 0xff);
loader = Gdk::PixbufLoader::create("svg");
vgdata = Glib::ustring::compose(StarSVG, color);
loader->write(reinterpret_cast<const unsigned char*>(vgdata.c_str()), vgdata.size());
loader->close();
m_StarPixbuf = loader->get_pixbuf();
loader = Gdk::PixbufLoader::create("svg");
vgdata = Glib::ustring::compose(StarOutlineSVG, color);
loader->write(reinterpret_cast<const unsigned char*>(vgdata.c_str()), vgdata.size());
loader->close();
m_StarOutlinePixbuf = loader->get_pixbuf();
g_free(color);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "builtin_extra.hh"
#include "lisp_ptr.hh"
#include "vm.hh"
#include "procedure.hh"
#include "s_closure.hh"
#include "util.hh"
#include "eval.hh"
#include "env.hh"
#include "equality.hh"
#include "builtin.hh"
#include "zs_error.hh"
#include "cons_util.hh"
#include "reader.hh"
#include "printer.hh"
#include "zs_memory.hh"
#ifdef _POSIX_C_SOURCE
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#endif
using namespace std;
using namespace proc_flag;
namespace builtin {
// used for interacting between 'exit' and 'hard-repl'
static bool hard_repl_continue = true;
Lisp_ptr traditional_transformer(ZsArgs args){
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw builtin_type_check_failed(nullptr, Ptr_tag::i_procedure, args[0]);
}
auto info = *iproc->info();
info.passing = Passing::quote;
info.returning = Returning::code;
return zs_new<IProcedure>(iproc->get(), info,
iproc->arg_list(), iproc->closure(), Lisp_ptr{});
}
Lisp_ptr gensym(ZsArgs){
static const string gensym_symname = {"(gensym)"};
return {zs_new<Symbol>(&gensym_symname)};
}
Lisp_ptr sc_macro_transformer(ZsArgs args){
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw builtin_type_check_failed(nullptr, Ptr_tag::i_procedure, args[0]);
}
auto info = *iproc->info();
if(info.required_args != 2 || info.max_args != 2){
throw zs_error_arg1(nullptr,
printf_string("procedure must take exactly 2 args (this takes %d-%d))",
info.required_args, info.max_args));
}
info.passing = Passing::whole;
info.returning = Returning::code;
info.leaving = Leaving::after_returning_op;
return zs_new<IProcedure>(iproc->get(), info,
iproc->arg_list(),
iproc->closure()->fork(), Lisp_ptr{});
}
Lisp_ptr make_syntactic_closure(ZsArgs args){
Env* e = args[0].get<Env*>();
if(!e){
throw builtin_type_check_failed(nullptr, Ptr_tag::env, args[0]);
}
if(args[1].tag() != Ptr_tag::cons){
throw builtin_type_check_failed(nullptr, Ptr_tag::cons, args[1]);
}
Cons* c = args[1].get<Cons*>();
return zs_new<SyntacticClosure>(e, c, args[2]);
}
Lisp_ptr capture_syntactic_environment(ZsArgs args){
if(args[0].tag() != Ptr_tag::i_procedure){
throw builtin_type_check_failed(nullptr, Ptr_tag::i_procedure, args[0]);
}
auto iproc = args[0].get<IProcedure*>();
assert(iproc && iproc->info());
if(iproc->info()->required_args != 1){
throw zs_error_arg1(nullptr,
printf_string("first arg must take exactly 1 arg (take %d)",
iproc->info()->required_args));
}
auto ret = make_cons_list
({find_builtin_nproc("eval"),
make_cons_list({find_builtin_nproc("apply"), iproc, vm_op_get_current_env}),
vm_op_get_current_env});
return ret;
}
Lisp_ptr identifierp(ZsArgs args){
return Lisp_ptr{identifierp(args[0])};
}
Lisp_ptr identifier_eq(ZsArgs args){
auto ident1_env = args[0].get<Env*>();
if(!ident1_env){
throw builtin_type_check_failed(nullptr, Ptr_tag::env, args[0]);
}
if(!identifierp(args[1])){
throw builtin_identifier_check_failed(nullptr, args[1]);
}
auto ident2_env = args[2].get<Env*>();
if(!ident2_env){
throw builtin_type_check_failed(nullptr, Ptr_tag::env, args[2]);
}
if(!identifierp(args[3])){
throw builtin_identifier_check_failed(nullptr, args[3]);
}
return
Lisp_ptr{identifier_eq(ident1_env, args[1], ident2_env, args[3])};
}
Lisp_ptr make_synthetic_identifier(ZsArgs args){
if(!identifierp(args[0])){
throw builtin_identifier_check_failed(nullptr, args[0]);
}
return zs_new<SyntacticClosure>(zs_new<Env>(nullptr), Cons::NIL, args[0]);
}
Lisp_ptr exit(ZsArgs args){
// cerr << "exiting..\n";
args.cleanup();
vm.stack.clear();
vm.code.clear();
hard_repl_continue = false;
return Lisp_ptr{true};
}
Lisp_ptr transcript_on(ZsArgs){
dump_mode = true;
return Lisp_ptr{true};
}
Lisp_ptr transcript_off(ZsArgs){
dump_mode = false;
return Lisp_ptr{true};
}
Lisp_ptr hard_repl(ZsArgs args){
args.cleanup();
vm.stack.clear();
vm.code.clear();
while(hard_repl_continue){
cout << ">> " << flush;
vm.code.push_back(read(cin));
eval();
print(cout, vm.return_value[0]);
cout << endl;
}
return {};
}
Lisp_ptr tmp_file(ZsArgs){
#ifdef _POSIX_C_SOURCE
char name[] =
#ifdef P_tmpdir
P_tmpdir
#else
"/tmp"
#endif
"/zs_temp_file_XXXXXX";
auto fd = mkstemp(name);
if(fd == -1){
auto eno = errno;
throw zs_error_arg1(nullptr, printf_string("mkstemp(3) error: %s", strerror(eno)));
}
unique_ptr<InputPort> i_port{new ifstream(static_cast<const char*>(name))};
if(!i_port){
throw zs_error_arg1(nullptr, "failed at opening file for input");
}
unique_ptr<OutputPort> o_port{new ofstream(static_cast<const char*>(name))};
if(!o_port){
throw zs_error_arg1(nullptr, "failed at opening file for output");
}
if(close(fd) == -1){
auto eno = errno;
throw zs_error_arg1(nullptr, printf_string("close(2) error: %s", strerror(eno)));
}
if(unlink(name) == -1){
auto eno = errno;
throw zs_error_arg1(nullptr, printf_string("unlink(2) error: %s", strerror(eno)));
}
zs_m_in(i_port.get(), Ptr_tag::input_port);
zs_m_in(o_port.get(), Ptr_tag::output_port);
return make_cons_list({i_port.release(), o_port.release()});
#else
throw zs_error_arg1(nullptr, "tmp-file is not supported");
#endif
}
} // namespace builtin
<commit_msg>bitly refactoring<commit_after>#include <iostream>
#include <fstream>
#include "builtin_extra.hh"
#include "lisp_ptr.hh"
#include "vm.hh"
#include "procedure.hh"
#include "s_closure.hh"
#include "util.hh"
#include "eval.hh"
#include "env.hh"
#include "equality.hh"
#include "builtin.hh"
#include "zs_error.hh"
#include "cons_util.hh"
#include "reader.hh"
#include "printer.hh"
#include "zs_memory.hh"
#ifdef _POSIX_C_SOURCE
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#endif
using namespace std;
using namespace proc_flag;
namespace builtin {
// used for interacting between 'exit' and 'hard-repl'
static bool hard_repl_continue = true;
Lisp_ptr traditional_transformer(ZsArgs args){
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw builtin_type_check_failed(nullptr, Ptr_tag::i_procedure, args[0]);
}
auto info = *iproc->info();
info.passing = Passing::quote;
info.returning = Returning::code;
return zs_new<IProcedure>(iproc->get(), info,
iproc->arg_list(), iproc->closure(), Lisp_ptr{});
}
Lisp_ptr gensym(ZsArgs){
static const string gensym_symname = {"(gensym)"};
return {zs_new<Symbol>(&gensym_symname)};
}
Lisp_ptr sc_macro_transformer(ZsArgs args){
auto iproc = args[0].get<IProcedure*>();
if(!iproc){
throw builtin_type_check_failed(nullptr, Ptr_tag::i_procedure, args[0]);
}
auto info = *iproc->info();
if(info.required_args != 2 || info.max_args != 2){
throw zs_error_arg1(nullptr,
printf_string("procedure must take exactly 2 args (this takes %d-%d))",
info.required_args, info.max_args));
}
info.passing = Passing::whole;
info.returning = Returning::code;
info.leaving = Leaving::after_returning_op;
return zs_new<IProcedure>(iproc->get(), info,
iproc->arg_list(),
iproc->closure()->fork(), Lisp_ptr{});
}
Lisp_ptr make_syntactic_closure(ZsArgs args){
Env* e = args[0].get<Env*>();
if(!e){
throw builtin_type_check_failed(nullptr, Ptr_tag::env, args[0]);
}
if(args[1].tag() != Ptr_tag::cons){
throw builtin_type_check_failed(nullptr, Ptr_tag::cons, args[1]);
}
Cons* c = args[1].get<Cons*>();
return zs_new<SyntacticClosure>(e, c, args[2]);
}
Lisp_ptr capture_syntactic_environment(ZsArgs args){
if(args[0].tag() != Ptr_tag::i_procedure){
throw builtin_type_check_failed(nullptr, Ptr_tag::i_procedure, args[0]);
}
auto iproc = args[0].get<IProcedure*>();
assert(iproc && iproc->info());
if(iproc->info()->required_args != 1){
throw zs_error_arg1(nullptr,
printf_string("first arg must take exactly 1 arg (take %d)",
iproc->info()->required_args));
}
auto ret = make_cons_list
({find_builtin_nproc("eval"),
make_cons_list({find_builtin_nproc("apply"), iproc, vm_op_get_current_env}),
vm_op_get_current_env});
return ret;
}
Lisp_ptr identifierp(ZsArgs args){
return Lisp_ptr{identifierp(args[0])};
}
Lisp_ptr identifier_eq(ZsArgs args){
auto ident1_env = args[0].get<Env*>();
if(!ident1_env){
throw builtin_type_check_failed(nullptr, Ptr_tag::env, args[0]);
}
if(!identifierp(args[1])){
throw builtin_identifier_check_failed(nullptr, args[1]);
}
auto ident2_env = args[2].get<Env*>();
if(!ident2_env){
throw builtin_type_check_failed(nullptr, Ptr_tag::env, args[2]);
}
if(!identifierp(args[3])){
throw builtin_identifier_check_failed(nullptr, args[3]);
}
return
Lisp_ptr{identifier_eq(ident1_env, args[1], ident2_env, args[3])};
}
Lisp_ptr make_synthetic_identifier(ZsArgs args){
if(!identifierp(args[0])){
throw builtin_identifier_check_failed(nullptr, args[0]);
}
return zs_new<SyntacticClosure>(zs_new<Env>(nullptr), Cons::NIL, args[0]);
}
Lisp_ptr exit(ZsArgs args){
// cerr << "exiting..\n";
args.cleanup();
vm.stack.clear();
vm.code.clear();
hard_repl_continue = false;
return Lisp_ptr{true};
}
Lisp_ptr transcript_on(ZsArgs){
dump_mode = true;
return Lisp_ptr{true};
}
Lisp_ptr transcript_off(ZsArgs){
dump_mode = false;
return Lisp_ptr{true};
}
Lisp_ptr hard_repl(ZsArgs args){
args.cleanup();
vm.stack.clear();
vm.code.clear();
while(hard_repl_continue){
cout << ">> " << flush;
vm.code.push_back(read(cin));
eval();
print(cout, vm.return_value[0]);
cout << endl;
}
return {};
}
Lisp_ptr tmp_file(ZsArgs){
#ifdef _POSIX_C_SOURCE
char name[] =
#ifdef P_tmpdir
P_tmpdir
#else
"/tmp"
#endif
"/zs_temp_file_XXXXXX";
auto fd = mkstemp(name);
if(fd == -1){
auto eno = errno;
throw zs_error_arg1(nullptr, printf_string("mkstemp(3) error: %s", strerror(eno)));
}
InputPort* i_port = zs_new_with_tag<ifstream, Ptr_tag::input_port>(static_cast<const char*>(name));
if(!i_port || !*i_port){
throw zs_error_arg1(nullptr, "failed at opening file for input");
}
OutputPort* o_port = zs_new_with_tag<ofstream, Ptr_tag::output_port>(static_cast<const char*>(name));
if(!o_port || !*o_port){
throw zs_error_arg1(nullptr, "failed at opening file for output");
}
if(close(fd) == -1){
auto eno = errno;
throw zs_error_arg1(nullptr, printf_string("close(2) error: %s", strerror(eno)));
}
if(unlink(name) == -1){
auto eno = errno;
throw zs_error_arg1(nullptr, printf_string("unlink(2) error: %s", strerror(eno)));
}
return make_cons_list({i_port, o_port});
#else
throw zs_error_arg1(nullptr, "tmp-file is not supported");
#endif
}
} // namespace builtin
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////
///////// /////////
//////// ҁ@݂r̃h[x} ////////
/////// ///////
///////////////////////////////////////////////////////
#include "ResultWindow.h"
#include "ParentWindow.h"
#include <DxLib.h>
#include "KeyBoardTools.h"
#include "PrintPicture.h"
//RXgN^
ResultWindow::ResultWindow(){
ZeroMemory(key, sizeof(int) * 256);
frame = 0;
score = -1;
length = 0;
remainingTime = 0;
goal = false;
select = RETRY;
select_num = 0;
LoadDivGraph("item/Nyan_s.png", 6, 6, 1, 32, 20, Nyan);
staffs=LoadGraph("item/staffs_oic.png");
}
//Abvf[^@eĂяo
//ʑJڎ͂̊parent->moveTo(ParentWindow::STAT);Ăяo
void ResultWindow::update(ParentWindow* parent){
if(frame > 10){
KeyBoardTools::GetHitKeyStateAll_2(key);
}
if(frame < 60){
frame++;
}
//L[
if(key[KEY_INPUT_UP] == 1){
select_num--;
}
if(key[KEY_INPUT_DOWN] == 1){
select_num++;
}
//I
if(select_num < 0){
select_num = 1;
}else if(select_num > 1){
select_num = 0;
}
select = static_cast<TRY>(select_num);
if(key[KEY_INPUT_SPACE] == 1 || key[KEY_INPUT_RETURN] == 1){
switch(select){
case RETRY:
//X^[g
parent->moveTo(ParentWindow::OPTION);
break;
case TITLE:
//TITLE
parent->moveTo(ParentWindow::TITLE);
break;
}
}
//XRAvZ
if(score == -1){
goal = parent->isGoal();
remainingTime = parent->getRemainingTime();
score = parent->getScore() + (remainingTime * 100);
score = score + (goal ? 1000 : 0); //S[Ȃ+1000P
for(int i = score; i > 0; i = i / 10){
length++;
}
}
render();//`
}
//`p
void ResultWindow::render(){
PrintPicture *print = PrintPicture::instance();
print->StringDraw("PLAYSCORE",270,100,3);
print->NumDraw(score, (800 + 28 * (10 - length)) / 2, 170,3);
print->StringDraw("REMAINING TIME",300, 280, 2);
print->NumDraw(remainingTime, 430, 280, 2);
DrawGraph(500,400,staffs,true);
if(!goal){
PrintPicture::instance()->StringDraw("NYAN IS DEAD!!", 400, 300, 2);
}
print->StringDraw("RETRY?",370,400,2);
print->StringDraw("TITLE",370,440,2);
switch(select){
//̏ꏊ
case RETRY:
DrawGraph(320, 400, Nyan[3], true);
break;
case TITLE:
DrawGraph(320, 440, Nyan[3], true);
break;
}
}
//fXgN^ 낢J肷
ResultWindow::~ResultWindow(){
//قJJHH@߂[A킽قJJЂႤ
}<commit_msg>リザルトの残り時間を修正<commit_after>//////////////////////////////////////////////////////////
///////// /////////
//////// ҁ@݂r̃h[x} ////////
/////// ///////
///////////////////////////////////////////////////////
#include "ResultWindow.h"
#include "ParentWindow.h"
#include <DxLib.h>
#include "KeyBoardTools.h"
#include "PrintPicture.h"
//RXgN^
ResultWindow::ResultWindow(){
ZeroMemory(key, sizeof(int) * 256);
frame = 0;
score = -1;
length = 0;
remainingTime = 0;
goal = false;
select = RETRY;
select_num = 0;
LoadDivGraph("item/Nyan_s.png", 6, 6, 1, 32, 20, Nyan);
staffs=LoadGraph("item/staffs_oic.png");
}
//Abvf[^@eĂяo
//ʑJڎ͂̊parent->moveTo(ParentWindow::STAT);Ăяo
void ResultWindow::update(ParentWindow* parent){
if(frame > 10){
KeyBoardTools::GetHitKeyStateAll_2(key);
}
if(frame < 60){
frame++;
}
//L[
if(key[KEY_INPUT_UP] == 1){
select_num--;
}
if(key[KEY_INPUT_DOWN] == 1){
select_num++;
}
//I
if(select_num < 0){
select_num = 1;
}else if(select_num > 1){
select_num = 0;
}
select = static_cast<TRY>(select_num);
if(key[KEY_INPUT_SPACE] == 1 || key[KEY_INPUT_RETURN] == 1){
switch(select){
case RETRY:
//X^[g
parent->moveTo(ParentWindow::OPTION);
break;
case TITLE:
//TITLE
parent->moveTo(ParentWindow::TITLE);
break;
}
}
//XRAvZ
if(score == -1){
goal = parent->isGoal();
remainingTime = parent->getRemainingTime();
score = parent->getScore() + (remainingTime * 100);
score = score + (goal ? 1000 : 0); //S[Ȃ+1000P
for(int i = score; i > 0; i = i / 10){
length++;
}
}
render();//`
}
//`p
void ResultWindow::render(){
PrintPicture *print = PrintPicture::instance();
print->StringDraw("PLAYSCORE",270,100,3);
print->NumDraw(score, (800 + 28 * (10 - length)) / 2, 170,3);
print->StringDraw("REMAINING TIME",300, 280, 2);
print->NumDraw(remainingTime, 530, 280, 2);
DrawGraph(500,400,staffs,true);
if(!goal){
PrintPicture::instance()->StringDraw("NYAN IS DEAD!!", 400, 300, 2);
}
print->StringDraw("RETRY?",370,400,2);
print->StringDraw("TITLE",370,440,2);
switch(select){
//̏ꏊ
case RETRY:
DrawGraph(320, 400, Nyan[3], true);
break;
case TITLE:
DrawGraph(320, 440, Nyan[3], true);
break;
}
}
//fXgN^ 낢J肷
ResultWindow::~ResultWindow(){
//قJJHH@߂[A킽قJJЂႤ
}<|endoftext|> |
<commit_before>#pragma once
/**
* FMM evaluator based on dual tree traversal
*/
#include <TransformIterator.hpp>
//! forward definition
template <typename Tree, typename Kernel>
class EvaluatorBase;
template <typename Tree, typename Kernel>
class EvaluatorTreecode : public EvaluatorBase<Tree,Kernel>
{
private:
typedef typename EvaluatorBase<Tree,Kernel>::charge_type charge_type;
typedef typename EvaluatorBase<Tree,Kernel>::result_type result_type;
typedef typename EvaluatorBase<Tree,Kernel>::point_type point_type;
typedef EvaluatorBase<Tree,Kernel> Base;
typename std::vector<result_type>::iterator results_begin;
typename std::vector<charge_type>::const_iterator charges_begin;
/** One-sided P2P!!
*/
void evalP2P(const typename Octree<point_type>::Box& b1,
const typename Octree<point_type>::Box& b2) {
// Point iters
auto body2point = [](const typename Octree<point_type>::Body& b) { return b.point(); };
auto p1_begin = make_transform_iterator(b1.body_begin(), body2point);
auto p1_end = make_transform_iterator(b1.body_end(), body2point);
auto p2_begin = make_transform_iterator(b2.body_begin(), body2point);
auto p2_end = make_transform_iterator(b2.body_end(), body2point);
// Charge iters
auto c1_begin = charges_begin + b1.body_begin()->index();
// Result iters
auto r2_begin = results_begin + b2.body_begin()->index();
printf("P2P: %d to %d\n",b1.index(),b2.index());
Base::K.P2P(p1_begin, p1_end, c1_begin,
p2_begin, p2_end,
r2_begin);
}
void evalM2P(const typename Octree<point_type>::Box& b1,
const typename Octree<point_type>::Box& b2)
{
// Target point iters
auto body2point = [](const typename Octree<point_type>::Body& b) { return b.point(); };
auto t_begin = make_transform_iterator(b2.body_begin(), body2point);
auto t_end = make_transform_iterator(b2.body_end(), body2point);
// Target result iters
auto r_begin = results_begin + b2.body_begin()->index();
printf("M2P: %d to %d\n", b1.index(), b2.index());
Base::K.M2P(Base::M[b1.index()], b1.center(),
t_begin, t_end,
r_begin);
}
void evalM2L(const typename Octree<point_type>::Box& b1,
const typename Octree<point_type>::Box& b2)
{
// unused -- quiet compiler warnings
(void) b1;
(void) b2;
}
template <typename BOX, typename Q>
void interact(const BOX& b1, const BOX& b2, Q& pairQ) {
double r0_norm = std::sqrt(normSq(b1.center() - b2.center()));
if (r0_norm * Base::THETA > b1.side_length()/2 + b2.side_length()/2) {
// These boxes satisfy the multipole acceptance criteria
evalM2P(b1,b2);
} else if(b1.is_leaf() && b2.is_leaf()) {
evalP2P(b2,b1);
} else {
pairQ.push_back(std::make_pair(b1,b2));
}
}
public:
//! constructor
EvaluatorTreecode(Tree& t, Kernel& k, double theta)
: EvaluatorBase<Tree,Kernel>(t,k,theta) {};
//! upward sweep
void upward(const std::vector<charge_type>& charges)
{
// set charges_begin iterator
charges_begin = charges.begin();
Base::M.resize(Base::tree.boxes());
Base::L.resize(Base::tree.boxes());
// EvaluatorBase<Tree,Kernel>::M.resize(10);
unsigned lowest_level = Base::tree.levels();
printf("lowest level in tree: %d\n",(int)lowest_level);
// For the lowest level up to the highest level
for (unsigned l = Base::tree.levels()-1; l != 0; --l) {
// For all boxes at this level
auto b_end = Base::tree.box_end(l);
for (auto bit = Base::tree.box_begin(l); bit != b_end; ++bit) {
auto box = *bit;
// Initialize box data
unsigned idx = box.index();
double box_size = box.side_length();
Base::K.init_multipole(Base::M[idx], box_size);
Base::K.init_local(Base::L[idx], box_size);
if (box.is_leaf()) {
// If leaf, make P2M calls
auto body2point = [](typename Octree<point_type>::Body b) { return b.point(); };
auto p_begin = make_transform_iterator(box.body_begin(), body2point);
auto p_end = make_transform_iterator(box.body_end(), body2point);
auto c_begin = charges.begin() + box.body_begin()->index();
printf("P2M: box: %d\n", (int)box.index());
Base::K.P2M(p_begin, p_end, c_begin, box.center(), Base::M[idx]);
} else {
// If not leaf, make M2M calls
// For all the children, M2M
auto c_end = box.child_end();
for (auto cit = box.child_begin(); cit != c_end; ++cit) {
auto cbox = *cit;
auto translation = box.center() - cbox.center();
printf("M2M: %d to %d\n", cbox.index(), idx);
Base::K.M2M(Base::M[cbox.index()], Base::M[idx], translation);
}
}
}
}
}
//! Box-Box interactions
void interactions(std::vector<result_type>& results)
{
// set reference to beginning of results
results_begin = results.begin();
typedef typename Octree<point_type>::Box Box;
typedef typename std::pair<Box, Box> box_pair;
std::deque<box_pair> pairQ;
// Queue based tree traversal for P2P, M2P, and/or M2L operations
pairQ.push_back(box_pair(Base::tree.root(), Base::tree.root()));
while (!pairQ.empty()) {
auto b1 = pairQ.front().first;
auto b2 = pairQ.front().second;
pairQ.pop_front();
if (b2.is_leaf() || (!b1.is_leaf() && b1.side_length() > b2.side_length())) {
// Split the first box into children and interact
auto c_end = b1.child_end();
for (auto cit = b1.child_begin(); cit != c_end; ++cit)
interact(*cit, b2, pairQ);
} else {
// Split the second box into children and interact
auto c_end = b2.child_end();
for (auto cit = b2.child_begin(); cit != c_end; ++cit)
interact(b1, *cit, pairQ);
}
}
}
//! downward sweep
void downward(std::vector<result_type>& results)
{
// not needed for treecode -- quiet warning
(void) results;
}
//! evaluator name
std::string name()
{
return "Treecode";
}
};
<commit_msg>removed useless evalM2L stub in treecode evaluator<commit_after>#pragma once
/**
* FMM evaluator based on dual tree traversal
*/
#include <TransformIterator.hpp>
//! forward definition
template <typename Tree, typename Kernel>
class EvaluatorBase;
template <typename Tree, typename Kernel>
class EvaluatorTreecode : public EvaluatorBase<Tree,Kernel>
{
private:
typedef typename EvaluatorBase<Tree,Kernel>::charge_type charge_type;
typedef typename EvaluatorBase<Tree,Kernel>::result_type result_type;
typedef typename EvaluatorBase<Tree,Kernel>::point_type point_type;
typedef EvaluatorBase<Tree,Kernel> Base;
typename std::vector<result_type>::iterator results_begin;
typename std::vector<charge_type>::const_iterator charges_begin;
/** One-sided P2P!!
*/
void evalP2P(const typename Octree<point_type>::Box& b1,
const typename Octree<point_type>::Box& b2) {
// Point iters
auto body2point = [](const typename Octree<point_type>::Body& b) { return b.point(); };
auto p1_begin = make_transform_iterator(b1.body_begin(), body2point);
auto p1_end = make_transform_iterator(b1.body_end(), body2point);
auto p2_begin = make_transform_iterator(b2.body_begin(), body2point);
auto p2_end = make_transform_iterator(b2.body_end(), body2point);
// Charge iters
auto c1_begin = charges_begin + b1.body_begin()->index();
// Result iters
auto r2_begin = results_begin + b2.body_begin()->index();
printf("P2P: %d to %d\n",b1.index(),b2.index());
Base::K.P2P(p1_begin, p1_end, c1_begin,
p2_begin, p2_end,
r2_begin);
}
void evalM2P(const typename Octree<point_type>::Box& b1,
const typename Octree<point_type>::Box& b2)
{
// Target point iters
auto body2point = [](const typename Octree<point_type>::Body& b) { return b.point(); };
auto t_begin = make_transform_iterator(b2.body_begin(), body2point);
auto t_end = make_transform_iterator(b2.body_end(), body2point);
// Target result iters
auto r_begin = results_begin + b2.body_begin()->index();
printf("M2P: %d to %d\n", b1.index(), b2.index());
Base::K.M2P(Base::M[b1.index()], b1.center(),
t_begin, t_end,
r_begin);
}
template <typename BOX, typename Q>
void interact(const BOX& b1, const BOX& b2, Q& pairQ) {
double r0_norm = std::sqrt(normSq(b1.center() - b2.center()));
if (r0_norm * Base::THETA > b1.side_length()/2 + b2.side_length()/2) {
// These boxes satisfy the multipole acceptance criteria
evalM2P(b1,b2);
} else if(b1.is_leaf() && b2.is_leaf()) {
evalP2P(b2,b1);
} else {
pairQ.push_back(std::make_pair(b1,b2));
}
}
public:
//! constructor
EvaluatorTreecode(Tree& t, Kernel& k, double theta)
: EvaluatorBase<Tree,Kernel>(t,k,theta) {};
//! upward sweep
void upward(const std::vector<charge_type>& charges)
{
// set charges_begin iterator
charges_begin = charges.begin();
Base::M.resize(Base::tree.boxes());
Base::L.resize(Base::tree.boxes());
// EvaluatorBase<Tree,Kernel>::M.resize(10);
unsigned lowest_level = Base::tree.levels();
printf("lowest level in tree: %d\n",(int)lowest_level);
// For the lowest level up to the highest level
for (unsigned l = Base::tree.levels()-1; l != 0; --l) {
// For all boxes at this level
auto b_end = Base::tree.box_end(l);
for (auto bit = Base::tree.box_begin(l); bit != b_end; ++bit) {
auto box = *bit;
// Initialize box data
unsigned idx = box.index();
double box_size = box.side_length();
Base::K.init_multipole(Base::M[idx], box_size);
Base::K.init_local(Base::L[idx], box_size);
if (box.is_leaf()) {
// If leaf, make P2M calls
auto body2point = [](typename Octree<point_type>::Body b) { return b.point(); };
auto p_begin = make_transform_iterator(box.body_begin(), body2point);
auto p_end = make_transform_iterator(box.body_end(), body2point);
auto c_begin = charges.begin() + box.body_begin()->index();
printf("P2M: box: %d\n", (int)box.index());
Base::K.P2M(p_begin, p_end, c_begin, box.center(), Base::M[idx]);
} else {
// If not leaf, make M2M calls
// For all the children, M2M
auto c_end = box.child_end();
for (auto cit = box.child_begin(); cit != c_end; ++cit) {
auto cbox = *cit;
auto translation = box.center() - cbox.center();
printf("M2M: %d to %d\n", cbox.index(), idx);
Base::K.M2M(Base::M[cbox.index()], Base::M[idx], translation);
}
}
}
}
}
//! Box-Box interactions
void interactions(std::vector<result_type>& results)
{
// set reference to beginning of results
results_begin = results.begin();
typedef typename Octree<point_type>::Box Box;
typedef typename std::pair<Box, Box> box_pair;
std::deque<box_pair> pairQ;
// Queue based tree traversal for P2P, M2P, and/or M2L operations
pairQ.push_back(box_pair(Base::tree.root(), Base::tree.root()));
while (!pairQ.empty()) {
auto b1 = pairQ.front().first;
auto b2 = pairQ.front().second;
pairQ.pop_front();
if (b2.is_leaf() || (!b1.is_leaf() && b1.side_length() > b2.side_length())) {
// Split the first box into children and interact
auto c_end = b1.child_end();
for (auto cit = b1.child_begin(); cit != c_end; ++cit)
interact(*cit, b2, pairQ);
} else {
// Split the second box into children and interact
auto c_end = b2.child_end();
for (auto cit = b2.child_begin(); cit != c_end; ++cit)
interact(b1, *cit, pairQ);
}
}
}
//! downward sweep
void downward(std::vector<result_type>& results)
{
// not needed for treecode -- quiet warning
(void) results;
}
//! evaluator name
std::string name()
{
return "Treecode";
}
};
<|endoftext|> |
<commit_before>
#include "Polygon.h"
namespace P_RVD
{
void Polygon::initialize_from_mesh_facet(
const Mesh* _mesh, t_index _facetIdx
)
{
clear();
Facet temp_facet = _mesh->meshFacets.getFacet(_facetIdx);
Vertex* v1 = add_vertex(
Vertex(
_mesh->meshVertices.getPoint(temp_facet.m_v1),
1.0,
_facetIdx
)
);
Vertex* v2 = add_vertex(
Vertex(
_mesh->meshVertices.getPoint(temp_facet.m_v2),
1.0,
_facetIdx
)
);
Vertex* v3 = add_vertex(
Vertex(
_mesh->meshVertices.getPoint(temp_facet.m_v3),
1.0,
_facetIdx
)
);
}
void Polygon::clip_by_plane(Polygon& _target, Points _points, t_index _i, t_index _j)
{
_target.clear();
if (getVertex_nb() == 0)
{
return;
}
//get the geometic position of the i and j.
Vector3d position_i = _points.getPoint(_i);
Vector3d position_j = _points.getPoint(_j);
// Compute d = n . (2m), where n is the
// normal vector of the bisector [i, j]
// and m the middle point of the bisector.
double d;
d = (position_i + position_j).dot(position_i - position_j);
//The predecessor of the first vertex is the last vertex
t_index prev_index_vertex = getVertex_nb() - 1;
const Vertex* prev_vertex = &(getVertex(prev_index_vertex));
Vector3d prev_vertex_position = prev_vertex->getPosition();
//then we compute prev_vertex_position "cross" n
//prev_l = prev_vertex_position . n
double prev_l = prev_vertex_position.dot(position_i - position_j);
P_RVD::Sign prev_status = P_RVD::geo_sgn(2.0 * prev_l - d);
//traverse the Vertex in this Polygon
for (t_index k = 0; k < getVertex_nb(); ++k)
{
const Vertex* vertex = &(getVertex(k));
Vector3d vertex_position = vertex->getPosition();
double l = vertex_position.dot(position_i - position_j);
//We compute:
// side1(pi, pj, q) = sign(2*q.n - n.m) = sign(2*l - d)
P_RVD::Sign status = P_RVD::geo_sgn(2.0 * l - d);
// If status of edge extremities differ,
// then there is an intersection.
if (status != prev_status && (prev_status) != 0)
{
// create the intersection and update the Polygon
Vertex I;
Vector3d temp_position;
//compute the position and weight
double denom = 2.0 * (prev_l - l);
double lambda1, lambda2;
// Shit happens ! [Forrest Gump]
if (::fabs(denom) < 1e-20) {
lambda1 = 0.5;
lambda2 = 0.5;
}
else {
lambda1 = (d - 2.0 * l) / denom;
// Note: lambda2 is also given
// by (2.0*l2-d)/denom
// (but 1.0 - lambda1 is a bit
// faster to compute...)
lambda2 = 1.0 - lambda1;
}
temp_position.x = lambda1 * prev_vertex_position.x + lambda2 * vertex_position.x;
temp_position.y = lambda1 * prev_vertex_position.y + lambda2 * vertex_position.y;
temp_position.z = lambda1 * prev_vertex_position.z + lambda2 * vertex_position.z;
//Set the position of Vertex
I.setPosition(temp_position);
//Set the weight of Veretex
I.setWeight(lambda1 * prev_vertex->getWeight() + lambda2 * vertex->getWeight());
//???? ûŪ
if (status > 0)
{
I.copy_edge_from(*prev_vertex);
I.setSeed(signed_t_index(_j));
}
else
{
I.setEdgeType(Intersection);
I.setSeed(vertex->getSeed());
}
_target.add_vertex(I);
printf("add I : %.17lf, %.17lf, %.17lf, %lf\n", I.getPosition().x, I.getPosition().y, I.getPosition().z, I.getWeight());
}
if (status > 0)
{
_target.add_vertex(*vertex);
printf("add vertex : %.17lf, %.17lf, %.17lf, %lf\n", vertex->getPosition().x, vertex->getPosition().y, vertex->getPosition().z, vertex->getWeight());
}
prev_vertex = vertex;
prev_vertex_position = vertex_position;
prev_status = status;
prev_l = l;
prev_index_vertex = k;
}
return;
}
void Polygon::show_polygon()
{
printf("vertex number : %d\n", this->getVertex_nb());
for (int i = 0; i < getVertex_nb(); ++i)
{
printf("number %d : x : %.17lf, y : %.17lf, z : %.17lf, w : %lf\n", i + 1, getVertex(i).getPosition().x,
getVertex(i).getPosition().y, getVertex(i).getPosition().z, getVertex(i).getWeight());
}
}
}<commit_msg>updatge<commit_after>
#include "Polygon.h"
namespace P_RVD
{
void Polygon::initialize_from_mesh_facet(
const Mesh* _mesh, t_index _facetIdx
)
{
clear();
Facet temp_facet = _mesh->meshFacets.getFacet(_facetIdx);
Vertex* v1 = add_vertex(
Vertex(
_mesh->meshVertices.getPoint(temp_facet.m_v1),
1.0,
_facetIdx
)
);
Vertex* v2 = add_vertex(
Vertex(
_mesh->meshVertices.getPoint(temp_facet.m_v2),
1.0,
_facetIdx
)
);
Vertex* v3 = add_vertex(
Vertex(
_mesh->meshVertices.getPoint(temp_facet.m_v3),
1.0,
_facetIdx
)
);
}
void Polygon::clip_by_plane(Polygon& _target, Points _points, t_index _i, t_index _j)
{
_target.clear();
if (getVertex_nb() == 0)
{
return;
}
//get the geometic position of the i and j.
Vector3d position_i = _points.getPoint(_i);
Vector3d position_j = _points.getPoint(_j);
// Compute d = n . (2m), where n is the
// normal vector of the bisector [i, j]
// and m the middle point of the bisector.
double d;
d = (position_i + position_j).dot(position_i - position_j);
//The predecessor of the first vertex is the last vertex
t_index prev_index_vertex = getVertex_nb() - 1;
const Vertex* prev_vertex = &(getVertex(prev_index_vertex));
Vector3d prev_vertex_position = prev_vertex->getPosition();
//then we compute prev_vertex_position "cross" n
//prev_l = prev_vertex_position . n
double prev_l = prev_vertex_position.dot(position_i - position_j);
P_RVD::Sign prev_status = P_RVD::geo_sgn(2.0 * prev_l - d);
//traverse the Vertex in this Polygon
for (t_index k = 0; k < getVertex_nb(); ++k)
{
const Vertex* vertex = &(getVertex(k));
Vector3d vertex_position = vertex->getPosition();
double l = vertex_position.dot(position_i - position_j);
//We compute:
// side1(pi, pj, q) = sign(2*q.n - n.m) = sign(2*l - d)
P_RVD::Sign status = P_RVD::geo_sgn(2.0 * l - d);
// If status of edge extremities differ,
// then there is an intersection.
if (status != prev_status && (prev_status) != 0)
{
// create the intersection and update the Polygon
Vertex I;
Vector3d temp_position;
//compute the position and weight
double denom = 2.0 * (prev_l - l);
double lambda1, lambda2;
// Shit happens ! [Forrest Gump]
if (::fabs(denom) < 1e-20) {
lambda1 = 0.5;
lambda2 = 0.5;
}
else {
lambda1 = (d - 2.0 * l) / denom;
// Note: lambda2 is also given
// by (2.0*l2-d)/denom
// (but 1.0 - lambda1 is a bit
// faster to compute...)
lambda2 = 1.0 - lambda1;
}
temp_position.x = lambda1 * prev_vertex_position.x + lambda2 * vertex_position.x;
temp_position.y = lambda1 * prev_vertex_position.y + lambda2 * vertex_position.y;
temp_position.z = lambda1 * prev_vertex_position.z + lambda2 * vertex_position.z;
//Set the position of Vertex
I.setPosition(temp_position);
//Set the weight of Veretex
I.setWeight(lambda1 * prev_vertex->getWeight() + lambda2 * vertex->getWeight());
//???? ûŪ
if (status > 0)
{
I.copy_edge_from(*prev_vertex);
I.setSeed(signed_t_index(_j));
}
else
{
I.setEdgeType(Intersection);
I.setSeed(vertex->getSeed());
}
_target.add_vertex(I);
//printf("add I : %.17lf, %.17lf, %.17lf, %lf\n", I.getPosition().x, I.getPosition().y, I.getPosition().z, I.getWeight());
}
if (status > 0)
{
_target.add_vertex(*vertex);
//printf("add vertex : %.17lf, %.17lf, %.17lf, %lf\n", vertex->getPosition().x, vertex->getPosition().y, vertex->getPosition().z, vertex->getWeight());
}
prev_vertex = vertex;
prev_vertex_position = vertex_position;
prev_status = status;
prev_l = l;
prev_index_vertex = k;
}
return;
}
void Polygon::show_polygon()
{
printf("vertex number : %d\n", this->getVertex_nb());
for (int i = 0; i < getVertex_nb(); ++i)
{
printf("number %d : x : %.17lf, y : %.17lf, z : %.17lf, w : %lf\n", i + 1, getVertex(i).getPosition().x,
getVertex(i).getPosition().y, getVertex(i).getPosition().z, getVertex(i).getWeight());
}
}
}<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2009-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h>
#include <llvm-c/Core.h>
#include <llvm-c/Disassembler.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/Host.h>
#include <llvm/IR/Module.h>
#include "util/u_math.h"
#include "util/u_debug.h"
#include "lp_bld_debug.h"
#ifdef __linux__
#include <sys/stat.h>
#include <fcntl.h>
#endif
/**
* Check alignment.
*
* It is important that this check is not implemented as a macro or inlined
* function, as the compiler assumptions in respect to alignment of global
* and stack variables would often make the check a no op, defeating the
* whole purpose of the exercise.
*/
extern "C" boolean
lp_check_alignment(const void *ptr, unsigned alignment)
{
assert(util_is_power_of_two(alignment));
return ((uintptr_t)ptr & (alignment - 1)) == 0;
}
class raw_debug_ostream :
public llvm::raw_ostream
{
private:
uint64_t pos;
public:
raw_debug_ostream() : pos(0) { }
void write_impl(const char *Ptr, size_t Size);
uint64_t current_pos() const { return pos; }
size_t preferred_buffer_size() const { return 512; }
};
void
raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
{
if (Size > 0) {
char *lastPtr = (char *)&Ptr[Size];
char last = *lastPtr;
*lastPtr = 0;
_debug_printf("%*s", Size, Ptr);
*lastPtr = last;
pos += Size;
}
}
extern "C" const char *
lp_get_module_id(LLVMModuleRef module)
{
return llvm::unwrap(module)->getModuleIdentifier().c_str();
}
/**
* Same as LLVMDumpValue, but through our debugging channels.
*/
extern "C" void
lp_debug_dump_value(LLVMValueRef value)
{
#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBEDDED)
raw_debug_ostream os;
llvm::unwrap(value)->print(os);
os.flush();
#else
LLVMDumpValue(value);
#endif
}
/*
* Disassemble a function, using the LLVM MC disassembler.
*
* See also:
* - http://blog.llvm.org/2010/01/x86-disassembler.html
* - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
*/
static size_t
disassemble(const void* func, llvm::raw_ostream & Out)
{
const uint8_t *bytes = (const uint8_t *)func;
/*
* Limit disassembly to this extent
*/
const uint64_t extent = 96 * 1024;
/*
* Initialize all used objects.
*/
std::string Triple = llvm::sys::getProcessTriple();
LLVMDisasmContextRef D = LLVMCreateDisasm(Triple.c_str(), NULL, 0, NULL, NULL);
char outline[1024];
if (!D) {
Out << "error: couldn't create disassembler for triple " << Triple << "\n";
return 0;
}
uint64_t pc;
pc = 0;
while (pc < extent) {
size_t Size;
/*
* Print address. We use addresses relative to the start of the function,
* so that between runs.
*/
Out << llvm::format("%6lu:\t", (unsigned long)pc);
Size = LLVMDisasmInstruction(D, (uint8_t *)bytes + pc, extent - pc, 0, outline,
sizeof outline);
if (!Size) {
Out << "invalid\n";
pc += 1;
break;
}
/*
* Output the bytes in hexidecimal format.
*/
if (0) {
unsigned i;
for (i = 0; i < Size; ++i) {
Out << llvm::format("%02x ", bytes[pc + i]);
}
for (; i < 16; ++i) {
Out << " ";
}
}
/*
* Print the instruction.
*/
Out << outline;
Out << "\n";
/*
* Stop disassembling on return statements, if there is no record of a
* jump to a successive address.
*
* XXX: This currently assumes x86
*/
if (Size == 1 && bytes[pc] == 0xc3) {
break;
}
/*
* Advance.
*/
pc += Size;
if (pc >= extent) {
Out << "disassembly larger than " << extent << "bytes, aborting\n";
break;
}
}
Out << "\n";
Out.flush();
LLVMDisasmDispose(D);
/*
* Print GDB command, useful to verify output.
*/
if (0) {
_debug_printf("disassemble %p %p\n", bytes, bytes + pc);
}
return pc;
}
extern "C" void
lp_disassemble(LLVMValueRef func, const void *code) {
raw_debug_ostream Out;
Out << LLVMGetValueName(func) << ":\n";
disassemble(code, Out);
}
/*
* Linux perf profiler integration.
*
* See also:
* - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
* - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
* - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
*/
extern "C" void
lp_profile(LLVMValueRef func, const void *code)
{
#if defined(__linux__) && defined(PROFILE)
static boolean first_time = TRUE;
static FILE *perf_map_file = NULL;
static int perf_asm_fd = -1;
if (first_time) {
/*
* We rely on the disassembler for determining a function's size, but
* the disassembly is a leaky and slow operation, so avoid running
* this except when running inside linux perf, which can be inferred
* by the PERF_BUILDID_DIR environment variable.
*/
if (getenv("PERF_BUILDID_DIR")) {
pid_t pid = getpid();
char filename[256];
util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
perf_map_file = fopen(filename, "wt");
util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
}
first_time = FALSE;
}
if (perf_map_file) {
const char *symbol = LLVMGetValueName(func);
unsigned long addr = (uintptr_t)code;
llvm::raw_fd_ostream Out(perf_asm_fd, false);
Out << symbol << ":\n";
unsigned long size = disassemble(code, Out);
fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
fflush(perf_map_file);
}
#else
(void)func;
(void)code;
#endif
}
<commit_msg>gallivm: Don't use raw_debug_ostream for dissasembling<commit_after>/**************************************************************************
*
* Copyright 2009-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h>
#include <llvm-c/Core.h>
#include <llvm-c/Disassembler.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/Host.h>
#include <llvm/IR/Module.h>
#include "util/u_math.h"
#include "util/u_debug.h"
#include "lp_bld_debug.h"
#ifdef __linux__
#include <sys/stat.h>
#include <fcntl.h>
#endif
/**
* Check alignment.
*
* It is important that this check is not implemented as a macro or inlined
* function, as the compiler assumptions in respect to alignment of global
* and stack variables would often make the check a no op, defeating the
* whole purpose of the exercise.
*/
extern "C" boolean
lp_check_alignment(const void *ptr, unsigned alignment)
{
assert(util_is_power_of_two(alignment));
return ((uintptr_t)ptr & (alignment - 1)) == 0;
}
class raw_debug_ostream :
public llvm::raw_ostream
{
private:
uint64_t pos;
public:
raw_debug_ostream() : pos(0) { }
void write_impl(const char *Ptr, size_t Size);
uint64_t current_pos() const { return pos; }
size_t preferred_buffer_size() const { return 512; }
};
void
raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
{
if (Size > 0) {
char *lastPtr = (char *)&Ptr[Size];
char last = *lastPtr;
*lastPtr = 0;
_debug_printf("%*s", Size, Ptr);
*lastPtr = last;
pos += Size;
}
}
extern "C" const char *
lp_get_module_id(LLVMModuleRef module)
{
return llvm::unwrap(module)->getModuleIdentifier().c_str();
}
/**
* Same as LLVMDumpValue, but through our debugging channels.
*/
extern "C" void
lp_debug_dump_value(LLVMValueRef value)
{
#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBEDDED)
raw_debug_ostream os;
llvm::unwrap(value)->print(os);
os.flush();
#else
LLVMDumpValue(value);
#endif
}
/*
* Disassemble a function, using the LLVM MC disassembler.
*
* See also:
* - http://blog.llvm.org/2010/01/x86-disassembler.html
* - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
*/
static size_t
disassemble(const void* func)
{
const uint8_t *bytes = (const uint8_t *)func;
/*
* Limit disassembly to this extent
*/
const uint64_t extent = 96 * 1024;
/*
* Initialize all used objects.
*/
std::string Triple = llvm::sys::getProcessTriple();
LLVMDisasmContextRef D = LLVMCreateDisasm(Triple.c_str(), NULL, 0, NULL, NULL);
char outline[1024];
if (!D) {
_debug_printf("error: couldn't create disassembler for triple %s\n",
Triple.c_str());
return 0;
}
uint64_t pc;
pc = 0;
while (pc < extent) {
size_t Size;
/*
* Print address. We use addresses relative to the start of the function,
* so that between runs.
*/
_debug_printf("%6lu:\t", (unsigned long)pc);
Size = LLVMDisasmInstruction(D, (uint8_t *)bytes + pc, extent - pc, 0, outline,
sizeof outline);
if (!Size) {
_debug_printf("invalid\n");
pc += 1;
break;
}
/*
* Output the bytes in hexidecimal format.
*/
if (0) {
unsigned i;
for (i = 0; i < Size; ++i) {
_debug_printf("%02x ", bytes[pc + i]);
}
for (; i < 16; ++i) {
_debug_printf(" ");
}
}
/*
* Print the instruction.
*/
_debug_printf("%*s", Size, outline);
_debug_printf("\n");
/*
* Stop disassembling on return statements, if there is no record of a
* jump to a successive address.
*
* XXX: This currently assumes x86
*/
if (Size == 1 && bytes[pc] == 0xc3) {
break;
}
/*
* Advance.
*/
pc += Size;
if (pc >= extent) {
_debug_printf("disassembly larger than %ull bytes, aborting\n", extent);
break;
}
}
_debug_printf("\n");
LLVMDisasmDispose(D);
/*
* Print GDB command, useful to verify output.
*/
if (0) {
_debug_printf("disassemble %p %p\n", bytes, bytes + pc);
}
return pc;
}
extern "C" void
lp_disassemble(LLVMValueRef func, const void *code) {
_debug_printf("%s:\n", LLVMGetValueName(func));
disassemble(code);
}
/*
* Linux perf profiler integration.
*
* See also:
* - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
* - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
* - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
*/
extern "C" void
lp_profile(LLVMValueRef func, const void *code)
{
#if defined(__linux__) && defined(PROFILE)
static boolean first_time = TRUE;
static FILE *perf_map_file = NULL;
static int perf_asm_fd = -1;
if (first_time) {
/*
* We rely on the disassembler for determining a function's size, but
* the disassembly is a leaky and slow operation, so avoid running
* this except when running inside linux perf, which can be inferred
* by the PERF_BUILDID_DIR environment variable.
*/
if (getenv("PERF_BUILDID_DIR")) {
pid_t pid = getpid();
char filename[256];
util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
perf_map_file = fopen(filename, "wt");
util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
}
first_time = FALSE;
}
if (perf_map_file) {
const char *symbol = LLVMGetValueName(func);
unsigned long addr = (uintptr_t)code;
llvm::raw_fd_ostream Out(perf_asm_fd, false);
Out << symbol << ":\n";
unsigned long size = disassemble(code, Out);
fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
fflush(perf_map_file);
}
#else
(void)func;
(void)code;
#endif
}
<|endoftext|> |
<commit_before>// PythonStuff.cpp
#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"
class CPyProcess : public wxProcess
{
protected:
int m_pid;
public:
CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }
void Execute(const char* cmd);
void Cancel(void);
void OnTerminate(int pid, int status);
virtual void ThenDo(void) { }
};
void CPyProcess::Execute(const char* cmd)
{
m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}
void CPyProcess::Cancel(void)
{
if (m_pid)
{
wxProcess::Kill(m_pid);
m_pid = 0;
}
}
void CPyProcess::OnTerminate(int pid, int status)
{
if (pid == m_pid)
{
m_pid = 0;
ThenDo();
}
}
////////////////////////////////////////////////////////
class CPyBackPlot : public CPyProcess
{
protected:
wxString m_filename;
static CPyBackPlot* m_object;
public:
CPyBackPlot(const char* filename): m_filename(filename) { m_object = this; }
~CPyBackPlot(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
#ifdef WIN32
Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("/nc_read.bat\" iso \"") + m_filename + _T("\""));
#else
Execute(wxString(_T("python \")) + theApp.GetDllFolder() + wxString(_T("/nc/iso_read.py\" ")) + m_filename);
#endif
}
void ThenDo(void)
{
// there should now be a .nc.xml written
wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
wxFile ofs(xml_file_str.c_str());
if(!ofs.IsOpened())
{
wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
return;
}
// read the xml file, just like paste, into the program
heeksCAD->OpenXMLFile(xml_file_str, true, theApp.m_program);
heeksCAD->Repaint();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
}
};
CPyBackPlot* CPyBackPlot::m_object = NULL;
class CPyPostProcess : public CPyProcess
{
protected:
wxString m_filename;
static CPyPostProcess* m_object;
public:
CPyPostProcess(const char* filename): m_filename(filename) { m_object = this; }
~CPyPostProcess(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
#ifdef WIN32
Execute(theApp.GetDllFolder() + wxString(_T("/post.bat")));
#else
Execute(wxString(_T("python ")) + theApp.GetDllFolder() + wxString(_T("/post.py")));
#endif
}
void ThenDo(void) { (new CPyBackPlot(m_filename))->Do(); }
};
CPyPostProcess* CPyPostProcess::m_object = NULL;
////////////////////////////////////////////////////////
static bool write_python_file(const wxString& python_file_path)
{
wxFile ofs(python_file_path.c_str(), wxFile::write);
if(!ofs.IsOpened())return false;
ofs.Write(theApp.m_program_canvas->m_textCtrl->GetValue());
return true;
}
bool HeeksPyPostProcess(const wxString &filepath)
{
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
// write the python file
wxString file_str = theApp.GetDllFolder() + wxString(_T("/post.py"));
if(!write_python_file(file_str))
{
wxMessageBox(_T("couldn't write post.py!"));
}
else
{
::wxSetWorkingDirectory(theApp.GetDllFolder());
// call the python file
(new CPyPostProcess(filepath))->Do();
return true;
}
}
catch(...)
{
wxMessageBox(_T("Error while post-processing the program!"));
}
return false;
}
bool HeeksPyBackplot(const wxString &filepath)
{
return true;
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
::wxSetWorkingDirectory(theApp.GetDllFolder());
// call the python file
(new CPyBackPlot(filepath))->Do();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
return true;
}
catch(...)
{
wxMessageBox(_T("Error while backplotting the program!"));
}
return false;
}
void HeeksPyCancel(void)
{
CPyBackPlot::StaticCancel();
CPyPostProcess::StaticCancel();
}
<commit_msg>I made the lastest changes for cancel button build for Linux<commit_after>// PythonStuff.cpp
#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"
class CPyProcess : public wxProcess
{
protected:
int m_pid;
public:
CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }
void Execute(const wxChar* cmd);
void Cancel(void);
void OnTerminate(int pid, int status);
virtual void ThenDo(void) { }
};
void CPyProcess::Execute(const wxChar* cmd)
{
m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}
void CPyProcess::Cancel(void)
{
if (m_pid)
{
wxProcess::Kill(m_pid);
m_pid = 0;
}
}
void CPyProcess::OnTerminate(int pid, int status)
{
if (pid == m_pid)
{
m_pid = 0;
ThenDo();
}
}
////////////////////////////////////////////////////////
class CPyBackPlot : public CPyProcess
{
protected:
wxString m_filename;
static CPyBackPlot* m_object;
public:
CPyBackPlot(const wxChar* filename): m_filename(filename) { m_object = this; }
~CPyBackPlot(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
#ifdef WIN32
Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("/nc_read.bat\" iso \"") + m_filename + _T("\""));
#else
Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + wxString(_T("/nc/iso_read.py\" ")) + m_filename);
#endif
}
void ThenDo(void)
{
// there should now be a .nc.xml written
wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
wxFile ofs(xml_file_str.c_str());
if(!ofs.IsOpened())
{
wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
return;
}
// read the xml file, just like paste, into the program
heeksCAD->OpenXMLFile(xml_file_str, true, theApp.m_program);
heeksCAD->Repaint();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
}
};
CPyBackPlot* CPyBackPlot::m_object = NULL;
class CPyPostProcess : public CPyProcess
{
protected:
wxString m_filename;
static CPyPostProcess* m_object;
public:
CPyPostProcess(const wxChar* filename): m_filename(filename) { m_object = this; }
~CPyPostProcess(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
#ifdef WIN32
Execute(theApp.GetDllFolder() + wxString(_T("/post.bat")));
#else
Execute(wxString(_T("python ")) + theApp.GetDllFolder() + wxString(_T("/post.py")));
#endif
}
void ThenDo(void) { (new CPyBackPlot(m_filename))->Do(); }
};
CPyPostProcess* CPyPostProcess::m_object = NULL;
////////////////////////////////////////////////////////
static bool write_python_file(const wxString& python_file_path)
{
wxFile ofs(python_file_path.c_str(), wxFile::write);
if(!ofs.IsOpened())return false;
ofs.Write(theApp.m_program_canvas->m_textCtrl->GetValue());
return true;
}
bool HeeksPyPostProcess(const wxString &filepath)
{
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
// write the python file
wxString file_str = theApp.GetDllFolder() + wxString(_T("/post.py"));
if(!write_python_file(file_str))
{
wxMessageBox(_T("couldn't write post.py!"));
}
else
{
::wxSetWorkingDirectory(theApp.GetDllFolder());
// call the python file
(new CPyPostProcess(filepath))->Do();
return true;
}
}
catch(...)
{
wxMessageBox(_T("Error while post-processing the program!"));
}
return false;
}
bool HeeksPyBackplot(const wxString &filepath)
{
return true;
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
::wxSetWorkingDirectory(theApp.GetDllFolder());
// call the python file
(new CPyBackPlot(filepath))->Do();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
return true;
}
catch(...)
{
wxMessageBox(_T("Error while backplotting the program!"));
}
return false;
}
void HeeksPyCancel(void)
{
CPyBackPlot::StaticCancel();
CPyPostProcess::StaticCancel();
}
<|endoftext|> |
<commit_before>// PythonStuff.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"
class CPyProcess : public wxProcess
{
protected:
int m_pid;
public:
CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }
void Execute(const wxChar* cmd);
void Cancel(void);
void OnTerminate(int pid, int status);
virtual void ThenDo(void) { }
};
void CPyProcess::Execute(const wxChar* cmd)
{
m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}
void CPyProcess::Cancel(void)
{
if (m_pid)
{
wxProcess::Kill(m_pid);
m_pid = 0;
}
}
void CPyProcess::OnTerminate(int pid, int status)
{
if (pid == m_pid)
{
m_pid = 0;
ThenDo();
}
}
////////////////////////////////////////////////////////
class CPyBackPlot : public CPyProcess
{
protected:
const CProgram* m_program;
HeeksObj* m_into;
wxString m_filename;
wxBusyCursor *m_busy_cursor;
static CPyBackPlot* m_object;
public:
CPyBackPlot(const CProgram* program, HeeksObj* into, const wxChar* filename): m_program(program), m_into(into),m_filename(filename),m_busy_cursor(NULL) { m_object = this; }
~CPyBackPlot(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
if(m_busy_cursor == NULL)m_busy_cursor = new wxBusyCursor();
if (m_program->m_machine.file_name == _T("not found"))
{
wxMessageBox(_T("Machine name (defined in Program Properties) not found"));
} // End if - then
else
{
#ifdef WIN32
Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("\\nc_read.bat\" ") + m_program->m_machine.file_name + _T(" \"") + m_filename + _T("\""));
#else
#ifdef RUNINPLACE
wxString path(_T("/nc/"));
#else
wxString path(_T("/../heekscnc/nc/"));
#endif
Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + path + m_program->m_machine.file_name + wxString(_T("_read.py\" \"")) + m_filename + wxString(_T("\"")) );
#endif
} // End if - else
}
void ThenDo(void)
{
// there should now be a .nc.xml written
wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
wxFile ofs(xml_file_str.c_str());
if(!ofs.IsOpened())
{
wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
return;
}
// read the xml file, just like paste, into the program
heeksCAD->OpenXMLFile(xml_file_str, m_into);
heeksCAD->Repaint();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
delete m_busy_cursor;
m_busy_cursor = NULL;
}
};
CPyBackPlot* CPyBackPlot::m_object = NULL;
class CPyPostProcess : public CPyProcess
{
protected:
const CProgram* m_program;
wxString m_filename;
bool m_include_backplot_processing;
static CPyPostProcess* m_object;
public:
CPyPostProcess(const CProgram* program,
const wxChar* filename,
const bool include_backplot_processing = true ) :
m_program(program), m_filename(filename), m_include_backplot_processing(include_backplot_processing)
{
m_object = this;
}
~CPyPostProcess(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
wxBusyCursor wait; // show an hour glass until the end of this function
wxStandardPaths standard_paths;
wxFileName path( standard_paths.GetTempDir().c_str(), _T("post.py"));
#ifdef WIN32
Execute(wxString(_T("\"")) + theApp.GetDllFolder() + wxString(_T("\\post.bat\" \"")) + path.GetFullPath() + wxString(_T("\"")));
#else
wxString path = wxString(_T("python ")) + path.GetFullPath();
cout<<path.c_str();
Execute(path);
#endif
}
void ThenDo(void)
{
if (m_include_backplot_processing)
{
(new CPyBackPlot(m_program, (HeeksObj*)m_program, m_filename))->Do();
}
}
};
CPyPostProcess* CPyPostProcess::m_object = NULL;
////////////////////////////////////////////////////////
static bool write_python_file(const wxString& python_file_path)
{
wxFile ofs(python_file_path.c_str(), wxFile::write);
if(!ofs.IsOpened())return false;
ofs.Write(theApp.m_program->m_python_program.c_str());
return true;
}
bool HeeksPyPostProcess(const CProgram* program, const wxString &filepath, const bool include_backplot_processing)
{
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
// write the python file
wxStandardPaths standard_paths;
wxFileName file_str( standard_paths.GetTempDir().c_str(), _T("post.py"));
if(!write_python_file(file_str.GetFullPath()))
{
wxString error;
error << _T("couldn't write ") << file_str.GetFullPath();
wxMessageBox(error.c_str());
}
else
{
#ifdef WIN32
// Set the working directory to the area that contains the DLL so that
// the system can find the post.bat file correctly.
::wxSetWorkingDirectory(theApp.GetDllFolder());
#else
::wxSetWorkingDirectory(standard_paths.GetTempDir());
#endif
// call the python file
(new CPyPostProcess(program, filepath, include_backplot_processing))->Do();
return true;
}
}
catch(...)
{
wxMessageBox(_T("Error while post-processing the program!"));
}
return false;
}
bool HeeksPyBackplot(const CProgram* program, HeeksObj* into, const wxString &filepath)
{
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
::wxSetWorkingDirectory(theApp.GetDllFolder());
// call the python file
(new CPyBackPlot(program, into, filepath))->Do();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
return true;
}
catch(...)
{
wxMessageBox(_T("Error while backplotting the program!"));
}
return false;
}
void HeeksPyCancel(void)
{
CPyBackPlot::StaticCancel();
CPyPostProcess::StaticCancel();
}
<commit_msg>I accidentally committed a test bit of code with "cout<<" in it, which didn't compile!<commit_after>// PythonStuff.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"
class CPyProcess : public wxProcess
{
protected:
int m_pid;
public:
CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }
void Execute(const wxChar* cmd);
void Cancel(void);
void OnTerminate(int pid, int status);
virtual void ThenDo(void) { }
};
void CPyProcess::Execute(const wxChar* cmd)
{
m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}
void CPyProcess::Cancel(void)
{
if (m_pid)
{
wxProcess::Kill(m_pid);
m_pid = 0;
}
}
void CPyProcess::OnTerminate(int pid, int status)
{
if (pid == m_pid)
{
m_pid = 0;
ThenDo();
}
}
////////////////////////////////////////////////////////
class CPyBackPlot : public CPyProcess
{
protected:
const CProgram* m_program;
HeeksObj* m_into;
wxString m_filename;
wxBusyCursor *m_busy_cursor;
static CPyBackPlot* m_object;
public:
CPyBackPlot(const CProgram* program, HeeksObj* into, const wxChar* filename): m_program(program), m_into(into),m_filename(filename),m_busy_cursor(NULL) { m_object = this; }
~CPyBackPlot(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
if(m_busy_cursor == NULL)m_busy_cursor = new wxBusyCursor();
if (m_program->m_machine.file_name == _T("not found"))
{
wxMessageBox(_T("Machine name (defined in Program Properties) not found"));
} // End if - then
else
{
#ifdef WIN32
Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("\\nc_read.bat\" ") + m_program->m_machine.file_name + _T(" \"") + m_filename + _T("\""));
#else
#ifdef RUNINPLACE
wxString path(_T("/nc/"));
#else
wxString path(_T("/../heekscnc/nc/"));
#endif
Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + path + m_program->m_machine.file_name + wxString(_T("_read.py\" \"")) + m_filename + wxString(_T("\"")) );
#endif
} // End if - else
}
void ThenDo(void)
{
// there should now be a .nc.xml written
wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
wxFile ofs(xml_file_str.c_str());
if(!ofs.IsOpened())
{
wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
return;
}
// read the xml file, just like paste, into the program
heeksCAD->OpenXMLFile(xml_file_str, m_into);
heeksCAD->Repaint();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
delete m_busy_cursor;
m_busy_cursor = NULL;
}
};
CPyBackPlot* CPyBackPlot::m_object = NULL;
class CPyPostProcess : public CPyProcess
{
protected:
const CProgram* m_program;
wxString m_filename;
bool m_include_backplot_processing;
static CPyPostProcess* m_object;
public:
CPyPostProcess(const CProgram* program,
const wxChar* filename,
const bool include_backplot_processing = true ) :
m_program(program), m_filename(filename), m_include_backplot_processing(include_backplot_processing)
{
m_object = this;
}
~CPyPostProcess(void) { m_object = NULL; }
static void StaticCancel(void) { if (m_object) m_object->Cancel(); }
void Do(void)
{
wxBusyCursor wait; // show an hour glass until the end of this function
wxStandardPaths standard_paths;
wxFileName path( standard_paths.GetTempDir().c_str(), _T("post.py"));
#ifdef WIN32
Execute(wxString(_T("\"")) + theApp.GetDllFolder() + wxString(_T("\\post.bat\" \"")) + path.GetFullPath() + wxString(_T("\"")));
#else
wxString path = wxString(_T("python ")) + path.GetFullPath();
Execute(path);
#endif
}
void ThenDo(void)
{
if (m_include_backplot_processing)
{
(new CPyBackPlot(m_program, (HeeksObj*)m_program, m_filename))->Do();
}
}
};
CPyPostProcess* CPyPostProcess::m_object = NULL;
////////////////////////////////////////////////////////
static bool write_python_file(const wxString& python_file_path)
{
wxFile ofs(python_file_path.c_str(), wxFile::write);
if(!ofs.IsOpened())return false;
ofs.Write(theApp.m_program->m_python_program.c_str());
return true;
}
bool HeeksPyPostProcess(const CProgram* program, const wxString &filepath, const bool include_backplot_processing)
{
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
// write the python file
wxStandardPaths standard_paths;
wxFileName file_str( standard_paths.GetTempDir().c_str(), _T("post.py"));
if(!write_python_file(file_str.GetFullPath()))
{
wxString error;
error << _T("couldn't write ") << file_str.GetFullPath();
wxMessageBox(error.c_str());
}
else
{
#ifdef WIN32
// Set the working directory to the area that contains the DLL so that
// the system can find the post.bat file correctly.
::wxSetWorkingDirectory(theApp.GetDllFolder());
#else
::wxSetWorkingDirectory(standard_paths.GetTempDir());
#endif
// call the python file
(new CPyPostProcess(program, filepath, include_backplot_processing))->Do();
return true;
}
}
catch(...)
{
wxMessageBox(_T("Error while post-processing the program!"));
}
return false;
}
bool HeeksPyBackplot(const CProgram* program, HeeksObj* into, const wxString &filepath)
{
try{
theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window
::wxSetWorkingDirectory(theApp.GetDllFolder());
// call the python file
(new CPyBackPlot(program, into, filepath))->Do();
// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
heeksCAD->GetMainFrame()->Raise();
return true;
}
catch(...)
{
wxMessageBox(_T("Error while backplotting the program!"));
}
return false;
}
void HeeksPyCancel(void)
{
CPyBackPlot::StaticCancel();
CPyPostProcess::StaticCancel();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Authors:
* Manjeet Dahiya
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <iostream>
#include <QDateTime>
#include <QTextStream>
#include <QFile>
#include "QXmppLogger.h"
QXmppLogger* QXmppLogger::m_logger = 0;
static const char *typeName(QXmppLogger::MessageType type)
{
switch (type)
{
case QXmppLogger::DebugMessage:
return "DEBUG";
case QXmppLogger::InformationMessage:
return "INFO";
case QXmppLogger::WarningMessage:
return "WARNING";
case QXmppLogger::ReceivedMessage:
return "RECEIVED";
case QXmppLogger::SentMessage:
return "SENT";
default:
return "";
}
}
static QString formatted(QXmppLogger::MessageType type, const QString& text)
{
return QDateTime::currentDateTime().toString() + " " +
QString::fromLatin1(typeName(type)) + " " +
text;
}
/// Constructs a new QXmppLogger.
///
/// \param parent
QXmppLogger::QXmppLogger(QObject *parent)
: QObject(parent),
m_loggingType(QXmppLogger::NoLogging),
m_logFilePath("QXmppClientLog.log"),
m_messageTypes(QXmppLogger::AnyMessage)
{
}
/// Returns the default logger.
///
QXmppLogger* QXmppLogger::getLogger()
{
if(!m_logger)
m_logger = new QXmppLogger();
return m_logger;
}
/// Returns the handler for logging messages.
///
QXmppLogger::LoggingType QXmppLogger::loggingType()
{
return m_loggingType;
}
/// Sets the handler for logging messages.
///
/// \param type
void QXmppLogger::setLoggingType(QXmppLogger::LoggingType type)
{
m_loggingType = type;
}
/// Returns the types of messages to log.
///
QXmppLogger::MessageTypes QXmppLogger::messageTypes()
{
return m_messageTypes;
}
/// Sets the types of messages to log.
///
/// \param types
void QXmppLogger::setMessageTypes(QXmppLogger::MessageTypes types)
{
m_messageTypes = types;
}
/// Add a logging message.
///
/// \param type
/// \param text
void QXmppLogger::log(QXmppLogger::MessageType type, const QString& text)
{
// filter messages
if (!m_messageTypes.testFlag(type))
return;
switch(m_loggingType)
{
case QXmppLogger::FileLogging:
{
QFile file(m_logFilePath);
file.open(QIODevice::Append);
QTextStream stream(&file);
stream << formatted(type, text) << "\n\n";
}
break;
case QXmppLogger::StdoutLogging:
std::cout << qPrintable(formatted(type, text)) << std::endl;
break;
case QXmppLogger::SignalLogging:
emit message(type, text);
break;
default:
break;
}
}
/// Returns the path to which logging messages should be written.
///
/// \sa loggingType()
QString QXmppLogger::logFilePath()
{
return m_logFilePath;
}
/// Sets the path to which logging messages should be written.
///
/// \param path
///
/// \sa setLoggingType()
void QXmppLogger::setLogFilePath(const QString &path)
{
m_logFilePath = path;
}
<commit_msg>don't use double end of line in files<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Authors:
* Manjeet Dahiya
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <iostream>
#include <QDateTime>
#include <QTextStream>
#include <QFile>
#include "QXmppLogger.h"
QXmppLogger* QXmppLogger::m_logger = 0;
static const char *typeName(QXmppLogger::MessageType type)
{
switch (type)
{
case QXmppLogger::DebugMessage:
return "DEBUG";
case QXmppLogger::InformationMessage:
return "INFO";
case QXmppLogger::WarningMessage:
return "WARNING";
case QXmppLogger::ReceivedMessage:
return "RECEIVED";
case QXmppLogger::SentMessage:
return "SENT";
default:
return "";
}
}
static QString formatted(QXmppLogger::MessageType type, const QString& text)
{
return QDateTime::currentDateTime().toString() + " " +
QString::fromLatin1(typeName(type)) + " " +
text;
}
/// Constructs a new QXmppLogger.
///
/// \param parent
QXmppLogger::QXmppLogger(QObject *parent)
: QObject(parent),
m_loggingType(QXmppLogger::NoLogging),
m_logFilePath("QXmppClientLog.log"),
m_messageTypes(QXmppLogger::AnyMessage)
{
}
/// Returns the default logger.
///
QXmppLogger* QXmppLogger::getLogger()
{
if(!m_logger)
m_logger = new QXmppLogger();
return m_logger;
}
/// Returns the handler for logging messages.
///
QXmppLogger::LoggingType QXmppLogger::loggingType()
{
return m_loggingType;
}
/// Sets the handler for logging messages.
///
/// \param type
void QXmppLogger::setLoggingType(QXmppLogger::LoggingType type)
{
m_loggingType = type;
}
/// Returns the types of messages to log.
///
QXmppLogger::MessageTypes QXmppLogger::messageTypes()
{
return m_messageTypes;
}
/// Sets the types of messages to log.
///
/// \param types
void QXmppLogger::setMessageTypes(QXmppLogger::MessageTypes types)
{
m_messageTypes = types;
}
/// Add a logging message.
///
/// \param type
/// \param text
void QXmppLogger::log(QXmppLogger::MessageType type, const QString& text)
{
// filter messages
if (!m_messageTypes.testFlag(type))
return;
switch(m_loggingType)
{
case QXmppLogger::FileLogging:
{
QFile file(m_logFilePath);
file.open(QIODevice::Append);
QTextStream stream(&file);
stream << formatted(type, text) << "\n";
}
break;
case QXmppLogger::StdoutLogging:
std::cout << qPrintable(formatted(type, text)) << std::endl;
break;
case QXmppLogger::SignalLogging:
emit message(type, text);
break;
default:
break;
}
}
/// Returns the path to which logging messages should be written.
///
/// \sa loggingType()
QString QXmppLogger::logFilePath()
{
return m_logFilePath;
}
/// Sets the path to which logging messages should be written.
///
/// \param path
///
/// \sa setLoggingType()
void QXmppLogger::setLogFilePath(const QString &path)
{
m_logFilePath = path;
}
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <archie/meta/eval.hpp>
#include <archie/fused/boolean.hpp>
#include <archie/meta/returns.hpp>
namespace archie {
namespace meta {
template <bool... Xs>
struct conjunction {
private:
static decltype(fused::True) test();
template <typename... Ts>
static decltype(fused::True) test(Ts*...);
template <typename... Ts>
static decltype(fused::False) test(Ts...);
public:
using type = decltype(test(eval<std::conditional<Xs, int*, int>>{}...));
};
template <bool... Xs>
using conjunction_t = eval<conjunction<Xs...>>;
template <bool... Xs>
struct disjunction {
private:
static decltype(fused::False) test();
template <typename... Ts>
static decltype(fused::False) test(Ts*...);
template <typename... Ts>
static decltype(fused::True) test(Ts...);
public:
using type = decltype(test(eval<std::conditional<Xs, int, int*>>{}...));
};
template <bool... Xs>
using disjunction_t = eval<disjunction<Xs...>>;
template <bool B>
using negation = boolean<!B>;
template <bool B>
using negation_t = eval<negation<B>>;
template <typename Tp>
using opposite = negation<Tp::value>;
template <typename Tp>
using opposite_t = negation_t<Tp::value>;
template <typename... Ts>
using all = conjunction_t<Ts::value...>;
template <typename... Ts>
using any = disjunction_t<Ts::value...>;
template <typename... Ts>
using none = opposite_t<any<Ts...>>;
}
}
<commit_msg>use fold expression in meta logic<commit_after>#pragma once
#include <type_traits>
#include <archie/meta/eval.hpp>
#include <archie/fused/boolean.hpp>
#include <archie/meta/returns.hpp>
namespace archie {
namespace meta {
template <bool B>
using negation = boolean<!B>;
template <bool B>
using negation_t = eval<negation<B>>;
template <typename Tp>
using opposite = negation<Tp::value>;
template <typename Tp>
using opposite_t = negation_t<Tp::value>;
template <typename... Ts>
struct all : boolean<(... && Ts::value)> {
};
template <typename... Ts>
struct any : boolean<(... || Ts::value)> {
};
template <typename... Ts>
using none = boolean<!any<Ts...>::value>;
}
}
<|endoftext|> |
<commit_before>#include "RenderModel.h"
RenderModel::~RenderModel() {
unsigned int vertexCount = sizeof(m_vertexBuffers)/sizeof(m_vertexBuffers[0]);
unsigned int indexCount = sizeof(m_indexBuffers)/sizeof(m_indexBuffers[0]);
unsigned int normalCount = sizeof(m_normalBuffers)/sizeof(m_normalBuffers[0]);
unsigned int texCoordCount = sizeof(m_textureCoordBuffers)/sizeof(m_textureCoordBuffers[0]);
unsigned int samplerCount = sizeof(m_samplers)/sizeof(m_samplers[0]);
// Release GPU resources
glDeleteBuffers(vertexCount, m_vertexBuffers);
glDeleteBuffers(indexCount, m_indexBuffers);
glDeleteBuffers(normalCount, m_normalBuffers);
glDeleteBuffers(texCoordCount, m_textureCoordBuffers);
glDeleteSamplers(samplerCount, m_samplers);
glDeleteProgram(m_shaderProgram);
delete[] m_vertexBuffers;
delete[] m_indexBuffers;
delete[] m_normalBuffers;
delete[] m_textureCoordBuffers;
delete[] m_samplers;
}
void RenderModel::loadShaders(const char* vertexShaderFilename,
const char* pixelShaderFilename,
const char* geometryShaderFilename) {
if(!PHYSFS_exists(vertexShaderFilename)) {
throw std::runtime_error(std::string("Could not find vertex shader: ") + vertexShaderFilename);
}
if(!PHYSFS_exists(pixelShaderFilename)) {
throw std::runtime_error(std::string("Could not find pixel shader: ") + pixelShaderFilename);
}
if(geometryShaderFilename != nullptr && !PHYSFS_exists(geometryShaderFilename)) {
throw std::runtime_error(std::string("Could not find geometry shader: ") + geometryShaderFilename);
}
// NOTE: It may be possible to find the size by seeking if
// PHYSFS_fileLength fails
// Compile vertex shader
PHYSFS_File* vertexShaderFile = PHYSFS_openRead(vertexShaderFilename);
if(!vertexShaderFile) {
throw std::runtime_error(std::string("Could not open vertex shader: ") + vertexShaderFilename);
}
PHYSFS_sint64 vsFileSizeLong = PHYSFS_fileLength(vertexShaderFile);
if(vsFileSizeLong == -1)
throw std::runtime_error(std::string("Could not determine size of vertex shader: ") + vertexShaderFilename);
if(vsFileSizeLong > std::numeric_limits<int>::max())
throw std::runtime_error(std::string("Vertex shader too large: ") + vertexShaderFilename);
int vsFileSize = (int)vsFileSizeLong;
char* vsBuffer = new char[vsFileSize];
int vsBytesRead = PHYSFS_read(vertexShaderFile, vsBuffer, 1, vsFileSize);
PHYSFS_close(vertexShaderFile);
if(vsBytesRead < vsFileSize || vsBytesRead == -1) {
delete[] vsBuffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of vertex shader: ") + vertexShaderFilename);
}
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vsBuffer, &vsFileSize);
delete vsBuffer;
glCompileShader(vertexShader);
int isVSCompiled;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isVSCompiled);
if(isVSCompiled == GL_FALSE) {
int maxLength;
glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(vertexShader, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteShader(vertexShader);
throw std::runtime_error("Failed to compile vertex shader");
}
// Compile pixel shader
PHYSFS_File* pixelShaderFile = PHYSFS_openRead(pixelShaderFilename);
if(!pixelShaderFile) {
throw std::runtime_error(std::string("Could not open pixel shader: ") + pixelShaderFilename);
}
PHYSFS_sint64 psFileSizeLong = PHYSFS_fileLength(pixelShaderFile);
if(psFileSizeLong == -1)
throw std::runtime_error(std::string("Could not determine size of pixel shader: ") + pixelShaderFilename);
if(psFileSizeLong > std::numeric_limits<int>::max())
throw std::runtime_error(std::string("Pixel shader too large: ") + pixelShaderFilename);
int psFileSize = (int)psFileSizeLong;
char* psBuffer = new char[psFileSize];
int psBytesRead = PHYSFS_read(pixelShaderFile, psBuffer, 1, psFileSize);
PHYSFS_close(pixelShaderFile);
if(psBytesRead < psFileSize || psBytesRead == -1) {
delete[] psBuffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of pixel shader: ") + pixelShaderFilename);
}
unsigned int pixelShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(pixelShader, 1, &psBuffer, &psFileSize);
delete psBuffer;
glCompileShader(pixelShader);
int isPSCompiled;
glGetShaderiv(pixelShader, GL_COMPILE_STATUS, &isPSCompiled);
if(isPSCompiled == GL_FALSE) {
int maxLength;
glGetShaderiv(pixelShader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(pixelShader, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteShader(pixelShader);
throw std::runtime_error("Failed to compile pixel shader");
}
// Compile geometry shader
unsigned int geometryShader;
if(geometryShaderFilename != nullptr) {
PHYSFS_File* geometryShaderFile = PHYSFS_openRead(geometryShaderFilename);
if(!geometryShaderFile) {
throw std::runtime_error(std::string("Could not open geometry shader: ") + geometryShaderFilename);
}
PHYSFS_sint64 gsFileSizeLong = PHYSFS_fileLength(geometryShaderFile);
if(gsFileSizeLong == -1)
throw std::runtime_error(std::string("Could not determine size of geometry shader: ") + geometryShaderFilename);
if(gsFileSizeLong > std::numeric_limits<int>::max())
throw std::runtime_error(std::string("Geometry shader too large: ") + geometryShaderFilename);
int gsFileSize = (int)gsFileSizeLong;
char* gsBuffer = new char[gsFileSize];
int gsBytesRead = PHYSFS_read(geometryShaderFile, gsBuffer, 1, gsFileSize);
PHYSFS_close(geometryShaderFile);
if(gsBytesRead < gsFileSize || gsBytesRead == -1) {
delete[] gsBuffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of geometry shader: ") + geometryShaderFilename);
}
geometryShader = glCreateShader(GL_GEOMETRY_SHADER);
glShaderSource(vertexShader, 1, &gsBuffer, &gsFileSize);
delete gsBuffer;
glCompileShader(geometryShader);
int isGSCompiled;
glGetShaderiv(geometryShader, GL_COMPILE_STATUS, &isGSCompiled);
if(isGSCompiled == GL_FALSE) {
int maxLength;
glGetShaderiv(geometryShader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(geometryShader, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteShader(geometryShader);
throw std::runtime_error("Failed to compile geometry shader");
}
}
// Link shaders
m_shaderProgram = glCreateProgram();
glAttachShader(m_shaderProgram, vertexShader);
glAttachShader(m_shaderProgram, pixelShader);
if(geometryShaderFilename != nullptr) {
glAttachShader(m_shaderProgram, geometryShader);
}
glLinkProgram(m_shaderProgram);
int isLinked;
glGetProgramiv(m_shaderProgram, GL_LINK_STATUS, &isLinked);
if(isLinked == GL_FALSE) {
int maxLength = 0;
glGetProgramiv(m_shaderProgram, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(m_shaderProgram, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteProgram(m_shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(pixelShader);
if(geometryShaderFilename != nullptr) {
glDeleteShader(geometryShader);
}
throw std::runtime_error("Failed to link shader program");
}
glDetachShader(m_shaderProgram, vertexShader);
glDetachShader(m_shaderProgram, pixelShader);
if(geometryShaderFilename != nullptr) {
glDetachShader(m_shaderProgram, geometryShader);
}
}
unsigned int RenderModel::loadDDSTextureToGPU(const char* filename, int* baseWidth, int* baseHeight) {
if(std::string(filename).compare("") == 0 || !PHYSFS_exists(filename))
throw std::runtime_error(std::string("Could not find texture: ") + filename);
PHYSFS_File* file = PHYSFS_openRead(filename);
if(!file)
throw std::runtime_error(std::string("Could not open texture: ") + filename);
PHYSFS_sint64 fileSize = PHYSFS_fileLength(file);
if(fileSize == -1)
throw std::runtime_error(std::string("Could not determine size of texture: ") + filename);
char* buffer = new char[fileSize];
int bytesRead = PHYSFS_read(file, buffer, 1, fileSize);
PHYSFS_close(file);
if(bytesRead < fileSize || bytesRead == -1) {
delete[] buffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of texture: ") + filename);
}
// TODO: We need to check whether this is a valid DDS image
gli::texture2D texture(gli::load_dds(buffer, fileSize));
delete buffer;
*baseWidth = texture[0].dimensions().x;
*baseHeight = texture[0].dimensions().y;
gli::gl gl;
const gli::gl::format format = gl.translate(texture.format());
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D_ARRAY, textureID);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, texture.levels()-1);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_R, format.Swizzle[0]);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_G, format.Swizzle[1]);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_B, format.Swizzle[2]);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_A, format.Swizzle[3]);
glTexStorage3D(GL_TEXTURE_2D_ARRAY,
texture.levels(),
format.Internal,
texture.dimensions().x,
texture.dimensions().y,
1);
if(gli::is_compressed(texture.format())) {
for(std::size_t level=0; level<texture.levels(); ++level) {
glCompressedTexSubImage3D(GL_TEXTURE_2D_ARRAY,
level,
0,
0,
0,
texture[level].dimensions().x,
texture[level].dimensions().y,
1,
format.External,
texture[level].size(),
texture[level].data());
}
}
else {
for(std::size_t level=0; level<texture.levels(); ++level) {
glTexSubImage3D(GL_TEXTURE_2D_ARRAY,
level,
0,
0,
0,
texture[level].dimensions().x,
texture[level].dimensions().y,
1,
format.External,
format.Type,
texture[level].data());
}
}
return textureID;
}
<commit_msg>Fix memory leaks<commit_after>#include "RenderModel.h"
RenderModel::~RenderModel() {
unsigned int vertexCount = sizeof(m_vertexBuffers)/sizeof(m_vertexBuffers[0]);
unsigned int indexCount = sizeof(m_indexBuffers)/sizeof(m_indexBuffers[0]);
unsigned int normalCount = sizeof(m_normalBuffers)/sizeof(m_normalBuffers[0]);
unsigned int texCoordCount = sizeof(m_textureCoordBuffers)/sizeof(m_textureCoordBuffers[0]);
unsigned int samplerCount = sizeof(m_samplers)/sizeof(m_samplers[0]);
unsigned int textureCount = sizeof(m_textures)/sizeof(m_textures[0]);
// Release GPU resources
glDeleteBuffers(vertexCount, m_vertexBuffers);
glDeleteBuffers(indexCount, m_indexBuffers);
glDeleteBuffers(normalCount, m_normalBuffers);
glDeleteBuffers(texCoordCount, m_textureCoordBuffers);
glDeleteSamplers(samplerCount, m_samplers);
glDeleteBuffers(textureCount, m_textures);
glDeleteProgram(m_shaderProgram);
delete[] m_vertexBuffers;
delete[] m_indexBuffers;
delete[] m_normalBuffers;
delete[] m_textureCoordBuffers;
delete[] m_samplers;
delete[] m_textures;
}
void RenderModel::loadShaders(const char* vertexShaderFilename,
const char* pixelShaderFilename,
const char* geometryShaderFilename) {
if(!PHYSFS_exists(vertexShaderFilename)) {
throw std::runtime_error(std::string("Could not find vertex shader: ") + vertexShaderFilename);
}
if(!PHYSFS_exists(pixelShaderFilename)) {
throw std::runtime_error(std::string("Could not find pixel shader: ") + pixelShaderFilename);
}
if(geometryShaderFilename != nullptr && !PHYSFS_exists(geometryShaderFilename)) {
throw std::runtime_error(std::string("Could not find geometry shader: ") + geometryShaderFilename);
}
// NOTE: It may be possible to find the size by seeking if
// PHYSFS_fileLength fails
// Compile vertex shader
PHYSFS_File* vertexShaderFile = PHYSFS_openRead(vertexShaderFilename);
if(!vertexShaderFile) {
throw std::runtime_error(std::string("Could not open vertex shader: ") + vertexShaderFilename);
}
PHYSFS_sint64 vsFileSizeLong = PHYSFS_fileLength(vertexShaderFile);
if(vsFileSizeLong == -1)
throw std::runtime_error(std::string("Could not determine size of vertex shader: ") + vertexShaderFilename);
if(vsFileSizeLong > std::numeric_limits<int>::max())
throw std::runtime_error(std::string("Vertex shader too large: ") + vertexShaderFilename);
int vsFileSize = (int)vsFileSizeLong;
char* vsBuffer = new char[vsFileSize];
int vsBytesRead = PHYSFS_read(vertexShaderFile, vsBuffer, 1, vsFileSize);
PHYSFS_close(vertexShaderFile);
if(vsBytesRead < vsFileSize || vsBytesRead == -1) {
delete[] vsBuffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of vertex shader: ") + vertexShaderFilename);
}
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vsBuffer, &vsFileSize);
delete[] vsBuffer;
glCompileShader(vertexShader);
int isVSCompiled;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isVSCompiled);
if(isVSCompiled == GL_FALSE) {
int maxLength;
glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(vertexShader, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteShader(vertexShader);
throw std::runtime_error("Failed to compile vertex shader");
}
// Compile pixel shader
PHYSFS_File* pixelShaderFile = PHYSFS_openRead(pixelShaderFilename);
if(!pixelShaderFile) {
throw std::runtime_error(std::string("Could not open pixel shader: ") + pixelShaderFilename);
}
PHYSFS_sint64 psFileSizeLong = PHYSFS_fileLength(pixelShaderFile);
if(psFileSizeLong == -1)
throw std::runtime_error(std::string("Could not determine size of pixel shader: ") + pixelShaderFilename);
if(psFileSizeLong > std::numeric_limits<int>::max())
throw std::runtime_error(std::string("Pixel shader too large: ") + pixelShaderFilename);
int psFileSize = (int)psFileSizeLong;
char* psBuffer = new char[psFileSize];
int psBytesRead = PHYSFS_read(pixelShaderFile, psBuffer, 1, psFileSize);
PHYSFS_close(pixelShaderFile);
if(psBytesRead < psFileSize || psBytesRead == -1) {
delete[] psBuffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of pixel shader: ") + pixelShaderFilename);
}
unsigned int pixelShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(pixelShader, 1, &psBuffer, &psFileSize);
delete[] psBuffer;
glCompileShader(pixelShader);
int isPSCompiled;
glGetShaderiv(pixelShader, GL_COMPILE_STATUS, &isPSCompiled);
if(isPSCompiled == GL_FALSE) {
int maxLength;
glGetShaderiv(pixelShader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(pixelShader, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteShader(pixelShader);
throw std::runtime_error("Failed to compile pixel shader");
}
// Compile geometry shader
unsigned int geometryShader;
if(geometryShaderFilename != nullptr) {
PHYSFS_File* geometryShaderFile = PHYSFS_openRead(geometryShaderFilename);
if(!geometryShaderFile) {
throw std::runtime_error(std::string("Could not open geometry shader: ") + geometryShaderFilename);
}
PHYSFS_sint64 gsFileSizeLong = PHYSFS_fileLength(geometryShaderFile);
if(gsFileSizeLong == -1)
throw std::runtime_error(std::string("Could not determine size of geometry shader: ") + geometryShaderFilename);
if(gsFileSizeLong > std::numeric_limits<int>::max())
throw std::runtime_error(std::string("Geometry shader too large: ") + geometryShaderFilename);
int gsFileSize = (int)gsFileSizeLong;
char* gsBuffer = new char[gsFileSize];
int gsBytesRead = PHYSFS_read(geometryShaderFile, gsBuffer, 1, gsFileSize);
PHYSFS_close(geometryShaderFile);
if(gsBytesRead < gsFileSize || gsBytesRead == -1) {
delete[] gsBuffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of geometry shader: ") + geometryShaderFilename);
}
geometryShader = glCreateShader(GL_GEOMETRY_SHADER);
glShaderSource(vertexShader, 1, &gsBuffer, &gsFileSize);
delete[] gsBuffer;
glCompileShader(geometryShader);
int isGSCompiled;
glGetShaderiv(geometryShader, GL_COMPILE_STATUS, &isGSCompiled);
if(isGSCompiled == GL_FALSE) {
int maxLength;
glGetShaderiv(geometryShader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(geometryShader, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteShader(geometryShader);
throw std::runtime_error("Failed to compile geometry shader");
}
}
// Link shaders
m_shaderProgram = glCreateProgram();
glAttachShader(m_shaderProgram, vertexShader);
glAttachShader(m_shaderProgram, pixelShader);
if(geometryShaderFilename != nullptr) {
glAttachShader(m_shaderProgram, geometryShader);
}
glLinkProgram(m_shaderProgram);
int isLinked;
glGetProgramiv(m_shaderProgram, GL_LINK_STATUS, &isLinked);
if(isLinked == GL_FALSE) {
int maxLength = 0;
glGetProgramiv(m_shaderProgram, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(m_shaderProgram, maxLength, &maxLength, &infoLog[0]);
g_logger->write(Logger::ERROR, infoLog.data());
glDeleteProgram(m_shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(pixelShader);
if(geometryShaderFilename != nullptr) {
glDeleteShader(geometryShader);
}
throw std::runtime_error("Failed to link shader program");
}
glDetachShader(m_shaderProgram, vertexShader);
glDetachShader(m_shaderProgram, pixelShader);
if(geometryShaderFilename != nullptr) {
glDetachShader(m_shaderProgram, geometryShader);
}
}
unsigned int RenderModel::loadDDSTextureToGPU(const char* filename, int* baseWidth, int* baseHeight) {
if(std::string(filename).compare("") == 0 || !PHYSFS_exists(filename))
throw std::runtime_error(std::string("Could not find texture: ") + filename);
PHYSFS_File* file = PHYSFS_openRead(filename);
if(!file)
throw std::runtime_error(std::string("Could not open texture: ") + filename);
PHYSFS_sint64 fileSize = PHYSFS_fileLength(file);
if(fileSize == -1)
throw std::runtime_error(std::string("Could not determine size of texture: ") + filename);
char* buffer = new char[fileSize];
int bytesRead = PHYSFS_read(file, buffer, 1, fileSize);
PHYSFS_close(file);
if(bytesRead < fileSize || bytesRead == -1) {
delete[] buffer;
g_logger->write(Logger::ERROR, PHYSFS_getLastError());
throw std::runtime_error(std::string("Could not read all of texture: ") + filename);
}
// TODO: We need to check whether this is a valid DDS image
gli::texture2D texture(gli::load_dds(buffer, fileSize));
delete[] buffer;
*baseWidth = texture[0].dimensions().x;
*baseHeight = texture[0].dimensions().y;
gli::gl gl;
const gli::gl::format format = gl.translate(texture.format());
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D_ARRAY, textureID);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, texture.levels()-1);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_R, format.Swizzle[0]);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_G, format.Swizzle[1]);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_B, format.Swizzle[2]);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_A, format.Swizzle[3]);
glTexStorage3D(GL_TEXTURE_2D_ARRAY,
texture.levels(),
format.Internal,
texture.dimensions().x,
texture.dimensions().y,
1);
if(gli::is_compressed(texture.format())) {
for(std::size_t level=0; level<texture.levels(); ++level) {
glCompressedTexSubImage3D(GL_TEXTURE_2D_ARRAY,
level,
0,
0,
0,
texture[level].dimensions().x,
texture[level].dimensions().y,
1,
format.External,
texture[level].size(),
texture[level].data());
}
}
else {
for(std::size_t level=0; level<texture.levels(); ++level) {
glTexSubImage3D(GL_TEXTURE_2D_ARRAY,
level,
0,
0,
0,
texture[level].dimensions().x,
texture[level].dimensions().y,
1,
format.External,
format.Type,
texture[level].data());
}
}
return textureID;
}
<|endoftext|> |
<commit_before>/** \file create_literary_remains_records.cc
* \author Dr. Johannes Ruscheinski
*
* A tool for creating literary remains MARC records from Beacon files.
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <unordered_set>
#include "MARC.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "util.h"
namespace {
void CopyMarc(MARC::Reader * const reader, MARC::Writer * const writer) {
while (auto record = reader->read())
writer->write(record);
}
struct LiteraryRemainsInfo {
std::string author_name_;
std::string url_;
public:
LiteraryRemainsInfo() = default;
LiteraryRemainsInfo(const LiteraryRemainsInfo &other) = default;
LiteraryRemainsInfo(const std::string &author_name, const std::string &url): author_name_(author_name), url_(url) { }
LiteraryRemainsInfo &operator=(const LiteraryRemainsInfo &rhs) = default;
};
void LoadAuthorGNDNumbers(
const std::string &filename,
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> * const gnd_numbers_to_literary_remains_infos_map)
{
auto reader(MARC::Reader::Factory(filename));
unsigned total_count(0), references_count(0);
while (auto record = reader->read()) {
++total_count;
auto beacon_field(record.findTag("BEA"));
if (beacon_field == record.end())
continue;
const auto _100_field(record.findTag("100"));
if (_100_field == record.end() or not _100_field->hasSubfield('a'))
continue;
std::string gnd_number;
if (not MARC::GetGNDCode(record, &gnd_number))
continue;
const std::string author_name(_100_field->getFirstSubfieldWithCode('a'));
std::vector<LiteraryRemainsInfo> literary_remains_infos;
while (beacon_field != record.end() and beacon_field->getTag() == "BEA") {
literary_remains_infos.emplace_back(author_name, beacon_field->getFirstSubfieldWithCode('u'));;
++beacon_field;
}
(*gnd_numbers_to_literary_remains_infos_map)[gnd_number] = literary_remains_infos;
references_count += literary_remains_infos.size();
}
LOG_INFO("Loaded " + std::to_string(references_count) + " literary remains references from \"" + filename
+ "\" which contained a total of " + std::to_string(total_count) + " records.");
}
void AppendLiteraryRemainsRecords(
MARC::Writer * const writer,
const std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> &gnd_numbers_to_literary_remains_infos_map)
{
unsigned creation_count(0);
for (const auto &gnd_numbers_and_literary_remains_infos : gnd_numbers_to_literary_remains_infos_map) {
MARC::Record new_record(MARC::Record::TypeOfRecord::MIXED_MATERIALS, MARC::Record::BibliographicLevel::COLLECTION,
"LR" + StringUtil::ToString(++creation_count, /* base = */10, /* width= */6, /* padding_char = */'0'));
const std::string &author_name(gnd_numbers_and_literary_remains_infos.second.front().author_name_);
new_record.insertField("003", "PipeLineGenerated");
new_record.insertField("005", TimeUtil::GetCurrentDateAndTime("%Y%m%d%H:%M:%S") + ".0");
new_record.insertField("100", { { 'a', author_name }, { '0', "(DE-588)" + gnd_numbers_and_literary_remains_infos.first } });
new_record.insertField("245", { { 'a', "Nachlass von " + author_name } });
for (const auto &literary_remains_info : gnd_numbers_and_literary_remains_infos.second)
new_record.insertField("856", { { 'u', literary_remains_info.url_ }, { '3', "Nachlassdatenbank" } });
writer->write(new_record);
}
LOG_INFO("Appended a total of " + std::to_string(creation_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 4)
::Usage("marc_input marc_output authority_records");
auto reader(MARC::Reader::Factory(argv[1]));
auto writer(MARC::Writer::Factory(argv[2]));
CopyMarc(reader.get(), writer.get());
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> gnd_numbers_to_literary_remains_infos_map;
LoadAuthorGNDNumbers(argv[3], &gnd_numbers_to_literary_remains_infos_map);
AppendLiteraryRemainsRecords(writer.get(), gnd_numbers_to_literary_remains_infos_map);
return EXIT_SUCCESS;
}
<commit_msg>Added a bogus 008 field.<commit_after>/** \file create_literary_remains_records.cc
* \author Dr. Johannes Ruscheinski
*
* A tool for creating literary remains MARC records from Beacon files.
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <unordered_set>
#include "MARC.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "util.h"
namespace {
void CopyMarc(MARC::Reader * const reader, MARC::Writer * const writer) {
while (auto record = reader->read())
writer->write(record);
}
struct LiteraryRemainsInfo {
std::string author_name_;
std::string url_;
public:
LiteraryRemainsInfo() = default;
LiteraryRemainsInfo(const LiteraryRemainsInfo &other) = default;
LiteraryRemainsInfo(const std::string &author_name, const std::string &url): author_name_(author_name), url_(url) { }
LiteraryRemainsInfo &operator=(const LiteraryRemainsInfo &rhs) = default;
};
void LoadAuthorGNDNumbers(
const std::string &filename,
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> * const gnd_numbers_to_literary_remains_infos_map)
{
auto reader(MARC::Reader::Factory(filename));
unsigned total_count(0), references_count(0);
while (auto record = reader->read()) {
++total_count;
auto beacon_field(record.findTag("BEA"));
if (beacon_field == record.end())
continue;
const auto _100_field(record.findTag("100"));
if (_100_field == record.end() or not _100_field->hasSubfield('a'))
continue;
std::string gnd_number;
if (not MARC::GetGNDCode(record, &gnd_number))
continue;
const std::string author_name(_100_field->getFirstSubfieldWithCode('a'));
std::vector<LiteraryRemainsInfo> literary_remains_infos;
while (beacon_field != record.end() and beacon_field->getTag() == "BEA") {
literary_remains_infos.emplace_back(author_name, beacon_field->getFirstSubfieldWithCode('u'));;
++beacon_field;
}
(*gnd_numbers_to_literary_remains_infos_map)[gnd_number] = literary_remains_infos;
references_count += literary_remains_infos.size();
}
LOG_INFO("Loaded " + std::to_string(references_count) + " literary remains references from \"" + filename
+ "\" which contained a total of " + std::to_string(total_count) + " records.");
}
void AppendLiteraryRemainsRecords(
MARC::Writer * const writer,
const std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> &gnd_numbers_to_literary_remains_infos_map)
{
unsigned creation_count(0);
for (const auto &gnd_numbers_and_literary_remains_infos : gnd_numbers_to_literary_remains_infos_map) {
MARC::Record new_record(MARC::Record::TypeOfRecord::MIXED_MATERIALS, MARC::Record::BibliographicLevel::COLLECTION,
"LR" + StringUtil::ToString(++creation_count, /* base = */10, /* width= */6, /* padding_char = */'0'));
const std::string &author_name(gnd_numbers_and_literary_remains_infos.second.front().author_name_);
new_record.insertField("003", "PipeLineGenerated");
new_record.insertField("005", TimeUtil::GetCurrentDateAndTime("%Y%m%d%H%M%S") + ".0");
new_record.insertField("008", "190606s2019 xx ||||| 00| ||ger c");
new_record.insertField("100", { { 'a', author_name }, { '0', "(DE-588)" + gnd_numbers_and_literary_remains_infos.first } });
new_record.insertField("245", { { 'a', "Nachlass von " + author_name } });
for (const auto &literary_remains_info : gnd_numbers_and_literary_remains_infos.second)
new_record.insertField("856", { { 'u', literary_remains_info.url_ }, { '3', "Nachlassdatenbank" } });
writer->write(new_record);
}
LOG_INFO("Appended a total of " + std::to_string(creation_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 4)
::Usage("marc_input marc_output authority_records");
auto reader(MARC::Reader::Factory(argv[1]));
auto writer(MARC::Writer::Factory(argv[2]));
CopyMarc(reader.get(), writer.get());
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> gnd_numbers_to_literary_remains_infos_map;
LoadAuthorGNDNumbers(argv[3], &gnd_numbers_to_literary_remains_infos_map);
AppendLiteraryRemainsRecords(writer.get(), gnd_numbers_to_literary_remains_infos_map);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <cppunit/TestFailure.h>
#include <cppunit/TextTestProgressListener.h>
#include <cppunit/portability/Stream.h>
CPPUNIT_NS_BEGIN
TextTestProgressListener::TextTestProgressListener()
{
}
TextTestProgressListener::~TextTestProgressListener()
{
}
void
TextTestProgressListener::startTest( Test * )
{
stdCOut() << ".";
}
void
TextTestProgressListener::addFailure( const TestFailure &failure )
{
stdCOut() << ( failure.isError() ? "E" : "F" );
}
void
TextTestProgressListener::endTestRun( Test *,
TestResult * )
{
stdCOut() << "\n";
stdCOut().flush();
}
CPPUNIT_NS_END
<commit_msg>Bug 1649369: Flush stdCOut after startTest() and addFailure(). Fix from the supplied flush patch.<commit_after>#include <cppunit/TestFailure.h>
#include <cppunit/TextTestProgressListener.h>
#include <cppunit/portability/Stream.h>
CPPUNIT_NS_BEGIN
TextTestProgressListener::TextTestProgressListener()
{
}
TextTestProgressListener::~TextTestProgressListener()
{
}
void
TextTestProgressListener::startTest( Test * )
{
stdCOut() << ".";
stdCOut().flush();
}
void
TextTestProgressListener::addFailure( const TestFailure &failure )
{
stdCOut() << ( failure.isError() ? "E" : "F" );
stdCOut().flush();
}
void
TextTestProgressListener::endTestRun( Test *,
TestResult * )
{
stdCOut() << "\n";
stdCOut().flush();
}
CPPUNIT_NS_END
<|endoftext|> |
<commit_before>#include "scheduler.h"
#include "cell.h"
#include "gtest/gtest.h"
#include "io_util.h"
#include "test_util.h"
#include "unistd.h"
#define ROOTFILE "bdmFile.root"
namespace bdm {
namespace scheduler_test_internal {
class TestSchedulerRestore : public Scheduler<> {
public:
explicit TestSchedulerRestore(const std::string& restore)
: Scheduler<>("", restore) {}
void Execute() override { execute_calls++; }
unsigned execute_calls = 0;
};
class TestSchedulerBackup : public Scheduler<> {
public:
explicit TestSchedulerBackup(const std::string& backup)
: Scheduler<>(backup, "") {}
void Execute() override {
// sleep
usleep(350000);
// backup should be created every second -> every three iterations
if (execute_calls_ % 3 != 0 || execute_calls_ == 0) {
EXPECT_FALSE(FileExists(ROOTFILE));
} else {
EXPECT_TRUE(FileExists(ROOTFILE));
remove(ROOTFILE);
}
execute_calls_++;
}
unsigned execute_calls_ = 0;
};
TEST(SchedulerTest, NoRestoreFile) {
remove(ROOTFILE);
// start restore validation
TestSchedulerRestore scheduler("");
scheduler.Simulate(100);
EXPECT_EQ(100u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
scheduler.Simulate(100);
EXPECT_EQ(200u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
scheduler.Simulate(100);
EXPECT_EQ(300u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
}
TEST(DISABLED_SchedulerTest, Restore) {
remove(ROOTFILE);
// create backup that will be restored later on
auto cells = Cell::NewEmptySoa();
cells.push_back(Cell());
SimulationBackup backup(ROOTFILE, "");
backup.Backup(&cells, 149);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
// start restore validation
TestSchedulerRestore scheduler(ROOTFILE);
// 149 simulation steps have already been calculated. Therefore, this call
// should be ignored
scheduler.Simulate(100);
EXPECT_EQ(0u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
// Restore should happen within this call
scheduler.Simulate(100);
// only 51 steps should be simulated
EXPECT_EQ(51u, scheduler.execute_calls);
EXPECT_EQ(1u, ResourceManager<>::Get()->Get<Cell>()->size());
// add element to see if if restore happens again
ResourceManager<>::Get()->Get<Cell>()->push_back(Cell());
// normal simulation - no restore
scheduler.Simulate(100);
EXPECT_EQ(151u, scheduler.execute_calls);
EXPECT_EQ(2u, ResourceManager<>::Get()->Get<Cell>()->size());
remove(ROOTFILE);
}
TEST(SchedulerTest, Backup) {
remove(ROOTFILE);
TestSchedulerBackup scheduler(ROOTFILE);
Param::backup_every_x_seconds_ = 1;
// one simulation step takes 350 ms -> backup should be created every three
// steps
scheduler.Simulate(7);
remove(ROOTFILE);
}
} // namespace scheduler_test_internal
} // namespace bdm
<commit_msg>Fix Travis-CI test timeout due to missing ResourceManager reset in SchedulerTest<commit_after>#include "scheduler.h"
#include "cell.h"
#include "gtest/gtest.h"
#include "io_util.h"
#include "test_util.h"
#include "unistd.h"
#define ROOTFILE "bdmFile.root"
namespace bdm {
namespace scheduler_test_internal {
class TestSchedulerRestore : public Scheduler<> {
public:
explicit TestSchedulerRestore(const std::string& restore)
: Scheduler<>("", restore) {}
void Execute() override { execute_calls++; }
unsigned execute_calls = 0;
};
class TestSchedulerBackup : public Scheduler<> {
public:
explicit TestSchedulerBackup(const std::string& backup)
: Scheduler<>(backup, "") {}
void Execute() override {
// sleep
usleep(350000);
// backup should be created every second -> every three iterations
if (execute_calls_ % 3 != 0 || execute_calls_ == 0) {
EXPECT_FALSE(FileExists(ROOTFILE));
} else {
EXPECT_TRUE(FileExists(ROOTFILE));
remove(ROOTFILE);
}
execute_calls_++;
}
unsigned execute_calls_ = 0;
};
TEST(SchedulerTest, NoRestoreFile) {
ResourceManager<>::Get()->Clear();
remove(ROOTFILE);
// start restore validation
TestSchedulerRestore scheduler("");
scheduler.Simulate(100);
EXPECT_EQ(100u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
scheduler.Simulate(100);
EXPECT_EQ(200u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
scheduler.Simulate(100);
EXPECT_EQ(300u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
}
TEST(DISABLED_SchedulerTest, Restore) {
ResourceManager<>::Get()->Clear();
remove(ROOTFILE);
// create backup that will be restored later on
auto cells = Cell::NewEmptySoa();
cells.push_back(Cell());
SimulationBackup backup(ROOTFILE, "");
backup.Backup(&cells, 149);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
// start restore validation
TestSchedulerRestore scheduler(ROOTFILE);
// 149 simulation steps have already been calculated. Therefore, this call
// should be ignored
scheduler.Simulate(100);
EXPECT_EQ(0u, scheduler.execute_calls);
EXPECT_EQ(0u, ResourceManager<>::Get()->Get<Cell>()->size());
// Restore should happen within this call
scheduler.Simulate(100);
// only 51 steps should be simulated
EXPECT_EQ(51u, scheduler.execute_calls);
EXPECT_EQ(1u, ResourceManager<>::Get()->Get<Cell>()->size());
// add element to see if if restore happens again
ResourceManager<>::Get()->Get<Cell>()->push_back(Cell());
// normal simulation - no restore
scheduler.Simulate(100);
EXPECT_EQ(151u, scheduler.execute_calls);
EXPECT_EQ(2u, ResourceManager<>::Get()->Get<Cell>()->size());
remove(ROOTFILE);
}
TEST(SchedulerTest, Backup) {
ResourceManager<>::Get()->Clear();
remove(ROOTFILE);
TestSchedulerBackup scheduler(ROOTFILE);
Param::backup_every_x_seconds_ = 1;
// one simulation step takes 350 ms -> backup should be created every three
// steps
scheduler.Simulate(7);
remove(ROOTFILE);
}
} // namespace scheduler_test_internal
} // namespace bdm
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 1000000
int s[56];
int getCallerAndCalled(int k, bool over) {
if (over) {
s[k] = (s[k + 55 - 24] + s[k]) % MAX;
}
else {
long long tmp = k;
tmp *= (long long)k;
tmp *= (long long)k;
tmp *= 300007;
tmp += 100003;
tmp -= (long long)(k * 200003);
s[k] = tmp % MAX;
}
return s[k];
}
vector<int> friend_index(MAX);
vector<int> free_index(MAX/2);
vector< vector<int> > friends(MAX/2);
int pm_friend_index = -1;
int next_free = 0;
int pm = 0;
void makeFriend(int caller, int called) {
if (friend_index[caller] < 0 && friend_index[called] < 0) {
// make new friend group
int new_index = next_free;
next_free = free_index[next_free];
friends[new_index].push_back(caller);
friends[new_index].push_back(called);
free_index[new_index] = -1;
friend_index[caller] = new_index;
friend_index[called] = new_index;
}
else if (friend_index[caller] >= 0 && friend_index[called] >= 0) {
// merge two friend groups
if (friend_index[caller] != friend_index[called]) {
int called_size = friends[friend_index[called]].size();
int caller_size = friends[friend_index[caller]].size();
int from_index;
int to_index;
if (caller_size > called_size) {
// called => caller
from_index = friend_index[called];
to_index = friend_index[caller];
}
else {
// caller => called
from_index = friend_index[caller];
to_index = friend_index[called];
}
for (size_t i = 0; i < friends[from_index].size(); i++) {
friends[to_index].push_back(friends[from_index][i]);
friend_index[friends[from_index][i]] = to_index;
}
friends[from_index].clear();
free_index[from_index] = next_free;
next_free = from_index;
}
}
else {
// add to one friend group
if (friend_index[caller] < 0) {
friend_index[caller] = friend_index[called];
friends[friend_index[called]].push_back(caller);
}
else {
// friend_index[called] < 0
friend_index[called] = friend_index[caller];
friends[friend_index[caller]].push_back(called);
}
}
if (pm == caller) {
pm_friend_index = friend_index[caller];
}
if (pm == called) {
pm_friend_index = friend_index[called];
}
}
int main() {
string prime_minister;
int p;
cin >> prime_minister >> p;
for (size_t i = 0; i < prime_minister.length(); i++) {
pm = pm * 10 + (prime_minister[0] - '0');
}
for (size_t i = 0; i < free_index.size(); i++) {
free_index[i] = i + 1;
}
for (size_t i = 0; i < friend_index.size(); i++) {
friend_index[i] = -1;
}
long long output = 0;
int k = 1;
bool over = false;
while(true) {
int caller = getCallerAndCalled(k, over);
k ++;
if (k > 55) {
k = 1;
over = true;
}
int called = getCallerAndCalled(k, over);
// cout << caller << " " << called << endl;
if (caller != called) {
output ++;
makeFriend(caller, called);
if (0 <= pm_friend_index) {
if ((friends[pm_friend_index].size() + 1) >= (MAX / 100 * p)) {
break;
}
}
}
k ++;
if (k > 55) {
k = 1;
over = true;
}
}
cout << output << endl;
return 0;
}
<commit_msg>35.00 points<commit_after>#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 1000000
int s[56];
int getCallerAndCalled(int k, bool over) {
if (over) {
if (k + 55 - 24 < 56) {
s[k] = (s[k + 55 - 24] + s[k]) % MAX;
}
else {
s[k] = (s[k - 24] + s[k]) % MAX;
}
}
else {
long long tmp = k;
tmp *= (long long)k;
tmp *= (long long)k;
tmp *= 300007;
tmp += 100003;
tmp -= (long long)(k * 200003);
s[k] = tmp % MAX;
}
return s[k];
}
vector<int> friend_index(MAX);
vector<int> free_index(MAX/2);
vector< vector<int> > friends(MAX/2);
int pm_friend_index = -1;
int next_free = 0;
int pm = 0;
void makeFriend(int caller, int called) {
if (friend_index[caller] < 0 && friend_index[called] < 0) {
// make new friend group
int new_index = next_free;
next_free = free_index[next_free];
friends[new_index].push_back(caller);
friends[new_index].push_back(called);
free_index[new_index] = -1;
friend_index[caller] = new_index;
friend_index[called] = new_index;
// cout << "make new friend group " << new_index << endl;
}
else if (friend_index[caller] >= 0 && friend_index[called] >= 0) {
// merge two friend groups
if (friend_index[caller] != friend_index[called]) {
int called_size = friends[friend_index[called]].size();
int caller_size = friends[friend_index[caller]].size();
int from_index;
int to_index;
if (caller_size > called_size) {
// called => caller
from_index = friend_index[called];
to_index = friend_index[caller];
}
else {
// caller => called
from_index = friend_index[caller];
to_index = friend_index[called];
}
for (size_t i = 0; i < friends[from_index].size(); i++) {
friends[to_index].push_back(friends[from_index][i]);
friend_index[friends[from_index][i]] = to_index;
}
friends[from_index].clear();
free_index[from_index] = next_free;
next_free = from_index;
// cout << "merge two friend groups " << from_index << " => " << to_index << endl;
}
}
else {
// add to one friend group
if (friend_index[caller] < 0) {
friend_index[caller] = friend_index[called];
friends[friend_index[called]].push_back(caller);
// cout << "add to friend group " << friend_index[called] << endl;
}
else {
// friend_index[called] < 0
friend_index[called] = friend_index[caller];
friends[friend_index[caller]].push_back(called);
// cout << "add to friend group " << friend_index[caller] << endl;
}
}
if (pm == caller) {
pm_friend_index = friend_index[caller];
}
if (pm == called) {
pm_friend_index = friend_index[called];
}
}
int main() {
string prime_minister;
int p;
cin >> prime_minister >> p;
for (size_t i = 0; i < prime_minister.length(); i++) {
pm = pm * 10 + (prime_minister[i] - '0');
}
for (size_t i = 0; i < free_index.size(); i++) {
free_index[i] = i + 1;
}
for (size_t i = 0; i < friend_index.size(); i++) {
friend_index[i] = -1;
}
long long output = 0;
int k = 1;
bool over = false;
while(true) {
int caller = getCallerAndCalled(k, over);
k ++;
if (k > 55) {
k = 1;
over = true;
}
int called = getCallerAndCalled(k, over);
// cout << caller << " " << called << endl;
if (caller != called) {
output ++;
makeFriend(caller, called);
if (0 <= pm_friend_index) {
if ((friends[pm_friend_index].size() + 1) >= (MAX / 100 * p)) {
break;
}
}
}
k ++;
if (k > 55) {
k = 1;
over = true;
}
}
cout << output << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* bench.cpp
*
* Benchmarks of libsrt vs C++ STL
*
* Copyright (c) 2015-2016, F. Aragon. All rights reserved. Released under
* the BSD 3-Clause License (see the doc/LICENSE file included).
*/
#include "../src/libsrt.h"
#include <map>
#include <set>
#include <string>
#if __cplusplus >= 201103L
#include <unordered_map>
#endif
#if defined(__linux__) || defined(__unix__) || defined(_POSIX_VERSION)
#include <time.h>
#include <stdio.h>
#define BENCH_INIT \
struct timespec ta, tb
#define BENCH_TIME_US \
((tb.tv_sec - ta.tv_sec) * 1000000 + (tb.tv_nsec - ta.tv_nsec) / 1000)
#define BENCH_FN(test_fn, count) \
clock_gettime(CLOCK_REALTIME, &ta); \
test_fn(count); \
clock_gettime(CLOCK_REALTIME, &tb); \
printf("test %s: %u.%03u seconds (%u elements)\n", #test_fn, \
(unsigned)(BENCH_TIME_MS / 1000), \
(unsigned)(BENCH_TIME_MS % 1000), \
(unsigned)count)
#else
#define BENCH_INIT
#define BENCH_FN
#define BENCH_TIME_US 0
#endif
#define BENCH_TIME_MS \
(BENCH_TIME_US / 1000)
void ctest_map_ii32(size_t count)
{
sm_t *m = sm_alloc(SM_II32, 0);
for (size_t i = 0; i < count; i++)
sm_insert_ii32(&m, (int32_t)i, (int32_t)i);
sm_free(&m);
}
void cxxtest_map_ii32(size_t count)
{
std::map <int32_t, int32_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int32_t)i;
}
void ctest_map_ii64(size_t count)
{
sm_t *m = sm_alloc(SM_II, 0);
for (size_t i = 0; i < count; i++)
sm_insert_ii32(&m, (int64_t)i, (int64_t)i);
sm_free(&m);
}
void cxxtest_map_ii64(size_t count)
{
std::map <int64_t, int64_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int64_t)i;
}
void ctest_map_s16(size_t count)
{
ss_t *btmp = ss_alloca(512);
sm_t *m = sm_alloc(SM_SS, 0);
for (size_t i = 0; i < count; i++) {
ss_printf(&btmp, 512, "%016i", (int)i);
sm_insert_ss(&m, btmp, btmp);
}
sm_free(&m);
}
void cxxtest_map_s16(size_t count)
{
char btmp[512];
std::map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%016i", (int)i);
m[btmp] = btmp;
}
}
void ctest_map_s64(size_t count)
{
ss_t *btmp = ss_alloca(512);
sm_t *m = sm_alloc(SM_SS, 0);
for (size_t i = 0; i < count; i++) {
ss_printf(&btmp, 512, "%064i", (int)i);
sm_insert_ss(&m, btmp, btmp);
}
sm_free(&m);
}
void cxxtest_map_s64(size_t count)
{
char btmp[512];
std::map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%064i", (int)i);
m[btmp] = btmp;
}
}
#if __cplusplus >= 201103L
void cxxtest_umap_ii32(size_t count)
{
std::unordered_map <int32_t, int32_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int32_t)i;
}
void cxxtest_umap_ii64(size_t count)
{
std::unordered_map <int64_t, int64_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int64_t)i;
}
void cxxtest_umap_s16(size_t count)
{
char btmp[512];
std::unordered_map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%016i", (int)i);
m[btmp] = btmp;
}
}
void cxxtest_umap_s64(size_t count)
{
char btmp[512];
std::unordered_map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%064i", (int)i);
m[btmp] = btmp;
}
}
#endif
int main(int argc, char *argv[])
{
BENCH_INIT;
size_t count = 1000000;
BENCH_FN(ctest_map_ii32, count);
BENCH_FN(cxxtest_map_ii32, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_ii32, count);
#endif
BENCH_FN(ctest_map_ii64, count);
BENCH_FN(cxxtest_map_ii64, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_ii64, count);
#endif
BENCH_FN(ctest_map_s16, count);
BENCH_FN(cxxtest_map_s16, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_s16, count);
#endif
BENCH_FN(ctest_map_s64, count);
BENCH_FN(cxxtest_map_s64, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_s64, count);
#endif
return 0;
}
<commit_msg>benchmarks<commit_after>/*
* bench.cpp
*
* Benchmarks of libsrt vs C++ STL
*
* Copyright (c) 2015-2016, F. Aragon. All rights reserved. Released under
* the BSD 3-Clause License (see the doc/LICENSE file included).
*/
#include "../src/libsrt.h"
#include <map>
#include <set>
#include <string>
#if __cplusplus >= 201103L
#include <unordered_map>
#endif
#if defined(__linux__) || defined(__unix__) || defined(_POSIX_VERSION)
#include <time.h>
#include <stdio.h>
#define BENCH_INIT \
struct timespec ta, tb
#define BENCH_TIME_US \
((tb.tv_sec - ta.tv_sec) * 1000000 + (tb.tv_nsec - ta.tv_nsec) / 1000)
#define BENCH_FN(test_fn, count) \
clock_gettime(CLOCK_REALTIME, &ta); \
test_fn(count); \
clock_gettime(CLOCK_REALTIME, &tb); \
printf("test %s: %u.%03u seconds (%u elements)\n", #test_fn, \
(unsigned)(BENCH_TIME_MS / 1000), \
(unsigned)(BENCH_TIME_MS % 1000), \
(unsigned)count)
#else
#define BENCH_INIT
#define BENCH_FN
#define BENCH_TIME_US 0
#endif
#define BENCH_TIME_MS \
(BENCH_TIME_US / 1000)
void ctest_map_ii32(size_t count)
{
sm_t *m = sm_alloc(SM_II32, 0);
for (size_t i = 0; i < count; i++)
sm_insert_ii32(&m, (int32_t)i, (int32_t)i);
sm_free(&m);
}
void cxxtest_map_ii32(size_t count)
{
std::map <int32_t, int32_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int32_t)i;
}
void ctest_map_ii64(size_t count)
{
sm_t *m = sm_alloc(SM_II, 0);
for (size_t i = 0; i < count; i++)
sm_insert_ii(&m, (int64_t)i, (int64_t)i);
sm_free(&m);
}
void cxxtest_map_ii64(size_t count)
{
std::map <int64_t, int64_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int64_t)i;
}
void ctest_map_s16(size_t count)
{
ss_t *btmp = ss_alloca(512);
sm_t *m = sm_alloc(SM_SS, 0);
for (size_t i = 0; i < count; i++) {
ss_printf(&btmp, 512, "%016i", (int)i);
sm_insert_ss(&m, btmp, btmp);
}
sm_free(&m);
}
void cxxtest_map_s16(size_t count)
{
char btmp[512];
std::map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%016i", (int)i);
m[btmp] = btmp;
}
}
void ctest_map_s64(size_t count)
{
ss_t *btmp = ss_alloca(512);
sm_t *m = sm_alloc(SM_SS, 0);
for (size_t i = 0; i < count; i++) {
ss_printf(&btmp, 512, "%064i", (int)i);
sm_insert_ss(&m, btmp, btmp);
}
sm_free(&m);
}
void cxxtest_map_s64(size_t count)
{
char btmp[512];
std::map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%064i", (int)i);
m[btmp] = btmp;
}
}
#if __cplusplus >= 201103L
void cxxtest_umap_ii32(size_t count)
{
std::unordered_map <int32_t, int32_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int32_t)i;
}
void cxxtest_umap_ii64(size_t count)
{
std::unordered_map <int64_t, int64_t> m;
for (size_t i = 0; i < count; i++)
m[i] = (int64_t)i;
}
void cxxtest_umap_s16(size_t count)
{
char btmp[512];
std::unordered_map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%016i", (int)i);
m[btmp] = btmp;
}
}
void cxxtest_umap_s64(size_t count)
{
char btmp[512];
std::unordered_map <std::string, std::string> m;
for (size_t i = 0; i < count; i++) {
sprintf(btmp, "%064i", (int)i);
m[btmp] = btmp;
}
}
#endif
int main(int argc, char *argv[])
{
BENCH_INIT;
size_t count = 1000000;
printf("Insert %zu elements, and then, release memory.\n", count);
BENCH_FN(ctest_map_ii32, count);
BENCH_FN(cxxtest_map_ii32, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_ii32, count);
#endif
BENCH_FN(ctest_map_ii64, count);
BENCH_FN(cxxtest_map_ii64, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_ii64, count);
#endif
BENCH_FN(ctest_map_s16, count);
BENCH_FN(cxxtest_map_s16, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_s16, count);
#endif
BENCH_FN(ctest_map_s64, count);
BENCH_FN(cxxtest_map_s64, count);
#if __cplusplus >= 201103L
BENCH_FN(cxxtest_umap_s64, count);
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*
* HemisphereA100GPS.cpp
*
* Created on: Nov 5, 2012
* Author: Matthew Barulic
*/
#include "nmeacompatiblegps.h"
#include "nmea.hpp"
#include <string>
NMEACompatibleGPS::NMEACompatibleGPS(string devicePath, uint baudRate)
:serialPort(devicePath, baudRate),
//serialPort("/dev/ttyGPS", 19200/*For HemisphereA100 4800*/),
LonNewSerialLine(this),
stateQueue()
{
serialPort.onNewLine += &LonNewSerialLine;
maxBufferLength = 10;
serialPort.startEvents();
std::cout << "GPS inited" << std::endl;
}
void NMEACompatibleGPS::onNewSerialLine(string line) {
GPSData state;
if(parseLine(line, state)) {
// TODO set time
// gettimeofday(&state.laptoptime, NULL);
boost::mutex::scoped_lock lock(queueLocker);
stateQueue.push_back(state);
if(stateQueue.size() > maxBufferLength) {
stateQueue.pop_front();
}
onNewData(state);
}
}
bool NMEACompatibleGPS::parseLine(std::string line, GPSData &state) {
return nmea::decodeGPGGA(line, state) ||
nmea::decodeGPRMC(line, state);
}
GPSData NMEACompatibleGPS::GetState() {
boost::mutex::scoped_lock lock(queueLocker);
GPSData state = stateQueue.back();
stateQueue.remove(state);
return state;
}
GPSData NMEACompatibleGPS::GetStateAtTime(timeval time) {
boost::mutex::scoped_lock lock(queueLocker);
std::list<GPSData>::iterator iter = stateQueue.begin();
//double acceptableError = 0.1;
while(iter != stateQueue.end()) {
GPSData s = (*iter);
/*time_t secDelta = difftime(time.tv_sec, s.laptoptime.tv_sec);
suseconds_t usecDelta = time.tv_usec - s.laptoptime.tv_usec;
double delta = double(secDelta) + 1e-6*double(usecDelta);
if(delta <= acceptableError) {
// iter = stateQueue.erase(iter);
return s;
} else {
iter++;
}*/
}
GPSData empty;
return empty;
}
bool NMEACompatibleGPS::StateIsAvailable() {
return !stateQueue.empty();
}
bool NMEACompatibleGPS::isOpen() {
return serialPort.isConnected();
}
NMEACompatibleGPS::~NMEACompatibleGPS() {
serialPort.stopEvents();
serialPort.close();
}
<commit_msg>Moves gps init printout to a log message.<commit_after>/*
* HemisphereA100GPS.cpp
*
* Created on: Nov 5, 2012
* Author: Matthew Barulic
*/
#include "nmeacompatiblegps.h"
#include "nmea.hpp"
#include <string>
#include <common/logger/logger.h>
NMEACompatibleGPS::NMEACompatibleGPS(string devicePath, uint baudRate)
:serialPort(devicePath, baudRate),
//serialPort("/dev/ttyGPS", 19200/*For HemisphereA100 4800*/),
LonNewSerialLine(this),
stateQueue()
{
serialPort.onNewLine += &LonNewSerialLine;
maxBufferLength = 10;
serialPort.startEvents();
Logger::Log(LogLevel::Info, "GPS Initialized");
}
void NMEACompatibleGPS::onNewSerialLine(string line) {
GPSData state;
if(parseLine(line, state)) {
// TODO set time
// gettimeofday(&state.laptoptime, NULL);
boost::mutex::scoped_lock lock(queueLocker);
stateQueue.push_back(state);
if(stateQueue.size() > maxBufferLength) {
stateQueue.pop_front();
}
onNewData(state);
}
}
bool NMEACompatibleGPS::parseLine(std::string line, GPSData &state) {
return nmea::decodeGPGGA(line, state) ||
nmea::decodeGPRMC(line, state);
}
GPSData NMEACompatibleGPS::GetState() {
boost::mutex::scoped_lock lock(queueLocker);
GPSData state = stateQueue.back();
stateQueue.remove(state);
return state;
}
GPSData NMEACompatibleGPS::GetStateAtTime(timeval time) {
boost::mutex::scoped_lock lock(queueLocker);
std::list<GPSData>::iterator iter = stateQueue.begin();
//double acceptableError = 0.1;
while(iter != stateQueue.end()) {
GPSData s = (*iter);
/*time_t secDelta = difftime(time.tv_sec, s.laptoptime.tv_sec);
suseconds_t usecDelta = time.tv_usec - s.laptoptime.tv_usec;
double delta = double(secDelta) + 1e-6*double(usecDelta);
if(delta <= acceptableError) {
// iter = stateQueue.erase(iter);
return s;
} else {
iter++;
}*/
}
GPSData empty;
return empty;
}
bool NMEACompatibleGPS::StateIsAvailable() {
return !stateQueue.empty();
}
bool NMEACompatibleGPS::isOpen() {
return serialPort.isConnected();
}
NMEACompatibleGPS::~NMEACompatibleGPS() {
serialPort.stopEvents();
serialPort.close();
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <string>
#include <vector>
#include "StateMachine.hpp"
#include "StateMachineBuilder.hpp"
#include "RdUtils.hpp"
#include "InitState.hpp"
#include "GameState.hpp"
#include "MockupNetworkManager.hpp"
#include "RdMockupImageManager.hpp"
#include "MockupInputManager.hpp"
#include "RdMentalMap.hpp"
#include "RdMockupRobotManager.hpp"
#include "MockupAudioManager.hpp"
#include "MockupState.hpp"
#include <yarp/os/Network.h>
#include <yarp/os/Time.h>
using namespace rd;
//-- Class for the setup of the enviroment for all the tests
//----------------------------------------------------------------------------------------
//-- This is required since MockupStates are used (and require yarp ports to be open)
class GameStateTestEnvironment : public testing::Environment
{
public:
GameStateTestEnvironment(int argc, char ** argv)
{
this->argc = argc;
this->argv = argv;
}
virtual void SetUp()
{
//-- Init yarp network & server
yarp::os::NetworkBase::setLocalMode(true);
yarp::os::Network::init();
}
virtual void TearDown()
{
yarp::os::Network::fini();
}
private:
int argc;
char ** argv;
};
//-- Class for the setup of each test
//--------------------------------------------------------------------------------------
class GameStateTest : public testing::Test
{
public:
virtual void SetUp()
{
//-- Start YARP network
yarp::os::Network::init();
//-- Register managers to be used:
MockupNetworkManager::RegisterManager();
RdMockupImageManager::RegisterManager();
MockupInputManager::RegisterManager();
MockupAudioManager::RegisterManager();
//-- Create managers
networkManager = RdNetworkManager::getNetworkManager("MOCKUP");
mockupNetworkManager = dynamic_cast<MockupNetworkManager *>(networkManager);
ASSERT_NE((RdNetworkManager*) NULL, networkManager);
ASSERT_NE((MockupNetworkManager*) NULL, mockupNetworkManager);
imageManager = RdImageManager::getImageManager("MOCKUP");
mockupImageManager = dynamic_cast<RdMockupImageManager *>(imageManager);
ASSERT_NE((RdImageManager*) NULL, imageManager);
ASSERT_NE((RdMockupImageManager*) NULL, mockupImageManager);
//-- Load test images
yarp::sig::file::read(test_frame_no_target, FRAME_NO_TARGET_PATH);
yarp::sig::file::read(test_frame_with_target, FRAME_WITH_TARGET_PATH);
inputManager = RdInputManager::getInputManager("MOCKUP");
mockupInputManager = dynamic_cast<MockupInputManager *>(inputManager);
ASSERT_NE((RdInputManager*) NULL, inputManager);
ASSERT_NE((MockupInputManager*) NULL, mockupInputManager);
audioManager = AudioManager::getAudioManager("MOCKUP");
mockupAudioManager = dynamic_cast<MockupAudioManager *>(audioManager);
ASSERT_NE((AudioManager*) NULL, audioManager);
ASSERT_NE((MockupAudioManager*) NULL, mockupAudioManager);
ASSERT_TRUE(mockupAudioManager->load("RD_THEME","RD_THEME", AudioManager::MUSIC));
ASSERT_TRUE(mockupAudioManager->load("shoot", "shoot", AudioManager::FX));
ASSERT_TRUE(mockupAudioManager->load("noAmmo", "noAmmo", AudioManager::FX));
ASSERT_TRUE(mockupAudioManager->load("reload", "reload", AudioManager::FX));
mentalMap = RdMentalMap::getMentalMap();
ASSERT_NE((RdMentalMap*) NULL, mentalMap);
mentalMap->addWeapon(RdWeapon("Machine gun", 10, MAX_AMMO));
ASSERT_TRUE(mentalMap->configure(0));
//-- Insert players for testing
std::vector<RdPlayer> players;
players.push_back(RdPlayer(1,"enemy", MAX_HEALTH, MAX_HEALTH, 0, 0) );
ASSERT_TRUE(mockupNetworkManager->setPlayerData(players));
players.push_back(RdPlayer(0,"test_player", MAX_HEALTH, MAX_HEALTH, 0, 0));
ASSERT_TRUE(mentalMap->updatePlayers(players));
mockupRobotManager = new RdMockupRobotManager("MOCKUP");
robotManager = (RdRobotManager *) mockupRobotManager;
ASSERT_NE((RdMockupRobotManager*) NULL, mockupRobotManager);
ASSERT_NE((RdRobotManager*) NULL, robotManager);
//-- Setup managers to the required initial state:
//-- Note: For simplicity, I'm using InitState here and manually calling
//-- the correct initialization sequence. The testInitState allows to test
//-- if InitState works correctly.
State * initState = new InitState(networkManager, imageManager, inputManager,
mentalMap, robotManager, audioManager);
initState->setup();
dynamic_cast<RdInputEventListener *>(initState)->onKeyUp(MockupKey(RdKey::KEY_ENTER));
initState->loop();
initState->cleanup();
delete initState;
initState = NULL;
}
virtual void TearDown()
{
//-- Close YARP network
yarp::os::Network::fini();
//-- Delete things
RdNetworkManager::destroyNetworkManager();
networkManager = NULL;
mockupNetworkManager = NULL;
RdImageManager::destroyImageManager();
imageManager = NULL;
mockupImageManager = NULL;
RdInputManager::destroyInputManager();
AudioManager::destroyAudioManager();
RdMentalMap::destroyMentalMap();
delete mockupRobotManager;
mockupRobotManager = NULL;
}
static const int MAX_HEALTH;
static const int MAX_AMMO;
protected:
FiniteStateMachine *fsm;
RdNetworkManager * networkManager;
MockupNetworkManager * mockupNetworkManager;
RdImageManager * imageManager;
RdMockupImageManager * mockupImageManager;
RdInputManager * inputManager;
MockupInputManager * mockupInputManager;
AudioManager * audioManager;
MockupAudioManager * mockupAudioManager;
RdMentalMap * mentalMap;
RdMockupRobotManager * mockupRobotManager;
RdRobotManager * robotManager;
RdImage test_frame_no_target;
RdImage test_frame_with_target;
static const std::string FRAME_NO_TARGET_PATH;
static const std::string FRAME_WITH_TARGET_PATH;
};
const int GameStateTest::MAX_HEALTH = 100;
const int GameStateTest::MAX_AMMO = 10;
const std::string GameStateTest::FRAME_NO_TARGET_PATH = "../../share/images/test_frame_qr.ppm";
const std::string GameStateTest::FRAME_WITH_TARGET_PATH = "../../share/images/test_frame_qr_centered.ppm";
//--- Tests ------------------------------------------------------------------------------------------
TEST_F(GameStateTest, GameStateGameFlowIsCorrect)
{
//-- Create fsm with GameState
StateMachineBuilder builder;
ASSERT_TRUE(builder.setDirectorType("YARP"));
int game_state_id = builder.addState(new GameState(networkManager, imageManager, inputManager, mentalMap,
robotManager, audioManager));
ASSERT_NE(-1, game_state_id);
int dead_state_id = builder.addState(new MockupState(1));
ASSERT_NE(-1, dead_state_id);
int end_state_id = builder.addState(State::getEndState());
ASSERT_TRUE(builder.addTransition(game_state_id, dead_state_id, GameState::KILLED));
ASSERT_TRUE(builder.addTransition(game_state_id, end_state_id, GameState::QUIT_REQUESTED));
ASSERT_TRUE(builder.setInitialState(game_state_id));
fsm = builder.buildStateMachine();
ASSERT_NE((FiniteStateMachine*)NULL, fsm);
//-- Check things that should happen before fsm starts (before setup):
//----------------------------------------------------------------------------
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
//-- Start state machine
ASSERT_TRUE(fsm->start());
yarp::os::Time::delay(0.5);
//-- Check things that should happen just after the fsm starts (after setup)
//----------------------------------------------------------------------------
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
//-- Testing game flow
//-----------------------------------------------------------------------------
//-- Check that GameState is active
ASSERT_EQ(game_state_id, fsm->getCurrentState());
//-- If my robot is hit, health decreases
ASSERT_TRUE(mockupNetworkManager->sendPlayerHit(mentalMap->getMyself(), 50));
yarp::os::Time::delay(0.5);
ASSERT_EQ(50, mentalMap->getMyself().getHealth());
//-- If I send move commands, robot moves
// mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ARROW_LEFT));
//-- If I shoot with no target in the scope, the enemies life is kept equal
mockupImageManager->receiveImage(test_frame_no_target);
yarp::os::Time::delay(0.5);
std::vector<RdPlayer> players_before = mentalMap->getPlayers();
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_SPACE));
std::vector<RdPlayer> players_after = mentalMap->getPlayers();
ASSERT_EQ(players_before.size(), players_after.size());
for(int i = 0; i < players_before.size(); i++)
EXPECT_EQ(players_before[i].getHealth(), players_after[i].getHealth());
//-- If I shoot all ammo, I run out of ammo, and I cannot shoot until reloading
for(int i = 0; i < GameStateTest::MAX_AMMO; i++)
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_SPACE));
ASSERT_EQ(0, mentalMap->getCurrentWeapon().getCurrentAmmo());
yarp::os::Time::delay(0.5);
//-- After reloading, I can shoot again
mockupInputManager->sendKeyPress(MockupKey('r'));
ASSERT_EQ(GameStateTest::MAX_AMMO, mentalMap->getCurrentWeapon().getCurrentAmmo());
//-- If I hit other robot, other robot health decreases
mockupImageManager->receiveImage(test_frame_with_target);
yarp::os::Time::delay(0.5);
players_before = mentalMap->getPlayers();
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_SPACE));
yarp::os::Time::delay(0.5);
players_after = mentalMap->getPlayers();
ASSERT_EQ(players_before.size(), players_after.size());
for(int i = 0; i < players_before.size(); i++)
if (players_before[i].getId() != mentalMap->getMyself().getId())
{
ASSERT_EQ(players_before[i].getId(), players_after[i].getId());
EXPECT_LT(players_after[i].getHealth(), players_before[i].getHealth());
}
//-- If I lose all health, game is over
ASSERT_TRUE(mockupNetworkManager->sendPlayerHit(mentalMap->getMyself(), 50));
ASSERT_EQ(0, mentalMap->getMyself().getHealth());
yarp::os::Time::delay(0.5);
//-- Check things that should occur before going to dead state (cleanup)
//------------------------------------------------------------------------------
// Player is dead
// Stuff is enabled
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that deadState is active
ASSERT_EQ(dead_state_id, fsm->getCurrentState());
}
TEST_F(GameStateTest, GameStateQuitsWhenRequested )
{
ASSERT_TRUE(false);
}
//--- Main -------------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
testing::Environment* env = testing::AddGlobalTestEnvironment(new GameStateTestEnvironment(argc, argv));
return RUN_ALL_TESTS();
}
<commit_msg>Add failing case for exiting game in testGameState<commit_after>#include "gtest/gtest.h"
#include <string>
#include <vector>
#include "StateMachine.hpp"
#include "StateMachineBuilder.hpp"
#include "RdUtils.hpp"
#include "InitState.hpp"
#include "GameState.hpp"
#include "MockupNetworkManager.hpp"
#include "RdMockupImageManager.hpp"
#include "MockupInputManager.hpp"
#include "RdMentalMap.hpp"
#include "RdMockupRobotManager.hpp"
#include "MockupAudioManager.hpp"
#include "MockupState.hpp"
#include <yarp/os/Network.h>
#include <yarp/os/Time.h>
using namespace rd;
//-- Class for the setup of the enviroment for all the tests
//----------------------------------------------------------------------------------------
//-- This is required since MockupStates are used (and require yarp ports to be open)
class GameStateTestEnvironment : public testing::Environment
{
public:
GameStateTestEnvironment(int argc, char ** argv)
{
this->argc = argc;
this->argv = argv;
}
virtual void SetUp()
{
//-- Init yarp network & server
yarp::os::NetworkBase::setLocalMode(true);
yarp::os::Network::init();
}
virtual void TearDown()
{
yarp::os::Network::fini();
}
private:
int argc;
char ** argv;
};
//-- Class for the setup of each test
//--------------------------------------------------------------------------------------
class GameStateTest : public testing::Test
{
public:
virtual void SetUp()
{
//-- Start YARP network
yarp::os::Network::init();
//-- Register managers to be used:
MockupNetworkManager::RegisterManager();
RdMockupImageManager::RegisterManager();
MockupInputManager::RegisterManager();
MockupAudioManager::RegisterManager();
//-- Create managers
networkManager = RdNetworkManager::getNetworkManager("MOCKUP");
mockupNetworkManager = dynamic_cast<MockupNetworkManager *>(networkManager);
ASSERT_NE((RdNetworkManager*) NULL, networkManager);
ASSERT_NE((MockupNetworkManager*) NULL, mockupNetworkManager);
imageManager = RdImageManager::getImageManager("MOCKUP");
mockupImageManager = dynamic_cast<RdMockupImageManager *>(imageManager);
ASSERT_NE((RdImageManager*) NULL, imageManager);
ASSERT_NE((RdMockupImageManager*) NULL, mockupImageManager);
//-- Load test images
yarp::sig::file::read(test_frame_no_target, FRAME_NO_TARGET_PATH);
yarp::sig::file::read(test_frame_with_target, FRAME_WITH_TARGET_PATH);
inputManager = RdInputManager::getInputManager("MOCKUP");
mockupInputManager = dynamic_cast<MockupInputManager *>(inputManager);
ASSERT_NE((RdInputManager*) NULL, inputManager);
ASSERT_NE((MockupInputManager*) NULL, mockupInputManager);
audioManager = AudioManager::getAudioManager("MOCKUP");
mockupAudioManager = dynamic_cast<MockupAudioManager *>(audioManager);
ASSERT_NE((AudioManager*) NULL, audioManager);
ASSERT_NE((MockupAudioManager*) NULL, mockupAudioManager);
ASSERT_TRUE(mockupAudioManager->load("RD_THEME","RD_THEME", AudioManager::MUSIC));
ASSERT_TRUE(mockupAudioManager->load("shoot", "shoot", AudioManager::FX));
ASSERT_TRUE(mockupAudioManager->load("noAmmo", "noAmmo", AudioManager::FX));
ASSERT_TRUE(mockupAudioManager->load("reload", "reload", AudioManager::FX));
mentalMap = RdMentalMap::getMentalMap();
ASSERT_NE((RdMentalMap*) NULL, mentalMap);
mentalMap->addWeapon(RdWeapon("Machine gun", 10, MAX_AMMO));
ASSERT_TRUE(mentalMap->configure(0));
//-- Insert players for testing
std::vector<RdPlayer> players;
players.push_back(RdPlayer(1,"enemy", MAX_HEALTH, MAX_HEALTH, 0, 0) );
ASSERT_TRUE(mockupNetworkManager->setPlayerData(players));
players.push_back(RdPlayer(0,"test_player", MAX_HEALTH, MAX_HEALTH, 0, 0));
ASSERT_TRUE(mentalMap->updatePlayers(players));
mockupRobotManager = new RdMockupRobotManager("MOCKUP");
robotManager = (RdRobotManager *) mockupRobotManager;
ASSERT_NE((RdMockupRobotManager*) NULL, mockupRobotManager);
ASSERT_NE((RdRobotManager*) NULL, robotManager);
//-- Setup managers to the required initial state:
//-- Note: For simplicity, I'm using InitState here and manually calling
//-- the correct initialization sequence. The testInitState allows to test
//-- if InitState works correctly.
State * initState = new InitState(networkManager, imageManager, inputManager,
mentalMap, robotManager, audioManager);
initState->setup();
dynamic_cast<RdInputEventListener *>(initState)->onKeyUp(MockupKey(RdKey::KEY_ENTER));
initState->loop();
initState->cleanup();
delete initState;
initState = NULL;
}
virtual void TearDown()
{
//-- Close YARP network
yarp::os::Network::fini();
//-- Delete things
RdNetworkManager::destroyNetworkManager();
networkManager = NULL;
mockupNetworkManager = NULL;
RdImageManager::destroyImageManager();
imageManager = NULL;
mockupImageManager = NULL;
RdInputManager::destroyInputManager();
AudioManager::destroyAudioManager();
RdMentalMap::destroyMentalMap();
delete mockupRobotManager;
mockupRobotManager = NULL;
}
static const int MAX_HEALTH;
static const int MAX_AMMO;
protected:
FiniteStateMachine *fsm;
RdNetworkManager * networkManager;
MockupNetworkManager * mockupNetworkManager;
RdImageManager * imageManager;
RdMockupImageManager * mockupImageManager;
RdInputManager * inputManager;
MockupInputManager * mockupInputManager;
AudioManager * audioManager;
MockupAudioManager * mockupAudioManager;
RdMentalMap * mentalMap;
RdMockupRobotManager * mockupRobotManager;
RdRobotManager * robotManager;
RdImage test_frame_no_target;
RdImage test_frame_with_target;
static const std::string FRAME_NO_TARGET_PATH;
static const std::string FRAME_WITH_TARGET_PATH;
};
const int GameStateTest::MAX_HEALTH = 100;
const int GameStateTest::MAX_AMMO = 10;
const std::string GameStateTest::FRAME_NO_TARGET_PATH = "../../share/images/test_frame_qr.ppm";
const std::string GameStateTest::FRAME_WITH_TARGET_PATH = "../../share/images/test_frame_qr_centered.ppm";
//--- Tests ------------------------------------------------------------------------------------------
TEST_F(GameStateTest, GameStateGameFlowIsCorrect)
{
//-- Create fsm with GameState
StateMachineBuilder builder;
ASSERT_TRUE(builder.setDirectorType("YARP"));
int game_state_id = builder.addState(new GameState(networkManager, imageManager, inputManager, mentalMap,
robotManager, audioManager));
ASSERT_NE(-1, game_state_id);
int dead_state_id = builder.addState(new MockupState(1));
ASSERT_NE(-1, dead_state_id);
int end_state_id = builder.addState(State::getEndState());
ASSERT_TRUE(builder.addTransition(game_state_id, dead_state_id, GameState::KILLED));
ASSERT_TRUE(builder.addTransition(game_state_id, end_state_id, GameState::QUIT_REQUESTED));
ASSERT_TRUE(builder.setInitialState(game_state_id));
fsm = builder.buildStateMachine();
ASSERT_NE((FiniteStateMachine*)NULL, fsm);
//-- Check things that should happen before fsm starts (before setup):
//----------------------------------------------------------------------------
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
//-- Start state machine
ASSERT_TRUE(fsm->start());
yarp::os::Time::delay(0.5);
//-- Check things that should happen just after the fsm starts (after setup)
//----------------------------------------------------------------------------
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
//-- Testing game flow
//-----------------------------------------------------------------------------
//-- Check that GameState is active
ASSERT_EQ(game_state_id, fsm->getCurrentState());
//-- If my robot is hit, health decreases
ASSERT_TRUE(mockupNetworkManager->sendPlayerHit(mentalMap->getMyself(), 50));
yarp::os::Time::delay(0.5);
ASSERT_EQ(50, mentalMap->getMyself().getHealth());
//-- If I send move commands, robot moves
// mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ARROW_LEFT));
//-- If I shoot with no target in the scope, the enemies life is kept equal
mockupImageManager->receiveImage(test_frame_no_target);
yarp::os::Time::delay(0.5);
std::vector<RdPlayer> players_before = mentalMap->getPlayers();
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_SPACE));
std::vector<RdPlayer> players_after = mentalMap->getPlayers();
ASSERT_EQ(players_before.size(), players_after.size());
for(int i = 0; i < players_before.size(); i++)
EXPECT_EQ(players_before[i].getHealth(), players_after[i].getHealth());
//-- If I shoot all ammo, I run out of ammo, and I cannot shoot until reloading
for(int i = 0; i < GameStateTest::MAX_AMMO; i++)
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_SPACE));
ASSERT_EQ(0, mentalMap->getCurrentWeapon().getCurrentAmmo());
yarp::os::Time::delay(0.5);
//-- After reloading, I can shoot again
mockupInputManager->sendKeyPress(MockupKey('r'));
ASSERT_EQ(GameStateTest::MAX_AMMO, mentalMap->getCurrentWeapon().getCurrentAmmo());
//-- If I hit other robot, other robot health decreases
mockupImageManager->receiveImage(test_frame_with_target);
yarp::os::Time::delay(0.5);
players_before = mentalMap->getPlayers();
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_SPACE));
yarp::os::Time::delay(0.5);
players_after = mentalMap->getPlayers();
ASSERT_EQ(players_before.size(), players_after.size());
for(int i = 0; i < players_before.size(); i++)
if (players_before[i].getId() != mentalMap->getMyself().getId())
{
ASSERT_EQ(players_before[i].getId(), players_after[i].getId());
EXPECT_LT(players_after[i].getHealth(), players_before[i].getHealth());
}
//-- If I lose all health, game is over
ASSERT_TRUE(mockupNetworkManager->sendPlayerHit(mentalMap->getMyself(), 50));
ASSERT_EQ(0, mentalMap->getMyself().getHealth());
yarp::os::Time::delay(0.5);
//-- Check things that should occur before going to dead state (cleanup)
//------------------------------------------------------------------------------
// Player is dead
// Stuff is enabled
ASSERT_EQ(0, mentalMap->getMyself().getHealth()); //-- Important thing to check
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that deadState is active
ASSERT_EQ(dead_state_id, fsm->getCurrentState());
}
TEST_F(GameStateTest, GameStateQuitsWhenRequested )
{
//-- Create fsm with GameState
StateMachineBuilder builder;
ASSERT_TRUE(builder.setDirectorType("YARP"));
int game_state_id = builder.addState(new GameState(networkManager, imageManager, inputManager, mentalMap,
robotManager, audioManager));
ASSERT_NE(-1, game_state_id);
int dead_state_id = builder.addState(new MockupState(1));
ASSERT_NE(-1, dead_state_id);
int end_state_id = builder.addState(State::getEndState());
ASSERT_TRUE(builder.addTransition(game_state_id, dead_state_id, GameState::KILLED));
ASSERT_TRUE(builder.addTransition(game_state_id, end_state_id, GameState::QUIT_REQUESTED));
ASSERT_TRUE(builder.setInitialState(game_state_id));
fsm = builder.buildStateMachine();
ASSERT_NE((FiniteStateMachine*)NULL, fsm);
//-- Check things that should happen before fsm starts (before setup):
//----------------------------------------------------------------------------
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
//-- Start state machine
ASSERT_TRUE(fsm->start());
yarp::os::Time::delay(0.5);
//-- Check things that should happen just after the fsm starts (after setup)
//----------------------------------------------------------------------------
ASSERT_FALSE(mockupAudioManager->isStopped());
ASSERT_TRUE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_FALSE(mockupNetworkManager->isStopped());
ASSERT_TRUE(mockupNetworkManager->isLoggedIn());
ASSERT_FALSE(mockupImageManager->isStopped());
ASSERT_FALSE(mockupInputManager->isStopped());
ASSERT_EQ(1, mockupInputManager->getNumListeners());
// ASSERT_FALSE(mockupRobotManager->isStopped());
// ASSERT_TRUE(mockupRobotManager->isConnected());
//-- Testing exiting game
//-----------------------------------------------------------------------------
//-- Check that GameState is active
ASSERT_EQ(game_state_id, fsm->getCurrentState());
//-- When esc is pressed, the system should exit the game:
mockupInputManager->sendKeyPress(MockupKey(RdKey::KEY_ESCAPE));
yarp::os::Time::delay(0.5);
//-- Check that it has stopped things and it is in the final state (cleanup):
ASSERT_TRUE(mockupImageManager->isStopped());
ASSERT_TRUE(mockupInputManager->isStopped());
ASSERT_EQ(0, mockupInputManager->getNumListeners());
ASSERT_TRUE(mockupAudioManager->isStopped());
ASSERT_FALSE(mockupAudioManager->isPlaying("RD_THEME"));
ASSERT_TRUE(mockupNetworkManager->isStopped());
ASSERT_FALSE(mockupNetworkManager->isLoggedIn());
//ASSERT_FALSE(mockupRobotManager->isStopped()); //-- Not correctly implemented
//ASSERT_FALSE(mockupRobotManager->isConnected());
//-- Check that end state is active
ASSERT_EQ(-1, fsm->getCurrentState()); //-- (When FSM is ended, no state is active, hence -1)
}
//--- Main -------------------------------------------------------------------------------------------
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
testing::Environment* env = testing::AddGlobalTestEnvironment(new GameStateTestEnvironment(argc, argv));
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>//
// Created by fred on 06/12/16.
//
#include "frnetlib/TcpListener.h"
namespace fr
{
const int yes = 1;
const int no = 0;
Socket::Status TcpListener::listen(const std::string &port)
{
addrinfo *info;
addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = ai_family;
hints.ai_socktype = SOCK_STREAM; //TCP
hints.ai_flags = AI_PASSIVE; //Have the IP filled in for us
if(getaddrinfo(NULL, port.c_str(), &hints, &info) != 0)
{
return Socket::Status::Unknown;
}
//Try each of the results until we listen successfully
addrinfo *c = nullptr;
for(c = info; c != nullptr; c = c->ai_next)
{
//Attempt to connect
if((socket_descriptor = socket(c->ai_family, c->ai_socktype, c->ai_protocol)) == INVALID_SOCKET)
{
continue;
}
//Set address re-use option
if(setsockopt(socket_descriptor, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(int)) == SOCKET_ERROR)
{
continue;
}
//If it's an IPv6 interface, attempt to allow IPv4 connections
if(c->ai_family == AF_INET6)
{
setsockopt(socket_descriptor, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&no, sizeof(no));
}
//Attempt to bind
if(bind(socket_descriptor, c->ai_addr, c->ai_addrlen) == SOCKET_ERROR)
{
closesocket(socket_descriptor);
continue;
}
break;
}
//Check that we've actually bound
if(c == nullptr)
{
return Socket::Status::BindFailed;
}
//We're done with this now, cleanup
freeaddrinfo(info);
//Listen to socket
if(::listen(socket_descriptor, 10) == SOCKET_ERROR)
{
return Socket::ListenFailed;
}
return Socket::Success;
}
Socket::Status TcpListener::accept(Socket &client_)
{
//Cast to TcpSocket. Will throw bad cast on failure.
TcpSocket &client = dynamic_cast<TcpSocket&>(client_);
//Prepare to wait for the client
sockaddr_storage client_addr;
int client_descriptor;
char client_printable_addr[INET6_ADDRSTRLEN];
//Accept one
socklen_t client_addr_len = sizeof client_addr;
client_descriptor = ::accept(socket_descriptor, (sockaddr*)&client_addr, &client_addr_len);
if(client_descriptor == SOCKET_ERROR)
return Socket::Unknown;
//Get printable address. If we failed then set it as just 'unknown'
int err = getnameinfo((sockaddr*)&client_addr, client_addr_len, client_printable_addr, sizeof(client_printable_addr), 0,0,NI_NUMERICHOST);
if(err != 0)
strcpy(client_printable_addr, "unknown");
//Set client data
client.set_descriptor(client_descriptor);
client.set_remote_address(client_printable_addr);
return Socket::Success;
}
void TcpListener::shutdown()
{
::shutdown(socket_descriptor, 0);
}
}<commit_msg>Windows compile issue<commit_after>//
// Created by fred on 06/12/16.
//
#include "frnetlib/TcpListener.h"
namespace fr
{
const int yes = 1;
const int no = 0;
Socket::Status TcpListener::listen(const std::string &port)
{
addrinfo *info;
addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = ai_family;
hints.ai_socktype = SOCK_STREAM; //TCP
hints.ai_flags = AI_PASSIVE; //Have the IP filled in for us
if(getaddrinfo(NULL, port.c_str(), &hints, &info) != 0)
{
return Socket::Status::Unknown;
}
//Try each of the results until we listen successfully
addrinfo *c = nullptr;
for(c = info; c != nullptr; c = c->ai_next)
{
//Attempt to connect
if((socket_descriptor = socket(c->ai_family, c->ai_socktype, c->ai_protocol)) == INVALID_SOCKET)
{
continue;
}
//Set address re-use option
if(setsockopt(socket_descriptor, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(int)) == SOCKET_ERROR)
{
continue;
}
//If it's an IPv6 interface, attempt to allow IPv4 connections
if(c->ai_family == AF_INET6)
{
setsockopt(socket_descriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&no, sizeof(no));
}
//Attempt to bind
if(bind(socket_descriptor, c->ai_addr, c->ai_addrlen) == SOCKET_ERROR)
{
closesocket(socket_descriptor);
continue;
}
break;
}
//Check that we've actually bound
if(c == nullptr)
{
return Socket::Status::BindFailed;
}
//We're done with this now, cleanup
freeaddrinfo(info);
//Listen to socket
if(::listen(socket_descriptor, 10) == SOCKET_ERROR)
{
return Socket::ListenFailed;
}
return Socket::Success;
}
Socket::Status TcpListener::accept(Socket &client_)
{
//Cast to TcpSocket. Will throw bad cast on failure.
TcpSocket &client = dynamic_cast<TcpSocket&>(client_);
//Prepare to wait for the client
sockaddr_storage client_addr;
int client_descriptor;
char client_printable_addr[INET6_ADDRSTRLEN];
//Accept one
socklen_t client_addr_len = sizeof client_addr;
client_descriptor = ::accept(socket_descriptor, (sockaddr*)&client_addr, &client_addr_len);
if(client_descriptor == SOCKET_ERROR)
return Socket::Unknown;
//Get printable address. If we failed then set it as just 'unknown'
int err = getnameinfo((sockaddr*)&client_addr, client_addr_len, client_printable_addr, sizeof(client_printable_addr), 0,0,NI_NUMERICHOST);
if(err != 0)
strcpy(client_printable_addr, "unknown");
//Set client data
client.set_descriptor(client_descriptor);
client.set_remote_address(client_printable_addr);
return Socket::Success;
}
void TcpListener::shutdown()
{
::shutdown(socket_descriptor, 0);
}
}<|endoftext|> |
<commit_before>#include "TeensyDelay.h"
#include "config.h"
namespace TeensyDelay
{
void(*callbacks[maxChannel])(void);
unsigned lastChannel = 0;
void begin()
{
if (USE_TIMER == TIMER_TPM1) { // enable clocks for tpm timers (ftm clocks are enabled by teensyduino)
SIM_SCGC2 |= SIM_SCGC2_TPM1;
SIM_SOPT2 |= SIM_SOPT2_TPMSRC(2);
}
else if (USE_TIMER == TIMER_TPM2) {
SIM_SCGC2 |= SIM_SCGC2_TPM2;
SIM_SOPT2 |= SIM_SOPT2_TPMSRC(2);
}
//Default Mode for FTM is (nearly) TPM compatibile
timer->SC = FTM_SC_CLKS(0b00); // Disable clock
timer->MOD = 0xFFFF; // Set full counter range
for (unsigned i = 0; i < maxChannel; i++) { // turn off all channels which were enabled by teensyduino for PWM generation
if (isFTM) { // compiletime constant, compiler optimizes conditional and not valid branch completely away
timer->CH[i].SC &= ~FTM_CSC_CHF; // FTM requires to clear flag by setting bit to 0
}
else {
timer->CH[i].SC |= FTM_CSC_CHF; // TPM requires to clear flag by setting bit to 1
}
timer->CH[i].SC &= ~FTM_CSC_CHIE; // Disable channel interupt
timer->CH[i].SC = FTM_CSC_MSA;
}
timer->SC = FTM_SC_CLKS(0b01) | FTM_SC_PS(prescale); // Start clock
NVIC_ENABLE_IRQ(irq); // Enable interrupt request for selected timer
}
unsigned addDelayChannel(void(*callback)(void), const int channel)
{
unsigned ch = channel < 0 ? lastChannel++ : channel;
callbacks[ch] = callback; //Just store the callback function, the rest is done in Trigger function
return ch;
}
}
//-------------------------------------------------------------------------------------------
// Interupt service routine of the timer selected in config.h.
// The code doesn't touch the other FTM/TPM ISRs so they can still be used for other purposes
//
// Unfortunately we can not inline the ISR because inlinig will generate a "weak" function.
// Since the original ISR (dummy_isr) is also defined weak the linker
// is allowed to choose any of them. In this case it desided to use dummy_isr :-(
// Using a "strong" (not inlined) function overrides the week dummy_isr
//--------------------------------------------------------------------------------------------
using namespace TeensyDelay;
#if USE_TIMER == TIMER_FTM0
void ftm0_isr(void)
#elif USE_TIMER == TIMER_FTM1
void ftm1_isr(void)
#elif USE_TIMER == TIMER_FTM2
void ftm2_isr(void)
#elif USE_TIMER == TIMER_FTM3
void ftm3_isr(void)
#elif USE_TIMER == TIMER_TPM1
void tpm1_isr(void)
#elif USE_TIMER == TIMER_TPM2
void tpm2_isr(void)
#endif
{
uint32_t status = timer->STATUS & 0x0F; // STATUS collects all channel event flags (bit0 = ch0, bit1 = ch1....)
unsigned i = 0;
while (status > 0) {
if (status & 0x01) {
if (isFTM) { // isFTM is a compiletime constant, compiler optimizes conditional and not valid branch completely away
timer->CH[i].SC &= ~FTM_CSC_CHF; // reset channel and interrupt enable (we only want one shot per trigger)
}
else {
timer->CH[i].SC |= FTM_CSC_CHF; // TPM needs inverse setting of the flags
}
if (timer->CH[i].SC & FTM_CSC_CHIE) // Channel flags will be set each time the counter overflows the channel value.
{ // In case that the interupt was triggered by another channel we need to prevent
timer->CH[i].SC &= ~FTM_CSC_CHIE; // the callback if this channel was not triggerd (CHIE of this channel not set)
callbacks[i](); // invoke callback function for the channel
}
}
i++;
status >>= 1;
}
}<commit_msg>Bug if channel nr > 4<commit_after>#include "TeensyDelay.h"
#include "config.h"
namespace TeensyDelay
{
void(*callbacks[maxChannel])(void);
unsigned lastChannel = 0;
void begin()
{
if (USE_TIMER == TIMER_TPM1) { // enable clocks for tpm timers (ftm clocks are enabled by teensyduino)
SIM_SCGC2 |= SIM_SCGC2_TPM1;
SIM_SOPT2 |= SIM_SOPT2_TPMSRC(2);
}
else if (USE_TIMER == TIMER_TPM2) {
SIM_SCGC2 |= SIM_SCGC2_TPM2;
SIM_SOPT2 |= SIM_SOPT2_TPMSRC(2);
}
//Default Mode for FTM is (nearly) TPM compatibile
timer->SC = FTM_SC_CLKS(0b00); // Disable clock
timer->MOD = 0xFFFF; // Set full counter range
for (unsigned i = 0; i < maxChannel; i++) { // turn off all channels which were enabled by teensyduino for PWM generation
if (isFTM) { // compiletime constant, compiler optimizes conditional and not valid branch completely away
timer->CH[i].SC &= ~FTM_CSC_CHF; // FTM requires to clear flag by setting bit to 0
}
else {
timer->CH[i].SC |= FTM_CSC_CHF; // TPM requires to clear flag by setting bit to 1
}
timer->CH[i].SC &= ~FTM_CSC_CHIE; // Disable channel interupt
timer->CH[i].SC = FTM_CSC_MSA;
}
timer->SC = FTM_SC_CLKS(0b01) | FTM_SC_PS(prescale); // Start clock
NVIC_ENABLE_IRQ(irq); // Enable interrupt request for selected timer
}
unsigned addDelayChannel(void(*callback)(void), const int channel)
{
unsigned ch = channel < 0 ? lastChannel++ : channel;
callbacks[ch] = callback; //Just store the callback function, the rest is done in Trigger function
return ch;
}
}
//-------------------------------------------------------------------------------------------
// Interupt service routine of the timer selected in config.h.
// The code doesn't touch the other FTM/TPM ISRs so they can still be used for other purposes
//
// Unfortunately we can not inline the ISR because inlinig will generate a "weak" function.
// Since the original ISR (dummy_isr) is also defined weak the linker
// is allowed to choose any of them. In this case it desided to use dummy_isr :-(
// Using a "strong" (not inlined) function overrides the week dummy_isr
//--------------------------------------------------------------------------------------------
using namespace TeensyDelay;
#if USE_TIMER == TIMER_FTM0
void ftm0_isr(void)
#elif USE_TIMER == TIMER_FTM1
void ftm1_isr(void)
#elif USE_TIMER == TIMER_FTM2
void ftm2_isr(void)
#elif USE_TIMER == TIMER_FTM3
void ftm3_isr(void)
#elif USE_TIMER == TIMER_TPM1
void tpm1_isr(void)
#elif USE_TIMER == TIMER_TPM2
void tpm2_isr(void)
#endif
{
uint32_t status = timer->STATUS & 0x0FF; // STATUS collects all channel event flags (bit0 = ch0, bit1 = ch1....)
unsigned i = 0;
while (status > 0) {
if (status & 0x01) {
if (isFTM) { // isFTM is a compiletime constant, compiler optimizes conditional and not valid branch completely away
timer->CH[i].SC &= ~FTM_CSC_CHF; // reset channel and interrupt enable (we only want one shot per trigger)
}
else {
timer->CH[i].SC |= FTM_CSC_CHF; // TPM needs inverse setting of the flags
}
if (timer->CH[i].SC & FTM_CSC_CHIE) // Channel flags will be set each time the counter overflows the channel value.
{ // In case that the interupt was triggered by another channel we need to prevent
timer->CH[i].SC &= ~FTM_CSC_CHIE; // the callback if this channel was not triggerd (CHIE of this channel not set)
callbacks[i](); // invoke callback function for the channel
}
}
i++;
status >>= 1;
}
}<|endoftext|> |
<commit_before>/**
* A class which describes the abstract properties and actions of a
* controller.
*
* @date Jun 2, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstring>
#include <fstream>
#include <sstream>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
// Application dependencies.
#include <ias/application/controller_application.h>
#include <ias/application/constants.h>
#include <ias/server/device_server.h>
#include <ias/network/posix/posix_tcp_socket.h>
#include <ias/network/posix/posix_tcp_server_socket.h>
#include <ias/network/posix/ssl/posix_ssl_socket.h>
#include <ias/network/proxy/socks.h>
#include <ias/network/util.h>
#include <ias/logger/logger.h>
#include <ias/logger/file/file_logger.h>
#include <ias/logger/console/console_logger.h>
// END Includes. /////////////////////////////////////////////////////
void ControllerApplication::initialize( void ) {
mSocket = nullptr;
mDeviceServer = nullptr;
}
void ControllerApplication::setup( const int argc , const char ** argv ) {
int index;
// Retrieve the configuration file path.
index = flagIndex(argc,argv,kFlagConfig);
if( index >= 0 && (index + 1) <= argc && strlen(argv[index + 1]) > 0 ) {
std::string configurationPath;
configurationPath = argv[index + 1];
readConfiguration(configurationPath);
initializeLogger();
connectToServer();
if( mSocket != nullptr ) {
authenticateWithServer();
if( mSocket->isConnected() ) {
readDevices();
allocateDeviceServer();
if( mDeviceServer != nullptr )
startDeviceProcesses();
}
}
}
}
void ControllerApplication::readConfiguration( const std::string & filePath ) {
std::ifstream file(filePath);
std::string line;
std::string key;
std::string value;
std::size_t i;
// Checking the precondition.
assert( !filePath.empty() );
while( std::getline(file,line) ) {
trim(line);
if( line.empty() || line.at(0) == '#' )
continue;
i = line.find('=');
key = line.substr(0,i);
value = line.substr(i + 1,line.length());
trim(key); trim(value);
if( !key.empty() && !value.empty() )
mProperties.add(key,value);
}
file.close();
}
void ControllerApplication::initializeSslContext( void ) {
mSslContext = SSL_CTX_new(SSLv23_client_method());
}
bool ControllerApplication::sslRequested( void ) const {
bool requested;
requested = false;
if( mProperties.contains(kConfigHostSslEnabled) ) {
const std::string & config = mProperties.get(kConfigHostSslEnabled);
if( config == "1" )
requested = true;
}
return ( requested );
}
int ControllerApplication::connectToProxy( const std::string & proxyAddress,
const std::string & proxyPort,
const std::string & serverAddress,
const std::string & serverPort ) const {
std::size_t pPort;
std::size_t sPort;
int fd;
// Checking the precondition.
assert( !proxyAddress.empty() && !proxyPort.empty() &&
!serverAddress.empty() && !serverPort.empty() );
fd = -1;
// Parse the specified ports.
pPort = static_cast<std::size_t>(std::stoi(proxyPort));
sPort = static_cast<std::size_t>(std::stoi(serverPort));
if( sPort > 0 && pPort > 0 ) {
fd = connect(proxyAddress,pPort);
if( fd >= 0 && !socksConnect(serverAddress,sPort,fd) ) {
close(fd);
fd = -1;
}
}
return ( fd );
}
void ControllerApplication::connectToServer( void ) {
const std::string & serverAddress = mProperties.get(kConfigHost);
const std::string & serverPort = mProperties.get(kConfigHostPort);
std::size_t port;
int fd;
fd = -1;
if( mProperties.contains(kConfigSocksAddress) &&
mProperties.contains(kConfigSocksPort) ) {
const std::string & proxyAddress = mProperties.get(kConfigSocksAddress);
const std::string & proxyPort = mProperties.get(kConfigSocksPort);
fd = connectToProxy(proxyAddress,proxyPort,
serverAddress,serverPort);
} else {
port = static_cast<std::size_t>(std::stoi(serverPort));
fd = connect(serverAddress,port);
}
// Check if a successful connection could be made.
if( fd >= 0 ) {
if( sslRequested() ) {
SSL * ssl;
initializeSslContext();
ssl = SSL_new(mSslContext);
SSL_set_fd(ssl,fd);
if( SSL_connect(ssl) <= 0 ) {
SSL_free(ssl);
close(fd);
} else {
mSocket = new PosixSslSocket(ssl);
}
} else {
mSocket = new PosixTcpSocket(fd);
}
}
}
std::size_t ControllerApplication::getServerPort( void ) const {
const std::string & serverPort = mProperties.get(kConfigHostPort);
std::size_t port;
if( serverPort.empty() ||
(port = static_cast<std::size_t>(std::stoi(serverPort))) == 0 )
port = kDefaultControllerServerPort;
return ( port );
}
void ControllerApplication::readDevices( void ) {
std::string filePath;
filePath = mProperties.get(kConfigDeviceList);
if( filePath.empty() )
return;
std::ifstream file(filePath);
std::string line;
std::string deviceIdentifier;
std::string deviceBash;
logi("Retrieving devices.");
while( std::getline(file,line) ) {
trim(line);
if( line.empty() || line.at(0) == '#' )
continue;
deviceIdentifier = line;
std::getline(file,line);
trim(line);
if( line.empty() || line.at(0) == '#' )
return;
deviceBash = line;
logi("Adding " + deviceIdentifier + ".");
mDevices.push_back(deviceIdentifier);
mDeviceCommands.push_back(deviceBash);
}
file.close();
logi("Devices have been read.");
}
void ControllerApplication::allocateDeviceServer( void ) {
ServerSocket * serverSocket;
std::string stringPort;
unsigned int port;
if( mProperties.contains(kConfigNetworkDevicePort) )
stringPort = mProperties.get(kConfigNetworkDevicePort);
if( !stringPort.empty() )
port = static_cast<unsigned int>(atol(stringPort.c_str()));
else
port = kDefaultDeviceServerPort;
logi("Allocating device server at port " + std::to_string(port) + ".");
serverSocket = new PosixTcpServerSocket(port);
if( serverSocket->bindToPort() ) {
mDeviceServer = new DeviceServer(serverSocket,
mSocket,
mDevices);
logi("Device server has been allocated.");
} else {
delete serverSocket;
loge("Could not bind device server to port " + std::to_string(port) + ".");
}
}
void ControllerApplication::authenticateWithServer( void ) {
std::uint8_t header[3];
std::uint8_t response;
std::string message;
std::size_t n;
Writer * writer;
Reader * reader;
bool success;
const std::string & controllerIdentifier =
mProperties.get(kConfigControllerIdentifier);
const std::string & securityCode =
mProperties.get(kConfigControllerSecurityCode);
if( controllerIdentifier.empty() ||
securityCode.empty() ) {
stop();
loge("Authentication credentials missing.");
return;
}
logi("Authenticating with server.");
success = true;
header[0] = 0x00;
header[1] = static_cast<std::uint8_t>(controllerIdentifier.length());
header[2] = static_cast<std::uint8_t>(securityCode.length());
message = controllerIdentifier + securityCode;
writer = mSocket->getWriter();
reader = mSocket->getReader();
writer->lock();
n = writer->writeBytes(reinterpret_cast<const char *>(header),3);
success &= ( n > 0 );
n = writer->writeBytes(reinterpret_cast<const char *>(message.c_str()),
message.length());
success &= ( n > 0 );
writer->unlock();
response = 0x00;
reader->readBytes(reinterpret_cast<char *>(&response),1);
if( !success && response == 0x01 ) {
mSocket->closeConnection();
logi("Authentication failed.");
} else {
logi("Authenticated.");
}
}
void ControllerApplication::startDeviceProcesses( void ) {
std::string path;
std::string argument;
std::size_t nArguments;
pid_t processId;
int status;
logi("Starting devices processes.");
for( auto it = mDeviceCommands.begin() ; it != mDeviceCommands.end() ; ++it ) {
const std::string & command = (*it);
std::stringstream ss;
ss << command;
ss >> path;
nArguments = numWords(command);
char * argv[nArguments + 1];
argv[nArguments] = static_cast<char *>(0);
argv[0] = new char[path.length() + 1];
strcpy(argv[0],path.c_str());
for( std::size_t i = 1 ; i < nArguments ; ++i ) {
ss >> argument;
argv[i] = new char[argument.length() + 1];
strcpy(argv[i],argument.c_str());
}
status = posix_spawn(&processId,path.c_str(),nullptr,nullptr,
argv,nullptr);
if( status == 0 ) {
mPids.push_back(processId);
}
for( std::size_t i = 0 ; i < nArguments ; ++i )
delete [] argv[i];
}
logi("Device processes have been started.");
}
void ControllerApplication::cleanupDeviceProcesses( void ) {
int status;
std::size_t n;
n = mPids.size();
for( std::size_t i = 0 ; i < n ; ++i ) {
waitpid(mPids.at(i),&status,0);
}
}
void ControllerApplication::initializeLogger( void ) {
std::string type;
if( mProperties.contains(kConfigLoggerType) ) {
type = mProperties.get(kConfigLoggerType);
if( type == std::string(ConsoleLogger::kType) ) {
Logger::setLogger(new ConsoleLogger());
std::cout.flush();
} else
if( type == std::string(FileLogger::kType) &&
mProperties.contains(kConfigLoggerLogfilePath) ) {
std::string logfile = mProperties.get(kConfigLoggerLogfilePath);
if( !logfile.empty() )
Logger::setLogger(new FileLogger(logfile));
}
}
}
ControllerApplication::ControllerApplication( const int argc,
const char ** argv ) {
initialize();
setup(argc,argv);
}
ControllerApplication::~ControllerApplication( void ) {
delete mSocket; mSocket = nullptr;
delete mDeviceServer; mDeviceServer = nullptr;
cleanupDeviceProcesses();
}
void ControllerApplication::run( void ) {
if( mDeviceServer != nullptr ) {
logi("Starting device server.");
mDeviceServer->start();
logi("Device server has been started.");
mDeviceServer->join();
logi("Device server has been stopped.");
}
}
void ControllerApplication::stop( void ) {
if( mDeviceServer != nullptr ) {
logi("Stopping the device server.");
mDeviceServer->stop();
mSocket->closeConnection();
}
}
<commit_msg>Modify protocol handling.<commit_after>/**
* A class which describes the abstract properties and actions of a
* controller.
*
* @date Jun 2, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstring>
#include <fstream>
#include <sstream>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
// Application dependencies.
#include <ias/application/controller_application.h>
#include <ias/application/constants.h>
#include <ias/server/device_server.h>
#include <ias/network/posix/posix_tcp_socket.h>
#include <ias/network/posix/posix_tcp_server_socket.h>
#include <ias/network/posix/ssl/posix_ssl_socket.h>
#include <ias/network/proxy/socks.h>
#include <ias/network/util.h>
#include <ias/logger/logger.h>
#include <ias/logger/file/file_logger.h>
#include <ias/logger/console/console_logger.h>
// END Includes. /////////////////////////////////////////////////////
void ControllerApplication::initialize( void ) {
mSocket = nullptr;
mDeviceServer = nullptr;
}
void ControllerApplication::setup( const int argc , const char ** argv ) {
int index;
// Retrieve the configuration file path.
index = flagIndex(argc,argv,kFlagConfig);
if( index >= 0 && (index + 1) <= argc && strlen(argv[index + 1]) > 0 ) {
std::string configurationPath;
configurationPath = argv[index + 1];
readConfiguration(configurationPath);
initializeLogger();
connectToServer();
if( mSocket != nullptr ) {
authenticateWithServer();
if( mSocket->isConnected() ) {
readDevices();
allocateDeviceServer();
if( mDeviceServer != nullptr )
startDeviceProcesses();
}
}
}
}
void ControllerApplication::readConfiguration( const std::string & filePath ) {
std::ifstream file(filePath);
std::string line;
std::string key;
std::string value;
std::size_t i;
// Checking the precondition.
assert( !filePath.empty() );
while( std::getline(file,line) ) {
trim(line);
if( line.empty() || line.at(0) == '#' )
continue;
i = line.find('=');
key = line.substr(0,i);
value = line.substr(i + 1,line.length());
trim(key); trim(value);
if( !key.empty() && !value.empty() )
mProperties.add(key,value);
}
file.close();
}
void ControllerApplication::initializeSslContext( void ) {
mSslContext = SSL_CTX_new(SSLv23_client_method());
}
bool ControllerApplication::sslRequested( void ) const {
bool requested;
requested = false;
if( mProperties.contains(kConfigHostSslEnabled) ) {
const std::string & config = mProperties.get(kConfigHostSslEnabled);
if( config == "1" )
requested = true;
}
return ( requested );
}
int ControllerApplication::connectToProxy( const std::string & proxyAddress,
const std::string & proxyPort,
const std::string & serverAddress,
const std::string & serverPort ) const {
std::size_t pPort;
std::size_t sPort;
int fd;
// Checking the precondition.
assert( !proxyAddress.empty() && !proxyPort.empty() &&
!serverAddress.empty() && !serverPort.empty() );
fd = -1;
// Parse the specified ports.
pPort = static_cast<std::size_t>(std::stoi(proxyPort));
sPort = static_cast<std::size_t>(std::stoi(serverPort));
if( sPort > 0 && pPort > 0 ) {
fd = connect(proxyAddress,pPort);
if( fd >= 0 && !socksConnect(serverAddress,sPort,fd) ) {
close(fd);
fd = -1;
}
}
return ( fd );
}
void ControllerApplication::connectToServer( void ) {
const std::string & serverAddress = mProperties.get(kConfigHost);
const std::string & serverPort = mProperties.get(kConfigHostPort);
std::size_t port;
int fd;
fd = -1;
if( mProperties.contains(kConfigSocksAddress) &&
mProperties.contains(kConfigSocksPort) ) {
const std::string & proxyAddress = mProperties.get(kConfigSocksAddress);
const std::string & proxyPort = mProperties.get(kConfigSocksPort);
fd = connectToProxy(proxyAddress,proxyPort,
serverAddress,serverPort);
} else {
port = static_cast<std::size_t>(std::stoi(serverPort));
fd = connect(serverAddress,port);
}
// Check if a successful connection could be made.
if( fd >= 0 ) {
if( sslRequested() ) {
SSL * ssl;
initializeSslContext();
ssl = SSL_new(mSslContext);
SSL_set_fd(ssl,fd);
if( SSL_connect(ssl) <= 0 ) {
SSL_free(ssl);
close(fd);
} else {
mSocket = new PosixSslSocket(ssl);
}
} else {
mSocket = new PosixTcpSocket(fd);
}
}
}
std::size_t ControllerApplication::getServerPort( void ) const {
const std::string & serverPort = mProperties.get(kConfigHostPort);
std::size_t port;
if( serverPort.empty() ||
(port = static_cast<std::size_t>(std::stoi(serverPort))) == 0 )
port = kDefaultControllerServerPort;
return ( port );
}
void ControllerApplication::readDevices( void ) {
std::string filePath;
filePath = mProperties.get(kConfigDeviceList);
if( filePath.empty() )
return;
std::ifstream file(filePath);
std::string line;
std::string deviceIdentifier;
std::string deviceBash;
logi("Retrieving devices.");
while( std::getline(file,line) ) {
trim(line);
if( line.empty() || line.at(0) == '#' )
continue;
deviceIdentifier = line;
std::getline(file,line);
trim(line);
if( line.empty() || line.at(0) == '#' )
return;
deviceBash = line;
logi("Adding " + deviceIdentifier + ".");
mDevices.push_back(deviceIdentifier);
mDeviceCommands.push_back(deviceBash);
}
file.close();
logi("Devices have been read.");
}
void ControllerApplication::allocateDeviceServer( void ) {
ServerSocket * serverSocket;
std::string stringPort;
unsigned int port;
if( mProperties.contains(kConfigNetworkDevicePort) )
stringPort = mProperties.get(kConfigNetworkDevicePort);
if( !stringPort.empty() )
port = static_cast<unsigned int>(atol(stringPort.c_str()));
else
port = kDefaultDeviceServerPort;
logi("Allocating device server at port " + std::to_string(port) + ".");
serverSocket = new PosixTcpServerSocket(port);
if( serverSocket->bindToPort() ) {
mDeviceServer = new DeviceServer(serverSocket,
mSocket,
mDevices);
logi("Device server has been allocated.");
} else {
delete serverSocket;
loge("Could not bind device server to port " + std::to_string(port) + ".");
}
}
void ControllerApplication::authenticateWithServer( void ) {
std::uint8_t header[3];
std::uint8_t response;
std::string message;
std::size_t n;
Writer * writer;
Reader * reader;
bool success;
const std::string & controllerIdentifier =
mProperties.get(kConfigControllerIdentifier);
const std::string & securityCode =
mProperties.get(kConfigControllerSecurityCode);
if( controllerIdentifier.empty() ||
securityCode.empty() ) {
stop();
loge("Authentication credentials missing.");
return;
}
logi("Authenticating with server.");
success = true;
header[0] = 0x00;
header[1] = static_cast<std::uint8_t>(controllerIdentifier.length());
header[2] = static_cast<std::uint8_t>(securityCode.length());
message = controllerIdentifier + securityCode;
writer = mSocket->getWriter();
reader = mSocket->getReader();
writer->lock();
n = writer->writeBytes(reinterpret_cast<const char *>(header),3);
success &= ( n > 0 );
n = writer->writeBytes(reinterpret_cast<const char *>(message.c_str()),
message.length());
success &= ( n > 0 );
writer->unlock();
response = 0x00;
reader->readBytes(reinterpret_cast<char *>(&response),1);
if( success && response == 0x01 ) {
logi("Authenticated.");
} else {
logi("Authentication failed.");
mSocket->closeConnection();
}
}
void ControllerApplication::startDeviceProcesses( void ) {
std::string path;
std::string argument;
std::size_t nArguments;
pid_t processId;
int status;
logi("Starting devices processes.");
for( auto it = mDeviceCommands.begin() ; it != mDeviceCommands.end() ; ++it ) {
const std::string & command = (*it);
std::stringstream ss;
ss << command;
ss >> path;
nArguments = numWords(command);
char * argv[nArguments + 1];
argv[nArguments] = static_cast<char *>(0);
argv[0] = new char[path.length() + 1];
strcpy(argv[0],path.c_str());
for( std::size_t i = 1 ; i < nArguments ; ++i ) {
ss >> argument;
argv[i] = new char[argument.length() + 1];
strcpy(argv[i],argument.c_str());
}
status = posix_spawn(&processId,path.c_str(),nullptr,nullptr,
argv,nullptr);
if( status == 0 ) {
mPids.push_back(processId);
}
for( std::size_t i = 0 ; i < nArguments ; ++i )
delete [] argv[i];
}
logi("Device processes have been started.");
}
void ControllerApplication::cleanupDeviceProcesses( void ) {
int status;
std::size_t n;
n = mPids.size();
for( std::size_t i = 0 ; i < n ; ++i ) {
waitpid(mPids.at(i),&status,0);
}
}
void ControllerApplication::initializeLogger( void ) {
std::string type;
if( mProperties.contains(kConfigLoggerType) ) {
type = mProperties.get(kConfigLoggerType);
if( type == std::string(ConsoleLogger::kType) ) {
Logger::setLogger(new ConsoleLogger());
std::cout.flush();
} else
if( type == std::string(FileLogger::kType) &&
mProperties.contains(kConfigLoggerLogfilePath) ) {
std::string logfile = mProperties.get(kConfigLoggerLogfilePath);
if( !logfile.empty() )
Logger::setLogger(new FileLogger(logfile));
}
}
}
ControllerApplication::ControllerApplication( const int argc,
const char ** argv ) {
initialize();
setup(argc,argv);
}
ControllerApplication::~ControllerApplication( void ) {
delete mSocket; mSocket = nullptr;
delete mDeviceServer; mDeviceServer = nullptr;
cleanupDeviceProcesses();
}
void ControllerApplication::run( void ) {
if( mDeviceServer != nullptr ) {
logi("Starting device server.");
mDeviceServer->start();
logi("Device server has been started.");
mDeviceServer->join();
logi("Device server has been stopped.");
}
}
void ControllerApplication::stop( void ) {
if( mDeviceServer != nullptr ) {
logi("Stopping the device server.");
mDeviceServer->stop();
mSocket->closeConnection();
}
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_GENERATOR_HPP_INCLUDED
#define CPPCORO_GENERATOR_HPP_INCLUDED
#include <experimental/coroutine>
#include <type_traits>
#include <utility>
#include <exception>
namespace cppcoro
{
template<typename T>
class generator;
namespace detail
{
template<typename T>
class generator_promise
{
public:
using value_type = std::remove_reference_t<T>;
using reference_type = std::conditional_t<std::is_reference_v<T>, T, T&>;
using pointer_type = value_type*;
generator_promise() = default;
generator<T> get_return_object() noexcept;
constexpr std::experimental::suspend_always initial_suspend() const { return {}; }
constexpr std::experimental::suspend_always final_suspend() const { return {}; }
template<
typename U = T,
std::enable_if_t<!std::is_rvalue_reference<U>::value, int> = 0>
std::experimental::suspend_always yield_value(std::remove_reference_t<T>& value) noexcept
{
m_value = std::addressof(value);
return {};
}
std::experimental::suspend_always yield_value(std::remove_reference_t<T>&& value) noexcept
{
m_value = std::addressof(value);
return {};
}
void unhandled_exception()
{
m_exception = std::current_exception();
}
void return_void()
{
}
reference_type value() const noexcept
{
return static_cast<reference_type>(*m_value);
}
// Don't allow any use of 'co_await' inside the generator coroutine.
template<typename U>
std::experimental::suspend_never await_transform(U&& value) = delete;
void rethrow_if_exception()
{
if (m_exception)
{
std::rethrow_exception(m_exception);
}
}
private:
pointer_type m_value;
std::exception_ptr m_exception;
};
struct generator_sentinel {};
template<typename T>
class generator_iterator
{
using coroutine_handle = std::experimental::coroutine_handle<generator_promise<T>>;
public:
using iterator_category = std::input_iterator_tag;
// What type should we use for counting elements of a potentially infinite sequence?
using difference_type = std::size_t;
using value_type = typename generator_promise<T>::value_type;
using reference = typename generator_promise<T>::reference_type;
using pointer = typename generator_promise<T>::pointer_type;
// Iterator needs to be default-constructible to satisfy the Range concept.
generator_iterator() noexcept
: m_coroutine(nullptr)
{}
explicit generator_iterator(coroutine_handle coroutine) noexcept
: m_coroutine(coroutine)
{}
bool operator==(const generator_iterator& other) const noexcept
{
return m_coroutine == other.m_coroutine;
}
bool operator==(generator_sentinel) const noexcept
{
return !m_coroutine || m_coroutine.done();
}
bool operator!=(const generator_iterator& other) const noexcept
{
return !(*this == other);
}
bool operator!=(generator_sentinel other) const noexcept
{
return !operator==(other);
}
generator_iterator& operator++()
{
m_coroutine.resume();
if (m_coroutine.done())
{
m_coroutine.promise().rethrow_if_exception();
}
return *this;
}
// Need to provide post-increment operator to implement the 'Range' concept.
void operator++(int)
{
(void)operator++();
}
reference operator*() const noexcept
{
return m_coroutine.promise().value();
}
pointer operator->() const noexcept
{
return std::addressof(operator*());
}
private:
coroutine_handle m_coroutine;
};
}
template<typename T>
class [[nodiscard]] generator
{
public:
using promise_type = detail::generator_promise<T>;
using iterator = detail::generator_iterator<T>;
generator() noexcept
: m_coroutine(nullptr)
{}
generator(generator&& other) noexcept
: m_coroutine(other.m_coroutine)
{
other.m_coroutine = nullptr;
}
generator(const generator& other) = delete;
~generator()
{
if (m_coroutine)
{
m_coroutine.destroy();
}
}
generator& operator=(generator other) noexcept
{
swap(other);
return *this;
}
iterator begin()
{
if (m_coroutine)
{
m_coroutine.resume();
if (m_coroutine.done())
{
m_coroutine.promise().rethrow_if_exception();
}
}
return iterator{ m_coroutine };
}
detail::generator_sentinel end() noexcept
{
return detail::generator_sentinel{};
}
void swap(generator& other) noexcept
{
std::swap(m_coroutine, other.m_coroutine);
}
private:
friend class detail::generator_promise<T>;
explicit generator(std::experimental::coroutine_handle<promise_type> coroutine) noexcept
: m_coroutine(coroutine)
{}
std::experimental::coroutine_handle<promise_type> m_coroutine;
};
template<typename T>
void swap(generator<T>& a, generator<T>& b)
{
a.swap(b);
}
namespace detail
{
template<typename T>
generator<T> generator_promise<T>::get_return_object() noexcept
{
using coroutine_handle = std::experimental::coroutine_handle<generator_promise<T>>;
return generator<T>{ coroutine_handle::from_promise(*this) };
}
}
template<typename FUNC, typename T>
generator<std::invoke_result_t<FUNC&, typename generator<T>::iterator::reference>> fmap(FUNC func, generator<T> source)
{
for (auto&& value : source)
{
co_yield std::invoke(func, static_cast<decltype(value)>(value));
}
}
}
#endif
<commit_msg>iterator_category needs <iterator><commit_after>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_GENERATOR_HPP_INCLUDED
#define CPPCORO_GENERATOR_HPP_INCLUDED
#include <experimental/coroutine>
#include <type_traits>
#include <utility>
#include <exception>
#include <iterator>
namespace cppcoro
{
template<typename T>
class generator;
namespace detail
{
template<typename T>
class generator_promise
{
public:
using value_type = std::remove_reference_t<T>;
using reference_type = std::conditional_t<std::is_reference_v<T>, T, T&>;
using pointer_type = value_type*;
generator_promise() = default;
generator<T> get_return_object() noexcept;
constexpr std::experimental::suspend_always initial_suspend() const { return {}; }
constexpr std::experimental::suspend_always final_suspend() const { return {}; }
template<
typename U = T,
std::enable_if_t<!std::is_rvalue_reference<U>::value, int> = 0>
std::experimental::suspend_always yield_value(std::remove_reference_t<T>& value) noexcept
{
m_value = std::addressof(value);
return {};
}
std::experimental::suspend_always yield_value(std::remove_reference_t<T>&& value) noexcept
{
m_value = std::addressof(value);
return {};
}
void unhandled_exception()
{
m_exception = std::current_exception();
}
void return_void()
{
}
reference_type value() const noexcept
{
return static_cast<reference_type>(*m_value);
}
// Don't allow any use of 'co_await' inside the generator coroutine.
template<typename U>
std::experimental::suspend_never await_transform(U&& value) = delete;
void rethrow_if_exception()
{
if (m_exception)
{
std::rethrow_exception(m_exception);
}
}
private:
pointer_type m_value;
std::exception_ptr m_exception;
};
struct generator_sentinel {};
template<typename T>
class generator_iterator
{
using coroutine_handle = std::experimental::coroutine_handle<generator_promise<T>>;
public:
using iterator_category = std::input_iterator_tag;
// What type should we use for counting elements of a potentially infinite sequence?
using difference_type = std::size_t;
using value_type = typename generator_promise<T>::value_type;
using reference = typename generator_promise<T>::reference_type;
using pointer = typename generator_promise<T>::pointer_type;
// Iterator needs to be default-constructible to satisfy the Range concept.
generator_iterator() noexcept
: m_coroutine(nullptr)
{}
explicit generator_iterator(coroutine_handle coroutine) noexcept
: m_coroutine(coroutine)
{}
bool operator==(const generator_iterator& other) const noexcept
{
return m_coroutine == other.m_coroutine;
}
bool operator==(generator_sentinel) const noexcept
{
return !m_coroutine || m_coroutine.done();
}
bool operator!=(const generator_iterator& other) const noexcept
{
return !(*this == other);
}
bool operator!=(generator_sentinel other) const noexcept
{
return !operator==(other);
}
generator_iterator& operator++()
{
m_coroutine.resume();
if (m_coroutine.done())
{
m_coroutine.promise().rethrow_if_exception();
}
return *this;
}
// Need to provide post-increment operator to implement the 'Range' concept.
void operator++(int)
{
(void)operator++();
}
reference operator*() const noexcept
{
return m_coroutine.promise().value();
}
pointer operator->() const noexcept
{
return std::addressof(operator*());
}
private:
coroutine_handle m_coroutine;
};
}
template<typename T>
class [[nodiscard]] generator
{
public:
using promise_type = detail::generator_promise<T>;
using iterator = detail::generator_iterator<T>;
generator() noexcept
: m_coroutine(nullptr)
{}
generator(generator&& other) noexcept
: m_coroutine(other.m_coroutine)
{
other.m_coroutine = nullptr;
}
generator(const generator& other) = delete;
~generator()
{
if (m_coroutine)
{
m_coroutine.destroy();
}
}
generator& operator=(generator other) noexcept
{
swap(other);
return *this;
}
iterator begin()
{
if (m_coroutine)
{
m_coroutine.resume();
if (m_coroutine.done())
{
m_coroutine.promise().rethrow_if_exception();
}
}
return iterator{ m_coroutine };
}
detail::generator_sentinel end() noexcept
{
return detail::generator_sentinel{};
}
void swap(generator& other) noexcept
{
std::swap(m_coroutine, other.m_coroutine);
}
private:
friend class detail::generator_promise<T>;
explicit generator(std::experimental::coroutine_handle<promise_type> coroutine) noexcept
: m_coroutine(coroutine)
{}
std::experimental::coroutine_handle<promise_type> m_coroutine;
};
template<typename T>
void swap(generator<T>& a, generator<T>& b)
{
a.swap(b);
}
namespace detail
{
template<typename T>
generator<T> generator_promise<T>::get_return_object() noexcept
{
using coroutine_handle = std::experimental::coroutine_handle<generator_promise<T>>;
return generator<T>{ coroutine_handle::from_promise(*this) };
}
}
template<typename FUNC, typename T>
generator<std::invoke_result_t<FUNC&, typename generator<T>::iterator::reference>> fmap(FUNC func, generator<T> source)
{
for (auto&& value : source)
{
co_yield std::invoke(func, static_cast<decltype(value)>(value));
}
}
}
#endif
<|endoftext|> |
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/intpoint.h" //To normalize vectors.
#include "utils/math.h" //For round_up_divide.
#include "utils/MinimumSpanningTree.h" //For the
#include "utils/polygonUtils.h" //For moveInside.
#include "TreeSupport.h"
#define SQRT_2 1.4142135623730950488 //Square root of 2.
namespace cura
{
TreeSupport::TreeSupport()
{
}
void TreeSupport::generateSupportAreas(SliceDataStorage& storage)
{
std::vector<std::unordered_set<Point>> contact_points;
contact_points.reserve(storage.support.supportLayers.size());
for (size_t layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) //Generate empty layers to store the points in.
{
contact_points.emplace_back();
}
for (SliceMeshStorage& mesh : storage.meshes)
{
if (!mesh.getSettingBoolean("support_tree_enable"))
{
return;
}
generateContactPoints(mesh, contact_points);
}
//Generate areas that have to be avoided.
const coord_t layer_height = storage.getSettingInMicrons("layer_height");
const double angle = storage.getSettingInAngleRadians("support_tree_angle");
const coord_t maximum_move_distance = tan(angle) * layer_height;
std::vector<Polygons> model_collision;
const coord_t xy_distance = storage.getSettingInMicrons("support_xy_distance"); //TODO: Add branch thickness.
constexpr bool include_helper_parts = false;
model_collision.push_back(storage.getLayerOutlines(0, include_helper_parts).offset(xy_distance));
//TODO: If allowing support to rest on model, these need to be just the model outlines.
for (size_t layer_nr = 1; layer_nr < storage.print_layer_count; layer_nr ++)
{
//Generate an area above the current layer where you'd still collide with the current layer if you were to move with at most maximum_move_distance.
model_collision.push_back(model_collision[layer_nr - 1].offset(-maximum_move_distance)); //Inset previous layer with maximum_move_distance to allow some movement.
model_collision[layer_nr] = model_collision[layer_nr].unionPolygons(storage.getLayerOutlines(layer_nr, include_helper_parts).offset(xy_distance)); //Add current layer's collision to that.
}
//Use Minimum Spanning Tree to connect the points on each layer and move them while dropping them down.
for (size_t layer_nr = contact_points.size() - 1; layer_nr > 0; layer_nr--) //Skip layer 0, since we can't drop down the vertices there.
{
MinimumSpanningTree mst(contact_points[layer_nr]);
for (Point vertex : contact_points[layer_nr])
{
std::vector<Point> neighbours = mst.adjacentNodes(vertex);
if (neighbours.size() == 1) //This is a leaf.
{
Point direction = neighbours[0] - vertex;
if (vSize2(direction) < maximum_move_distance * maximum_move_distance) //Smaller than one step. Leave this one out.
{
continue;
}
Point motion = normal(direction, maximum_move_distance);
Point next_layer_vertex = vertex + motion;
PolygonUtils::moveOutside(model_collision[layer_nr], next_layer_vertex, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(next_layer_vertex);
}
else //Not a leaf or just a single vertex.
{
PolygonUtils::moveOutside(model_collision[layer_nr], vertex, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(vertex); //Just drop the leaves directly down.
//TODO: Avoid collisions.
}
}
}
//TODO: When reaching the bottom, cut away all edges of the MST that are still not contracted.
//TODO: Do a second pass of dropping down but with leftover edges removed.
//Placeholder to test with that generates a simple diamond at each contact point (without generating any trees yet).
for (size_t layer_nr = 0; layer_nr < contact_points.size(); layer_nr++)
{
for (Point point : contact_points[layer_nr])
{
PolygonsPart outline;
Polygon diamond;
diamond.add(point + Point(0, 1000));
diamond.add(point + Point(-1000, 0));
diamond.add(point + Point(0, -1000));
diamond.add(point + Point(1000, 0));
outline.add(diamond);
storage.support.supportLayers[layer_nr].support_infill_parts.emplace_back(outline, 350);
}
if (!contact_points[layer_nr].empty())
{
storage.support.layer_nr_max_filled_layer = layer_nr;
}
}
//TODO: Apply some diameter to the tree branches.
storage.support.generated = true;
}
void TreeSupport::generateContactPoints(const SliceMeshStorage& mesh, std::vector<std::unordered_set<Point>>& contact_points)
{
const coord_t layer_height = mesh.getSettingInMicrons("layer_height");
const coord_t z_distance_top = mesh.getSettingInMicrons("support_top_distance");
const size_t z_distance_top_layers = std::max(0U, round_up_divide(z_distance_top, layer_height)) + 1; //Support must always be 1 layer below overhang.
for (size_t layer_nr = 0; layer_nr < mesh.overhang_areas.size() - z_distance_top_layers; layer_nr++)
{
const Polygons& overhang = mesh.overhang_areas[layer_nr + z_distance_top_layers];
if (overhang.empty())
{
continue;
}
//First generate a lot of points in a grid pattern.
Polygons outside_polygons = overhang.getOutsidePolygons();
AABB bounding_box(outside_polygons); //To know how far we should generate points.
coord_t point_spread = mesh.getSettingInMicrons("support_tree_branch_distance");
point_spread *= SQRT_2; //We'll rotate these points 45 degrees, so this is the point distance when axis-aligned.
bounding_box.round(point_spread);
for (PolygonRef overhang_part : outside_polygons)
{
AABB bounding_box(outside_polygons);
bounding_box.round(point_spread);
bool added = false; //Did we add a point this way?
for (coord_t x = bounding_box.min.X; x <= bounding_box.max.X; x += point_spread << 1)
{
for (coord_t y = bounding_box.min.Y + (point_spread << 1) * (x % 2); y <= bounding_box.max.Y; y += point_spread) //This produces points in a 45-degree rotated grid.
{
Point candidate(x, y);
constexpr bool border_is_inside = true;
if (overhang_part.inside(candidate, border_is_inside))
{
contact_points[layer_nr].insert(candidate);
added = true;
}
}
}
if (!added) //If we didn't add any points due to bad luck, we want to add one anyway such that loose parts are also supported.
{
Point candidate = bounding_box.getMiddle();
PolygonUtils::moveInside(overhang_part, candidate);
contact_points[layer_nr].insert(candidate);
}
}
}
}
}<commit_msg>Take branch thickness into account when avoiding<commit_after>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/intpoint.h" //To normalize vectors.
#include "utils/math.h" //For round_up_divide.
#include "utils/MinimumSpanningTree.h" //For the
#include "utils/polygonUtils.h" //For moveInside.
#include "TreeSupport.h"
#define SQRT_2 1.4142135623730950488 //Square root of 2.
namespace cura
{
TreeSupport::TreeSupport()
{
}
void TreeSupport::generateSupportAreas(SliceDataStorage& storage)
{
std::vector<std::unordered_set<Point>> contact_points;
contact_points.reserve(storage.support.supportLayers.size());
for (size_t layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) //Generate empty layers to store the points in.
{
contact_points.emplace_back();
}
for (SliceMeshStorage& mesh : storage.meshes)
{
if (!mesh.getSettingBoolean("support_tree_enable"))
{
return;
}
generateContactPoints(mesh, contact_points);
}
//Generate areas that have to be avoided.
const coord_t layer_height = storage.getSettingInMicrons("layer_height");
const double angle = storage.getSettingInAngleRadians("support_tree_angle");
const coord_t maximum_move_distance = tan(angle) * layer_height;
std::vector<Polygons> model_collision;
const coord_t xy_distance = storage.getSettingInMicrons("support_xy_distance") + (storage.getSettingInMicrons("support_tree_branch_diameter") >> 1);
constexpr bool include_helper_parts = false;
model_collision.push_back(storage.getLayerOutlines(0, include_helper_parts).offset(xy_distance));
//TODO: If allowing support to rest on model, these need to be just the model outlines.
for (size_t layer_nr = 1; layer_nr < storage.print_layer_count; layer_nr ++)
{
//Generate an area above the current layer where you'd still collide with the current layer if you were to move with at most maximum_move_distance.
model_collision.push_back(model_collision[layer_nr - 1].offset(-maximum_move_distance)); //Inset previous layer with maximum_move_distance to allow some movement.
model_collision[layer_nr] = model_collision[layer_nr].unionPolygons(storage.getLayerOutlines(layer_nr, include_helper_parts).offset(xy_distance)); //Add current layer's collision to that.
}
//Use Minimum Spanning Tree to connect the points on each layer and move them while dropping them down.
for (size_t layer_nr = contact_points.size() - 1; layer_nr > 0; layer_nr--) //Skip layer 0, since we can't drop down the vertices there.
{
MinimumSpanningTree mst(contact_points[layer_nr]);
for (Point vertex : contact_points[layer_nr])
{
std::vector<Point> neighbours = mst.adjacentNodes(vertex);
if (neighbours.size() == 1) //This is a leaf.
{
Point direction = neighbours[0] - vertex;
if (vSize2(direction) < maximum_move_distance * maximum_move_distance) //Smaller than one step. Leave this one out.
{
continue;
}
Point motion = normal(direction, maximum_move_distance);
Point next_layer_vertex = vertex + motion;
PolygonUtils::moveOutside(model_collision[layer_nr], next_layer_vertex, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(next_layer_vertex);
}
else //Not a leaf or just a single vertex.
{
PolygonUtils::moveOutside(model_collision[layer_nr], vertex, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(vertex); //Just drop the leaves directly down.
//TODO: Avoid collisions.
}
}
}
//TODO: When reaching the bottom, cut away all edges of the MST that are still not contracted.
//TODO: Do a second pass of dropping down but with leftover edges removed.
//Placeholder to test with that generates a simple diamond at each contact point (without generating any trees yet).
for (size_t layer_nr = 0; layer_nr < contact_points.size(); layer_nr++)
{
for (Point point : contact_points[layer_nr])
{
PolygonsPart outline;
Polygon diamond;
diamond.add(point + Point(0, 1000));
diamond.add(point + Point(-1000, 0));
diamond.add(point + Point(0, -1000));
diamond.add(point + Point(1000, 0));
outline.add(diamond);
storage.support.supportLayers[layer_nr].support_infill_parts.emplace_back(outline, 350);
}
if (!contact_points[layer_nr].empty())
{
storage.support.layer_nr_max_filled_layer = layer_nr;
}
}
//TODO: Apply some diameter to the tree branches.
storage.support.generated = true;
}
void TreeSupport::generateContactPoints(const SliceMeshStorage& mesh, std::vector<std::unordered_set<Point>>& contact_points)
{
const coord_t layer_height = mesh.getSettingInMicrons("layer_height");
const coord_t z_distance_top = mesh.getSettingInMicrons("support_top_distance");
const size_t z_distance_top_layers = std::max(0U, round_up_divide(z_distance_top, layer_height)) + 1; //Support must always be 1 layer below overhang.
for (size_t layer_nr = 0; layer_nr < mesh.overhang_areas.size() - z_distance_top_layers; layer_nr++)
{
const Polygons& overhang = mesh.overhang_areas[layer_nr + z_distance_top_layers];
if (overhang.empty())
{
continue;
}
//First generate a lot of points in a grid pattern.
Polygons outside_polygons = overhang.getOutsidePolygons();
AABB bounding_box(outside_polygons); //To know how far we should generate points.
coord_t point_spread = mesh.getSettingInMicrons("support_tree_branch_distance");
point_spread *= SQRT_2; //We'll rotate these points 45 degrees, so this is the point distance when axis-aligned.
bounding_box.round(point_spread);
for (PolygonRef overhang_part : outside_polygons)
{
AABB bounding_box(outside_polygons);
bounding_box.round(point_spread);
bool added = false; //Did we add a point this way?
for (coord_t x = bounding_box.min.X; x <= bounding_box.max.X; x += point_spread >> 1)
{
for (coord_t y = bounding_box.min.Y + (point_spread << 1) * (x % 2); y <= bounding_box.max.Y; y += point_spread) //This produces points in a 45-degree rotated grid.
{
Point candidate(x, y);
constexpr bool border_is_inside = true;
if (overhang_part.inside(candidate, border_is_inside))
{
contact_points[layer_nr].insert(candidate);
added = true;
}
}
}
if (!added) //If we didn't add any points due to bad luck, we want to add one anyway such that loose parts are also supported.
{
Point candidate = bounding_box.getMiddle();
PolygonUtils::moveInside(overhang_part, candidate);
contact_points[layer_nr].insert(candidate);
}
}
}
}
}<|endoftext|> |
<commit_before>//This file only exist to document the scripting API with doxygen. This file should NEVER be included ANYWERE
#pragma once
#include "Annwvyn.h"
#include "doxygen_dummy.hpp"
#include "AnnGameObject.hpp"
#include "AnnLevelManager.hpp"
namespace Annwvyn
{
//As a safety measure, if anybody include this file even with the warning in the 1st line, it will put it's junk in a sub-namespace
///List prototypes of C++ non-existing functions that match the interface of the Script functions you can use!
namespace ChaiScriptAPIDoc
{
///ScriptFunction: Log a string
/// \param s String to log
void AnnDebugLog(const std::string& s);
///ScriptFunction: Log a 2D vector
/// \param v Vector to log
void AnnDebugLog(const Ogre::Vector2& v);
///ScriptFunction: Log a 3D vector
/// \param v Vector to log
void AnnDebugLog(const Ogre::Vector3& v);
///ScriptFunction: Log a Quaternion
/// \param q Quaternion to log
void AnnDebugLog(const Ogre::Quaternion& q);
///ScriptFunction: Log an angle in Radian
/// \param a Angle to log
void AnnDebugLog(const Ogre::Radian& a);
///ScriptFunction: Log an angle in Degree
/// \param a Angle to log
void AnnDebugLog(const Ogre::Degree& a);
///ScriptFunction: Log a color
/// \param c Color to log
void AnnDebugLog(const AnnColor& c);
///ScritpFunciton: Set the world's background color
/// \param c Color
void AnnSetWorldBackgroundColor(const AnnColor& c);
///ScriptFunction: Set the value of the ambient lighting
/// \param c Color
void AnnSetAmbientLight(const AnnColor& c);
///ScriptFunction: Create a game object. Will be added to the current level if a level is running
/// \param mesh Mesh to use
/// \param objectName Name that the object will bear
void AnnCreateGameObject(const std::string& mesh, const std::string& objectName);
///ScriptFunction: Remove a game boject. Will be removed from the current level if a level is running
/// \param objectName Name of the object
void AnnRemoveGameObject(const std::string& objectName);
///ScriptFunction: get a GameObject from it's ID
/// \param id The string ID of the object you want
AnnGameObject* AnnGetGameObject(std::string id);
///ScriptFunction: set the gravity vector
/// \param gravity The vector to use as `g`
void AnnChangeGravity(const Ogre::Vector3& gravity);
///ScriptFunction: restore the gravity vector
void AnnRestoreGravity(void);
///ScriptFunction: Jump the level manager to another level
/// \param id The ID number of the level
void AnnJumpLevel(Annwvyn::level_id id);
}
}<commit_msg>insert some classes into the documentation of the scripting API<commit_after>//This file only exist to document the scripting API with doxygen. This file should NEVER be included ANYWERE
#pragma once
#include "Annwvyn.h"
#include "doxygen_dummy.hpp"
#include "AnnGameObject.hpp"
#include "AnnLevelManager.hpp"
namespace Annwvyn
{
//As a safety measure, if anybody include this file even with the warning in the 1st line, it will put it's junk in a sub-namespace
//As a side effect of the above statement, this permit to access the whole thing via a single link on the generated website. GREAT.
///List prototypes of C++ non-existing functions that match the interface of the Script functions you can use!
namespace ChaiScriptAPIDoc
{
///ScriptFunction: Log a string
/// \param s String to log
void AnnDebugLog(const std::string& s);
///ScriptFunction: Log a 2D vector
/// \param v Vector to log
void AnnDebugLog(const Ogre::Vector2& v);
///ScriptFunction: Log a 3D vector
/// \param v Vector to log
void AnnDebugLog(const Ogre::Vector3& v);
///ScriptFunction: Log a Quaternion
/// \param q Quaternion to log
void AnnDebugLog(const Ogre::Quaternion& q);
///ScriptFunction: Log an angle in Radian
/// \param a Angle to log
void AnnDebugLog(const Ogre::Radian& a);
///ScriptFunction: Log an angle in Degree
/// \param a Angle to log
void AnnDebugLog(const Ogre::Degree& a);
///ScriptFunction: Log a color
/// \param c Color to log
void AnnDebugLog(const AnnColor& c);
///ScriptFunction: Log a keycode
/// \param c KeyCode number
void AnnDebugLog(KeyCode::code c);
///ScriptFunction: Log a mouse axis
/// \param a Axis
void AnnDebugLog(MouseAxisId a);
///ScriptFunction: log a boolean
/// \param b bool to log
void AnnDebugLog(bool b);
///ScriptFunction: log an integer
/// \param i int
void AnnDebugLog(int i);
///ScriptFunction: log a simple precision floating point number
/// \param f float
void AnnDebugLog(float f);
//-----------------------------------------------------------------------
///ScritpFunciton: Set the world's background color
/// \param c Color
void AnnSetWorldBackgroundColor(const AnnColor& c);
///ScriptFunction: Set the value of the ambient lighting
/// \param c Color
void AnnSetAmbientLight(const AnnColor& c);
///ScriptFunction: Create a game object. Will be added to the current level if a level is running
/// \param mesh Mesh to use
/// \param objectName Name that the object will bear
void AnnCreateGameObject(const std::string& mesh, const std::string& objectName);
///ScriptFunction: Remove a game object. Will be removed from the current level if a level is running
/// \param objectName Name of the object
void AnnRemoveGameObject(const std::string& objectName);
///ScriptFunction: get a GameObject from it's ID
/// \param id The string ID of the object you want
AnnGameObject* AnnGetGameObject(std::string id);
///ScriptFunction: set the gravity vector
/// \param gravity The vector to use as `g`
void AnnChangeGravity(const Ogre::Vector3& gravity);
///ScriptFunction: restore the gravity vector
void AnnRestoreGravity(void);
///ScriptFunction: Jump the level manager to another level
/// \param id The ID number of the level
void AnnJumpLevel(Annwvyn::level_id id);
//-classes-----------------------------------------------------
///Keyboard event from scripts
class AnnKeyEvent
{
public:
///Return if event is press event
bool isPressed();
///Return if event is released event
bool isReleased();
///Key concerned by this event
KeyCode::code getKey();
};
///Mouse event from script
class AnnMouseEvent
{
public:
///Axis of the mouse 0 is horizontal, 1 is vertical and 2 is scrolling
AnnStickAxis getAxis(const int id);
///State of a button, left, right, middle, and others, maybe...
bool getButtonState(const int id);
};
///Axis of a mouse
class AnnMouseAxis
{
public:
///get relative value
int getRelValue();
///get absolute value
int getAbsValue();
};
///Joystick event
class AnnStickEvent
{
public:
///return how many buttons
size_t getNbButtons();
///return how many axes
size_t getNbAxis();
///return how many PoV
size_t getNbPov();
///return the vendor string of this controller. In practice it's the name of the controller
std::string getVendor();
///Get the ID number of this controller
unsigned int getSitckID();
///Return true if this controller is an xbox controller. Usefull for oculus rift games...
bool isXboxController();
///Is button `i` pressed
bool isPressed(const int i);
///Is button `i` released
bool isReleased(const int i);
///Is button `i` <strong>currently down</strong>
bool isDown(const int i);
///Get the wanted axis
AnnStickAxis getAxis(const int i);
///Get the wanted pov
AnnStickPov getPov(const int i);
};
///state of a PoV from a controller
class AnnStickPov
{
public:
///N
bool getNorth();
///S
bool getSouth();
///E
bool getEast();
///W
bool getWest();
/// N && E
bool getNorthEast();
/// N && W
bool getNorthWest();
/// S && E
bool getSouthEast();
/// S && W
bool getSouthWest();
};
///Wait for a timer to go to 0
class AnnTimeEvent
{
public:
///Get the ID of the timer that timeouted
timerID getID();
};
///A color
class AnnColor
{
///Construct with RGBA
AnnColor(float r, float g, float b, float a);
///Construct with a color from Ogre
AnnColor(const Ogre::ColourValue& c);
///Asign another color to this one
AnnColor operator=(AnnColor& c);
///Get Red as [0;1] float
float getRed();
///Get Green as [0;1] float
float getGreen();
///Get Blue as [0;1] float
float getBlue();
///Get Alpha as [0;1] float
float getAlpha();
///Set Red as [0;1] float
void setRed(float f);
///Set Green as [0;1] float
void setGreen(float f);
///Set Blue as [0;1] float
void setBlue(float f);
///Set Alpha as [0;1] float
void setAlpha(float f);
};
///A game object
class AnnGameObject
{
public:
///Set the position of this object
void setPosition(AnnVect3 v);
///Set the orientation of this object
void setOrientation(AnnQuaternion q);
///Set the scaling of this object
void setScale(AnnVect3 v);
///Get the position of this object
AnnVect3 getPosition();
///Get the orientation of this object
AnnQuaternion getOrientation();
///Get the scale of this object
AnnVect3 getScale();
///Play a sound
void playSound(std::string name, bool loop = true);
};
///Value of Pi
float PI;
///Value of Pi/2
float HALF_PI;
}
}<|endoftext|> |
<commit_before>#include <SimpleITKTestHarness.h>
#include <sitkImageFileReader.h>
#include <sitkImageFileWriter.h>
#include <sitkImageHashFilter.h>
#include <sitkPixelContainer.h>
#include <itkIntTypes.h>
#include "itkImage.h"
#include "itkVectorImage.h"
using itk::simple::InstantiatedPixelIDTypeList;
class PixelContainer : public ::testing::Test {
public:
virtual void SetUp() {
itk::ImageBase<3>::IndexType index;
itk::ImageBase<3>::SizeType size;
itk::ImageBase<3>::RegionType region;
// Create an image
for ( int i = 0; i < 3; i++ ) {
index[i] = 0;
size[i] = 64+i;
}
region.SetSize ( size );
region.SetIndex ( index );
itkShortImage = ShortImageType::New();
itkShortImage->SetRegions ( region );
itkShortImage->Allocate();
itkShortImage->FillBuffer ( 100 );
itkShortImageBase = itkShortImage;
shortImage = new itk::simple::Image( itkShortImage.GetPointer() );
shortPixelContainer = shortImage->GetPixelContainer();
shortBuffer = shortPixelContainer->GetBufferAsInt16();
itkFloatImage = FloatImageType::New();
itkFloatImage->SetRegions ( region );
itkFloatImage->Allocate();
itkFloatImage->FillBuffer ( 0.0 );
itkFloatImageBase = itkFloatImage;
floatImage = new itk::simple::Image( itkFloatImage.GetPointer() );
floatPixelContainer = floatImage->GetPixelContainer();
floatBuffer = floatPixelContainer->GetBufferAsFloat();
itkFloatVectorImage = FloatVectorImageType::New();
floatVectorImage = new itk::simple::Image( itkFloatVectorImage.GetPointer() );
itkFloatVector2DImage = FloatVector2DImageType::New();
floatVector2DImage = new itk::simple::Image( itkFloatVector2DImage );
}
itk::simple::Image::Pointer image;
itk::ImageBase<3>::Pointer itkShortImageBase;
itk::ImageBase<3>::IndexType index;
itk::ImageBase<3>::SizeType size;
itk::ImageBase<3>::RegionType region;
typedef itk::Image<short,3> ShortImageType;
ShortImageType::Pointer itkShortImage;
itk::simple::Image::Pointer shortImage;
itk::simple::PixelContainer::Pointer shortPixelContainer;
int16_t * shortBuffer;
itk::ImageBase<3>::Pointer itkFloatImageBase;
typedef itk::Image<float,3> FloatImageType;
FloatImageType::Pointer itkFloatImage;
itk::simple::Image::Pointer floatImage;
itk::simple::PixelContainer::Pointer floatPixelContainer;
float * floatBuffer;
typedef itk::VectorImage<float,3> FloatVectorImageType;
itk::simple::Image::Pointer floatVectorImage;
FloatVectorImageType::Pointer itkFloatVectorImage;
typedef itk::VectorImage<float,2> FloatVector2DImageType;
itk::simple::Image::Pointer floatVector2DImage;
FloatVector2DImageType::Pointer itkFloatVector2DImage;
itk::simple::Image::Pointer differentSizedImage;
ShortImageType::Pointer itkDifferentSizedImage;
};
TEST_F(PixelContainer,Create) {
ASSERT_TRUE ( shortImage->GetImageBase().IsNotNull() );
EXPECT_EQ ( shortImage->GetWidth(), itkShortImageBase->GetLargestPossibleRegion().GetSize()[0] ) << " Checking image width";
EXPECT_EQ ( shortImage->GetHeight(), itkShortImageBase->GetLargestPossibleRegion().GetSize()[1] ) << " Checking image height";
EXPECT_EQ ( shortImage->GetDepth(), itkShortImageBase->GetLargestPossibleRegion().GetSize()[2] ) << " Checking image depth";
EXPECT_EQ ( shortBuffer, itkShortImage->GetBufferPointer() ) << " Checking Short Image Buffer Pointer";
EXPECT_EQ ( floatImage->GetWidth(), itkFloatImageBase->GetLargestPossibleRegion().GetSize()[0] ) << " Checking image width";
EXPECT_EQ ( floatImage->GetHeight(), itkFloatImageBase->GetLargestPossibleRegion().GetSize()[1] ) << " Checking image height";
EXPECT_EQ ( floatImage->GetDepth(), itkFloatImageBase->GetLargestPossibleRegion().GetSize()[2] ) << " Checking image depth";
EXPECT_EQ ( floatBuffer, itkFloatImage->GetBufferPointer() ) << " Checking Float Image Buffer Pointer";
}
TEST_F(PixelContainer,ImageDataType) {
// this test checks that the DataType of the PixelContainers are correct
int result;
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<short> >::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result);
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<float> >::Result;
EXPECT_EQ( floatPixelContainer->GetPixelIDValue(), result );
result = itk::simple::PixelIDToPixelIDValue< itk::simple::BasicPixelID<short> >::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result);
result = itk::simple::PixelIDToPixelIDValue< itk::simple::BasicPixelID<float> >::Result;
EXPECT_EQ( floatPixelContainer->GetPixelIDValue(), result );
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::ImageTypeToPixelID<ShortImageType>::PixelIDType >::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result );
result = itk::simple::ImageTypeToPixelIDValue<ShortImageType>::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result );
}
TEST_F(PixelContainer,Constructors) {
itk::simple::PixelContainer::Pointer pixelContainer;
itk::simple::Image::Pointer image;
itk::simple::ImageHashFilter hasher;
int result;
image = new itk::simple::Image ( 64, 65, 66, itk::simple::sitkUInt8 );
pixelContainer = image->GetPixelContainer();
EXPECT_EQ ( pixelContainer->GetNumberOfPixels(), image->GetWidth() * image->GetHeight() * image->GetDepth() );
EXPECT_EQ ( "08183e1b0c50fd2cf6f070b58e218443fb7d5317", hasher.SetHashFunction ( itk::simple::ImageHashFilter::SHA1 ).Execute ( image ) ) << " SHA1 hash value sitkUInt8";
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<unsigned char> >::Result;
EXPECT_EQ ( image->GetPixelIDValue(), result );
EXPECT_EQ ( image->GetPixelIDTypeAsString(), "8-bit unsigned integer" );
EXPECT_EQ ( image->GetDimension(), 3u );
EXPECT_EQ ( 64u, image->GetWidth() );
EXPECT_EQ ( 65u, image->GetHeight() );
EXPECT_EQ ( 66u, image->GetDepth() );
image = new itk::simple::Image ( 64, 65, 66, itk::simple::sitkInt16 );
EXPECT_EQ ( "645b71695b94923c868e16b943d8acf8f6788617", hasher.SetHashFunction ( itk::simple::ImageHashFilter::SHA1 ).Execute ( image ) ) << " SHA1 hash value sitkUInt16";
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<short> >::Result;
EXPECT_EQ ( image->GetPixelIDValue(), result );
EXPECT_EQ ( image->GetPixelIDTypeAsString(), "16-bit signed integer" );
EXPECT_EQ ( image->GetDimension(), 3u );
EXPECT_EQ ( 64u, image->GetWidth() );
EXPECT_EQ ( 65u, image->GetHeight() );
EXPECT_EQ ( 66u, image->GetDepth() );
image = new itk::simple::Image ( 64, 65, itk::simple::sitkUInt16 );
EXPECT_EQ ( "e3c464cc1b73df3f48bacf238a80f88b5ab0d3e6", hasher.SetHashFunction ( itk::simple::ImageHashFilter::SHA1 ).Execute ( image ) ) << " SHA1 hash value sitkUInt16";
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<unsigned short> >::Result;
EXPECT_EQ ( image->GetPixelIDValue(), result );
EXPECT_EQ ( image->GetPixelIDTypeAsString(), "16-bit unsigned integer" );
EXPECT_EQ ( image->GetDimension(), 2u );
EXPECT_EQ ( 64u, image->GetWidth() );
EXPECT_EQ ( 65u, image->GetHeight() );
EXPECT_EQ ( 0u, image->GetDepth() );
}
<commit_msg>COMP: ImageHashFilter was renamed.<commit_after>#include <SimpleITKTestHarness.h>
#include <sitkImageFileReader.h>
#include <sitkImageFileWriter.h>
#include <sitkHashImageFilter.h>
#include <sitkPixelContainer.h>
#include <itkIntTypes.h>
#include "itkImage.h"
#include "itkVectorImage.h"
using itk::simple::InstantiatedPixelIDTypeList;
class PixelContainer : public ::testing::Test {
public:
virtual void SetUp() {
itk::ImageBase<3>::IndexType index;
itk::ImageBase<3>::SizeType size;
itk::ImageBase<3>::RegionType region;
// Create an image
for ( int i = 0; i < 3; i++ ) {
index[i] = 0;
size[i] = 64+i;
}
region.SetSize ( size );
region.SetIndex ( index );
itkShortImage = ShortImageType::New();
itkShortImage->SetRegions ( region );
itkShortImage->Allocate();
itkShortImage->FillBuffer ( 100 );
itkShortImageBase = itkShortImage;
shortImage = new itk::simple::Image( itkShortImage.GetPointer() );
shortPixelContainer = shortImage->GetPixelContainer();
shortBuffer = shortPixelContainer->GetBufferAsInt16();
itkFloatImage = FloatImageType::New();
itkFloatImage->SetRegions ( region );
itkFloatImage->Allocate();
itkFloatImage->FillBuffer ( 0.0 );
itkFloatImageBase = itkFloatImage;
floatImage = new itk::simple::Image( itkFloatImage.GetPointer() );
floatPixelContainer = floatImage->GetPixelContainer();
floatBuffer = floatPixelContainer->GetBufferAsFloat();
itkFloatVectorImage = FloatVectorImageType::New();
floatVectorImage = new itk::simple::Image( itkFloatVectorImage.GetPointer() );
itkFloatVector2DImage = FloatVector2DImageType::New();
floatVector2DImage = new itk::simple::Image( itkFloatVector2DImage );
}
itk::simple::Image::Pointer image;
itk::ImageBase<3>::Pointer itkShortImageBase;
itk::ImageBase<3>::IndexType index;
itk::ImageBase<3>::SizeType size;
itk::ImageBase<3>::RegionType region;
typedef itk::Image<short,3> ShortImageType;
ShortImageType::Pointer itkShortImage;
itk::simple::Image::Pointer shortImage;
itk::simple::PixelContainer::Pointer shortPixelContainer;
int16_t * shortBuffer;
itk::ImageBase<3>::Pointer itkFloatImageBase;
typedef itk::Image<float,3> FloatImageType;
FloatImageType::Pointer itkFloatImage;
itk::simple::Image::Pointer floatImage;
itk::simple::PixelContainer::Pointer floatPixelContainer;
float * floatBuffer;
typedef itk::VectorImage<float,3> FloatVectorImageType;
itk::simple::Image::Pointer floatVectorImage;
FloatVectorImageType::Pointer itkFloatVectorImage;
typedef itk::VectorImage<float,2> FloatVector2DImageType;
itk::simple::Image::Pointer floatVector2DImage;
FloatVector2DImageType::Pointer itkFloatVector2DImage;
itk::simple::Image::Pointer differentSizedImage;
ShortImageType::Pointer itkDifferentSizedImage;
};
TEST_F(PixelContainer,Create) {
ASSERT_TRUE ( shortImage->GetImageBase().IsNotNull() );
EXPECT_EQ ( shortImage->GetWidth(), itkShortImageBase->GetLargestPossibleRegion().GetSize()[0] ) << " Checking image width";
EXPECT_EQ ( shortImage->GetHeight(), itkShortImageBase->GetLargestPossibleRegion().GetSize()[1] ) << " Checking image height";
EXPECT_EQ ( shortImage->GetDepth(), itkShortImageBase->GetLargestPossibleRegion().GetSize()[2] ) << " Checking image depth";
EXPECT_EQ ( shortBuffer, itkShortImage->GetBufferPointer() ) << " Checking Short Image Buffer Pointer";
EXPECT_EQ ( floatImage->GetWidth(), itkFloatImageBase->GetLargestPossibleRegion().GetSize()[0] ) << " Checking image width";
EXPECT_EQ ( floatImage->GetHeight(), itkFloatImageBase->GetLargestPossibleRegion().GetSize()[1] ) << " Checking image height";
EXPECT_EQ ( floatImage->GetDepth(), itkFloatImageBase->GetLargestPossibleRegion().GetSize()[2] ) << " Checking image depth";
EXPECT_EQ ( floatBuffer, itkFloatImage->GetBufferPointer() ) << " Checking Float Image Buffer Pointer";
}
TEST_F(PixelContainer,ImageDataType) {
// this test checks that the DataType of the PixelContainers are correct
int result;
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<short> >::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result);
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<float> >::Result;
EXPECT_EQ( floatPixelContainer->GetPixelIDValue(), result );
result = itk::simple::PixelIDToPixelIDValue< itk::simple::BasicPixelID<short> >::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result);
result = itk::simple::PixelIDToPixelIDValue< itk::simple::BasicPixelID<float> >::Result;
EXPECT_EQ( floatPixelContainer->GetPixelIDValue(), result );
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::ImageTypeToPixelID<ShortImageType>::PixelIDType >::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result );
result = itk::simple::ImageTypeToPixelIDValue<ShortImageType>::Result;
EXPECT_EQ( shortPixelContainer->GetPixelIDValue(), result );
}
TEST_F(PixelContainer,Constructors) {
itk::simple::PixelContainer::Pointer pixelContainer;
itk::simple::Image::Pointer image;
itk::simple::HashImageFilter hasher;
int result;
image = new itk::simple::Image ( 64, 65, 66, itk::simple::sitkUInt8 );
pixelContainer = image->GetPixelContainer();
EXPECT_EQ ( pixelContainer->GetNumberOfPixels(), image->GetWidth() * image->GetHeight() * image->GetDepth() );
EXPECT_EQ ( "08183e1b0c50fd2cf6f070b58e218443fb7d5317", hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).Execute ( image ) ) << " SHA1 hash value sitkUInt8";
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<unsigned char> >::Result;
EXPECT_EQ ( image->GetPixelIDValue(), result );
EXPECT_EQ ( image->GetPixelIDTypeAsString(), "8-bit unsigned integer" );
EXPECT_EQ ( image->GetDimension(), 3u );
EXPECT_EQ ( 64u, image->GetWidth() );
EXPECT_EQ ( 65u, image->GetHeight() );
EXPECT_EQ ( 66u, image->GetDepth() );
image = new itk::simple::Image ( 64, 65, 66, itk::simple::sitkInt16 );
EXPECT_EQ ( "645b71695b94923c868e16b943d8acf8f6788617", hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).Execute ( image ) ) << " SHA1 hash value sitkUInt16";
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<short> >::Result;
EXPECT_EQ ( image->GetPixelIDValue(), result );
EXPECT_EQ ( image->GetPixelIDTypeAsString(), "16-bit signed integer" );
EXPECT_EQ ( image->GetDimension(), 3u );
EXPECT_EQ ( 64u, image->GetWidth() );
EXPECT_EQ ( 65u, image->GetHeight() );
EXPECT_EQ ( 66u, image->GetDepth() );
image = new itk::simple::Image ( 64, 65, itk::simple::sitkUInt16 );
EXPECT_EQ ( "e3c464cc1b73df3f48bacf238a80f88b5ab0d3e6", hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).Execute ( image ) ) << " SHA1 hash value sitkUInt16";
result = typelist::IndexOf< InstantiatedPixelIDTypeList, itk::simple::BasicPixelID<unsigned short> >::Result;
EXPECT_EQ ( image->GetPixelIDValue(), result );
EXPECT_EQ ( image->GetPixelIDTypeAsString(), "16-bit unsigned integer" );
EXPECT_EQ ( image->GetDimension(), 2u );
EXPECT_EQ ( 64u, image->GetWidth() );
EXPECT_EQ ( 65u, image->GetHeight() );
EXPECT_EQ ( 0u, image->GetDepth() );
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace lexer {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
/*!
* \class SimpleLexer
* \brief The EDDI lexer.
*
* This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's
* used by the parser to parse a source file.
*/
template<typename L>
class SpiritLexer : public lex::lexer<L> {
public:
SpiritLexer() {
//Define keywords
for_ = "for";
while_ = "while";
do_ = "do";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
const_ = "const";
include = "include";
identifier = "[a-zA-Z_]?[a-zA-Z0-9_]+";
integer = "[0-9]+";
litteral = "\\\"[^\\\"]*\\\"";
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
/* Assignment operators */
swap = "<=>";
assign = '=';
/* compound assignment operators */
compound_add = "\\+=";
compound_sub = "-=";
compound_mul = "\\*=";
compound_div = "\\/=";
compound_mod = "%=";
/* Math operators */
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
/* Suffix and prefix math operators */
increment = "\\+\\+";
decrement = "--";
/* Logical operators */
and_ = "\\&\\&";
or_ = "\\|\\|";
/* Relational operators */
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += comma | stop;
this->self += assign | swap;
this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod;
this->self += addition | subtraction | multiplication | division | modulo;
this->self += increment | decrement;
this->self += and_ | or_;
this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += integer | identifier | litteral;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
StringToken identifier, litteral;
IntegerToken integer;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken increment, decrement;
StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
StringToken and_, or_;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma;
ConsumedToken assign, swap;
//Keywords
ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_, include;
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
//Typedef for the parsers
typedef lexer::lexer_type::iterator_type Iterator;
typedef lexer::SpiritLexer<lexer::lexer_type> Lexer;
} //end of lexer
} //end of eddic
#endif
<commit_msg>Introduce floating point litteral in the lexer<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace lexer {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
/*!
* \class SimpleLexer
* \brief The EDDI lexer.
*
* This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's
* used by the parser to parse a source file.
*/
template<typename L>
class SpiritLexer : public lex::lexer<L> {
public:
SpiritLexer() {
//Define keywords
for_ = "for";
while_ = "while";
do_ = "do";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
const_ = "const";
include = "include";
identifier = "[a-zA-Z_]?[a-zA-Z0-9_]+";
float_ = "[0-9]+\".\"[0-9]+";
integer = "[0-9]+";
litteral = "\\\"[^\\\"]*\\\"";
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
/* Assignment operators */
swap = "<=>";
assign = '=';
/* compound assignment operators */
compound_add = "\\+=";
compound_sub = "-=";
compound_mul = "\\*=";
compound_div = "\\/=";
compound_mod = "%=";
/* Math operators */
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
/* Suffix and prefix math operators */
increment = "\\+\\+";
decrement = "--";
/* Logical operators */
and_ = "\\&\\&";
or_ = "\\|\\|";
/* Relational operators */
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += comma | stop;
this->self += assign | swap;
this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod;
this->self += addition | subtraction | multiplication | division | modulo;
this->self += increment | decrement;
this->self += and_ | or_;
this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += float_ | integer | identifier | litteral;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
typedef lex::token_def<double> FloatToken;
StringToken identifier, litteral;
IntegerToken integer;
FloatToken float_;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken increment, decrement;
StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
StringToken and_, or_;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma;
ConsumedToken assign, swap;
//Keywords
ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_, include;
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
//Typedef for the parsers
typedef lexer::lexer_type::iterator_type Iterator;
typedef lexer::SpiritLexer<lexer::lexer_type> Lexer;
} //end of lexer
} //end of eddic
#endif
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include "boost_cfg.hpp"
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace lexer {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
/*!
* \class SimpleLexer
* \brief The EDDI lexer.
*
* This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's
* used by the parser to parse a source file.
*/
template<typename L>
class SpiritLexer : public lex::lexer<L> {
public:
SpiritLexer() {
/* keywords */
for_ = "for";
while_ = "while";
do_ = "do";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
const_ = "const";
include = "include";
struct_ = "struct";
null = "null";
this_ = "this";
new_ = "new";
delete_ = "delete";
switch_ = "switch";
case_ = "case";
default_ = "default";
type = "type";
template_ = "template";
/* Raw values */
identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
float_ = "[0-9]+\".\"[0-9]+";
integer = "[0-9]+";
string_literal = "\\\"[^\\\"]*\\\"";
char_literal = "'[a-zA-Z0-9]'";
/* Constructs */
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
dot = '.';
tilde = '~';
/* Ternary operator */
double_dot = ':';
question_mark = '?';
/* Assignment operators */
swap = "<=>";
assign = '=';
/* compound assignment operators */
compound_add = "\\+=";
compound_sub = "-=";
compound_mul = "\\*=";
compound_div = "\\/=";
compound_mod = "%=";
/* Math operators */
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
/* Suffix and prefix math operators */
increment = "\\+\\+";
decrement = "--";
/* Logical operators */
and_ = "\\&\\&";
or_ = "\\|\\|";
/* Relational operators */
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += assign | swap;
this->self += comma | stop | dot;
this->self += double_dot | question_mark | tilde;
this->self += addition | subtraction | multiplication | division | modulo;
this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod;
this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include | struct_ | null | this_;
this->self += template_ | type;
this->self += increment | decrement;
this->self += new_ | delete_;
this->self += and_ | or_;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += case_ | switch_ | default_;
this->self += float_ | integer | identifier | string_literal | char_literal;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
typedef lex::token_def<double> FloatToken;
StringToken identifier, string_literal, char_literal;
IntegerToken integer;
FloatToken float_;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken increment, decrement;
StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
StringToken and_, or_;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma, dot;
ConsumedToken assign, swap;
ConsumedToken question_mark, double_dot, tilde;
//Keywords
ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_, include;
ConsumedToken struct_, null;
ConsumedToken case_, switch_, default_;
ConsumedToken new_, delete_;
ConsumedToken template_, type;
StringToken this_; //As this is handled like a variable, we need its value
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
//Typedef for the parsers
typedef lexer::lexer_type::iterator_type Iterator;
typedef lexer::SpiritLexer<lexer::lexer_type> Lexer;
} //end of lexer
} //end of eddic
#endif
<commit_msg>Add support for the not operator<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include "boost_cfg.hpp"
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace lexer {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
/*!
* \class SimpleLexer
* \brief The EDDI lexer.
*
* This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's
* used by the parser to parse a source file.
*/
template<typename L>
class SpiritLexer : public lex::lexer<L> {
public:
SpiritLexer() {
/* keywords */
for_ = "for";
while_ = "while";
do_ = "do";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
const_ = "const";
include = "include";
struct_ = "struct";
null = "null";
this_ = "this";
new_ = "new";
delete_ = "delete";
switch_ = "switch";
case_ = "case";
default_ = "default";
type = "type";
template_ = "template";
/* Raw values */
identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
float_ = "[0-9]+\".\"[0-9]+";
integer = "[0-9]+";
string_literal = "\\\"[^\\\"]*\\\"";
char_literal = "'[a-zA-Z0-9]'";
/* Constructs */
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
dot = '.';
tilde = '~';
/* Ternary operator */
double_dot = ':';
question_mark = '?';
/* Assignment operators */
swap = "<=>";
assign = '=';
/* compound assignment operators */
compound_add = "\\+=";
compound_sub = "-=";
compound_mul = "\\*=";
compound_div = "\\/=";
compound_mod = "%=";
/* Binary operators */
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
/* Unary operators */
not_ = '!';
/* Suffix and prefix math operators */
increment = "\\+\\+";
decrement = "--";
/* Logical operators */
and_ = "\\&\\&";
or_ = "\\|\\|";
/* Relational operators */
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += assign | swap;
this->self += comma | stop | dot;
this->self += double_dot | question_mark | tilde;
this->self += addition | subtraction | multiplication | division | modulo;
this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod;
this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include | struct_ | null | this_;
this->self += template_ | type;
this->self += increment | decrement;
this->self += new_ | delete_;
this->self += and_ | or_;
this->self += equals | not_equals | greater_equals | less_equals | greater | less | not_;
this->self += case_ | switch_ | default_;
this->self += float_ | integer | identifier | string_literal | char_literal;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
typedef lex::token_def<double> FloatToken;
StringToken identifier, string_literal, char_literal;
IntegerToken integer;
FloatToken float_;
CharToken addition, subtraction, multiplication, division, modulo, not_;
StringToken increment, decrement;
StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
StringToken and_, or_;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma, dot;
ConsumedToken assign, swap;
ConsumedToken question_mark, double_dot, tilde;
//Keywords
ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_, include;
ConsumedToken struct_, null;
ConsumedToken case_, switch_, default_;
ConsumedToken new_, delete_;
ConsumedToken template_, type;
StringToken this_; //As this is handled like a variable, we need its value
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
//Typedef for the parsers
typedef lexer::lexer_type::iterator_type Iterator;
typedef lexer::SpiritLexer<lexer::lexer_type> Lexer;
} //end of lexer
} //end of eddic
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
//#define TORRENT_BUFFER_DEBUG
#include "libtorrent/invariant_check.hpp"
#include <memory>
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
assert(begin + index < end);
return begin[index];
}
int left() const { assert(end > begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
assert(begin + index < end);
return begin[index];
}
int left() const { assert(end > begin); return end - begin; }
char const* begin;
char const* end;
};
typedef std::pair<const_interval, const_interval> interval_type;
buffer(std::size_t n = 0);
~buffer();
interval allocate(std::size_t n);
void insert(char const* first, char const* last);
void erase(std::size_t n);
std::size_t size() const;
std::size_t capacity() const;
void reserve(std::size_t n);
interval_type data() const;
bool empty() const;
std::size_t space_left() const;
char const* raw_data() const
{
return m_first;
}
#ifndef NDEBUG
void check_invariant() const;
#endif
private:
char* m_first;
char* m_last;
char* m_write_cursor;
char* m_read_cursor;
char* m_read_end;
bool m_empty;
#ifdef TORRENT_BUFFER_DEBUG
mutable std::vector<char> m_debug;
mutable int m_pending_copy;
#endif
};
inline buffer::buffer(std::size_t n)
: m_first((char*)::operator new(n))
, m_last(m_first + n)
, m_write_cursor(m_first)
, m_read_cursor(m_first)
, m_read_end(m_last)
, m_empty(true)
{
#ifdef TORRENT_BUFFER_DEBUG
m_pending_copy = 0;
#endif
}
inline buffer::~buffer()
{
::operator delete (m_first);
}
inline buffer::interval buffer::allocate(std::size_t n)
{
assert(m_read_cursor <= m_read_end || m_empty);
INVARIANT_CHECK;
#ifdef TORRENT_BUFFER_DEBUG
if (m_pending_copy)
{
std::copy(m_write_cursor - m_pending_copy, m_write_cursor
, m_debug.end() - m_pending_copy);
m_pending_copy = 0;
}
m_debug.resize(m_debug.size() + n);
m_pending_copy = n;
#endif
if (m_read_cursor < m_write_cursor || m_empty)
{
// ..R***W..
if (m_last - m_write_cursor >= (std::ptrdiff_t)n)
{
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
m_read_end = m_write_cursor;
assert(m_read_cursor <= m_read_end);
if (n) m_empty = false;
return ret;
}
if (m_read_cursor - m_first >= (std::ptrdiff_t)n)
{
m_read_end = m_write_cursor;
interval ret(m_first, m_first + n);
m_write_cursor = m_first + n;
assert(m_read_cursor <= m_read_end);
if (n) m_empty = false;
return ret;
}
reserve(capacity() + n - (m_last - m_write_cursor));
assert(m_last - m_write_cursor >= (std::ptrdiff_t)n);
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
m_read_end = m_write_cursor;
if (n) m_empty = false;
assert(m_read_cursor <= m_read_end);
return ret;
}
//**W...R**
if (m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n)
{
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
if (n) m_empty = false;
return ret;
}
reserve(capacity() + n - (m_read_cursor - m_write_cursor));
assert(m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n);
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
if (n) m_empty = false;
return ret;
}
inline void buffer::insert(char const* first, char const* last)
{
INVARIANT_CHECK;
std::size_t n = last - first;
#ifdef TORRENT_BUFFER_DEBUG
if (m_pending_copy)
{
std::copy(m_write_cursor - m_pending_copy, m_write_cursor
, m_debug.end() - m_pending_copy);
m_pending_copy = 0;
}
m_debug.insert(m_debug.end(), first, last);
#endif
if (space_left() < n)
{
reserve(capacity() + n);
}
m_empty = false;
char const* end = (m_last - m_write_cursor) < (std::ptrdiff_t)n ?
m_last : m_write_cursor + n;
std::size_t copied = end - m_write_cursor;
std::memcpy(m_write_cursor, first, copied);
m_write_cursor += copied;
if (m_write_cursor > m_read_end) m_read_end = m_write_cursor;
first += copied;
n -= copied;
if (n == 0) return;
assert(m_write_cursor == m_last);
m_write_cursor = m_first;
memcpy(m_write_cursor, first, n);
m_write_cursor += n;
}
inline void buffer::erase(std::size_t n)
{
INVARIANT_CHECK;
if (n == 0) return;
assert(!m_empty);
#ifndef NDEBUG
int prev_size = size();
#endif
assert(m_read_cursor <= m_read_end);
m_read_cursor += n;
if (m_read_cursor > m_read_end)
{
m_read_cursor = m_first + (m_read_cursor - m_read_end);
assert(m_read_cursor <= m_write_cursor);
}
m_empty = m_read_cursor == m_write_cursor;
assert(prev_size - n == size());
#ifdef TORRENT_BUFFER_DEBUG
m_debug.erase(m_debug.begin(), m_debug.begin() + n);
#endif
}
inline std::size_t buffer::size() const
{
// ...R***W.
if (m_read_cursor < m_write_cursor)
{
return m_write_cursor - m_read_cursor;
}
// ***W..R*
else
{
if (m_empty) return 0;
return (m_write_cursor - m_first) + (m_read_end - m_read_cursor);
}
}
inline std::size_t buffer::capacity() const
{
return m_last - m_first;
}
inline void buffer::reserve(std::size_t size)
{
std::size_t n = (std::size_t)(capacity() * 1.f);
if (n < size) n = size;
char* buf = (char*)::operator new(n);
char* old = m_first;
if (m_read_cursor < m_write_cursor)
{
// ...R***W.<>.
std::memcpy(
buf + (m_read_cursor - m_first)
, m_read_cursor
, m_write_cursor - m_read_cursor
);
m_write_cursor = buf + (m_write_cursor - m_first);
m_read_cursor = buf + (m_read_cursor - m_first);
m_read_end = m_write_cursor;
m_first = buf;
m_last = buf + n;
}
else
{
// **W..<>.R**
std::size_t skip = n - (m_last - m_first);
std::memcpy(buf, m_first, m_write_cursor - m_first);
std::memcpy(
buf + (m_read_cursor - m_first) + skip
, m_read_cursor
, m_last - m_read_cursor
);
m_write_cursor = buf + (m_write_cursor - m_first);
if (!m_empty)
{
m_read_cursor = buf + (m_read_cursor - m_first) + skip;
m_read_end = buf + (m_read_end - m_first) + skip;
}
else
{
m_read_cursor = m_write_cursor;
m_read_end = m_write_cursor;
}
m_first = buf;
m_last = buf + n;
}
::operator delete (old);
}
#ifndef NDEBUG
inline void buffer::check_invariant() const
{
assert(m_read_end >= m_read_cursor);
assert(m_last >= m_read_cursor);
assert(m_last >= m_write_cursor);
assert(m_last >= m_first);
assert(m_first <= m_read_cursor);
assert(m_first <= m_write_cursor);
#ifdef TORRENT_BUFFER_DEBUG
int a = m_debug.size();
int b = size();
(void)a;
(void)b;
assert(m_debug.size() == size());
#endif
}
#endif
inline buffer::interval_type buffer::data() const
{
INVARIANT_CHECK;
#ifdef TORRENT_BUFFER_DEBUG
if (m_pending_copy)
{
std::copy(m_write_cursor - m_pending_copy, m_write_cursor
, m_debug.end() - m_pending_copy);
m_pending_copy = 0;
}
#endif
// ...R***W.
if (m_read_cursor < m_write_cursor)
{
#ifdef TORRENT_BUFFER_DEBUG
assert(m_debug.size() == size());
assert(std::equal(m_debug.begin(), m_debug.end(), m_read_cursor));
#endif
return interval_type(
const_interval(m_read_cursor, m_write_cursor)
, const_interval(m_last, m_last)
);
}
// **W...R**
else
{
if (m_read_cursor == m_read_end)
{
#ifdef TORRENT_BUFFER_DEBUG
assert(m_debug.size() == size());
assert(std::equal(m_debug.begin(), m_debug.end(), m_first));
#endif
return interval_type(
const_interval(m_first, m_write_cursor)
, const_interval(m_last, m_last));
}
#ifdef TORRENT_BUFFER_DEBUG
assert(m_debug.size() == size());
assert(std::equal(m_debug.begin(), m_debug.begin() + (m_read_end
- m_read_cursor), m_read_cursor));
assert(std::equal(m_debug.begin() + (m_read_end - m_read_cursor), m_debug.end()
, m_first));
#endif
assert(m_read_cursor <= m_read_end || m_empty);
return interval_type(
const_interval(m_read_cursor, m_read_end)
, const_interval(m_first, m_write_cursor)
);
}
}
inline bool buffer::empty() const
{
return m_empty;
}
inline std::size_t buffer::space_left() const
{
if (m_empty) return m_last - m_first;
// ...R***W.
if (m_read_cursor < m_write_cursor)
{
return (m_last - m_write_cursor) + (m_read_cursor - m_first);
}
// ***W..R*
else
{
return m_read_cursor - m_write_cursor;
}
}
}
#endif // LIBTORRENT_BUFFER_HPP
<commit_msg>fixed incorrect assert<commit_after>/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
//#define TORRENT_BUFFER_DEBUG
#include "libtorrent/invariant_check.hpp"
#include <memory>
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
assert(begin + index < end);
return begin[index];
}
int left() const { assert(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
assert(begin + index < end);
return begin[index];
}
int left() const { assert(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
typedef std::pair<const_interval, const_interval> interval_type;
buffer(std::size_t n = 0);
~buffer();
interval allocate(std::size_t n);
void insert(char const* first, char const* last);
void erase(std::size_t n);
std::size_t size() const;
std::size_t capacity() const;
void reserve(std::size_t n);
interval_type data() const;
bool empty() const;
std::size_t space_left() const;
char const* raw_data() const
{
return m_first;
}
#ifndef NDEBUG
void check_invariant() const;
#endif
private:
char* m_first;
char* m_last;
char* m_write_cursor;
char* m_read_cursor;
char* m_read_end;
bool m_empty;
#ifdef TORRENT_BUFFER_DEBUG
mutable std::vector<char> m_debug;
mutable int m_pending_copy;
#endif
};
inline buffer::buffer(std::size_t n)
: m_first((char*)::operator new(n))
, m_last(m_first + n)
, m_write_cursor(m_first)
, m_read_cursor(m_first)
, m_read_end(m_last)
, m_empty(true)
{
#ifdef TORRENT_BUFFER_DEBUG
m_pending_copy = 0;
#endif
}
inline buffer::~buffer()
{
::operator delete (m_first);
}
inline buffer::interval buffer::allocate(std::size_t n)
{
assert(m_read_cursor <= m_read_end || m_empty);
INVARIANT_CHECK;
#ifdef TORRENT_BUFFER_DEBUG
if (m_pending_copy)
{
std::copy(m_write_cursor - m_pending_copy, m_write_cursor
, m_debug.end() - m_pending_copy);
m_pending_copy = 0;
}
m_debug.resize(m_debug.size() + n);
m_pending_copy = n;
#endif
if (m_read_cursor < m_write_cursor || m_empty)
{
// ..R***W..
if (m_last - m_write_cursor >= (std::ptrdiff_t)n)
{
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
m_read_end = m_write_cursor;
assert(m_read_cursor <= m_read_end);
if (n) m_empty = false;
return ret;
}
if (m_read_cursor - m_first >= (std::ptrdiff_t)n)
{
m_read_end = m_write_cursor;
interval ret(m_first, m_first + n);
m_write_cursor = m_first + n;
assert(m_read_cursor <= m_read_end);
if (n) m_empty = false;
return ret;
}
reserve(capacity() + n - (m_last - m_write_cursor));
assert(m_last - m_write_cursor >= (std::ptrdiff_t)n);
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
m_read_end = m_write_cursor;
if (n) m_empty = false;
assert(m_read_cursor <= m_read_end);
return ret;
}
//**W...R**
if (m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n)
{
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
if (n) m_empty = false;
return ret;
}
reserve(capacity() + n - (m_read_cursor - m_write_cursor));
assert(m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n);
interval ret(m_write_cursor, m_write_cursor + n);
m_write_cursor += n;
if (n) m_empty = false;
return ret;
}
inline void buffer::insert(char const* first, char const* last)
{
INVARIANT_CHECK;
std::size_t n = last - first;
#ifdef TORRENT_BUFFER_DEBUG
if (m_pending_copy)
{
std::copy(m_write_cursor - m_pending_copy, m_write_cursor
, m_debug.end() - m_pending_copy);
m_pending_copy = 0;
}
m_debug.insert(m_debug.end(), first, last);
#endif
if (space_left() < n)
{
reserve(capacity() + n);
}
m_empty = false;
char const* end = (m_last - m_write_cursor) < (std::ptrdiff_t)n ?
m_last : m_write_cursor + n;
std::size_t copied = end - m_write_cursor;
std::memcpy(m_write_cursor, first, copied);
m_write_cursor += copied;
if (m_write_cursor > m_read_end) m_read_end = m_write_cursor;
first += copied;
n -= copied;
if (n == 0) return;
assert(m_write_cursor == m_last);
m_write_cursor = m_first;
memcpy(m_write_cursor, first, n);
m_write_cursor += n;
}
inline void buffer::erase(std::size_t n)
{
INVARIANT_CHECK;
if (n == 0) return;
assert(!m_empty);
#ifndef NDEBUG
int prev_size = size();
#endif
assert(m_read_cursor <= m_read_end);
m_read_cursor += n;
if (m_read_cursor > m_read_end)
{
m_read_cursor = m_first + (m_read_cursor - m_read_end);
assert(m_read_cursor <= m_write_cursor);
}
m_empty = m_read_cursor == m_write_cursor;
assert(prev_size - n == size());
#ifdef TORRENT_BUFFER_DEBUG
m_debug.erase(m_debug.begin(), m_debug.begin() + n);
#endif
}
inline std::size_t buffer::size() const
{
// ...R***W.
if (m_read_cursor < m_write_cursor)
{
return m_write_cursor - m_read_cursor;
}
// ***W..R*
else
{
if (m_empty) return 0;
return (m_write_cursor - m_first) + (m_read_end - m_read_cursor);
}
}
inline std::size_t buffer::capacity() const
{
return m_last - m_first;
}
inline void buffer::reserve(std::size_t size)
{
std::size_t n = (std::size_t)(capacity() * 1.f);
if (n < size) n = size;
char* buf = (char*)::operator new(n);
char* old = m_first;
if (m_read_cursor < m_write_cursor)
{
// ...R***W.<>.
std::memcpy(
buf + (m_read_cursor - m_first)
, m_read_cursor
, m_write_cursor - m_read_cursor
);
m_write_cursor = buf + (m_write_cursor - m_first);
m_read_cursor = buf + (m_read_cursor - m_first);
m_read_end = m_write_cursor;
m_first = buf;
m_last = buf + n;
}
else
{
// **W..<>.R**
std::size_t skip = n - (m_last - m_first);
std::memcpy(buf, m_first, m_write_cursor - m_first);
std::memcpy(
buf + (m_read_cursor - m_first) + skip
, m_read_cursor
, m_last - m_read_cursor
);
m_write_cursor = buf + (m_write_cursor - m_first);
if (!m_empty)
{
m_read_cursor = buf + (m_read_cursor - m_first) + skip;
m_read_end = buf + (m_read_end - m_first) + skip;
}
else
{
m_read_cursor = m_write_cursor;
m_read_end = m_write_cursor;
}
m_first = buf;
m_last = buf + n;
}
::operator delete (old);
}
#ifndef NDEBUG
inline void buffer::check_invariant() const
{
assert(m_read_end >= m_read_cursor);
assert(m_last >= m_read_cursor);
assert(m_last >= m_write_cursor);
assert(m_last >= m_first);
assert(m_first <= m_read_cursor);
assert(m_first <= m_write_cursor);
#ifdef TORRENT_BUFFER_DEBUG
int a = m_debug.size();
int b = size();
(void)a;
(void)b;
assert(m_debug.size() == size());
#endif
}
#endif
inline buffer::interval_type buffer::data() const
{
INVARIANT_CHECK;
#ifdef TORRENT_BUFFER_DEBUG
if (m_pending_copy)
{
std::copy(m_write_cursor - m_pending_copy, m_write_cursor
, m_debug.end() - m_pending_copy);
m_pending_copy = 0;
}
#endif
// ...R***W.
if (m_read_cursor < m_write_cursor)
{
#ifdef TORRENT_BUFFER_DEBUG
assert(m_debug.size() == size());
assert(std::equal(m_debug.begin(), m_debug.end(), m_read_cursor));
#endif
return interval_type(
const_interval(m_read_cursor, m_write_cursor)
, const_interval(m_last, m_last)
);
}
// **W...R**
else
{
if (m_read_cursor == m_read_end)
{
#ifdef TORRENT_BUFFER_DEBUG
assert(m_debug.size() == size());
assert(std::equal(m_debug.begin(), m_debug.end(), m_first));
#endif
return interval_type(
const_interval(m_first, m_write_cursor)
, const_interval(m_last, m_last));
}
#ifdef TORRENT_BUFFER_DEBUG
assert(m_debug.size() == size());
assert(std::equal(m_debug.begin(), m_debug.begin() + (m_read_end
- m_read_cursor), m_read_cursor));
assert(std::equal(m_debug.begin() + (m_read_end - m_read_cursor), m_debug.end()
, m_first));
#endif
assert(m_read_cursor <= m_read_end || m_empty);
return interval_type(
const_interval(m_read_cursor, m_read_end)
, const_interval(m_first, m_write_cursor)
);
}
}
inline bool buffer::empty() const
{
return m_empty;
}
inline std::size_t buffer::space_left() const
{
if (m_empty) return m_last - m_first;
// ...R***W.
if (m_read_cursor < m_write_cursor)
{
return (m_last - m_write_cursor) + (m_read_cursor - m_first);
}
// ***W..R*
else
{
return m_read_cursor - m_write_cursor;
}
}
}
#endif // LIBTORRENT_BUFFER_HPP
<|endoftext|> |
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
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 author 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
#if (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#define TORRENT_USE_I2P 1
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 0
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#defined TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#ifdef TORRENT_WINDOWS
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#if !defined TORRENT_WINDOWS && !defined __APPLE__
// libiconv presence, not implemented yet
#define TORRENT_USE_ICONV 1
#else
#define TORRENT_ISE_ICONV 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>updated config header to be slightly more structured<commit_after>/*
Copyright (c) 2005, Arvid Norberg
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 author 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#ifdef TORRENT_WINDOWS
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#if !defined TORRENT_WINDOWS && !defined __APPLE__ && !defined TORRENT_AMIGA
// libiconv presence, not implemented yet
#define TORRENT_USE_ICONV 1
#else
#define TORRENT_ISE_ICONV 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
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 author 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for _TRUNCATE (windows)
#include <stdarg.h>
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
// determine what timer implementation we can use
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>enable floating point API by default<commit_after>/*
Copyright (c) 2005, Arvid Norberg
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 author 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for _TRUNCATE (windows)
#include <stdarg.h>
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 0
#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
// determine what timer implementation we can use
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Hermann Kraus
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef METAWRITER_HPP
#define METAWRITER_HPP
// Mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/font_engine_freetype.hpp>
// Boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <boost/concept_check.hpp>
// STL
#include <set>
#include <string>
namespace mapnik {
struct placement;
/** Implementation of std::map that also returns const& for operator[]. */
class metawriter_property_map
{
public:
metawriter_property_map() {}
UnicodeString const& operator[](std::string const& key) const;
UnicodeString& operator[](std::string const& key) {return m_[key];}
private:
std::map<std::string, UnicodeString> m_;
UnicodeString not_found_;
};
/** All properties to be output by a metawriter. */
class metawriter_properties : public std::set<std::string>
{
public:
metawriter_properties(boost::optional<std::string> str);
metawriter_properties() {};
template <class InputIterator> metawriter_properties(
InputIterator first, InputIterator last) : std::set<std::string>(first, last) {};
std::string to_string() const;
};
/** Abstract baseclass for all metawriter classes. */
class metawriter
{
public:
typedef coord_transform2<CoordTransform,geometry_type> path_type;
metawriter(metawriter_properties dflt_properties) : dflt_properties_(dflt_properties) {}
virtual ~metawriter() {};
/** Output a rectangular area.
* \param box Area (in pixel coordinates)
* \param feature The feature being processed
* \param prj_trans Projection transformation
* \param t Cooridnate transformation
* \param properties List of properties to output
*/
virtual void add_box(box2d<double> const& box, Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_text(placement const& placement,
face_set_ptr face,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_polygon(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_line(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
/** Start processing.
* Write file header, init database connection, ...
*
* \param properties metawriter_property_map object with userdefined values.
* Useful for setting filename etc.
*/
virtual void start(metawriter_property_map const& properties)
{
boost::ignore_unused_variable_warning(properties);
};
/** Stop processing.
* Write file footer, close database connection, ...
*/
virtual void stop() {};
/** Set output size (pixels).
* All features that are completely outside this size are discarded.
*/
void set_size(int width, int height) { width_ = width; height_ = height; }
/** Set Map object's srs. */
virtual void set_map_srs(projection const& proj) = 0;
/** Return the list of default properties. */
metawriter_properties const& get_default_properties() const { return dflt_properties_;}
protected:
metawriter_properties dflt_properties_;
/** Output width (pixels). */
int width_;
/** Output height (pixels). */
int height_;
};
/** Shared pointer to metawriter object. */
typedef boost::shared_ptr<metawriter> metawriter_ptr;
/** Metawriter object + properties. */
typedef std::pair<metawriter_ptr, metawriter_properties> metawriter_with_properties;
}
#endif
<commit_msg>initialize all metawriter members<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 Hermann Kraus
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef METAWRITER_HPP
#define METAWRITER_HPP
// Mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/font_engine_freetype.hpp>
// Boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <boost/concept_check.hpp>
// STL
#include <set>
#include <string>
namespace mapnik {
struct placement;
/** Implementation of std::map that also returns const& for operator[]. */
class metawriter_property_map
{
public:
metawriter_property_map() {}
UnicodeString const& operator[](std::string const& key) const;
UnicodeString& operator[](std::string const& key) {return m_[key];}
private:
std::map<std::string, UnicodeString> m_;
UnicodeString not_found_;
};
/** All properties to be output by a metawriter. */
class metawriter_properties : public std::set<std::string>
{
public:
metawriter_properties(boost::optional<std::string> str);
metawriter_properties() {};
template <class InputIterator> metawriter_properties(
InputIterator first, InputIterator last) : std::set<std::string>(first, last) {};
std::string to_string() const;
};
/** Abstract baseclass for all metawriter classes. */
class metawriter
{
public:
typedef coord_transform2<CoordTransform,geometry_type> path_type;
metawriter(metawriter_properties dflt_properties) :
dflt_properties_(dflt_properties),
width_(0),
height_(0) {}
virtual ~metawriter() {};
/** Output a rectangular area.
* \param box Area (in pixel coordinates)
* \param feature The feature being processed
* \param prj_trans Projection transformation
* \param t Cooridnate transformation
* \param properties List of properties to output
*/
virtual void add_box(box2d<double> const& box, Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_text(placement const& placement,
face_set_ptr face,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_polygon(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_line(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
/** Start processing.
* Write file header, init database connection, ...
*
* \param properties metawriter_property_map object with userdefined values.
* Useful for setting filename etc.
*/
virtual void start(metawriter_property_map const& properties)
{
boost::ignore_unused_variable_warning(properties);
};
/** Stop processing.
* Write file footer, close database connection, ...
*/
virtual void stop() {};
/** Set output size (pixels).
* All features that are completely outside this size are discarded.
*/
void set_size(int width, int height) { width_ = width; height_ = height; }
/** Set Map object's srs. */
virtual void set_map_srs(projection const& proj) = 0;
/** Return the list of default properties. */
metawriter_properties const& get_default_properties() const { return dflt_properties_;}
protected:
metawriter_properties dflt_properties_;
/** Output width (pixels). */
int width_;
/** Output height (pixels). */
int height_;
};
/** Shared pointer to metawriter object. */
typedef boost::shared_ptr<metawriter> metawriter_ptr;
/** Metawriter object + properties. */
typedef std::pair<metawriter_ptr, metawriter_properties> metawriter_with_properties;
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VALUE_HASH_HPP
#define MAPNIK_VALUE_HASH_HPP
// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/value/types.hpp>
// stl
#include <functional>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <unicode/unistr.h>
#pragma GCC diagnostic pop
namespace mapnik {
namespace detail {
inline void hash_combine(std::size_t & seed, std::size_t val)
{
seed ^= val + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
struct value_hasher
{
std::size_t operator() (value_null val) const
{
return hash_value(val);
}
std::size_t operator() (value_unicode_string const& val) const
{
return static_cast<std::size_t>(val.hashCode());
}
std::size_t operator()(value_integer val) const
{
return static_cast<std::size_t>(val);
}
template <class T>
std::size_t operator()(T const& val) const
{
std::hash<T> hasher;
return hasher(val);
}
};
} // namespace detail
template <typename T>
std::size_t value_hash(T const& val)
{
std::size_t seed = 0;
detail::hash_combine(seed, util::apply_visitor(detail::value_hasher(), val));
detail::hash_combine(seed, val.which());
return seed;
}
} // namespace mapnik
#endif // MAPNIK_VALUE_HASH_HPP
<commit_msg>simplify hash calculation (we don't need combine with which(), using hash<T> is sufficient)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VALUE_HASH_HPP
#define MAPNIK_VALUE_HASH_HPP
// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/value/types.hpp>
// stl
#include <functional>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <unicode/unistr.h>
#pragma GCC diagnostic pop
namespace mapnik {
namespace detail {
inline void hash_combine(std::size_t & seed, std::size_t val)
{
seed ^= val + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
struct value_hasher
{
std::size_t operator() (value_null val) const
{
return hash_value(val);
}
std::size_t operator() (value_unicode_string const& val) const
{
return static_cast<std::size_t>(val.hashCode());
}
template <class T>
std::size_t operator()(T const& val) const
{
std::hash<T> hasher;
return hasher(val);
}
};
} // namespace detail
template <typename T>
std::size_t value_hash(T const& val)
{
return util::apply_visitor(detail::value_hasher(), val);
}
} // namespace mapnik
#endif // MAPNIK_VALUE_HASH_HPP
<|endoftext|> |
<commit_before>#ifndef UNESCAPE_COPY_ROW_HPP
#define UNESCAPE_COPY_ROW_HPP
#include <boost/noncopyable.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/include/for_each.hpp>
#include "types.hpp"
template <typename S, typename T>
struct unescape_copy_row
: public boost::noncopyable {
static const size_t s_num_columns = boost::fusion::result_of::size<T>::value;
explicit unescape_copy_row(S &source)
: m_source(source),
m_reorder(calculate_reorder(m_source.column_names())) {
}
~unescape_copy_row() {
}
size_t read(T &row) {
std::string line;
size_t num = m_source.read(line);
if (num > 0) {
unpack(line, row);
}
return num;
}
private:
void unpack(std::string &line, T &row) {
const size_t sz = s_num_columns;
std::vector<std::pair<char *, size_t> > columns, old_columns;
{
char *prev_ptr = &line[0];
char * const end_ptr = &line[line.size()];
char *ptr = &line[0];
for (; ptr != end_ptr; ++ptr) {
if (*ptr == '\t') {
*ptr = '\0';
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
prev_ptr = ptr + 1;
}
}
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
}
columns.reserve(sz);
for (size_t i = 0; i < sz; ++i) {
if (i >= m_reorder.size()) {
throw std::runtime_error("Index exceeds m_reorder.size(), this is a bug.");
}
size_t j = m_reorder[i];
if (j >= old_columns.size()) {
throw std::runtime_error("Reordered index exceeds old_columns.size(), this is a bug.");
}
columns.push_back(old_columns[j]);
}
if (columns.size() != sz) {
throw std::runtime_error((boost::format("Wrong number of columns: expecting %1%, got %2% in line `%3%'.")
% sz % columns.size() % line).str());
}
try {
set_values(row, columns);
} catch (const std::exception &e) {
throw std::runtime_error((boost::format("%1%: in line `%2%'.") % e.what() % line).str());
}
}
inline void set_values(T &t, std::vector<std::pair<char *, size_t> > &vs) {
boost::fusion::for_each(t, set_value(vs.begin()));
}
struct set_value {
explicit set_value(std::vector<std::pair<char *, size_t> >::iterator i) : itr(i) {}
void operator()(bool &b) const {
std::pair<char *, size_t> str = *itr++;
switch (str.first[0]) {
case 't':
b = true;
break;
case 'f':
b = false;
break;
default:
throw std::runtime_error((boost::format("Unrecognised value for bool: `%1%'") % str.first).str());
}
}
void operator()(int16_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int16_t(strtol(str.first, NULL, 10));
}
void operator()(int32_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int32_t(strtol(str.first, NULL, 10));
}
void operator()(int64_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int64_t(strtoll(str.first, NULL, 10));
}
void operator()(double &d) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
d = strtod(str.first, NULL);
}
void operator()(std::string &v) const {
std::pair<char *, size_t> str = *itr++;
v.assign(str.first, str.second);
}
void operator()(boost::posix_time::ptime &t) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
// 11111111112
// 12345678901234567890
// format is 2013-09-11 13:39:52.742365
if (str.second < 19) {
throw std::runtime_error((boost::format("Unexpected format for timestamp: `%1%'.")
% str.first).str());
}
int year = ((str.first[0] - '0') * 1000 +
(str.first[1] - '0') * 100 +
(str.first[2] - '0') * 10 +
(str.first[3] - '0'));
int month = ((str.first[5] - '0') * 10 + (str.first[6] - '0'));
int day = ((str.first[8] - '0') * 10 + (str.first[9] - '0'));
int hour = ((str.first[11] - '0') * 10 + (str.first[12] - '0'));
int min = ((str.first[14] - '0') * 10 + (str.first[15] - '0'));
int sec = ((str.first[17] - '0') * 10 + (str.first[19] - '0'));
t = boost::posix_time::ptime(boost::gregorian::date(year, month, day),
boost::posix_time::time_duration(hour, min, sec));
}
template <typename V>
void operator()(boost::optional<V> &o) const {
std::pair<char *, size_t> s = *itr;
if (strncmp(s.first, "\\N", s.second) == 0) {
o = boost::none;
++itr;
} else {
V v;
operator()(v);
o = v;
}
}
void operator()(user_status_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "pending", str.second) == 0) {
e = user_status_pending;
} else if (strncmp(str.first, "active", str.second) == 0) {
e = user_status_active;
} else if (strncmp(str.first, "confirmed", str.second) == 0) {
e = user_status_confirmed;
} else if (strncmp(str.first, "suspended", str.second) == 0) {
e = user_status_suspended;
} else if (strncmp(str.first, "deleted", str.second) == 0) {
e = user_status_deleted;
} else {
throw std::runtime_error((boost::format("Unrecognised value for user_status_enum: `%1%'.") % str.first).str());
}
}
void operator()(format_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "html", str.second) == 0) {
e = format_html;
} else if (strncmp(str.first, "markdown", str.second) == 0) {
e = format_markdown;
} else if (strncmp(str.first, "text", str.second) == 0) {
e = format_text;
} else {
throw std::runtime_error((boost::format("Unrecognised value for format_enum: `%1%'.") % str.first).str());
}
}
void operator()(nwr_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "Node", str.second) == 0) {
e = nwr_node;
} else if (strncmp(str.first, "Way", str.second) == 0) {
e = nwr_way;
} else if (strncmp(str.first, "Relation", str.second) == 0) {
e = nwr_relation;
} else {
throw std::runtime_error((boost::format("Unrecognised value for nwr_enum: `%1%'.") % str.first).str());
}
}
inline int hex2digit(char ch) const {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return int(ch - '0');
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
return 10 + int(ch - 'a');
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return 10 + int(ch - 'A');
default:
throw std::runtime_error("Invalid hex digit.");
}
}
inline int oct2digit(char ch) const {
if ((ch >= '0') && (ch <= '7')) {
return int(ch - '0');
} else {
throw std::runtime_error("Invalid octal digit.");
}
}
void unescape(std::pair<char *, size_t> &s) const {
const size_t end = s.second;
char *str = s.first;
size_t j = 0;
for (size_t i = 0; i < end; ++i) {
switch (str[i]) {
case '\\':
++i;
if (i < end) {
switch (str[i]) {
case 'b':
str[j] = '\b';
break;
case 'f':
str[j] = '\f';
break;
case 'n':
str[j] = '\n';
break;
case 'r':
str[j] = '\r';
break;
case 't':
str[j] = '\t';
break;
case 'v':
str[j] = '\v';
break;
case 'x':
i += 2;
if (i < end) {
} else {
str[j] = char(hex2digit(str[i-1]) * 16 + hex2digit(str[i]));
throw std::runtime_error("Unterminated hex escape sequence.");
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
i += 2;
if (i < end) {
str[j] = char(oct2digit(str[i-2]) * 64 + oct2digit(str[i-1]) * 8 + oct2digit(str[i]));
} else {
throw std::runtime_error("Unterminated octal escape sequence.");
}
break;
default:
// an unnecessary escape
str[j] = str[i];
}
} else {
throw std::runtime_error("Unterminated escape sequence.");
}
break;
default:
if (i != j) {
str[j] = str[i];
}
}
++j;
}
str[j] = '\0';
s.second = j;
}
mutable std::vector<std::pair<char *, size_t> >::iterator itr;
};
static std::vector<size_t> calculate_reorder(const std::vector<std::string> &names) {
std::vector<size_t> indexes;
const std::vector<std::string> &wanted_names = T::column_names();
const size_t num_columns = wanted_names.size();
indexes.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i) {
const std::string &wanted_name = wanted_names[i];
size_t j = i;
if (wanted_name != "*") {
std::vector<std::string>::const_iterator itr = std::find(names.begin(), names.end(), wanted_name);
if (itr == names.end()) {
std::ostringstream ostr;
ostr << "Unable to find wanted column name \"" << wanted_name << "\" in available names: ";
for (std::vector<std::string>::const_iterator jtr = names.begin(); jtr != names.end(); ++jtr) {
ostr << "\"" << *jtr << "\", ";
}
throw std::runtime_error(ostr.str());
}
j = std::distance(names.begin(), itr);
}
indexes.push_back(j);
}
return indexes;
}
S &m_source;
std::vector<size_t> m_reorder;
};
#endif /* UNESCAPE_COPY_ROW_HPP */
<commit_msg>Fix bug in time parsing.<commit_after>#ifndef UNESCAPE_COPY_ROW_HPP
#define UNESCAPE_COPY_ROW_HPP
#include <boost/noncopyable.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/include/for_each.hpp>
#include "types.hpp"
template <typename S, typename T>
struct unescape_copy_row
: public boost::noncopyable {
static const size_t s_num_columns = boost::fusion::result_of::size<T>::value;
explicit unescape_copy_row(S &source)
: m_source(source),
m_reorder(calculate_reorder(m_source.column_names())) {
}
~unescape_copy_row() {
}
size_t read(T &row) {
std::string line;
size_t num = m_source.read(line);
if (num > 0) {
unpack(line, row);
}
return num;
}
private:
void unpack(std::string &line, T &row) {
const size_t sz = s_num_columns;
std::vector<std::pair<char *, size_t> > columns, old_columns;
{
char *prev_ptr = &line[0];
char * const end_ptr = &line[line.size()];
char *ptr = &line[0];
for (; ptr != end_ptr; ++ptr) {
if (*ptr == '\t') {
*ptr = '\0';
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
prev_ptr = ptr + 1;
}
}
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
}
columns.reserve(sz);
for (size_t i = 0; i < sz; ++i) {
if (i >= m_reorder.size()) {
throw std::runtime_error("Index exceeds m_reorder.size(), this is a bug.");
}
size_t j = m_reorder[i];
if (j >= old_columns.size()) {
throw std::runtime_error("Reordered index exceeds old_columns.size(), this is a bug.");
}
columns.push_back(old_columns[j]);
}
if (columns.size() != sz) {
throw std::runtime_error((boost::format("Wrong number of columns: expecting %1%, got %2% in line `%3%'.")
% sz % columns.size() % line).str());
}
try {
set_values(row, columns);
} catch (const std::exception &e) {
throw std::runtime_error((boost::format("%1%: in line `%2%'.") % e.what() % line).str());
}
}
inline void set_values(T &t, std::vector<std::pair<char *, size_t> > &vs) {
boost::fusion::for_each(t, set_value(vs.begin()));
}
struct set_value {
explicit set_value(std::vector<std::pair<char *, size_t> >::iterator i) : itr(i) {}
void operator()(bool &b) const {
std::pair<char *, size_t> str = *itr++;
switch (str.first[0]) {
case 't':
b = true;
break;
case 'f':
b = false;
break;
default:
throw std::runtime_error((boost::format("Unrecognised value for bool: `%1%'") % str.first).str());
}
}
void operator()(int16_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int16_t(strtol(str.first, NULL, 10));
}
void operator()(int32_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int32_t(strtol(str.first, NULL, 10));
}
void operator()(int64_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int64_t(strtoll(str.first, NULL, 10));
}
void operator()(double &d) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
d = strtod(str.first, NULL);
}
void operator()(std::string &v) const {
std::pair<char *, size_t> str = *itr++;
v.assign(str.first, str.second);
}
void operator()(boost::posix_time::ptime &t) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
// 11111111112
// 12345678901234567890
// format is 2013-09-11 13:39:52.742365
if (str.second < 19) {
throw std::runtime_error((boost::format("Unexpected format for timestamp: `%1%'.")
% str.first).str());
}
int year = ((str.first[0] - '0') * 1000 +
(str.first[1] - '0') * 100 +
(str.first[2] - '0') * 10 +
(str.first[3] - '0'));
int month = ((str.first[5] - '0') * 10 + (str.first[6] - '0'));
int day = ((str.first[8] - '0') * 10 + (str.first[9] - '0'));
int hour = ((str.first[11] - '0') * 10 + (str.first[12] - '0'));
int min = ((str.first[14] - '0') * 10 + (str.first[15] - '0'));
int sec = ((str.first[17] - '0') * 10 + (str.first[18] - '0'));
t = boost::posix_time::ptime(boost::gregorian::date(year, month, day),
boost::posix_time::time_duration(hour, min, sec));
}
template <typename V>
void operator()(boost::optional<V> &o) const {
std::pair<char *, size_t> s = *itr;
if (strncmp(s.first, "\\N", s.second) == 0) {
o = boost::none;
++itr;
} else {
V v;
operator()(v);
o = v;
}
}
void operator()(user_status_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "pending", str.second) == 0) {
e = user_status_pending;
} else if (strncmp(str.first, "active", str.second) == 0) {
e = user_status_active;
} else if (strncmp(str.first, "confirmed", str.second) == 0) {
e = user_status_confirmed;
} else if (strncmp(str.first, "suspended", str.second) == 0) {
e = user_status_suspended;
} else if (strncmp(str.first, "deleted", str.second) == 0) {
e = user_status_deleted;
} else {
throw std::runtime_error((boost::format("Unrecognised value for user_status_enum: `%1%'.") % str.first).str());
}
}
void operator()(format_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "html", str.second) == 0) {
e = format_html;
} else if (strncmp(str.first, "markdown", str.second) == 0) {
e = format_markdown;
} else if (strncmp(str.first, "text", str.second) == 0) {
e = format_text;
} else {
throw std::runtime_error((boost::format("Unrecognised value for format_enum: `%1%'.") % str.first).str());
}
}
void operator()(nwr_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "Node", str.second) == 0) {
e = nwr_node;
} else if (strncmp(str.first, "Way", str.second) == 0) {
e = nwr_way;
} else if (strncmp(str.first, "Relation", str.second) == 0) {
e = nwr_relation;
} else {
throw std::runtime_error((boost::format("Unrecognised value for nwr_enum: `%1%'.") % str.first).str());
}
}
inline int hex2digit(char ch) const {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return int(ch - '0');
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
return 10 + int(ch - 'a');
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return 10 + int(ch - 'A');
default:
throw std::runtime_error("Invalid hex digit.");
}
}
inline int oct2digit(char ch) const {
if ((ch >= '0') && (ch <= '7')) {
return int(ch - '0');
} else {
throw std::runtime_error("Invalid octal digit.");
}
}
void unescape(std::pair<char *, size_t> &s) const {
const size_t end = s.second;
char *str = s.first;
size_t j = 0;
for (size_t i = 0; i < end; ++i) {
switch (str[i]) {
case '\\':
++i;
if (i < end) {
switch (str[i]) {
case 'b':
str[j] = '\b';
break;
case 'f':
str[j] = '\f';
break;
case 'n':
str[j] = '\n';
break;
case 'r':
str[j] = '\r';
break;
case 't':
str[j] = '\t';
break;
case 'v':
str[j] = '\v';
break;
case 'x':
i += 2;
if (i < end) {
} else {
str[j] = char(hex2digit(str[i-1]) * 16 + hex2digit(str[i]));
throw std::runtime_error("Unterminated hex escape sequence.");
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
i += 2;
if (i < end) {
str[j] = char(oct2digit(str[i-2]) * 64 + oct2digit(str[i-1]) * 8 + oct2digit(str[i]));
} else {
throw std::runtime_error("Unterminated octal escape sequence.");
}
break;
default:
// an unnecessary escape
str[j] = str[i];
}
} else {
throw std::runtime_error("Unterminated escape sequence.");
}
break;
default:
if (i != j) {
str[j] = str[i];
}
}
++j;
}
str[j] = '\0';
s.second = j;
}
mutable std::vector<std::pair<char *, size_t> >::iterator itr;
};
static std::vector<size_t> calculate_reorder(const std::vector<std::string> &names) {
std::vector<size_t> indexes;
const std::vector<std::string> &wanted_names = T::column_names();
const size_t num_columns = wanted_names.size();
indexes.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i) {
const std::string &wanted_name = wanted_names[i];
size_t j = i;
if (wanted_name != "*") {
std::vector<std::string>::const_iterator itr = std::find(names.begin(), names.end(), wanted_name);
if (itr == names.end()) {
std::ostringstream ostr;
ostr << "Unable to find wanted column name \"" << wanted_name << "\" in available names: ";
for (std::vector<std::string>::const_iterator jtr = names.begin(); jtr != names.end(); ++jtr) {
ostr << "\"" << *jtr << "\", ";
}
throw std::runtime_error(ostr.str());
}
j = std::distance(names.begin(), itr);
}
indexes.push_back(j);
}
return indexes;
}
S &m_source;
std::vector<size_t> m_reorder;
};
#endif /* UNESCAPE_COPY_ROW_HPP */
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file robust_mutex.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Robust mutex that can be shared between processes.
//----------------------------------------------------------------------------
// Created: 2009-11-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_ROBUST_MUTEX_HPP_
#define _UTXX_ROBUST_MUTEX_HPP_
#include <mutex>
#include <functional>
#include <utxx/error.hpp>
namespace utxx {
class robust_mutex {
public:
using self_type = robust_mutex;
using make_consistent_functor = std::function<int (robust_mutex&)>;
using native_handle_type = pthread_mutex_t*;
using scoped_lock = std::lock_guard<robust_mutex>;
using scoped_try_lock = std::unique_lock<robust_mutex>;
make_consistent_functor on_make_consistent;
explicit robust_mutex(bool a_destroy_on_exit = false)
: m(NULL), m_destroy(a_destroy_on_exit)
{}
robust_mutex(pthread_mutex_t& a_mutex,
bool a_init = false, bool a_destroy_on_exit = false)
{
if (a_init)
init(a_mutex);
else
set(a_mutex);
m_destroy = a_destroy_on_exit;
}
void set(pthread_mutex_t& a_mutex) { m = &a_mutex; }
void init(pthread_mutex_t& a_mutex, pthread_mutexattr_t* a_attr=NULL) {
m = &a_mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_t* mutex_attr = a_attr ? a_attr : &attr;
if (pthread_mutexattr_setpshared(mutex_attr, PTHREAD_PROCESS_SHARED) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutexattr_setrobust_np(mutex_attr, PTHREAD_MUTEX_ROBUST_NP) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutexattr_setprotocol(mutex_attr, PTHREAD_PRIO_INHERIT) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutex_init(m, mutex_attr) < 0)
UTXX_THROW_IO_ERROR(errno);
}
~robust_mutex() {
if (!m_destroy) return;
destroy();
}
void lock() {
assert(m);
int res;
while (1) {
res = pthread_mutex_lock(m);
switch (res) {
case 0:
return;
case EINTR:
continue;
case EOWNERDEAD:
res = on_make_consistent
? on_make_consistent(*this)
: make_consistent();
if (res)
UTXX_THROW_IO_ERROR(res);
return;
default:
// If ENOTRECOVERABLE - mutex is not recoverable, must be destroyed.
UTXX_THROW_IO_ERROR(res);
return;
}
}
}
void unlock() {
assert(m);
int ret;
do { ret = pthread_mutex_unlock(m); } while (ret == EINTR);
}
bool try_lock() {
assert(m);
int res;
do { res = pthread_mutex_trylock(m); } while (res == EINTR);
if ( res && (res!=EBUSY) )
UTXX_THROW_IO_ERROR(res);
return !res;
}
int make_consistent() {
assert(m);
return pthread_mutex_consistent_np(m);
}
void destroy() {
if (!m) return;
int ret;
do { ret = pthread_mutex_destroy(m); } while (ret == EINTR);
m = NULL;
}
native_handle_type native_handle() { return m; }
private:
pthread_mutex_t* m;
bool m_destroy;
robust_mutex(const robust_mutex&);
};
} // namespace utxx
#endif // _UTXX_ROBUST_MUTEX_HPP_
<commit_msg>Update robust_mutex.hpp<commit_after>//----------------------------------------------------------------------------
/// \file robust_mutex.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Robust mutex that can be shared between processes.
//----------------------------------------------------------------------------
// Created: 2009-11-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#pragma once
#include <mutex>
#include <functional>
#include <utxx/error.hpp>
namespace utxx {
class robust_mutex {
public:
using self_type = robust_mutex;
using make_consistent_functor = std::function<int (robust_mutex&)>;
using native_handle_type = pthread_mutex_t*;
using scoped_lock = std::lock_guard<robust_mutex>;
using scoped_try_lock = std::unique_lock<robust_mutex>;
make_consistent_functor on_make_consistent;
explicit robust_mutex(bool a_destroy_on_exit = false)
: m(NULL), m_destroy(a_destroy_on_exit)
{}
robust_mutex(pthread_mutex_t& a_mutex,
bool a_init = false, bool a_destroy_on_exit = false)
{
if (a_init)
init(a_mutex);
else
set(a_mutex);
m_destroy = a_destroy_on_exit;
}
void set(pthread_mutex_t& a_mutex) { m = &a_mutex; }
void init(pthread_mutex_t& a_mutex, pthread_mutexattr_t* a_attr=NULL) {
m = &a_mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_t* mutex_attr = a_attr ? a_attr : &attr;
if (pthread_mutexattr_setpshared(mutex_attr, PTHREAD_PROCESS_SHARED) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutexattr_setrobust_np(mutex_attr, PTHREAD_MUTEX_ROBUST_NP) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutexattr_setprotocol(mutex_attr, PTHREAD_PRIO_INHERIT) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutex_init(m, mutex_attr) < 0)
UTXX_THROW_IO_ERROR(errno);
}
~robust_mutex() {
if (!m_destroy) return;
destroy();
}
void lock() {
assert(m);
int res;
while (1) {
res = pthread_mutex_lock(m);
switch (res) {
case 0:
return;
case EINTR:
continue;
case EOWNERDEAD:
res = on_make_consistent
? on_make_consistent(*this)
: make_consistent();
if (res)
UTXX_THROW_IO_ERROR(res);
return;
default:
// If ENOTRECOVERABLE - mutex is not recoverable, must be destroyed.
UTXX_THROW_IO_ERROR(res);
return;
}
}
}
void unlock() {
assert(m);
int ret;
do { ret = pthread_mutex_unlock(m); } while (ret == EINTR);
}
bool try_lock() {
assert(m);
int res;
do { res = pthread_mutex_trylock(m); } while (res == EINTR);
if ( res && (res!=EBUSY) )
UTXX_THROW_IO_ERROR(res);
return !res;
}
int make_consistent() {
assert(m);
return pthread_mutex_consistent_np(m);
}
void destroy() {
if (!m) return;
int ret;
do { ret = pthread_mutex_destroy(m); } while (ret == EINTR);
m = NULL;
}
native_handle_type native_handle() { return m; }
private:
pthread_mutex_t* m;
bool m_destroy;
robust_mutex(const robust_mutex&);
};
} // namespace utxx
<|endoftext|> |
<commit_before>#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1InputManager.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1FadeToBlack.h"
#include "j1PathFinding.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
#include "j1Scene.h"
#include "j1SceneIntro.h"
#include "Soldier.h"
#include "j1Player.h"
#include "j1DynamicObjects.h"
#include "j1FileSystem.h"
#include "j1Collision.h"
#include "j1AnimationManager.h"
j1SceneIntro::j1SceneIntro() : j1Module()
{
name = "scene";
}
// Destructor
j1SceneIntro::~j1SceneIntro()
{}
// Called before render is available
bool j1SceneIntro::Awake()
{
LOG("Loading SceneIntro");
bool ret = true;
return ret;
}
// Called before the first frame
bool j1SceneIntro::Start()
{
TitleScreen_letters = App->tex->Load("gui/title_screen/letters.png");
TitleScreen_bg = App->tex->Load("gui/title_screen/bg_anim.png"); //TODO LOW -> .png
Menu_bg = App->tex->Load("gui/title_screen/menu_bg.png");
Menu_Cursor = App->audio->LoadFx("audio/fx/LTTP_Menu_Cursor.wav");
App->audio->PlayMusic("audio/music/ZELDA/ZeldaScreenSelection.ogg");
App->input_manager->AddListener(this);
fade = true;
return true;
}
// Called each loop iteration
bool j1SceneIntro::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1SceneIntro::Update(float dt)
{
if (App->scene->ingame == false)
{
if (menu == false)
{
if (bg_anim < -180) {
right = true;
}
if (bg_anim > 0) {
right = false;
}
if (right)
{
bg_anim += 0.3;
}
else
{
bg_anim -= 0.3;
}
App->render->Blit(TitleScreen_bg, 0, 0, NULL, NULL, false, NULL, NULL, NULL, { bg_anim,0 });
App->render->Blit(TitleScreen_letters, 0, 0, NULL, NULL, false);
}
else
{
if (bg_anim > -70) {
bg_anim -= 0.2;
}
App->render->Blit(Menu_bg, 0, 0, NULL, NULL, false, NULL, NULL, NULL, { bg_anim,0 });
App->render->Blit(TitleScreen_letters, -10, 0, NULL, NULL, false);
}
}
if (goHouse)
{
if (fade)
{
App->fadetoblack->FadeToBlack(3);
App->audio->FadeMusic(3);
fade = false;
}
else
{
if (App->fadetoblack->Checkfadetoblack())
{
App->scene->ingame = true;
App->scene->Start();
main_menu->OpenClose(false);
goHouse = false;
}
}
}
return true;
}
// Called each loop iteration
bool j1SceneIntro::PostUpdate()
{
bool ret = true;
if (App->scene->ingame == false )
{
if (menu)
{
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(1);
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(-1);
}
}
if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
{
ret = false;
}
if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN)
{
if (menu == false)
{
menu = true;
bg_anim = 0;
TitleScreen_letters = App->tex->Load("gui/title_screen/letters_menu.png");
LoadMainMenu();
}
if (main_menu->id_selected == 1)
{
goHouse = true;
}
}
}
return ret;
}
void j1SceneIntro::LoadMainMenu()
{
main_menu = App->gui->CreateZeldaMenu();
Button* menu_button=App->gui->CreateButton({ 1,146,110,17 }, { 172 / 2,180 / 2 }, { 0,0 }, { 112,164 }, true);
menu_button->selected = true;
menu_button->anim->PushBack({ 112,146,110,17 });
menu_button->anim->PushBack({ 223,146,110,17 });
menu_button->anim->PushBack({ 334,146,110,17 });
menu_button->anim->PushBack({ 1,164,110,17 });
menu_button->anim->PushBack({ 334,146,110,17 });
menu_button->anim->PushBack({ 223,146,110,17 });
menu_button->anim->speed = 0.25f;
menu_button->resize = false;
main_menu->AddElement(menu_button);
menu_button= App->gui->CreateButton({ 1,182,125,17 }, { 172 / 2,210 / 2 }, { 0,0 }, { 127,200 }, true);
menu_button->anim->PushBack({ 127,182,125,17 });
menu_button->anim->PushBack({ 253,182,125,17 });
menu_button->anim->PushBack({ 379,182,125,17 });
menu_button->anim->PushBack({ 1,200,125,17 });
menu_button->anim->PushBack({ 379,182,125,17 });
menu_button->anim->PushBack({ 253,182,125,17 });
menu_button->anim->speed = 0.25f;
menu_button->resize = false;
main_menu->AddElement(menu_button);
menu_button = App->gui->CreateButton({ 1,218,110,17 }, { 172 / 2, 240/ 2 }, { 0,0 }, { 112,236 }, true);
menu_button->anim->PushBack({ 112,218,110,17 });
menu_button->anim->PushBack({ 223,218,110,17 });
menu_button->anim->PushBack({ 334,218,110,17 });
menu_button->anim->PushBack({ 1,236,110,17 });
menu_button->anim->PushBack({ 334,218,110,17 });
menu_button->anim->PushBack({ 223,218,110,17 });
menu_button->anim->speed = 0.25f;
menu_button->resize = false;
main_menu->AddElement(menu_button);
}
void j1SceneIntro::OnInputCallback(INPUTEVENT action, EVENTSTATE state)
{
if (App->scene->ingame == false)
{
switch (action)
{
case MUP:
if (menu == true)
{
if (state == E_DOWN)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(-1);
}
}
break;
case MDOWN:
if (menu == true)
{
if (state == E_DOWN)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(1);
}
}
break;
case BUTTON_START:
if (state == E_DOWN)
{
if (menu == false)
{
menu = true;
bg_anim = 0;
TitleScreen_letters = App->tex->Load("gui/title_screen/letters_menu.png");
LoadMainMenu();
}
}
break;
case BUTTON_A:
if (menu == true)
{
if (main_menu->id_selected == 1)
{
App->audio->FadeMusic(2);
App->scene->ingame = true;
App->scene->Start();
main_menu->OpenClose(false);
}
}
break;
}
}
}
// Called before quitting
bool j1SceneIntro::CleanUp()
{
LOG("Freeing sceneintro");
return true;
}<commit_msg>Resize first menu<commit_after>#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1InputManager.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1FadeToBlack.h"
#include "j1PathFinding.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
#include "j1Scene.h"
#include "j1SceneIntro.h"
#include "Soldier.h"
#include "j1Player.h"
#include "j1DynamicObjects.h"
#include "j1FileSystem.h"
#include "j1Collision.h"
#include "j1AnimationManager.h"
j1SceneIntro::j1SceneIntro() : j1Module()
{
name = "scene";
}
// Destructor
j1SceneIntro::~j1SceneIntro()
{}
// Called before render is available
bool j1SceneIntro::Awake()
{
LOG("Loading SceneIntro");
bool ret = true;
return ret;
}
// Called before the first frame
bool j1SceneIntro::Start()
{
TitleScreen_letters = App->tex->Load("gui/title_screen/letters.png");
TitleScreen_bg = App->tex->Load("gui/title_screen/bg_anim.png"); //TODO LOW -> .png
Menu_bg = App->tex->Load("gui/title_screen/menu_bg.png");
Menu_Cursor = App->audio->LoadFx("audio/fx/LTTP_Menu_Cursor.wav");
App->audio->PlayMusic("audio/music/ZELDA/ZeldaScreenSelection.ogg");
App->input_manager->AddListener(this);
fade = true;
return true;
}
// Called each loop iteration
bool j1SceneIntro::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1SceneIntro::Update(float dt)
{
if (App->scene->ingame == false)
{
if (menu == false)
{
if (bg_anim < -180) {
right = true;
}
if (bg_anim > 0) {
right = false;
}
if (right)
{
bg_anim += 0.3;
}
else
{
bg_anim -= 0.3;
}
App->render->Blit(TitleScreen_bg, 0, 0, NULL, NULL, false, NULL, NULL, NULL, { bg_anim,0 });
App->render->Blit(TitleScreen_letters, 50, 10, NULL, NULL, false);
}
else
{
if (bg_anim > -70) {
bg_anim -= 0.2;
}
App->render->Blit(Menu_bg, 0, 0, NULL, NULL, false, NULL, NULL, NULL, { bg_anim,0 });
App->render->Blit(TitleScreen_letters, -10, 0, NULL, NULL, false);
}
}
if (goHouse)
{
if (fade)
{
App->fadetoblack->FadeToBlack(3);
App->audio->FadeMusic(3);
fade = false;
}
else
{
if (App->fadetoblack->Checkfadetoblack())
{
App->scene->ingame = true;
App->scene->Start();
main_menu->OpenClose(false);
goHouse = false;
}
}
}
return true;
}
// Called each loop iteration
bool j1SceneIntro::PostUpdate()
{
bool ret = true;
if (App->scene->ingame == false )
{
if (menu)
{
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(1);
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(-1);
}
}
if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
{
ret = false;
}
if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN)
{
if (menu == false)
{
menu = true;
bg_anim = 0;
TitleScreen_letters = App->tex->Load("gui/title_screen/letters_menu.png");
LoadMainMenu();
}
if (main_menu->id_selected == 1)
{
goHouse = true;
}
}
}
return ret;
}
void j1SceneIntro::LoadMainMenu()
{
main_menu = App->gui->CreateZeldaMenu();
Button* menu_button=App->gui->CreateButton({ 1,146,110,17 }, { 172 / 2,180 / 2 }, { 0,0 }, { 112,164 }, true);
menu_button->selected = true;
menu_button->anim->PushBack({ 112,146,110,17 });
menu_button->anim->PushBack({ 223,146,110,17 });
menu_button->anim->PushBack({ 334,146,110,17 });
menu_button->anim->PushBack({ 1,164,110,17 });
menu_button->anim->PushBack({ 334,146,110,17 });
menu_button->anim->PushBack({ 223,146,110,17 });
menu_button->anim->speed = 0.25f;
menu_button->resize = false;
main_menu->AddElement(menu_button);
menu_button= App->gui->CreateButton({ 1,182,125,17 }, { 172 / 2,210 / 2 }, { 0,0 }, { 127,200 }, true);
menu_button->anim->PushBack({ 127,182,125,17 });
menu_button->anim->PushBack({ 253,182,125,17 });
menu_button->anim->PushBack({ 379,182,125,17 });
menu_button->anim->PushBack({ 1,200,125,17 });
menu_button->anim->PushBack({ 379,182,125,17 });
menu_button->anim->PushBack({ 253,182,125,17 });
menu_button->anim->speed = 0.25f;
menu_button->resize = false;
main_menu->AddElement(menu_button);
menu_button = App->gui->CreateButton({ 1,218,110,17 }, { 172 / 2, 240/ 2 }, { 0,0 }, { 112,236 }, true);
menu_button->anim->PushBack({ 112,218,110,17 });
menu_button->anim->PushBack({ 223,218,110,17 });
menu_button->anim->PushBack({ 334,218,110,17 });
menu_button->anim->PushBack({ 1,236,110,17 });
menu_button->anim->PushBack({ 334,218,110,17 });
menu_button->anim->PushBack({ 223,218,110,17 });
menu_button->anim->speed = 0.25f;
menu_button->resize = false;
main_menu->AddElement(menu_button);
}
void j1SceneIntro::OnInputCallback(INPUTEVENT action, EVENTSTATE state)
{
if (App->scene->ingame == false)
{
switch (action)
{
case MUP:
if (menu == true)
{
if (state == E_DOWN)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(-1);
}
}
break;
case MDOWN:
if (menu == true)
{
if (state == E_DOWN)
{
App->audio->PlayFx(Menu_Cursor);
main_menu->Select(1);
}
}
break;
case BUTTON_START:
if (state == E_DOWN)
{
if (menu == false)
{
menu = true;
bg_anim = 0;
TitleScreen_letters = App->tex->Load("gui/title_screen/letters_menu.png");
LoadMainMenu();
}
}
break;
case BUTTON_A:
if (menu == true)
{
if (main_menu->id_selected == 1)
{
App->audio->FadeMusic(2);
App->scene->ingame = true;
App->scene->Start();
main_menu->OpenClose(false);
}
}
break;
}
}
}
// Called before quitting
bool j1SceneIntro::CleanUp()
{
LOG("Freeing sceneintro");
return true;
}<|endoftext|> |
<commit_before>#include "NetworkManagerClient.h"
NetworkManagerClient::NetworkManagerClient(void) : connected(false)
{
if(SDL_Init(0) != 0)
{
std::cerr << "SDL_Init done goofed: " << SDL_GetError() << std::endl;
exit(1);
}
if(SDLNet_Init() != 0)
std::cerr << "SDLNet_Init done goofed: " << SDLNet_GetError() << std::endl;
}
NetworkManagerClient::~NetworkManagerClient(void)
{
SDLNet_Quit();
SDL_Quit();
}
int NetworkManagerClient::connect(char *host, char *name)
{
//std::cout << "Entering connect" << std::endl << std::endl;
Uint16 port = (Uint16) TCP_PORT;
SDLNet_SocketSet set = SDLNet_AllocSocketSet(1);
if(!set)
{
std::cerr << "SDLNet_AllocSocketSet done goofed: " << SDLNet_GetError() << std::endl;
SDLNet_Quit();
SDL_Quit();
exit(4); //most of the time this is a major error, but do what you want.
}
// Resolve the argument into an IPaddress type
//std::cout << "Connecting to " << host << " port " << port << std::endl;
IPaddress ip;
if(SDLNet_ResolveHost(&ip, host, port)==-1)
{
std::cerr << "SDLNet_ResolveHost done goofed: " << SDLNet_GetError() << std::endl;
std::string exception = "fail_to_connect";
throw exception;
}
// open the TCP socket
//std::cout << "Opening server socket." << std::endl;
TCPServerSock = SDLNet_TCP_Open(&ip);
if(!TCPServerSock)
{
std::cerr << "SDLNet_TCP_Open done goofed: " << SDLNet_GetError() << std::endl;
SDLNet_Quit();
SDL_Quit();
std::string exception = "fail_to_connect";
throw exception;
}
// open the UDP socket
UDPServerSock = SDLNet_UDP_Open(0);
if(!UDPServerSock)
{
std::cerr << "SDLNet_UDP_Open done goofed: " << SDLNet_GetError() << std::endl;
SDLNet_Quit();
SDL_Quit();
std::string exception = "fail_to_connect";
throw exception;
}
// login with a name
Packet pack;
pack.type = CONNECTION;
pack.message = name; // FIXME: SHOULD USE? :char message[MAXLEN];
char* out = NetworkUtil::PacketToCharArray(pack);
if(!NetworkUtil::TCPSend(TCPServerSock, out))
{
SDLNet_TCP_Close(TCPServerSock);
exit(8);
}
//std::cout << "Sent " << out << std::endl;
free(out);
// store our connection info
mName = name;
serverIP = ip;
connected = true;
//std::cout << "Logged in as " << mName << std::endl;
//std::cout << "Exiting TCPConnect" << std::endl << std::endl;
}
TCPsocket& NetworkManagerClient::getSocket(){return this->TCPServerSock;}
bool NetworkManagerClient::isOnline(){return connected;}
void NetworkManagerClient::resetReadyState()
{
//std::cout << "Entering resetReadyState" << std::endl << std::endl;
Packet outgoing;
outgoing.type = READY;
outgoing.message = const_cast<char*>("RESET");
NetworkUtil::TCPSend(TCPServerSock, NetworkUtil::PacketToCharArray(outgoing));
//std::cout << "Exiting resetReadyState" << std::endl << std::endl;
}
void NetworkManagerClient::quit()
{
//std::cout << "Entering quit" << std::endl << std::endl << std::endl;
Packet outgoing;
outgoing.type = CONNECTION;
outgoing.message = const_cast<char*>("QUIT");
char* out = NetworkUtil::PacketToCharArray(outgoing);
NetworkUtil::TCPSend(TCPServerSock, out);
free(out);
connected = false;
//std::cout << "You have quit the game." << std::endl;
//std::cout << "Exiting quit" << std::endl << std::endl << std::endl;
}
void NetworkManagerClient::sendPlayerInput(ISpaceShipController* controller)
{
//std::cout << "Entering sendPlayerInput" << std::endl << std::endl;
Packet outgoing;
bool left = controller->left();
bool right = controller->right();
bool up = controller->up();
bool down = controller->down();
bool forward = controller->forward();
bool back = controller->back();
bool shoot = controller->shoot();
char result = left;
result = (result << 1) + right;
result = (result << 1) + up;
result = (result << 1) + down;
result = (result << 1) + forward;
result = (result << 1) + back;
result = (result << 1) + shoot;
outgoing.type = PLAYERINPUT;
outgoing.message = &result;
char* out = NetworkUtil::PacketToCharArray(outgoing);
NetworkUtil::TCPSend(TCPServerSock, out);
/* //TODO: Use TCP to send input instead?
UDPpacket *UDPPack = NetworkUtil::AllocPacket(sizeof(int)+1);
if(!UDPPack) return;
UDPPack->data = (Uint8*)out;
UDPPack->len = strlen(out) + 1;
UDPPack->address = serverIP;
NetworkUtil::UDPSend(UDPServerSock, -1, UDPPack);
std::cout << "UDPSend player input." << std::endl;
SDLNet_FreePacket(UDPPack);
*/
free(out);
//std::cout << "Exiting sendPlayerInput" << std::endl << std::endl;
}
void NetworkManagerClient::receiveData(Ogre::SceneManager* sceneManager, std::vector<Mineral*>& minerals, std::vector<SpaceShip*>& spaceships)
{
//std::cout << "Entering receiveData" << std::endl << std::endl;
static int iii = 0;
Packet outgoing;
Packet infoPacket;
outgoing.type = STATE;
outgoing.message = const_cast<char*>("");
char* incoming = NULL;
char* out = NetworkUtil::PacketToCharArray(outgoing);
//TODO: Use TCP to send request, but use UDP to receive data
/* //FIXME: Fix the other UDP bugs first.
UDPpacket *UDPPack = NetworkUtil::AllocPacket(65535);
if(!UDPPack) return;
if(NetworkUtil::UDPReceive(UDPServerSock, UDPPack) > 0)
{
std::cout << "Received UDP Packet." << std::endl;
infoPacket = NetworkUtil::charArrayToPacket((char*)UDPPack->data);
SDLNet_FreePacket(UDPPack);
}
else
return;
*/
if(NetworkUtil::TCPSend(TCPServerSock, out) && NetworkUtil::TCPReceive(TCPServerSock, &incoming)) {
infoPacket = NetworkUtil::charArrayToPacket(incoming);
//std::cout << iii++ << ": " << infoPacket.message << std::endl << std::endl;
std::string message(infoPacket.message);
int mineralsAmount = atoi(message.substr(message.find(":") + 1, message.find(",")).c_str());
for (int i = 0; i < mineralsAmount; i++) {
message = message.substr(message.find(",") + 1);
std::string name = message.substr(0, message.find(","));
message = message.substr(message.find(",") + 1);
double pos_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_w = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double radius = atof(message.substr(0, message.find(",")).c_str());
// FIXME: THIS IS BAD, oh well
bool found = false;
for(int j = 0; j < minerals.size(); ++j)
{
//std::cout << "Checking to see if " << name << " already exists." << std::endl;
if(minerals[j]->getName() == name)
{
//std::cout << "Exists." << std::endl;
found = true;
minerals[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
minerals[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
break;
}
}
if(!found)
{
//std::cout << "Doesn't exist, create it." << std::endl;
minerals.push_back(new Mineral(name, sceneManager->getRootSceneNode(), pos_x, pos_y, pos_z, radius));
minerals.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
}
}
message = message.substr(message.find(",") + 1);
int spaceShipAmount = atoi(message.substr(message.find(":") + 1, message.find(",")).c_str());
for (int i = 0; i < spaceShipAmount; i++) {
message = message.substr(message.find(",") + 1);
std::string name = message.substr(0, message.find(","));
message = message.substr(message.find(",") + 1);
double pos_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_w = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double size = atof(message.substr(0, message.find(",")).c_str());
// FIXME: THIS IS BAD, oh well
bool found = false;
std::cout << "Examining " << name << ". Our name is " << mName << std::endl;
if(name == mName)
{
std::cout << "Setting player at " << pos_x << " " << pos_y << " " << pos_z << std::endl;
spaceships[0]->getSceneNode()->getParentSceneNode()->setPosition(pos_x, pos_y, pos_z);
std::cout << "With rotation " << rot_w << " " << rot_x << " " << rot_y << " " << rot_z << std::endl;
spaceships[0]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
continue;
}
for(int j = 0; j < spaceships.size(); ++j)
{
//std::cout << "Checking to see if " << name << " already exists." << std::endl;
if(spaceships[j]->getName() == name)
{
//std::cout << "Exists." << std::endl;
found = true;
spaceships[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
spaceships[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
break;
}
}
if(!found)
{
//std::cout << "Doesn't exist, create it." << std::endl;
ISpaceShipController* controller = new ClientSpaceShipController();
spaceships.push_back(new SpaceShip(name, controller, sceneManager->getRootSceneNode()->createChildSceneNode(), pos_x, pos_y, pos_z, size));
spaceships.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
}
}
// TODO: WALLS AND BULLETS?
}
free(out);
free(incoming);
//std::cout << "Exiting receiveData" << std::endl << std::endl;
}
<commit_msg>bullet info parsed<commit_after>#include "NetworkManagerClient.h"
NetworkManagerClient::NetworkManagerClient(void) : connected(false)
{
if(SDL_Init(0) != 0)
{
std::cerr << "SDL_Init done goofed: " << SDL_GetError() << std::endl;
exit(1);
}
if(SDLNet_Init() != 0)
std::cerr << "SDLNet_Init done goofed: " << SDLNet_GetError() << std::endl;
}
NetworkManagerClient::~NetworkManagerClient(void)
{
SDLNet_Quit();
SDL_Quit();
}
int NetworkManagerClient::connect(char *host, char *name)
{
//std::cout << "Entering connect" << std::endl << std::endl;
Uint16 port = (Uint16) TCP_PORT;
SDLNet_SocketSet set = SDLNet_AllocSocketSet(1);
if(!set)
{
std::cerr << "SDLNet_AllocSocketSet done goofed: " << SDLNet_GetError() << std::endl;
SDLNet_Quit();
SDL_Quit();
exit(4); //most of the time this is a major error, but do what you want.
}
// Resolve the argument into an IPaddress type
//std::cout << "Connecting to " << host << " port " << port << std::endl;
IPaddress ip;
if(SDLNet_ResolveHost(&ip, host, port)==-1)
{
std::cerr << "SDLNet_ResolveHost done goofed: " << SDLNet_GetError() << std::endl;
std::string exception = "fail_to_connect";
throw exception;
}
// open the TCP socket
//std::cout << "Opening server socket." << std::endl;
TCPServerSock = SDLNet_TCP_Open(&ip);
if(!TCPServerSock)
{
std::cerr << "SDLNet_TCP_Open done goofed: " << SDLNet_GetError() << std::endl;
SDLNet_Quit();
SDL_Quit();
std::string exception = "fail_to_connect";
throw exception;
}
// open the UDP socket
UDPServerSock = SDLNet_UDP_Open(0);
if(!UDPServerSock)
{
std::cerr << "SDLNet_UDP_Open done goofed: " << SDLNet_GetError() << std::endl;
SDLNet_Quit();
SDL_Quit();
std::string exception = "fail_to_connect";
throw exception;
}
// login with a name
Packet pack;
pack.type = CONNECTION;
pack.message = name; // FIXME: SHOULD USE? :char message[MAXLEN];
char* out = NetworkUtil::PacketToCharArray(pack);
if(!NetworkUtil::TCPSend(TCPServerSock, out))
{
SDLNet_TCP_Close(TCPServerSock);
exit(8);
}
//std::cout << "Sent " << out << std::endl;
free(out);
// store our connection info
mName = name;
serverIP = ip;
connected = true;
//std::cout << "Logged in as " << mName << std::endl;
//std::cout << "Exiting TCPConnect" << std::endl << std::endl;
}
TCPsocket& NetworkManagerClient::getSocket(){return this->TCPServerSock;}
bool NetworkManagerClient::isOnline(){return connected;}
void NetworkManagerClient::resetReadyState()
{
//std::cout << "Entering resetReadyState" << std::endl << std::endl;
Packet outgoing;
outgoing.type = READY;
outgoing.message = const_cast<char*>("RESET");
NetworkUtil::TCPSend(TCPServerSock, NetworkUtil::PacketToCharArray(outgoing));
//std::cout << "Exiting resetReadyState" << std::endl << std::endl;
}
void NetworkManagerClient::quit()
{
//std::cout << "Entering quit" << std::endl << std::endl << std::endl;
Packet outgoing;
outgoing.type = CONNECTION;
outgoing.message = const_cast<char*>("QUIT");
char* out = NetworkUtil::PacketToCharArray(outgoing);
NetworkUtil::TCPSend(TCPServerSock, out);
free(out);
connected = false;
//std::cout << "You have quit the game." << std::endl;
//std::cout << "Exiting quit" << std::endl << std::endl << std::endl;
}
void NetworkManagerClient::sendPlayerInput(ISpaceShipController* controller)
{
//std::cout << "Entering sendPlayerInput" << std::endl << std::endl;
Packet outgoing;
bool left = controller->left();
bool right = controller->right();
bool up = controller->up();
bool down = controller->down();
bool forward = controller->forward();
bool back = controller->back();
bool shoot = controller->shoot();
char result = left;
result = (result << 1) + right;
result = (result << 1) + up;
result = (result << 1) + down;
result = (result << 1) + forward;
result = (result << 1) + back;
result = (result << 1) + shoot;
outgoing.type = PLAYERINPUT;
outgoing.message = &result;
char* out = NetworkUtil::PacketToCharArray(outgoing);
NetworkUtil::TCPSend(TCPServerSock, out);
/* //TODO: Use TCP to send input instead?
UDPpacket *UDPPack = NetworkUtil::AllocPacket(sizeof(int)+1);
if(!UDPPack) return;
UDPPack->data = (Uint8*)out;
UDPPack->len = strlen(out) + 1;
UDPPack->address = serverIP;
NetworkUtil::UDPSend(UDPServerSock, -1, UDPPack);
std::cout << "UDPSend player input." << std::endl;
SDLNet_FreePacket(UDPPack);
*/
free(out);
//std::cout << "Exiting sendPlayerInput" << std::endl << std::endl;
}
void NetworkManagerClient::receiveData(Ogre::SceneManager* sceneManager, std::vector<Mineral*>& minerals, std::vector<SpaceShip*>& spaceships)
{
//std::cout << "Entering receiveData" << std::endl << std::endl;
static int iii = 0;
Packet outgoing;
Packet infoPacket;
outgoing.type = STATE;
outgoing.message = const_cast<char*>("");
char* incoming = NULL;
char* out = NetworkUtil::PacketToCharArray(outgoing);
//TODO: Use TCP to send request, but use UDP to receive data
/* //FIXME: Fix the other UDP bugs first.
UDPpacket *UDPPack = NetworkUtil::AllocPacket(65535);
if(!UDPPack) return;
if(NetworkUtil::UDPReceive(UDPServerSock, UDPPack) > 0)
{
std::cout << "Received UDP Packet." << std::endl;
infoPacket = NetworkUtil::charArrayToPacket((char*)UDPPack->data);
SDLNet_FreePacket(UDPPack);
}
else
return;
*/
if(NetworkUtil::TCPSend(TCPServerSock, out) && NetworkUtil::TCPReceive(TCPServerSock, &incoming)) {
infoPacket = NetworkUtil::charArrayToPacket(incoming);
//std::cout << iii++ << ": " << infoPacket.message << std::endl << std::endl;
std::string message(infoPacket.message);
int mineralsAmount = atoi(message.substr(message.find(":") + 1, message.find(",")).c_str());
for (int i = 0; i < mineralsAmount; i++) {
message = message.substr(message.find(",") + 1);
std::string name = message.substr(0, message.find(","));
message = message.substr(message.find(",") + 1);
double pos_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_w = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double radius = atof(message.substr(0, message.find(",")).c_str());
// FIXME: THIS IS BAD, oh well
bool found = false;
for(int j = 0; j < minerals.size(); ++j)
{
//std::cout << "Checking to see if " << name << " already exists." << std::endl;
if(minerals[j]->getName() == name)
{
//std::cout << "Exists." << std::endl;
found = true;
minerals[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
minerals[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
break;
}
}
if(!found)
{
//std::cout << "Doesn't exist, create it." << std::endl;
minerals.push_back(new Mineral(name, sceneManager->getRootSceneNode(), pos_x, pos_y, pos_z, radius));
minerals.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
}
}
message = message.substr(message.find(",") + 1);
int spaceShipAmount = atoi(message.substr(message.find(":") + 1, message.find(",")).c_str());
for (int i = 0; i < spaceShipAmount; i++) {
message = message.substr(message.find(",") + 1);
std::string name = message.substr(0, message.find(","));
message = message.substr(message.find(",") + 1);
double pos_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_w = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double rot_z = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double size = atof(message.substr(0, message.find(",")).c_str());
// FIXME: THIS IS BAD, oh well
bool found = false;
std::cout << "Examining " << name << ". Our name is " << mName << std::endl;
if(name == mName)
{
std::cout << "Setting player at " << pos_x << " " << pos_y << " " << pos_z << std::endl;
spaceships[0]->getSceneNode()->getParentSceneNode()->setPosition(pos_x, pos_y, pos_z);
std::cout << "With rotation " << rot_w << " " << rot_x << " " << rot_y << " " << rot_z << std::endl;
spaceships[0]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
continue;
}
for(int j = 0; j < spaceships.size(); ++j)
{
//std::cout << "Checking to see if " << name << " already exists." << std::endl;
if(spaceships[j]->getName() == name)
{
//std::cout << "Exists." << std::endl;
found = true;
spaceships[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
spaceships[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
break;
}
}
if(!found)
{
//std::cout << "Doesn't exist, create it." << std::endl;
ISpaceShipController* controller = new ClientSpaceShipController();
spaceships.push_back(new SpaceShip(name, controller, sceneManager->getRootSceneNode()->createChildSceneNode(), pos_x, pos_y, pos_z, size));
spaceships.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z);
}
}
message = message.substr(message.find(",") + 1);
int bulletsAmount = atoi(message.substr(message.find(":") + 1, message.find(",")).c_str());
for (int i = 0; i < bulletsAmount; i++) {
message = message.substr(message.find(",") + 1);
std::string name = message.substr(0, message.find(","));
message = message.substr(message.find(",") + 1);
double pos_x = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_y = atof(message.substr(0, message.find(",")).c_str());
message = message.substr(message.find(",") + 1);
double pos_z = atof(message.substr(0, message.find(",")).c_str());
// FIXME: THIS IS BAD, oh well
bool found = false;
for(int j = 0; j < bullets.size(); ++j)
{
//std::cout << "Checking to see if " << name << " already exists." << std::endl;
if(bullets[j]->getName() == name)
{
//std::cout << "Exists." << std::endl;
found = true;
bullets[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z);
break;
}
}
if(!found)
{
//std::cout << "Doesn't exist, create it." << std::endl;
bullets.push_back(new Bullet(name, sceneManager->getRootSceneNode(), NULL, pos_x, pos_y, pos_z));
}
}
}
free(out);
free(incoming);
//std::cout << "Exiting receiveData" << std::endl << std::endl;
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/inspect.h>
#include <fnord-base/logging.h>
#include "fnord-http/httpserverconnection.h"
#include <fnord-http/httpservice.h>
#include <fnord-http/httpresponsestream.h>
namespace fnord {
namespace http {
void HTTPService::handleHTTPRequest(
RefPtr<HTTPRequestStream> req_stream,
RefPtr<HTTPResponseStream> res_stream) {
const auto& req = req_stream->request();
HTTPResponse res;
res.populateFromRequest(req);
handleHTTPRequest(const_cast<HTTPRequest*>(&req), &res);
auto body_size = res.body().size();
if (body_size > 0) {
res.setHeader("Content-Length", StringUtil::toString(body_size));
}
res_stream->writeResponse(res);
}
HTTPServiceHandler::HTTPServiceHandler(
StreamingHTTPService* service,
TaskScheduler* scheduler,
HTTPServerConnection* conn,
HTTPRequest* req) :
service_(service),
scheduler_(scheduler),
conn_(conn),
req_(req) {}
void HTTPServiceHandler::handleHTTPRequest() {
if (service_->isStreaming()) {
dispatchRequest();
} else {
conn_->readRequestBody([this] (
const void* data,
size_t size,
bool last_chunk) {
req_->appendBody((char *) data, size);
if (last_chunk) {
dispatchRequest();
}
});
}
}
void HTTPServiceHandler::dispatchRequest() {
auto runnable = [this] () {
auto res_stream = new HTTPResponseStream(conn_);
res_stream->incRef();
RefPtr<HTTPRequestStream> req_stream(new HTTPRequestStream(*req_, conn_));
try {
service_->handleHTTPRequest(req_stream.get(), res_stream);
} catch (const std::exception& e) {
logError("fnord.http.service", e, "Error while processing HTTP request");
if (!res_stream->isOutputStarted()) {
http::HTTPResponse res;
res.setStatus(http::kStatusInternalServerError);
res.addBody("server error");
res_stream->writeResponse(res);
}
}
};
if (scheduler_ == nullptr) {
runnable();
} else {
scheduler_->run(runnable);
}
}
}
}
<commit_msg>include fix<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/inspect.h>
#include <fnord-base/logging.h>
#include "fnord-http/httpserverconnection.h"
#include <fnord-http/httpservice.h>
#include <fnord-http/HTTPResponseStream.h>
namespace fnord {
namespace http {
void HTTPService::handleHTTPRequest(
RefPtr<HTTPRequestStream> req_stream,
RefPtr<HTTPResponseStream> res_stream) {
const auto& req = req_stream->request();
HTTPResponse res;
res.populateFromRequest(req);
handleHTTPRequest(const_cast<HTTPRequest*>(&req), &res);
auto body_size = res.body().size();
if (body_size > 0) {
res.setHeader("Content-Length", StringUtil::toString(body_size));
}
res_stream->writeResponse(res);
}
HTTPServiceHandler::HTTPServiceHandler(
StreamingHTTPService* service,
TaskScheduler* scheduler,
HTTPServerConnection* conn,
HTTPRequest* req) :
service_(service),
scheduler_(scheduler),
conn_(conn),
req_(req) {}
void HTTPServiceHandler::handleHTTPRequest() {
if (service_->isStreaming()) {
dispatchRequest();
} else {
conn_->readRequestBody([this] (
const void* data,
size_t size,
bool last_chunk) {
req_->appendBody((char *) data, size);
if (last_chunk) {
dispatchRequest();
}
});
}
}
void HTTPServiceHandler::dispatchRequest() {
auto runnable = [this] () {
auto res_stream = new HTTPResponseStream(conn_);
res_stream->incRef();
RefPtr<HTTPRequestStream> req_stream(new HTTPRequestStream(*req_, conn_));
try {
service_->handleHTTPRequest(req_stream.get(), res_stream);
} catch (const std::exception& e) {
logError("fnord.http.service", e, "Error while processing HTTP request");
if (!res_stream->isOutputStarted()) {
http::HTTPResponse res;
res.setStatus(http::kStatusInternalServerError);
res.addBody("server error");
res_stream->writeResponse(res);
}
}
};
if (scheduler_ == nullptr) {
runnable();
} else {
scheduler_->run(runnable);
}
}
}
}
<|endoftext|> |
<commit_before>/*
This file is part of Csound.
Copyright (C) 2014 Rory Walsh
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include "OpcodeBase.hpp"
#include <algorithm>
#include <cmath>
#include <dirent.h>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <vector>
using namespace std;
using namespace csound;
/* this function will load all samples of supported types into function
tables number 'index' and upwards.
It return the number of samples loaded */
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel);
//-----------------------------------------------------------------
// i-rate class
//-----------------------------------------------------------------
class iftsamplebank : public OpcodeBase<iftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
// MYFLT* trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
iftsamplebank() {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
numberOfFiles = 0;
sDirectory = NULL;
}
// init-pass
int init(CSOUND *csound) {
*numberOfFiles = loadSamplesToTables(
csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel);
return OK;
}
int noteoff(CSOUND *) { return OK; }
};
//-----------------------------------------------------------------
// k-rate class
//-----------------------------------------------------------------
class kftsamplebank : public OpcodeBase<kftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
MYFLT *trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
int internalCounter;
kftsamplebank() : internalCounter(0) {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
trigger = 0;
}
// init-pass
int init(CSOUND *csound) {
IGN(csound);
*numberOfFiles = 0;
// loadSamplesToTables(csound, *index, fileNames,
// (char* )sDirectory->data, *skiptime, *format, *channel);
// csound->Message(csound, (char* )sDirectory->data);
*trigger = 0;
return OK;
}
int noteoff(CSOUND *) { return OK; }
int kontrol(CSOUND *csound) {
// if directry changes update tables..
if (*trigger == 1) {
*numberOfFiles =
loadSamplesToTables(csound, *index, (char *)sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
}
return OK;
}
};
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel) {
if (directory) {
DIR *dir = opendir(directory);
std::vector<std::string> fileNames;
std::vector<std::string> fileExtensions;
int noOfFiles = 0;
fileExtensions.push_back(".wav");
fileExtensions.push_back(".aiff");
fileExtensions.push_back(".ogg");
fileExtensions.push_back(".flac");
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
// only use supported file types
for (int i = 0; (size_t)i < fileExtensions.size(); i++)
{
std::string fname = ent->d_name;
std::string extension;
if(fname.find_last_of(".") != std::string::npos)
extension = fname.substr(fname.find_last_of(".")+1);
if(extension == fileExtensions[i])
{
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
// push statements to score, starting with table number 'index'
for (int y = 0; (size_t)y < fileNames.size(); y++) {
std::ostringstream statement;
statement << "f" << index + y << " 0 0 1 \"" << fileNames[y] << "\" "
<< skiptime << " " << format << " " << channel << "\n";
// csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());
csound->InputMessage(csound, statement.str().c_str());
}
closedir(dir);
} else {
csound->Message(csound,
Str("Cannot load file. Error opening directory: %s\n"),
directory);
}
// return number of files
return noOfFiles;
} else
return 0;
}
typedef struct {
OPDS h;
ARRAYDAT *outArr;
STRINGDAT *directoryName;
MYFLT *extension;
} DIR_STRUCT;
/* this function will looks for files of a set type, in a particular directory
*/
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension);
#include "arrays.h"
#if 0
/* from Opcodes/arrays.c */
static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) {
if (p->data==NULL || p->dimensions == 0 ||
(p->dimensions==1 && p->sizes[0] < size)) {
size_t ss;
if (p->data == NULL) {
CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);
p->arrayMemberSize = var->memBlockSize;
}
ss = p->arrayMemberSize*size;
if (p->data==NULL) {
p->data = (MYFLT*)csound->Calloc(csound, ss);
p->allocated = ss;
}
else if (ss > p->allocated) {
p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);
p->allocated = ss;
}
if (p->dimensions==0) {
p->dimensions = 1;
p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t));
}
}
p->sizes[0] = size;
}
#endif
static int directory(CSOUND *csound, DIR_STRUCT *p) {
int inArgCount = p->INOCOUNT;
char *extension, *file;
std::vector<std::string> fileNames;
if (inArgCount == 0)
return csound->InitError(
csound, "%s", Str("Error: you must pass a directory as a string."));
if (inArgCount == 1) {
fileNames = searchDir(csound, p->directoryName->data, (char *)"");
}
else if (inArgCount == 2) {
CS_TYPE *argType = csound->GetTypeForArg(p->extension);
if (strcmp("S", argType->varTypeName) == 0) {
extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);
fileNames = searchDir(csound, p->directoryName->data, extension);
} else
return csound->InitError(csound,
"%s", Str("Error: second parameter to directory"
" must be a string"));
}
int numberOfFiles = fileNames.size();
tabensure(csound, p->outArr, numberOfFiles);
STRINGDAT *strings = (STRINGDAT *)p->outArr->data;
for (int i = 0; i < numberOfFiles; i++) {
file = &fileNames[i][0u];
strings[i].size = strlen(file) + 1;
strings[i].data = csound->Strdup(csound, file);
}
fileNames.clear();
return OK;
}
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension) {
std::vector<std::string> fileNames;
if (directory) {
DIR *dir = opendir(directory);
std::string fileExtension(extension);
int noOfFiles = 0;
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
if (std::string(ent->d_name).find(fileExtension) != std::string::npos &&
strlen(ent->d_name) > 2) {
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
} else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
} else {
csound->Message(csound, Str("Cannot find directory. "
"Error opening directory: %s\n"),
directory);
}
closedir(dir);
}
return fileNames;
}
extern "C" {
PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) {
int status = csound->AppendOpcode(
csound, (char *)"ftsamplebank.k", sizeof(kftsamplebank), 0, 3,
(char *)"k", (char *)"Skkkkk",
(int (*)(CSOUND *, void *))kftsamplebank::init_,
(int (*)(CSOUND *, void *))kftsamplebank::kontrol_,
(int (*)(CSOUND *, void *))0);
status |= csound->AppendOpcode(
csound, (char *)"ftsamplebank.i", sizeof(iftsamplebank), 0, 1,
(char *)"i", (char *)"Siiii",
(int (*)(CSOUND *, void *))iftsamplebank::init_,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
/* status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank",
0xffff,
0,
0,
0,
0,
0,
0,
0); */
status |= csound->AppendOpcode(
csound, (char *)"directory", sizeof(DIR_STRUCT), 0, 1, (char *)"S[]",
(char *)"SN", (int (*)(CSOUND *, void *))directory,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
return status;
}
#ifndef INIT_STATIC_MODULES
PUBLIC int csoundModuleCreate(CSOUND *csound) {
IGN(csound);
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound) {
return csoundModuleInit_ftsamplebank(csound);
}
PUBLIC int csoundModuleDestroy(CSOUND *csound) {
IGN(csound);
return 0;
}
#endif
}
<commit_msg>fixed file extension issue<commit_after>/*
This file is part of Csound.
Copyright (C) 2014 Rory Walsh
The Csound Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include "OpcodeBase.hpp"
#include <algorithm>
#include <cmath>
#include <dirent.h>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <vector>
using namespace std;
using namespace csound;
/* this function will load all samples of supported types into function
tables number 'index' and upwards.
It return the number of samples loaded */
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel);
//-----------------------------------------------------------------
// i-rate class
//-----------------------------------------------------------------
class iftsamplebank : public OpcodeBase<iftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
// MYFLT* trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
iftsamplebank() {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
numberOfFiles = 0;
sDirectory = NULL;
}
// init-pass
int init(CSOUND *csound) {
*numberOfFiles = loadSamplesToTables(
csound, *index, (char *)sDirectory->data, *skiptime, *format, *channel);
return OK;
}
int noteoff(CSOUND *) { return OK; }
};
//-----------------------------------------------------------------
// k-rate class
//-----------------------------------------------------------------
class kftsamplebank : public OpcodeBase<kftsamplebank> {
public:
// Outputs.
MYFLT *numberOfFiles;
// Inputs.
STRINGDAT *sDirectory;
MYFLT *index;
MYFLT *trigger;
MYFLT *skiptime;
MYFLT *format;
MYFLT *channel;
int internalCounter;
kftsamplebank() : internalCounter(0) {
channel = 0;
index = 0;
skiptime = 0;
format = 0;
index = 0;
trigger = 0;
}
// init-pass
int init(CSOUND *csound) {
IGN(csound);
*numberOfFiles = 0;
// loadSamplesToTables(csound, *index, fileNames,
// (char* )sDirectory->data, *skiptime, *format, *channel);
// csound->Message(csound, (char* )sDirectory->data);
*trigger = 0;
return OK;
}
int noteoff(CSOUND *) { return OK; }
int kontrol(CSOUND *csound) {
// if directry changes update tables..
if (*trigger == 1) {
*numberOfFiles =
loadSamplesToTables(csound, *index, (char *)sDirectory->data,
*skiptime, *format, *channel);
*trigger = 0;
}
return OK;
}
};
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
int loadSamplesToTables(CSOUND *csound, int index, char *directory,
int skiptime, int format, int channel) {
if (directory) {
DIR *dir = opendir(directory);
std::vector<std::string> fileNames;
std::vector<std::string> fileExtensions;
int noOfFiles = 0;
fileExtensions.push_back(".wav");
fileExtensions.push_back(".aiff");
fileExtensions.push_back(".ogg");
fileExtensions.push_back(".flac");
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
// only use supported file types
for (int i = 0; (size_t)i < fileExtensions.size(); i++)
{
std::string fname = ent->d_name;
std::string extension;
if(fname.find_last_of(".") != std::string::npos)
extension = fname.substr(fname.find_last_of(".")+1);
if(extension == fileExtensions[i])
{
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
}
else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
// push statements to score, starting with table number 'index'
for (int y = 0; (size_t)y < fileNames.size(); y++) {
std::ostringstream statement;
statement << "f" << index + y << " 0 0 1 \"" << fileNames[y] << "\" "
<< skiptime << " " << format << " " << channel << "\n";
// csound->MessageS(csound, CSOUNDMSG_ORCH, statement.str().c_str());
csound->InputMessage(csound, statement.str().c_str());
}
closedir(dir);
} else {
csound->Message(csound,
Str("Cannot load file. Error opening directory: %s\n"),
directory);
}
// return number of files
return noOfFiles;
} else
return 0;
}
typedef struct {
OPDS h;
ARRAYDAT *outArr;
STRINGDAT *directoryName;
MYFLT *extension;
} DIR_STRUCT;
/* this function will looks for files of a set type, in a particular directory
*/
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension);
#include "arrays.h"
#if 0
/* from Opcodes/arrays.c */
static inline void tabensure(CSOUND *csound, ARRAYDAT *p, int size) {
if (p->data==NULL || p->dimensions == 0 ||
(p->dimensions==1 && p->sizes[0] < size)) {
size_t ss;
if (p->data == NULL) {
CS_VARIABLE* var = p->arrayType->createVariable(csound, NULL);
p->arrayMemberSize = var->memBlockSize;
}
ss = p->arrayMemberSize*size;
if (p->data==NULL) {
p->data = (MYFLT*)csound->Calloc(csound, ss);
p->allocated = ss;
}
else if (ss > p->allocated) {
p->data = (MYFLT*) csound->ReAlloc(csound, p->data, ss);
p->allocated = ss;
}
if (p->dimensions==0) {
p->dimensions = 1;
p->sizes = (int32_t*)csound->Malloc(csound, sizeof(int32_t));
}
}
p->sizes[0] = size;
}
#endif
static int directory(CSOUND *csound, DIR_STRUCT *p) {
int inArgCount = p->INOCOUNT;
char *extension, *file;
std::vector<std::string> fileNames;
if (inArgCount == 0)
return csound->InitError(
csound, "%s", Str("Error: you must pass a directory as a string."));
if (inArgCount == 1) {
fileNames = searchDir(csound, p->directoryName->data, (char *)"");
}
else if (inArgCount == 2) {
CS_TYPE *argType = csound->GetTypeForArg(p->extension);
if (strcmp("S", argType->varTypeName) == 0) {
extension = csound->Strdup(csound, ((STRINGDAT *)p->extension)->data);
fileNames = searchDir(csound, p->directoryName->data, extension);
} else
return csound->InitError(csound,
"%s", Str("Error: second parameter to directory"
" must be a string"));
}
int numberOfFiles = fileNames.size();
tabensure(csound, p->outArr, numberOfFiles);
STRINGDAT *strings = (STRINGDAT *)p->outArr->data;
for (int i = 0; i < numberOfFiles; i++) {
file = &fileNames[i][0u];
strings[i].size = strlen(file) + 1;
strings[i].data = csound->Strdup(csound, file);
}
fileNames.clear();
return OK;
}
//-----------------------------------------------------------------
// load samples into function tables
//-----------------------------------------------------------------
std::vector<std::string> searchDir(CSOUND *csound, char *directory,
char *extension) {
std::vector<std::string> fileNames;
if (directory) {
DIR *dir = opendir(directory);
std::string fileExtension(extension);
int noOfFiles = 0;
// check for valid path first
if (dir) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
std::ostringstream fullFileName;
std::string fname = ent->d_name;
size_t lastPos = fname.find_last_of(".");
if (fname.length() > 2 && (fileExtension.empty() ||
(lastPos != std::string::npos &&
fname.substr(lastPos) == fileExtension))) {
if (strlen(directory) > 2) {
#if defined(WIN32)
fullFileName << directory << "\\" << ent->d_name;
#else
fullFileName << directory << "/" << ent->d_name;
#endif
} else
fullFileName << ent->d_name;
noOfFiles++;
fileNames.push_back(fullFileName.str());
}
}
// Sort names
std::sort(fileNames.begin(), fileNames.end());
} else {
csound->Message(csound, Str("Cannot find directory. "
"Error opening directory: %s\n"),
directory);
}
closedir(dir);
}
return fileNames;
}
extern "C" {
PUBLIC int csoundModuleInit_ftsamplebank(CSOUND *csound) {
int status = csound->AppendOpcode(
csound, (char *)"ftsamplebank.k", sizeof(kftsamplebank), 0, 3,
(char *)"k", (char *)"Skkkkk",
(int (*)(CSOUND *, void *))kftsamplebank::init_,
(int (*)(CSOUND *, void *))kftsamplebank::kontrol_,
(int (*)(CSOUND *, void *))0);
status |= csound->AppendOpcode(
csound, (char *)"ftsamplebank.i", sizeof(iftsamplebank), 0, 1,
(char *)"i", (char *)"Siiii",
(int (*)(CSOUND *, void *))iftsamplebank::init_,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
/* status |= csound->AppendOpcode(csound,
(char*)"ftsamplebank",
0xffff,
0,
0,
0,
0,
0,
0,
0); */
status |= csound->AppendOpcode(
csound, (char *)"directory", sizeof(DIR_STRUCT), 0, 1, (char *)"S[]",
(char *)"SN", (int (*)(CSOUND *, void *))directory,
(int (*)(CSOUND *, void *))0, (int (*)(CSOUND *, void *))0);
return status;
}
#ifndef INIT_STATIC_MODULES
PUBLIC int csoundModuleCreate(CSOUND *csound) {
IGN(csound);
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound) {
return csoundModuleInit_ftsamplebank(csound);
}
PUBLIC int csoundModuleDestroy(CSOUND *csound) {
IGN(csound);
return 0;
}
#endif
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <zlib.h>
#include "vector_tile.pb.h"
#define XMAX 4096
#define YMAX 4096
extern "C" {
#include "graphics.h"
#include "clip.h"
}
class env {
public:
mapnik::vector::tile tile;
mapnik::vector::tile_layer *layer;
mapnik::vector::tile_feature *feature;
int x;
int y;
int cmd_idx;
int cmd;
int length;
};
#define MOVE_TO 1
#define LINE_TO 2
#define CLOSE_PATH 7
#define CMD_BITS 3
double *graphics_init() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
env *e = new env;
e->layer = e->tile.add_layers();
e->layer->set_name("world");
e->layer->set_version(1);
e->layer->set_extent(4096);
e->feature = e->layer->add_features();
e->feature->set_type(mapnik::vector::tile::LineString);
e->x = 0;
e->y = 0;
e->cmd_idx = -1;
e->cmd = -1;
e->length = 0;
return (double *) e;
}
// from mapnik-vector-tile/src/vector_tile_compression.hpp
static inline int compress(std::string const& input, std::string & output)
{
z_stream deflate_s;
deflate_s.zalloc = Z_NULL;
deflate_s.zfree = Z_NULL;
deflate_s.opaque = Z_NULL;
deflate_s.avail_in = 0;
deflate_s.next_in = Z_NULL;
deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);
deflate_s.next_in = (Bytef *)input.data();
deflate_s.avail_in = input.size();
size_t length = 0;
do {
size_t increase = input.size() / 2 + 1024;
output.resize(length + increase);
deflate_s.avail_out = increase;
deflate_s.next_out = (Bytef *)(output.data() + length);
int ret = deflate(&deflate_s, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {
return -1;
}
length += (increase - deflate_s.avail_out);
} while (deflate_s.avail_out == 0);
deflateEnd(&deflate_s);
output.resize(length);
return 0;
}
void out(double *src, double *cx, double *cy, int width, int height, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask) {
env *e = (env *) src;
if (e->cmd_idx >= 0) {
//printf("old command: %d %d\n", e->cmd, e->length);
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
std::string s;
e->tile.SerializeToString(&s);
std::string compressed;
compress(s, compressed);
std::cout << compressed;
}
static void op(env *e, int cmd, int x, int y) {
if (cmd != e->cmd) {
if (e->cmd_idx >= 0) {
//printf("old command: %d %d\n", e->cmd, e->length);
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
e->cmd = cmd;
e->length = 0;
e->cmd_idx = e->feature->geometry_size();
e->feature->add_geometry(0); // placeholder
}
if (cmd == MOVE_TO || cmd == LINE_TO) {
int dx = x - e->x;
int dy = y - e->y;
//printf("new geom: %d %d\n", x, y);
e->feature->add_geometry((dx << 1) ^ (dx >> 31));
e->feature->add_geometry((dy << 1) ^ (dy >> 31));
e->x = x;
e->y = y;
e->length++;
} else if (cmd == CLOSE_PATH) {
e->length++;
}
}
int drawClip(double x0, double y0, double x1, double y1, double *image, double *cx, double *cy, double bright, double hue, int antialias, double thick) {
int accept = clip(&x0, &y0, &x1, &y1, 0, 0, XMAX / 16.0, YMAX / 16.0);
if (accept) {
int xx0 = x0 * 16;
int yy0 = y0 * 16;
int xx1 = x1 * 16;
int yy1 = y1 * 16;
// Guarding against rounding error
if (xx0 < 0) {
xx0 = 0;
}
if (xx0 > 4095) {
xx0 = 4095;
}
if (yy0 < 0) {
yy0 = 0;
}
if (yy0 > 4095) {
yy0 = 4095;
}
if (xx1 < 0) {
xx1 = 0;
}
if (xx1 > 4095) {
xx1 = 4095;
}
if (yy1 < 0) {
yy1 = 0;
}
if (yy1 > 4095) {
yy1 = 4095;
}
env *e = (env *) image;
op(e, MOVE_TO, xx0, yy0);
op(e, LINE_TO, xx1, yy1);
// op(e, CLOSE_PATH, 0, 0);
}
return 0;
}
void drawPixel(double x, double y, double *image, double *cx, double *cy, double bright, double hue) {
}
void drawBrush(double x, double y, double *image, double *cx, double *cy, double bright, double brush, double hue) {
}
<commit_msg>Accumulate lines into a buffer instead of outputting directly.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <zlib.h>
#include "vector_tile.pb.h"
#define XMAX 4096
#define YMAX 4096
extern "C" {
#include "graphics.h"
#include "clip.h"
}
struct line {
int x0;
int y0;
int x1;
int y1;
};
int linecmp(const void *v1, const void *v2) {
const struct line *l1 = (const struct line *) v1;
const struct line *l2 = (const struct line *) v2;
if (l1->x0 != l2->x0) {
return l1->x0 - l2->x0;
}
if (l1->x1 != l2->x1) {
return l1->x1 - l2->x1;
}
if (l1->y0 != l2->y0) {
return l1->y0 - l2->y0;
}
return l1->y1 - l2->y1;
}
class env {
public:
mapnik::vector::tile tile;
mapnik::vector::tile_layer *layer;
mapnik::vector::tile_feature *feature;
int x;
int y;
int cmd_idx;
int cmd;
int length;
struct line *lines;
int nlines;
int nlalloc;
};
#define MOVE_TO 1
#define LINE_TO 2
#define CLOSE_PATH 7
#define CMD_BITS 3
double *graphics_init() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
env *e = new env;
e->nlalloc = 1024;
e->nlines = 0;
e->lines = (struct line *) malloc(e->nlalloc * sizeof(struct line));
return (double *) e;
}
// from mapnik-vector-tile/src/vector_tile_compression.hpp
static inline int compress(std::string const& input, std::string & output)
{
z_stream deflate_s;
deflate_s.zalloc = Z_NULL;
deflate_s.zfree = Z_NULL;
deflate_s.opaque = Z_NULL;
deflate_s.avail_in = 0;
deflate_s.next_in = Z_NULL;
deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);
deflate_s.next_in = (Bytef *)input.data();
deflate_s.avail_in = input.size();
size_t length = 0;
do {
size_t increase = input.size() / 2 + 1024;
output.resize(length + increase);
deflate_s.avail_out = increase;
deflate_s.next_out = (Bytef *)(output.data() + length);
int ret = deflate(&deflate_s, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {
return -1;
}
length += (increase - deflate_s.avail_out);
} while (deflate_s.avail_out == 0);
deflateEnd(&deflate_s);
output.resize(length);
return 0;
}
static void op(env *e, int cmd, int x, int y);
void out(double *src, double *cx, double *cy, int width, int height, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask) {
env *e = (env *) src;
// qsort(e->lines, e->nlines, sizeof(struct line), linecmp);
e->layer = e->tile.add_layers();
e->layer->set_name("world");
e->layer->set_version(1);
e->layer->set_extent(4096);
e->feature = e->layer->add_features();
e->feature->set_type(mapnik::vector::tile::LineString);
e->x = 0;
e->y = 0;
e->cmd_idx = -1;
e->cmd = -1;
e->length = 0;
int i;
for (i = 0; i < e->nlines; i++) {
op(e, MOVE_TO, e->lines[i].x0, e->lines[i].y0);
op(e, LINE_TO, e->lines[i].x1, e->lines[i].y1);
}
if (e->cmd_idx >= 0) {
//printf("old command: %d %d\n", e->cmd, e->length);
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
std::string s;
e->tile.SerializeToString(&s);
std::string compressed;
compress(s, compressed);
std::cout << compressed;
}
static void op(env *e, int cmd, int x, int y) {
// printf("from cmd %d to %d\n", e->cmd, cmd);
if (cmd != e->cmd) {
if (e->cmd_idx >= 0) {
// printf("old command: %d %d\n", e->cmd, e->length);
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
e->cmd = cmd;
e->length = 0;
e->cmd_idx = e->feature->geometry_size();
e->feature->add_geometry(0); // placeholder
}
if (cmd == MOVE_TO || cmd == LINE_TO) {
int dx = x - e->x;
int dy = y - e->y;
// printf("new geom: %d %d\n", x, y);
e->feature->add_geometry((dx << 1) ^ (dx >> 31));
e->feature->add_geometry((dy << 1) ^ (dy >> 31));
e->x = x;
e->y = y;
e->length++;
} else if (cmd == CLOSE_PATH) {
e->length++;
}
}
int drawClip(double x0, double y0, double x1, double y1, double *image, double *cx, double *cy, double bright, double hue, int antialias, double thick) {
int accept = clip(&x0, &y0, &x1, &y1, 0, 0, XMAX / 16.0, YMAX / 16.0);
if (accept) {
int xx0 = x0 * 16;
int yy0 = y0 * 16;
int xx1 = x1 * 16;
int yy1 = y1 * 16;
// Guarding against rounding error
if (xx0 < 0) {
xx0 = 0;
}
if (xx0 > 4095) {
xx0 = 4095;
}
if (yy0 < 0) {
yy0 = 0;
}
if (yy0 > 4095) {
yy0 = 4095;
}
if (xx1 < 0) {
xx1 = 0;
}
if (xx1 > 4095) {
xx1 = 4095;
}
if (yy1 < 0) {
yy1 = 0;
}
if (yy1 > 4095) {
yy1 = 4095;
}
env *e = (env *) image;
if (e->nlines + 1 >= e->nlalloc) {
e->nlalloc *= 2;
e->lines = (struct line *) realloc((void *) e->lines, e->nlalloc * sizeof(struct line));
}
e->lines[e->nlines].x0 = xx0;
e->lines[e->nlines].y0 = yy0;
e->lines[e->nlines].x1 = xx1;
e->lines[e->nlines].y1 = yy1;
e->nlines++;
}
return 0;
}
void drawPixel(double x, double y, double *image, double *cx, double *cy, double bright, double hue) {
}
void drawBrush(double x, double y, double *image, double *cx, double *cy, double bright, double brush, double hue) {
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#include <sstream>
#else
#include <iostream>
#include <sstream>
#endif
#include <stdio.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ostringstream;
#endif
#include <xercesc/parsers/DOMParser.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
void
setHelp(FileUtility& h)
{
h.args.getHelpStream() << endl
<< "conf dir [-sub -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
"output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(const XalanDOMString& currentFile)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (equals(currentFile, excludeStylesheets[i]))
{
return true;
}
}
return false;
}
void
parseWithTransformer(
int sourceType,
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XMLFileReporter& logFile,
FileUtility& h)
{
const XalanParsedSource* parsedSource = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
}
else
{
xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree");
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
else
{
xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
}
void
parseWithXerces(
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XMLFileReporter& logFile,
FileUtility& h)
{
h.data.xmlFormat = XalanDOMString("Xerces_DOM");
DOMParser theParser;
theParser.setToCreateXMLDeclTypeNode(false);
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOM_Document theDOM = theParser.getDocument();
theDOM.normalize();
XercesDOMSupport theDOMSupport;
XercesParserLiaison theParserLiaison;
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId()));
xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
try
{
HarnessInit xmlPlatformUtils;
FileUtility h;
// Set the program help string, then get the command line parameters.
//
setHelp(h);
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer::initialize();
{
XalanTransformer xalan;
// Get drive designation for final analysis and generate Unique name for results log.
//
const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis
const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name.
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + FileUtility::s_xmlSuffix);
// Open results log, and do some initialization of result data.
//
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet");
// Get the list of Directories that are below conf and iterate through them
//
// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
bool foundDir = false;
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString currentDir(dirs[j]);
if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
{
continue;
}
// Check that output directory is there.
//
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
if (checkForExclusion(currentFile))
continue;
h.data.testOrFile = currentFile;
const XalanDOMString theXSLFile = h.args.base + currentDir + FileUtility::s_pathSep + currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile = h.args.gold + currentDir + FileUtility::s_pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + FileUtility::s_pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
cout << "Failed to PARSE stylesheet for " << currentFile << endl;
h.data.fail += 1;
logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
case 2:
parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
}
XalanTransformer::terminate();
}
catch(...)
{
cerr << "Initialization failed!!!" << endl << endl;
}
return 0;
}
<commit_msg>Added missing include files.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#include <sstream>
#else
#include <iostream>
#include <sstream>
#endif
#include <stdio.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ostringstream;
#endif
#include <xercesc/parsers/DOMParser.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
#include <XercesParserLiaison/XercesDOMSupport.hpp>
#include <XalanTransformer/XalanTransformer.hpp>
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>
// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
void
setHelp(FileUtility& h)
{
h.args.getHelpStream() << endl
<< "conf dir [-sub -out -gold -source (XST | XPL | DOM)]"
<< endl
<< endl
<< "dir (base directory for testcases)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl
<< "-gold dir (base directory for gold files)"
<< endl
<< "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
<< endl;
}
static const char* const excludeStylesheets[] =
{
"output22.xsl", // Excluded because it outputs EBCDIC
0
};
inline bool
checkForExclusion(const XalanDOMString& currentFile)
{
for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
{
if (equals(currentFile, excludeStylesheets[i]))
{
return true;
}
}
return false;
}
void
parseWithTransformer(
int sourceType,
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XMLFileReporter& logFile,
FileUtility& h)
{
const XalanParsedSource* parsedSource = 0;
// Parse the XML source accordingly.
//
if (sourceType != 0 )
{
xalan.parseSource(xmlInput, parsedSource, true);
h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
}
else
{
xalan.parseSource(xmlInput, parsedSource, false);
h.data.xmlFormat = XalanDOMString("XalanSourceTree");
}
// If the source was parsed correctly then perform the transform else report the failure.
//
if (parsedSource == 0)
{
// Report the failure and be sure to increment fail count.
//
cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
else
{
xalan.transform(*parsedSource, styleSheet, output);
xalan.destroyParsedSource(parsedSource);
}
}
void
parseWithXerces(
XalanTransformer& xalan,
const XSLTInputSource& xmlInput,
const XalanCompiledStylesheet* styleSheet,
const XSLTResultTarget& output,
XMLFileReporter& logFile,
FileUtility& h)
{
h.data.xmlFormat = XalanDOMString("Xerces_DOM");
DOMParser theParser;
theParser.setToCreateXMLDeclTypeNode(false);
theParser.setDoValidation(true);
theParser.setDoNamespaces(true);
theParser.parse(xmlInput);
DOM_Document theDOM = theParser.getDocument();
theDOM.normalize();
XercesDOMSupport theDOMSupport;
XercesParserLiaison theParserLiaison;
try
{
const XercesDOMWrapperParsedSource parsedSource(
theDOM,
theParserLiaison,
theDOMSupport,
XalanDOMString(xmlInput.getSystemId()));
xalan.transform(parsedSource, styleSheet, output);
}
catch(...)
{
// Report the failure and be sure to increment fail count.
//
cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
++h.data.fail;
logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
}
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
try
{
HarnessInit xmlPlatformUtils;
FileUtility h;
// Set the program help string, then get the command line parameters.
//
setHelp(h);
if (h.getParams(argc, argv, "CONF-RESULTS") == true)
{
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer::initialize();
{
XalanTransformer xalan;
// Get drive designation for final analysis and generate Unique name for results log.
//
const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis
const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name.
const XalanDOMString UniqRunid = h.generateUniqRunid();
const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + FileUtility::s_xmlSuffix);
// Open results log, and do some initialization of result data.
//
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Conformance Testing:");
h.data.xmlFormat = XalanDOMString("NotSet");
// Get the list of Directories that are below conf and iterate through them
//
// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
bool foundDir = false;
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// Skip all but the specified directory if the -sub cmd-line option was used.
//
const XalanDOMString currentDir(dirs[j]);
if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
{
continue;
}
// Check that output directory is there.
//
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
//
foundDir = true;
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);
// Log directory in results log and process it's files.
//
logFile.logTestCaseInit(currentDir);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
if (checkForExclusion(currentFile))
continue;
h.data.testOrFile = currentFile;
const XalanDOMString theXSLFile = h.args.base + currentDir + FileUtility::s_pathSep + currentFile;
// Check and see if the .xml file exists. If not skip this .xsl file and continue.
bool fileStatus = true;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
if (!fileStatus)
continue;
h.data.xmlFileURL = theXMLFile;
h.data.xslFileURL = theXSLFile;
XalanDOMString theGoldFile = h.args.gold + currentDir + FileUtility::s_pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + FileUtility::s_pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
// Report the failure and be sure to increment fail count.
//
cout << "Failed to PARSE stylesheet for " << currentFile << endl;
h.data.fail += 1;
logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
continue;
}
// Parse the Source XML based on input parameters, and then perform transform.
//
switch (h.args.source)
{
case 0:
case 1:
parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
case 2:
parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h);
break;
}
// Check and report results... Then delete compiled stylesheet.
//
h.checkResults(theOutputFile, theGoldFile, logFile);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
//
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
h.analyzeResults(xalan, resultsFile);
}
}
XalanTransformer::terminate();
}
catch(...)
{
cerr << "Initialization failed!!!" << endl << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Orbit 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 <gtest/gtest.h>
#include <memory>
#include <optional>
#include "OrbitBase/Logging.h"
#include "OrbitSsh/Error.h"
#include "OrbitSsh/Socket.h"
namespace OrbitSsh {
TEST(Socket, Create) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
}
TEST(Socket, GetSocketAddrAndPort) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
// when bound (0 for getting a free port)
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0));
const auto result = socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().addr, "127.0.0.1");
EXPECT_NE(result.value().port, -1);
}
TEST(Socket, Bind) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
// invalid ip address
ASSERT_TRUE(socket.value().Bind("256.0.0.1", 0).has_error());
ASSERT_TRUE(socket.value().Bind("localhost", 0).has_error());
// get free port from operating system
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0).has_value());
const auto result = socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().addr, "127.0.0.1");
EXPECT_NE(result.value().port, -1);
// cant have two sockets binding to the same address & port
auto socket_2 = Socket::Create();
ASSERT_TRUE(socket_2);
ASSERT_TRUE(socket_2.has_value());
ASSERT_TRUE(
socket_2.value().Bind("127.0.0.1", result.value().port).has_error());
}
TEST(Socket, Listen) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
// bind to 127.0.0.1
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0));
const auto result = socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().addr, "127.0.0.1");
EXPECT_NE(result.value().port, -1);
// can't call bind again on the same socket
EXPECT_FALSE(socket.value().Bind("127.0.0.1", 0));
// bind first then listen
socket = Socket::Create(); // fresh socket
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(socket.value().Listen());
}
TEST(Socket, Connect) {
const std::string ip_address = "127.0.0.1";
const int port = 0;
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind(ip_address, 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// connection should be possible
auto connect_socket = Socket::Create();
ASSERT_TRUE(connect_socket);
ASSERT_TRUE(connect_socket.has_value());
const auto result = connect_socket.value().Connect(addr_and_port.value());
ASSERT_TRUE(result);
// can't listen when already in use
ASSERT_FALSE(connect_socket.value().Listen());
// can't connect again when already connected
ASSERT_FALSE(connect_socket.value().Connect(ip_address, port));
}
TEST(Socket, Accept) {
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// setup connect socket
auto connect_socket = Socket::Create();
ASSERT_TRUE(connect_socket);
ASSERT_TRUE(connect_socket.has_value());
ASSERT_TRUE(connect_socket.value().Connect(addr_and_port.value()));
// accept should be possible
auto accepted_socket = listen_socket.value().Accept();
ASSERT_TRUE(accepted_socket);
}
TEST(Socket, SendAndReceive) {
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// setup client socket
auto client_socket = Socket::Create();
ASSERT_TRUE(client_socket);
ASSERT_TRUE(client_socket.has_value());
ASSERT_TRUE(client_socket.value().Connect(addr_and_port.value()));
// accept should be possible
auto server_socket = listen_socket.value().Accept();
ASSERT_TRUE(server_socket);
// listen no longer needed
listen_socket = OrbitSsh::Error::kUnknown;
// no data available -> receive would block (aka kAgain)
EXPECT_TRUE(OrbitSsh::shouldITryAgain(server_socket.value().Receive()));
EXPECT_TRUE(OrbitSsh::shouldITryAgain(client_socket.value().Receive()));
// Send client -> server
const std::string_view send_text = "test text";
EXPECT_TRUE(client_socket.value().SendBlocking(send_text));
// Receive at server
const auto result = server_socket.value().Receive();
ASSERT_TRUE(result);
EXPECT_EQ(result.value(), send_text);
// no data available -> receive would block (aka kAgain)
EXPECT_TRUE(OrbitSsh::shouldITryAgain(server_socket.value().Receive()));
EXPECT_TRUE(OrbitSsh::shouldITryAgain(client_socket.value().Receive()));
// Send server -> client
const std::string_view send_text2 = "test text 2";
ASSERT_TRUE(server_socket.value().SendBlocking(send_text2));
// Receive at client
const auto result2 = client_socket.value().Receive();
ASSERT_TRUE(result2);
EXPECT_EQ(result2.value(), send_text2);
}
TEST(Socket, Shutdown) {
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// setup client socket
auto client_socket = Socket::Create();
ASSERT_TRUE(client_socket);
ASSERT_TRUE(client_socket.has_value());
ASSERT_TRUE(client_socket.value().Connect(addr_and_port.value()));
// accept should be possible
auto server_socket = listen_socket.value().Accept();
ASSERT_TRUE(server_socket);
ASSERT_TRUE(server_socket.has_value());
// no data available -> receive would block (aka kAgain)
EXPECT_TRUE(OrbitSsh::shouldITryAgain(server_socket.value().Receive()));
EXPECT_TRUE(OrbitSsh::shouldITryAgain(client_socket.value().Receive()));
// send shutdown client
ASSERT_TRUE(client_socket.value().Shutdown());
// server should have an immidiate result with WaitDisconnect
ASSERT_TRUE(server_socket.value().WaitDisconnect());
}
} // namespace OrbitSsh
<commit_msg>Fix flaky OrbitSsh test<commit_after>// Copyright (c) 2020 The Orbit 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 <gtest/gtest.h>
#include <chrono>
#include <memory>
#include <optional>
#include <thread>
#include "OrbitBase/Logging.h"
#include "OrbitSsh/Error.h"
#include "OrbitSsh/Socket.h"
namespace OrbitSsh {
TEST(Socket, Create) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
}
TEST(Socket, GetSocketAddrAndPort) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
// when bound (0 for getting a free port)
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0));
const auto result = socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().addr, "127.0.0.1");
EXPECT_NE(result.value().port, -1);
}
TEST(Socket, Bind) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
// invalid ip address
ASSERT_TRUE(socket.value().Bind("256.0.0.1", 0).has_error());
ASSERT_TRUE(socket.value().Bind("localhost", 0).has_error());
// get free port from operating system
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0).has_value());
const auto result = socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().addr, "127.0.0.1");
EXPECT_NE(result.value().port, -1);
// cant have two sockets binding to the same address & port
auto socket_2 = Socket::Create();
ASSERT_TRUE(socket_2);
ASSERT_TRUE(socket_2.has_value());
ASSERT_TRUE(
socket_2.value().Bind("127.0.0.1", result.value().port).has_error());
}
TEST(Socket, Listen) {
auto socket = Socket::Create();
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
// bind to 127.0.0.1
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0));
const auto result = socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().addr, "127.0.0.1");
EXPECT_NE(result.value().port, -1);
// can't call bind again on the same socket
EXPECT_FALSE(socket.value().Bind("127.0.0.1", 0));
// bind first then listen
socket = Socket::Create(); // fresh socket
ASSERT_TRUE(socket);
ASSERT_TRUE(socket.has_value());
ASSERT_TRUE(socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(socket.value().Listen());
}
TEST(Socket, Connect) {
const std::string ip_address = "127.0.0.1";
const int port = 0;
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind(ip_address, 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// connection should be possible
auto connect_socket = Socket::Create();
ASSERT_TRUE(connect_socket);
ASSERT_TRUE(connect_socket.has_value());
const auto result = connect_socket.value().Connect(addr_and_port.value());
ASSERT_TRUE(result);
// can't listen when already in use
ASSERT_FALSE(connect_socket.value().Listen());
// can't connect again when already connected
ASSERT_FALSE(connect_socket.value().Connect(ip_address, port));
}
TEST(Socket, Accept) {
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// setup connect socket
auto connect_socket = Socket::Create();
ASSERT_TRUE(connect_socket);
ASSERT_TRUE(connect_socket.has_value());
ASSERT_TRUE(connect_socket.value().Connect(addr_and_port.value()));
// accept should be possible
auto accepted_socket = listen_socket.value().Accept();
ASSERT_TRUE(accepted_socket);
}
TEST(Socket, SendAndReceive) {
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// setup client socket
auto client_socket = Socket::Create();
ASSERT_TRUE(client_socket);
ASSERT_TRUE(client_socket.has_value());
ASSERT_TRUE(client_socket.value().Connect(addr_and_port.value()));
// accept should be possible
auto server_socket = listen_socket.value().Accept();
ASSERT_TRUE(server_socket);
// listen no longer needed
listen_socket = OrbitSsh::Error::kUnknown;
// no data available -> receive would block (aka kAgain)
EXPECT_TRUE(OrbitSsh::shouldITryAgain(server_socket.value().Receive()));
EXPECT_TRUE(OrbitSsh::shouldITryAgain(client_socket.value().Receive()));
// Send client -> server
const std::string_view send_text = "test text";
EXPECT_TRUE(client_socket.value().SendBlocking(send_text));
// Even though this is only a local connection, it might take a split second.
if (OrbitSsh::shouldITryAgain(server_socket.value().CanBeRead())) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// Receive at server
const auto result = server_socket.value().Receive();
ASSERT_TRUE(result);
EXPECT_EQ(result.value(), send_text);
// no data available -> receive would block (aka kAgain)
EXPECT_TRUE(OrbitSsh::shouldITryAgain(server_socket.value().Receive()));
EXPECT_TRUE(OrbitSsh::shouldITryAgain(client_socket.value().Receive()));
// Send server -> client
const std::string_view send_text2 = "test text 2";
ASSERT_TRUE(server_socket.value().SendBlocking(send_text2));
// Even though this is only a local connection, it might take a split second.
if (OrbitSsh::shouldITryAgain(client_socket.value().CanBeRead())) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// Receive at client
const auto result2 = client_socket.value().Receive();
ASSERT_TRUE(result2);
EXPECT_EQ(result2.value(), send_text2);
}
TEST(Socket, Shutdown) {
// setup listen socket
auto listen_socket = Socket::Create();
ASSERT_TRUE(listen_socket);
ASSERT_TRUE(listen_socket.has_value());
ASSERT_TRUE(listen_socket.value().Bind("127.0.0.1", 0));
ASSERT_TRUE(listen_socket.value().Listen());
const auto addr_and_port = listen_socket.value().GetSocketAddrAndPort();
ASSERT_TRUE(addr_and_port);
// setup client socket
auto client_socket = Socket::Create();
ASSERT_TRUE(client_socket);
ASSERT_TRUE(client_socket.has_value());
ASSERT_TRUE(client_socket.value().Connect(addr_and_port.value()));
// accept should be possible
auto server_socket = listen_socket.value().Accept();
ASSERT_TRUE(server_socket);
ASSERT_TRUE(server_socket.has_value());
// no data available -> receive would block (aka kAgain)
EXPECT_TRUE(OrbitSsh::shouldITryAgain(server_socket.value().Receive()));
EXPECT_TRUE(OrbitSsh::shouldITryAgain(client_socket.value().Receive()));
// send shutdown client
ASSERT_TRUE(client_socket.value().Shutdown());
// server should have an immidiate result with WaitDisconnect
ASSERT_TRUE(server_socket.value().WaitDisconnect());
}
} // namespace OrbitSsh
<|endoftext|> |
<commit_before>/******************************************************************************\
* gloperate
*
* Copyright (C) 2014 Computer Graphics Systems Group at the
* Hasso-Plattner-Institut (HPI), Potsdam, Germany.
\******************************************************************************/
#include <gloperate/base/RenderTarget.h>
namespace gloperate
{
/**
* @brief
* Standard Constructor
*/
RenderTarget::RenderTarget()
: m_valid(false)
{
}
/**
* @brief
* Constructor
*/
RenderTarget::RenderTarget(
globjects::ref_ptr<globjects::Framebuffer> framebuffer,
gl::GLenum attachment,
gl::GLenum format)
: m_framebuffer(framebuffer)
, m_attachment(attachment)
, m_format(format)
, m_valid(true)
{
}
/**
* @brief
* Copy Constructor
*/
RenderTarget::RenderTarget(
const RenderTarget & renderTarget)
: m_framebuffer(renderTarget.m_framebuffer)
, m_attachment(renderTarget.m_attachment)
, m_format(renderTarget.m_format)
, m_valid(renderTarget.m_valid)
{
}
/**
* @brief
* Destructor
*/
RenderTarget::~RenderTarget()
{
}
bool RenderTarget::isValid() const
{
return m_valid;
}
globjects::ref_ptr<globjects::Framebuffer> RenderTarget::framebuffer() const
{
return m_framebuffer;
}
gl::GLenum RenderTarget::attachment() const
{
return m_attachment;
}
gl::GLenum RenderTarget::format() const
{
return m_format;
}
} // namespace gloperate<commit_msg>Fix CID #51215<commit_after>/******************************************************************************\
* gloperate
*
* Copyright (C) 2014 Computer Graphics Systems Group at the
* Hasso-Plattner-Institut (HPI), Potsdam, Germany.
\******************************************************************************/
#include <gloperate/base/RenderTarget.h>
namespace gloperate
{
/**
* @brief
* Standard Constructor
*/
RenderTarget::RenderTarget()
: m_attachment()
, m_format()
, m_valid(false)
{
}
/**
* @brief
* Constructor
*/
RenderTarget::RenderTarget(
globjects::ref_ptr<globjects::Framebuffer> framebuffer,
gl::GLenum attachment,
gl::GLenum format)
: m_framebuffer(framebuffer)
, m_attachment(attachment)
, m_format(format)
, m_valid(true)
{
}
/**
* @brief
* Copy Constructor
*/
RenderTarget::RenderTarget(
const RenderTarget & renderTarget)
: m_framebuffer(renderTarget.m_framebuffer)
, m_attachment(renderTarget.m_attachment)
, m_format(renderTarget.m_format)
, m_valid(renderTarget.m_valid)
{
}
/**
* @brief
* Destructor
*/
RenderTarget::~RenderTarget()
{
}
bool RenderTarget::isValid() const
{
return m_valid;
}
globjects::ref_ptr<globjects::Framebuffer> RenderTarget::framebuffer() const
{
return m_framebuffer;
}
gl::GLenum RenderTarget::attachment() const
{
return m_attachment;
}
gl::GLenum RenderTarget::format() const
{
return m_format;
}
} // namespace gloperate
<|endoftext|> |
<commit_before>#include <ir/index_manager/store/FSDirectory.h>
#include <ir/index_manager/store/FSIndexInput.h>
#include <ir/index_manager/store/FSIndexOutput.h>
#include <ir/index_manager/utility/Utilities.h>
#include <dirent.h>
#include <map>
using namespace std;
using namespace izenelib::ir::indexmanager;
FSDirectory::FSDirectory(const string& path,bool bCreate)
: nRefCount(0)
, rwLock_(NULL)
{
directory = path;
if (bCreate)
{
create();
}
if (!Utilities::dirExists(directory.c_str()))
{
string s = directory;
s += " is not a directory.";
SF1V5_THROW(ERROR_FILEIO,s);
}
rwLock_ = new izenelib::util::ReadWriteLock;
}
FSDirectory::~FSDirectory(void)
{
if(rwLock_)
delete rwLock_;
}
void FSDirectory::create()
{
if ( !Utilities::dirExists(directory.c_str()) )
{
if ( mkdir(directory.c_str(),0777) == -1 )
{
string s = "Couldn't create directory: ";
s += directory;
SF1V5_THROW(ERROR_FILEIO,s);
}
return;
}
}
FSDirectory* FSDirectory::getDirectory(const string& path,bool bCreate)
{
FSDirectory* pS = NULL;
directory_map& dm = getDirectoryMap();
directory_iterator iter = dm.find(path);
if (iter == dm.end())
{
pS = new FSDirectory(path,bCreate);
dm.insert(pair<string,FSDirectory*>(path,pS));
}
else
{
pS = iter->second;
}
pS->nRefCount++;
return pS;
}
void FSDirectory::deleteFile(const string& filename,bool throwError)
{
string fullpath = directory + "/" + filename;
if ( unlink(fullpath.c_str()) == -1 && throwError)
{
string str = "deleteFile error:";
str += fullpath;
throw FileIOException(str);
}
}
void FSDirectory::renameFile(const string& from, const string& to)
{
string tofullpath = directory + "/" + to;
string fromfullpath = directory + "/" + from;
if ( fileExists(to.c_str()) )
{
string s = to;
s += " already exist";
throw FileIOException(s);
}
else
{
if ( rename(fromfullpath.c_str(),tofullpath.c_str()) != 0 )
{
string s;
s = "couldn't rename ";
s += fromfullpath;
s += " to ";
s += tofullpath;
throw FileIOException(s);
}
}
}
void FSDirectory::deleteFiles(const string& filename,bool throwError)
{
DIR* dir = opendir(directory.c_str());
struct dirent* fl = readdir(dir);
struct stat64 buf;
string path;
string fname;
string::size_type npos = (size_t)-1;
while ( fl != NULL )
{
path = directory;
path += "/";
path += fl->d_name;
int32_t ret = stat64(path.c_str(),&buf);
if ( ret==0 && !(buf.st_mode & S_IFDIR) )
{
if ( (strcmp(fl->d_name, ".")) && (strcmp(fl->d_name, "..")) )
{
fname = fl->d_name;
string::size_type pos = fname.rfind('.');
if (pos != npos)
fname = fname.substr(0,pos);
if (fname == filename)
{
if ( ( unlink( path.c_str() ) == -1 ) && (throwError) )
{
closedir(dir);
string s;
s = "Couldn't delete file:";
s += path;
SF1V5_THROW(ERROR_FILEIO,s);
}
fname.clear();
}
}
}
fl = readdir(dir);
}
closedir(dir);
}
void FSDirectory::renameFiles(const string& from, const string& to)
{
DIR* dir = opendir(directory.c_str());
struct dirent* fl = readdir(dir);
struct stat64 buf;
string path,fname,fext,s;
string::size_type npos = (size_t)-1;
while ( fl != NULL )
{
path = directory;
path += "/";
path += fl->d_name;
int32_t ret = stat64(path.c_str(),&buf);
if ( ret==0 && !(buf.st_mode & S_IFDIR) )
{
if ( (strcmp(fl->d_name, ".")) && (strcmp(fl->d_name, "..")) )
{
s = fl->d_name;
string::size_type pos = s.rfind('.');
if (pos != npos)
{
fname = s.substr(0,pos);
fext = s.substr(pos,s.length()-pos);
}
if (fname == from)
{
renameFile(fl->d_name,to+fext);
fname.clear();
}
}
}
fl = readdir(dir);
}
closedir(dir);
}
bool FSDirectory::fileExists(const string& name) const
{
string s = directory + "/" + name;
return Utilities::dirExists(s.c_str());
}
IndexInput* FSDirectory::openInput(const string& name)
{
string fullpath = directory + "/" + name;
return new FSIndexInput(fullpath.c_str());
}
IndexInput* FSDirectory::openInput(const string& name, size_t bufsize)
{
string fullpath = directory + "/" + name;
return new FSIndexInput(fullpath.c_str(),bufsize);
}
IndexOutput* FSDirectory::createOutput(const string& name, const string& mode)
{
string fullpath = directory + "/" + name;
return new FSIndexOutput(fullpath.c_str(), mode);
}
IndexOutput* FSDirectory::createOutput(const string& name, size_t buffersize, const string& mode)
{
string fullpath = directory + "/" + name;
return new FSIndexOutput(fullpath.c_str(), buffersize, mode);
}
void FSDirectory::close()
{
nRefCount--;
if (nRefCount < 1)
{
//TODO segment error here, why
directory_map& dm = getDirectoryMap();
delete dm[directory];
//getDirectoryMap().erase(directory);
// delete this;
}
}
FSDirectory::directory_map& FSDirectory::getDirectoryMap()
{
static directory_map FS_DIRECTORIES;
return FS_DIRECTORIES;
}
<commit_msg>FSDirectory is a static variable, and it is not destoryed correctly in destructor<commit_after>#include <ir/index_manager/store/FSDirectory.h>
#include <ir/index_manager/store/FSIndexInput.h>
#include <ir/index_manager/store/FSIndexOutput.h>
#include <ir/index_manager/utility/Utilities.h>
#include <dirent.h>
#include <map>
using namespace std;
using namespace izenelib::ir::indexmanager;
FSDirectory::FSDirectory(const string& path,bool bCreate)
: nRefCount(0)
, rwLock_(NULL)
{
directory = path;
if (bCreate)
{
create();
}
if (!Utilities::dirExists(directory.c_str()))
{
string s = directory;
s += " is not a directory.";
SF1V5_THROW(ERROR_FILEIO,s);
}
rwLock_ = new izenelib::util::ReadWriteLock;
}
FSDirectory::~FSDirectory(void)
{
if(rwLock_)
delete rwLock_;
}
void FSDirectory::create()
{
if ( !Utilities::dirExists(directory.c_str()) )
{
if ( mkdir(directory.c_str(),0777) == -1 )
{
string s = "Couldn't create directory: ";
s += directory;
SF1V5_THROW(ERROR_FILEIO,s);
}
return;
}
}
FSDirectory* FSDirectory::getDirectory(const string& path,bool bCreate)
{
FSDirectory* pS = NULL;
directory_map& dm = getDirectoryMap();
directory_iterator iter = dm.find(path);
if (iter == dm.end())
{
pS = new FSDirectory(path,bCreate);
dm.insert(pair<string,FSDirectory*>(path,pS));
}
else
{
pS = iter->second;
}
pS->nRefCount++;
return pS;
}
void FSDirectory::deleteFile(const string& filename,bool throwError)
{
string fullpath = directory + "/" + filename;
if ( unlink(fullpath.c_str()) == -1 && throwError)
{
string str = "deleteFile error:";
str += fullpath;
throw FileIOException(str);
}
}
void FSDirectory::renameFile(const string& from, const string& to)
{
string tofullpath = directory + "/" + to;
string fromfullpath = directory + "/" + from;
if ( fileExists(to.c_str()) )
{
string s = to;
s += " already exist";
throw FileIOException(s);
}
else
{
if ( rename(fromfullpath.c_str(),tofullpath.c_str()) != 0 )
{
string s;
s = "couldn't rename ";
s += fromfullpath;
s += " to ";
s += tofullpath;
throw FileIOException(s);
}
}
}
void FSDirectory::deleteFiles(const string& filename,bool throwError)
{
DIR* dir = opendir(directory.c_str());
struct dirent* fl = readdir(dir);
struct stat64 buf;
string path;
string fname;
string::size_type npos = (size_t)-1;
while ( fl != NULL )
{
path = directory;
path += "/";
path += fl->d_name;
int32_t ret = stat64(path.c_str(),&buf);
if ( ret==0 && !(buf.st_mode & S_IFDIR) )
{
if ( (strcmp(fl->d_name, ".")) && (strcmp(fl->d_name, "..")) )
{
fname = fl->d_name;
string::size_type pos = fname.rfind('.');
if (pos != npos)
fname = fname.substr(0,pos);
if (fname == filename)
{
if ( ( unlink( path.c_str() ) == -1 ) && (throwError) )
{
closedir(dir);
string s;
s = "Couldn't delete file:";
s += path;
SF1V5_THROW(ERROR_FILEIO,s);
}
fname.clear();
}
}
}
fl = readdir(dir);
}
closedir(dir);
}
void FSDirectory::renameFiles(const string& from, const string& to)
{
DIR* dir = opendir(directory.c_str());
struct dirent* fl = readdir(dir);
struct stat64 buf;
string path,fname,fext,s;
string::size_type npos = (size_t)-1;
while ( fl != NULL )
{
path = directory;
path += "/";
path += fl->d_name;
int32_t ret = stat64(path.c_str(),&buf);
if ( ret==0 && !(buf.st_mode & S_IFDIR) )
{
if ( (strcmp(fl->d_name, ".")) && (strcmp(fl->d_name, "..")) )
{
s = fl->d_name;
string::size_type pos = s.rfind('.');
if (pos != npos)
{
fname = s.substr(0,pos);
fext = s.substr(pos,s.length()-pos);
}
if (fname == from)
{
renameFile(fl->d_name,to+fext);
fname.clear();
}
}
}
fl = readdir(dir);
}
closedir(dir);
}
bool FSDirectory::fileExists(const string& name) const
{
string s = directory + "/" + name;
return Utilities::dirExists(s.c_str());
}
IndexInput* FSDirectory::openInput(const string& name)
{
string fullpath = directory + "/" + name;
return new FSIndexInput(fullpath.c_str());
}
IndexInput* FSDirectory::openInput(const string& name, size_t bufsize)
{
string fullpath = directory + "/" + name;
return new FSIndexInput(fullpath.c_str(),bufsize);
}
IndexOutput* FSDirectory::createOutput(const string& name, const string& mode)
{
string fullpath = directory + "/" + name;
return new FSIndexOutput(fullpath.c_str(), mode);
}
IndexOutput* FSDirectory::createOutput(const string& name, size_t buffersize, const string& mode)
{
string fullpath = directory + "/" + name;
return new FSIndexOutput(fullpath.c_str(), buffersize, mode);
}
void FSDirectory::close()
{
nRefCount--;
if (nRefCount < 1)
{
//TODO segment error here, why
directory_map& dm = getDirectoryMap();
delete dm[directory];
dm.erase(directory);
// delete this;
}
}
FSDirectory::directory_map& FSDirectory::getDirectoryMap()
{
static directory_map FS_DIRECTORIES;
return FS_DIRECTORIES;
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <map>
#include <cstdlib>
#include <optional>
#include "acmacs-base/fmt.hh"
#include "acmacs-base/sfinae.hh"
#include "acmacs-base/to-string.hh"
// ----------------------------------------------------------------------
namespace to_json
{
inline namespace v2
{
class json
{
private:
static constexpr auto comma_after = [](auto iter, auto first) -> bool {
if (iter == first)
return false;
switch (std::prev(iter)->back()) {
case '[':
case '{':
case ':':
return false;
default:
return true;
}
};
static constexpr auto comma_before = [](auto iter) -> bool {
switch (iter->back()) {
case ']':
case '}':
case ':':
return false;
default:
return true;
}
};
static constexpr auto indent_after = [](auto iter, auto first) -> bool {
if (iter == first)
return false;
switch (std::prev(iter)->back()) {
case '[':
case '{':
return true;
default:
return false;
}
};
static constexpr auto unindent_before = [](auto iter) -> bool {
return iter->size() == 1 && (iter->front() == ']' || iter->front() == '}');
};
public:
enum class compact_output { no, yes };
enum class embed_space { no, yes };
enum class escape_double_quotes { no, yes };
std::string compact(embed_space space = embed_space::no) const
{
const std::string comma(space == embed_space::yes ? ", " : ",");
fmt::memory_buffer out;
for (auto chunk = data_.begin(); chunk != data_.end(); ++chunk) {
if (comma_after(chunk, data_.begin()) && comma_before(chunk))
fmt::format_to(out, "{}{}", comma, *chunk);
else if (space == embed_space::yes && chunk != data_.begin() && std::prev(chunk)->back() == ':')
fmt::format_to(out, " {}", *chunk);
else
fmt::format_to(out, "{}", *chunk);
}
return fmt::to_string(out);
}
std::string pretty(size_t indent) const
{
fmt::memory_buffer out;
size_t current_indent = 0;
for (auto chunk = data_.begin(); chunk != data_.end(); ++chunk) {
if (comma_after(chunk, data_.begin()) && comma_before(chunk)) {
fmt::format_to(out, ",\n{: >{}s}{}", "", current_indent, *chunk);
}
else {
if (const auto ia = indent_after(chunk, data_.begin()), ub = unindent_before(chunk); ia && !ub) {
current_indent += indent;
fmt::format_to(out, "\n{: >{}s}{}", "", current_indent, *chunk);
}
else if (!ia && ub) {
current_indent -= indent;
fmt::format_to(out, "\n{: >{}s}{}", "", current_indent, *chunk);
}
else if ((ia && ub) || chunk == data_.begin())
fmt::format_to(out, "{}", *chunk);
else if (chunk->front() == ':')
fmt::format_to(out, "{}", *chunk);
else
fmt::format_to(out, " {}", *chunk);
}
}
return fmt::to_string(out);
}
void move_before_end(json&& value) { std::move(value.data_.begin(), value.data_.end(), std::inserter(data_, std::prev(data_.end()))); }
protected:
using data_t = std::vector<std::string>;
data_t data_;
json() = default;
json(char beg, char end)
{
push_back(beg);
push_back(end);
}
void push_back(std::string_view str) { data_.emplace_back(str); }
void push_back(const char* str) { data_.emplace_back(str); }
void push_back(std::string&& str) { data_.push_back(std::move(str)); }
void push_back(char c) { data_.push_back(std::string(1, c)); }
void move(json&& value) { std::move(value.data_.begin(), value.data_.end(), std::back_inserter(data_)); }
void make_compact()
{
data_[0] = compact(embed_space::yes);
data_.erase(std::next(data_.begin()), data_.end());
}
}; // class json
class val : public json
{
public:
template <typename T> inline val(T&& a_val, escape_double_quotes esc = escape_double_quotes::no)
{
if constexpr (acmacs::sfinae::is_string_v<T>) {
if (esc == escape_double_quotes::yes)
push_back(fmt::format("\"{}\"", escape(a_val)));
else
push_back(fmt::format("\"{}\"", std::forward<T>(a_val)));
}
else if constexpr (std::numeric_limits<std::decay_t<T>>::is_integer || std::is_floating_point_v<std::decay_t<T>>)
push_back(fmt::format("{}", std::forward<T>(a_val)));
else if constexpr (acmacs::sfinae::decay_equiv_v<T, bool>)
push_back(a_val ? "true" : "false");
else
static_assert(std::is_same_v<int, std::decay_t<T>>, "invalid arg type for to_json::val");
}
static inline std::string escape(std::string_view str)
{
std::string result(static_cast<size_t>(str.size() * 1.2), ' ');
auto output = std::begin(result);
for (auto input = std::begin(str); input != std::end(str); ++input, ++output) {
switch (*input) {
case '"':
*output++ = '\\';
*output = *input;
break;
case '\n':
*output++ = '\\';
*output = 'n';
break;
case '\t':
*output = ' '; // old seqdb reader cannot read tabs
break;
default:
*output = *input;
break;
}
}
return result;
}
};
class raw : public json
{
public:
raw(std::string_view data) { push_back(data); }
raw(std::string&& data) { push_back(std::move(data)); }
};
class key_val : public json
{
public:
template <typename T> key_val(std::string_view key, T&& value, escape_double_quotes esc = escape_double_quotes::no)
{
move(val(key, esc));
push_back(':');
if constexpr (std::is_convertible_v<std::decay_t<T>, json>)
move(std::move(value));
else
move(val(std::forward<T>(value)));
}
};
class key_val_if_not_empty
{
public:
template <typename T> key_val_if_not_empty(std::string_view key, T&& value, json::escape_double_quotes esc = json::escape_double_quotes::no)
{
if (!value.empty())
kv_ = key_val(key, std::move(value), esc);
}
constexpr bool empty() const { return !kv_.has_value(); }
constexpr key_val&& get() && { return std::move(kv_.value()); }
private:
std::optional<key_val> kv_;
};
class array : public json
{
public:
array() : json('[', ']') {}
template <typename... Args> array(Args&&... args) : array() { append(std::forward<Args>(args)...); }
template <typename Iterator, typename Transformer, typename = acmacs::sfinae::iterator_t<Iterator>>
array(Iterator first, Iterator last, Transformer transformer, compact_output co = compact_output::no, escape_double_quotes esc = escape_double_quotes::no)
: array()
{
for (; first != last; ++first) {
auto value = transformer(*first);
if constexpr (std::is_convertible_v<std::decay_t<decltype(value)>, json>)
move_before_end(std::move(value));
else
move_before_end(val(std::move(value), esc));
}
if (co == compact_output::yes)
make_compact();
}
template <typename Iterator, typename = acmacs::sfinae::iterator_t<Iterator>> array(Iterator first, Iterator last, compact_output co = compact_output::no, escape_double_quotes esc = escape_double_quotes::no)
: array()
{
for (; first != last; ++first)
move_before_end(val(*first, esc));
if (co == compact_output::yes)
make_compact();
}
private:
template <typename Arg1, typename... Args> void append(Arg1&& arg1, Args&&... args)
{
if constexpr (std::is_same_v<std::decay_t<Arg1>, compact_output>) {
if (arg1 == compact_output::yes)
make_compact();
}
else if constexpr (std::is_convertible_v<std::decay_t<Arg1>, json>)
move_before_end(std::move(arg1));
else
move_before_end(val(std::forward<Arg1>(arg1)));
if constexpr (sizeof...(args) > 0)
append(std::forward<Args>(args)...);
}
};
class object : public json
{
public:
object() : json('{', '}') {}
template <typename... Args> object(Args&&... args) : object() { append(std::forward<Args>(args)...); }
bool empty() const { return data_.size() == 2; }
template <typename K, typename V> static object from(const std::map<K, V>& src)
{
object result;
for (const auto& [key, val] : src)
result.move_before_end(key_val{acmacs::to_string(key), val});
return result;
}
private:
template <typename Arg1, typename... Args> void append(Arg1&& arg1, Args&&... args)
{
if constexpr (std::is_same_v<std::decay_t<Arg1>, compact_output>) {
if (arg1 == compact_output::yes)
make_compact();
}
else {
static_assert(std::is_convertible_v<std::decay_t<Arg1>, key_val>, "invalid arg type for to_json::object, must be to_json::key_val");
move_before_end(std::move(arg1));
if constexpr (sizeof...(args) > 0)
append(std::forward<Args>(args)...);
}
}
friend object& operator<<(object& target, key_val&& kv);
friend object& operator<<(object& target, key_val_if_not_empty&& kv);
};
template <typename T> inline array& operator<<(array& target, T&& value)
{
if constexpr (std::is_convertible_v<std::decay_t<T>, json>)
target.move_before_end(std::forward<T>(value));
else
target.move_before_end(val(std::forward<T>(value)));
return target;
}
inline object& operator<<(object& target, key_val&& kv)
{
target.move_before_end(std::move(kv));
return target;
}
inline object& operator<<(object& target, key_val_if_not_empty&& kv)
{
if (!kv.empty())
target.move_before_end(std::move(kv).get());
return target;
}
} // namespace v2
} // namespace to_json
// ----------------------------------------------------------------------
// "{}" -> pretty(2)
// "{:4}" -> pretty(4)
// "{:0}" -> compact()
// "{:4c}" -> compact()
template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of<to_json::json, T>::value, char>> : fmt::formatter<std::string>
{
template <typename ParseContext> auto parse(ParseContext& ctx) -> decltype(ctx.begin())
{
auto it = ctx.begin();
if (it != ctx.end() && *it == ':')
++it;
if (it != ctx.end() && *it != '}') {
char* end;
indent_ = std::strtoul(&*it, &end, 10);
it = std::next(it, end - &*it);
}
if (*it == 'c') {
indent_ = 0; // compact anyway
++it;
}
while (it != ctx.end() && *it != '}')
++it;
return it;
}
template <typename FormatCtx> auto format(const to_json::json& js, FormatCtx& ctx)
{
if (indent_ > 0)
return fmt::formatter<std::string>::format(js.pretty(indent_), ctx);
else
return fmt::formatter<std::string>::format(js.compact(), ctx);
}
size_t indent_ = 2;
};
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>porting to g++9<commit_after>#pragma once
#include <vector>
#include <map>
#include <cstdlib>
#include <optional>
#include "acmacs-base/fmt.hh"
#include "acmacs-base/sfinae.hh"
#include "acmacs-base/to-string.hh"
// ----------------------------------------------------------------------
namespace to_json
{
inline namespace v2
{
class json
{
private:
static constexpr auto comma_after = [](auto iter, auto first) -> bool {
if (iter == first)
return false;
switch (std::prev(iter)->back()) {
case '[':
case '{':
case ':':
return false;
default:
return true;
}
};
static constexpr auto comma_before = [](auto iter) -> bool {
switch (iter->back()) {
case ']':
case '}':
case ':':
return false;
default:
return true;
}
};
static constexpr auto indent_after = [](auto iter, auto first) -> bool {
if (iter == first)
return false;
switch (std::prev(iter)->back()) {
case '[':
case '{':
return true;
default:
return false;
}
};
static constexpr auto unindent_before = [](auto iter) -> bool {
return iter->size() == 1 && (iter->front() == ']' || iter->front() == '}');
};
public:
enum class compact_output { no, yes };
enum class embed_space { no, yes };
enum class escape_double_quotes { no, yes };
std::string compact(embed_space space = embed_space::no) const
{
const std::string comma(space == embed_space::yes ? ", " : ",");
fmt::memory_buffer out;
for (auto chunk = data_.begin(); chunk != data_.end(); ++chunk) {
if (comma_after(chunk, data_.begin()) && comma_before(chunk))
fmt::format_to(out, "{}{}", comma, *chunk);
else if (space == embed_space::yes && chunk != data_.begin() && std::prev(chunk)->back() == ':')
fmt::format_to(out, " {}", *chunk);
else
fmt::format_to(out, "{}", *chunk);
}
return fmt::to_string(out);
}
std::string pretty(size_t indent) const
{
fmt::memory_buffer out;
size_t current_indent = 0;
for (auto chunk = data_.begin(); chunk != data_.end(); ++chunk) {
if (comma_after(chunk, data_.begin()) && comma_before(chunk)) {
fmt::format_to(out, ",\n{: >{}s}{}", "", current_indent, *chunk);
}
else {
if (const auto ia = indent_after(chunk, data_.begin()), ub = unindent_before(chunk); ia && !ub) {
current_indent += indent;
fmt::format_to(out, "\n{: >{}s}{}", "", current_indent, *chunk);
}
else if (!ia && ub) {
current_indent -= indent;
fmt::format_to(out, "\n{: >{}s}{}", "", current_indent, *chunk);
}
else if ((ia && ub) || chunk == data_.begin())
fmt::format_to(out, "{}", *chunk);
else if (chunk->front() == ':')
fmt::format_to(out, "{}", *chunk);
else
fmt::format_to(out, " {}", *chunk);
}
}
return fmt::to_string(out);
}
void move_before_end(json&& value) { std::move(value.data_.begin(), value.data_.end(), std::inserter(data_, std::prev(data_.end()))); }
protected:
using data_t = std::vector<std::string>;
data_t data_;
json() = default;
json(char beg, char end)
{
push_back(beg);
push_back(end);
}
void push_back(std::string_view str) { data_.emplace_back(str); }
void push_back(const char* str) { data_.emplace_back(str); }
void push_back(std::string&& str) { data_.push_back(std::move(str)); }
void push_back(char c) { data_.push_back(std::string(1, c)); }
void move(json&& value) { std::move(value.data_.begin(), value.data_.end(), std::back_inserter(data_)); }
void make_compact()
{
data_[0] = compact(embed_space::yes);
data_.erase(std::next(data_.begin()), data_.end());
}
}; // class json
class val : public json
{
public:
template <typename T> inline val(T&& a_val, escape_double_quotes esc = escape_double_quotes::no)
{
if constexpr (acmacs::sfinae::is_string_v<T>) {
if (esc == escape_double_quotes::yes)
push_back(fmt::format("\"{}\"", escape(a_val)));
else
push_back(fmt::format("\"{}\"", std::forward<T>(a_val)));
}
else if constexpr (std::numeric_limits<std::decay_t<T>>::is_integer || std::is_floating_point_v<std::decay_t<T>>)
push_back(fmt::format("{}", std::forward<T>(a_val)));
else if constexpr (acmacs::sfinae::decay_equiv_v<T, bool>)
push_back(a_val ? "true" : "false");
else
static_assert(std::is_same_v<int, std::decay_t<T>>, "invalid arg type for to_json::val");
}
static inline std::string escape(std::string_view str)
{
std::string result(static_cast<size_t>(str.size() * 1.2), ' ');
auto output = std::begin(result);
for (auto input = std::begin(str); input != std::end(str); ++input, ++output) {
switch (*input) {
case '"':
*output++ = '\\';
*output = *input;
break;
case '\n':
*output++ = '\\';
*output = 'n';
break;
case '\t':
*output = ' '; // old seqdb reader cannot read tabs
break;
default:
*output = *input;
break;
}
}
return result;
}
};
class raw : public json
{
public:
raw(std::string_view data) { push_back(data); }
raw(std::string&& data) { push_back(std::move(data)); }
};
class key_val : public json
{
public:
template <typename T> key_val(std::string_view key, T&& value, escape_double_quotes esc = escape_double_quotes::no)
{
move(val(key, esc));
push_back(':');
if constexpr (std::is_convertible_v<std::decay_t<T>, json>)
move(std::move(value));
else
move(val(std::forward<T>(value)));
}
};
class key_val_if_not_empty
{
public:
template <typename T> key_val_if_not_empty(std::string_view key, T&& value, json::escape_double_quotes esc = json::escape_double_quotes::no)
{
if (!value.empty())
kv_ = key_val(key, std::move(value), esc);
}
constexpr bool empty() const { return !kv_.has_value(); }
constexpr key_val&& get() && { return std::move(kv_.value()); }
private:
std::optional<key_val> kv_;
};
class array : public json
{
public:
array() : json('[', ']') {}
template <typename... Args> array(Args&&... args) : array() { append(std::forward<Args>(args)...); }
template <typename Iterator, typename Transformer, typename = acmacs::sfinae::iterator_t<Iterator>>
array(Iterator first, Iterator last, Transformer transformer, compact_output co = compact_output::no, [[maybe_unused]] escape_double_quotes esc = escape_double_quotes::no)
: array()
{
for (; first != last; ++first) {
auto value = transformer(*first);
if constexpr (std::is_convertible_v<std::decay_t<decltype(value)>, json>)
move_before_end(std::move(value));
else
move_before_end(val(std::move(value), esc));
}
if (co == compact_output::yes)
make_compact();
}
template <typename Iterator, typename = acmacs::sfinae::iterator_t<Iterator>> array(Iterator first, Iterator last, compact_output co = compact_output::no, escape_double_quotes esc = escape_double_quotes::no)
: array()
{
for (; first != last; ++first)
move_before_end(val(*first, esc));
if (co == compact_output::yes)
make_compact();
}
private:
template <typename Arg1, typename... Args> void append(Arg1&& arg1, Args&&... args)
{
if constexpr (std::is_same_v<std::decay_t<Arg1>, compact_output>) {
if (arg1 == compact_output::yes)
make_compact();
}
else if constexpr (std::is_convertible_v<std::decay_t<Arg1>, json>)
move_before_end(std::move(arg1));
else
move_before_end(val(std::forward<Arg1>(arg1)));
if constexpr (sizeof...(args) > 0)
append(std::forward<Args>(args)...);
}
};
class object : public json
{
public:
object() : json('{', '}') {}
template <typename... Args> object(Args&&... args) : object() { append(std::forward<Args>(args)...); }
bool empty() const { return data_.size() == 2; }
template <typename K, typename V> static object from(const std::map<K, V>& src)
{
object result;
for (const auto& [key, val] : src)
result.move_before_end(key_val{acmacs::to_string(key), val});
return result;
}
private:
template <typename Arg1, typename... Args> void append(Arg1&& arg1, Args&&... args)
{
if constexpr (std::is_same_v<std::decay_t<Arg1>, compact_output>) {
if (arg1 == compact_output::yes)
make_compact();
}
else {
static_assert(std::is_convertible_v<std::decay_t<Arg1>, key_val>, "invalid arg type for to_json::object, must be to_json::key_val");
move_before_end(std::move(arg1));
if constexpr (sizeof...(args) > 0)
append(std::forward<Args>(args)...);
}
}
friend object& operator<<(object& target, key_val&& kv);
friend object& operator<<(object& target, key_val_if_not_empty&& kv);
};
template <typename T> inline array& operator<<(array& target, T&& value)
{
if constexpr (std::is_convertible_v<std::decay_t<T>, json>)
target.move_before_end(std::forward<T>(value));
else
target.move_before_end(val(std::forward<T>(value)));
return target;
}
inline object& operator<<(object& target, key_val&& kv)
{
target.move_before_end(std::move(kv));
return target;
}
inline object& operator<<(object& target, key_val_if_not_empty&& kv)
{
if (!kv.empty())
target.move_before_end(std::move(kv).get());
return target;
}
} // namespace v2
} // namespace to_json
// ----------------------------------------------------------------------
// "{}" -> pretty(2)
// "{:4}" -> pretty(4)
// "{:0}" -> compact()
// "{:4c}" -> compact()
template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of<to_json::json, T>::value, char>> : fmt::formatter<std::string>
{
template <typename ParseContext> auto parse(ParseContext& ctx) -> decltype(ctx.begin())
{
auto it = ctx.begin();
if (it != ctx.end() && *it == ':')
++it;
if (it != ctx.end() && *it != '}') {
char* end;
indent_ = std::strtoul(&*it, &end, 10);
it = std::next(it, end - &*it);
}
if (*it == 'c') {
indent_ = 0; // compact anyway
++it;
}
while (it != ctx.end() && *it != '}')
++it;
return it;
}
template <typename FormatCtx> auto format(const to_json::json& js, FormatCtx& ctx)
{
if (indent_ > 0)
return fmt::formatter<std::string>::format(js.pretty(indent_), ctx);
else
return fmt::formatter<std::string>::format(js.compact(), ctx);
}
size_t indent_ = 2;
};
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include "getpid.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
using namespace std;
using namespace dynet;
using namespace dynet::expr;
//parameters
unsigned LAYERS = 3;
unsigned INPUT_DIM = 500;
unsigned HIDDEN_DIM = 500;
unsigned INPUT_VOCAB_SIZE = 0;
unsigned OUTPUT_VOCAB_SIZE = 0;
dynet::Dict d, devd;
int kSOS;
int kEOS;
template <class Builder>
struct EncoderDecoder {
LookupParameter p_c;
LookupParameter p_ec; // map input to embedding (used in fwd and rev models)
Parameter p_ie2h;
Parameter p_bie;
Parameter p_h2oe;
Parameter p_boe;
Parameter p_R;
Parameter p_bias;
Builder dec_builder;
Builder rev_enc_builder;
Builder fwd_enc_builder;
EncoderDecoder() {}
explicit EncoderDecoder(Model& model) :
dec_builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model),
rev_enc_builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model),
fwd_enc_builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model) {
p_ie2h = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS * 1.5), unsigned(HIDDEN_DIM * LAYERS * 2)});
p_bie = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS * 1.5)});
p_h2oe = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS), unsigned(HIDDEN_DIM * LAYERS * 1.5)});
p_boe = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS)});
p_c = model.add_lookup_parameters(INPUT_VOCAB_SIZE, {INPUT_DIM});
p_ec = model.add_lookup_parameters(INPUT_VOCAB_SIZE, {INPUT_DIM});
p_R = model.add_parameters({OUTPUT_VOCAB_SIZE, HIDDEN_DIM});
p_bias = model.add_parameters({OUTPUT_VOCAB_SIZE});
}
// build graph and return Expression for total loss
Expression BuildGraph(const vector<int>& insent, const vector<int>& osent, ComputationGraph& cg) {
// forward encoder
fwd_enc_builder.new_graph(cg);
fwd_enc_builder.start_new_sequence();
for (unsigned t = 0; t < insent.size(); ++t) {
Expression i_x_t = lookup(cg,p_ec,insent[t]);
fwd_enc_builder.add_input(i_x_t);
}
// backward encoder
rev_enc_builder.new_graph(cg);
rev_enc_builder.start_new_sequence();
for (int t = insent.size() - 1; t >= 0; --t) {
Expression i_x_t = lookup(cg, p_ec, insent[t]);
rev_enc_builder.add_input(i_x_t);
}
// encoder -> decoder transformation
vector<Expression> to;
for (auto h_l : fwd_enc_builder.final_h()) to.push_back(h_l);
for (auto h_l : rev_enc_builder.final_h()) to.push_back(h_l);
Expression i_combined = concatenate(to);
Expression i_ie2h = parameter(cg, p_ie2h);
Expression i_bie = parameter(cg, p_bie);
Expression i_t = i_bie + i_ie2h * i_combined;
cg.incremental_forward(i_t);
Expression i_h = rectify(i_t);
Expression i_h2oe = parameter(cg,p_h2oe);
Expression i_boe = parameter(cg,p_boe);
Expression i_nc = i_boe + i_h2oe * i_h;
vector<Expression> oein1, oein2, oein;
for (unsigned i = 0; i < LAYERS; ++i) {
oein1.push_back(pickrange(i_nc, i * HIDDEN_DIM, (i + 1) * HIDDEN_DIM));
oein2.push_back(tanh(oein1[i]));
}
for (unsigned i = 0; i < LAYERS; ++i) oein.push_back(oein1[i]);
for (unsigned i = 0; i < LAYERS; ++i) oein.push_back(oein2[i]);
dec_builder.new_graph(cg);
dec_builder.start_new_sequence(oein);
// decoder
Expression i_R = parameter(cg,p_R);
Expression i_bias = parameter(cg,p_bias);
vector<Expression> errs;
const unsigned oslen = osent.size() - 1;
for (unsigned t = 0; t < oslen; ++t) {
Expression i_x_t = lookup(cg, p_c, osent[t]);
Expression i_y_t = dec_builder.add_input(i_x_t);
Expression i_r_t = i_bias + i_R * i_y_t;
Expression i_ydist = log_softmax(i_r_t);
errs.push_back(pick(i_ydist,osent[t+1]));
}
Expression i_nerr = sum(errs);
return -i_nerr;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int) {
ar & p_c & p_ec;
ar & p_ie2h & p_bie & p_h2oe & p_boe & p_R & p_bias;
ar & dec_builder & rev_enc_builder & fwd_enc_builder;
}
};
int main(int argc, char** argv) {
dynet::initialize(argc, argv);
if (argc != 3 && argc != 4) {
cerr << "Usage: " << argv[0] << " corpus.txt dev.txt [model.params]\n";
return 1;
}
kSOS = d.convert("<s>");
kEOS = d.convert("</s>");
vector<vector<int>> training, dev;
string line;
int tlc = 0;
int ttoks = 0;
cerr << "Reading training data from " << argv[1] << "...\n";
{
ifstream in(argv[1]);
assert(in);
while(getline(in, line)) {
++tlc;
training.push_back(read_sentence(line, &d));
ttoks += training.back().size();
if (training.back().front() != kSOS && training.back().back() != kEOS) {
cerr << "Training sentence in " << argv[1] << ":" << tlc << " didn't start or end with <s>, </s>\n";
abort();
}
}
cerr << tlc << " lines, " << ttoks << " tokens, " << d.size() << " types\n";
}
d.freeze(); // no new word types allowed
INPUT_VOCAB_SIZE = d.size();
OUTPUT_VOCAB_SIZE = d.size();
int dlc = 0;
int dtoks = 0;
cerr << "Reading dev data from " << argv[2] << "...\n";
{
ifstream in(argv[2]);
assert(in);
while(getline(in, line)) {
++dlc;
dev.push_back(read_sentence(line, &devd));
dtoks += dev.back().size();
if (dev.back().front() != kSOS && dev.back().back() != kEOS) {
cerr << "Dev sentence in " << argv[2] << ":" << dlc << " didn't start or end with <s>, </s>\n";
abort();
}
}
cerr << dlc << " lines, " << dtoks << " tokens\n";
}
ostringstream os;
os << "bilm"
<< '_' << LAYERS
<< '_' << INPUT_DIM
<< '_' << HIDDEN_DIM
<< "-pid" << getpid() << ".params";
const string fname = os.str();
cerr << "Parameters will be written to: " << fname << endl;
double best = 9e+99;
Model model;
bool use_momentum = false;
Trainer* sgd = nullptr;
if (use_momentum)
sgd = new MomentumSGDTrainer(&model);
else
sgd = new SimpleSGDTrainer(&model);
//RNNBuilder rnn(LAYERS, INPUT_DIM, HIDDEN_DIM, &model);
//EncoderDecoder<SimpleRNNBuilder> lm(model);
EncoderDecoder<LSTMBuilder> lm;
if (argc == 4) {
string fname = argv[3];
ifstream in(fname);
boost::archive::text_iarchive ia(in);
ia >> model;
}
else {
lm = EncoderDecoder<LSTMBuilder>(model);
}
unsigned report_every_i = 50;
unsigned dev_every_i_reports = 10;
unsigned si = training.size();
vector<unsigned> order(training.size());
for (unsigned i = 0; i < order.size(); ++i) order[i] = i;
bool first = true;
int report = 0;
unsigned lines = 0;
while(1) {
Timer iteration("completed in");
double loss = 0;
unsigned chars = 0;
for (unsigned i = 0; i < report_every_i; ++i) {
if (si == training.size()) {
si = 0;
if (first) { first = false; } else { sgd->update_epoch(); }
cerr << "**SHUFFLE\n";
random_shuffle(order.begin(), order.end());
}
// build graph for this instance
ComputationGraph cg;
auto& sent = training[order[si]];
chars += sent.size() - 1;
++si;
Expression loss_expr = lm.BuildGraph(sent, sent, cg);
//cg.print_graphviz();
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
sgd->update();
++lines;
}
sgd->status();
cerr << " E = " << (loss / chars) << " ppl=" << exp(loss / chars) << ' ';
#if 0
lm.RandomSample();
#endif
// show score on dev data?
report++;
if (report % dev_every_i_reports == 0) {
double dloss = 0;
int dchars = 0;
for (auto& sent : dev) {
ComputationGraph cg;
Expression loss_expr = lm.BuildGraph(sent, sent, cg);
dloss += as_scalar(cg.forward(loss_expr));
dchars += sent.size() - 1;
}
if (dloss < best) {
best = dloss;
ofstream out(fname);
boost::archive::text_oarchive oa(out);
oa << model << lm;
}
cerr << "\n***DEV [epoch=" << (lines / (double)training.size()) << "] E = " << (dloss / dchars) << " ppl=" << exp(dloss / dchars) << ' ';
}
}
delete sgd;
}
<commit_msg>Removed unnecessary incremental_forward from encdec example<commit_after>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include "getpid.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
using namespace std;
using namespace dynet;
using namespace dynet::expr;
//parameters
unsigned LAYERS = 3;
unsigned INPUT_DIM = 500;
unsigned HIDDEN_DIM = 500;
unsigned INPUT_VOCAB_SIZE = 0;
unsigned OUTPUT_VOCAB_SIZE = 0;
dynet::Dict d, devd;
int kSOS;
int kEOS;
template <class Builder>
struct EncoderDecoder {
LookupParameter p_c;
LookupParameter p_ec; // map input to embedding (used in fwd and rev models)
Parameter p_ie2h;
Parameter p_bie;
Parameter p_h2oe;
Parameter p_boe;
Parameter p_R;
Parameter p_bias;
Builder dec_builder;
Builder rev_enc_builder;
Builder fwd_enc_builder;
EncoderDecoder() {}
explicit EncoderDecoder(Model& model) :
dec_builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model),
rev_enc_builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model),
fwd_enc_builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model) {
p_ie2h = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS * 1.5), unsigned(HIDDEN_DIM * LAYERS * 2)});
p_bie = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS * 1.5)});
p_h2oe = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS), unsigned(HIDDEN_DIM * LAYERS * 1.5)});
p_boe = model.add_parameters({unsigned(HIDDEN_DIM * LAYERS)});
p_c = model.add_lookup_parameters(INPUT_VOCAB_SIZE, {INPUT_DIM});
p_ec = model.add_lookup_parameters(INPUT_VOCAB_SIZE, {INPUT_DIM});
p_R = model.add_parameters({OUTPUT_VOCAB_SIZE, HIDDEN_DIM});
p_bias = model.add_parameters({OUTPUT_VOCAB_SIZE});
}
// build graph and return Expression for total loss
Expression BuildGraph(const vector<int>& insent, const vector<int>& osent, ComputationGraph& cg) {
// forward encoder
fwd_enc_builder.new_graph(cg);
fwd_enc_builder.start_new_sequence();
for (unsigned t = 0; t < insent.size(); ++t) {
Expression i_x_t = lookup(cg,p_ec,insent[t]);
fwd_enc_builder.add_input(i_x_t);
}
// backward encoder
rev_enc_builder.new_graph(cg);
rev_enc_builder.start_new_sequence();
for (int t = insent.size() - 1; t >= 0; --t) {
Expression i_x_t = lookup(cg, p_ec, insent[t]);
rev_enc_builder.add_input(i_x_t);
}
// encoder -> decoder transformation
vector<Expression> to;
for (auto h_l : fwd_enc_builder.final_h()) to.push_back(h_l);
for (auto h_l : rev_enc_builder.final_h()) to.push_back(h_l);
Expression i_combined = concatenate(to);
Expression i_ie2h = parameter(cg, p_ie2h);
Expression i_bie = parameter(cg, p_bie);
Expression i_t = i_bie + i_ie2h * i_combined;
Expression i_h = rectify(i_t);
Expression i_h2oe = parameter(cg,p_h2oe);
Expression i_boe = parameter(cg,p_boe);
Expression i_nc = i_boe + i_h2oe * i_h;
vector<Expression> oein1, oein2, oein;
for (unsigned i = 0; i < LAYERS; ++i) {
oein1.push_back(pickrange(i_nc, i * HIDDEN_DIM, (i + 1) * HIDDEN_DIM));
oein2.push_back(tanh(oein1[i]));
}
for (unsigned i = 0; i < LAYERS; ++i) oein.push_back(oein1[i]);
for (unsigned i = 0; i < LAYERS; ++i) oein.push_back(oein2[i]);
dec_builder.new_graph(cg);
dec_builder.start_new_sequence(oein);
// decoder
Expression i_R = parameter(cg,p_R);
Expression i_bias = parameter(cg,p_bias);
vector<Expression> errs;
const unsigned oslen = osent.size() - 1;
for (unsigned t = 0; t < oslen; ++t) {
Expression i_x_t = lookup(cg, p_c, osent[t]);
Expression i_y_t = dec_builder.add_input(i_x_t);
Expression i_r_t = i_bias + i_R * i_y_t;
Expression i_ydist = log_softmax(i_r_t);
errs.push_back(pick(i_ydist,osent[t+1]));
}
Expression i_nerr = sum(errs);
return -i_nerr;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int) {
ar & p_c & p_ec;
ar & p_ie2h & p_bie & p_h2oe & p_boe & p_R & p_bias;
ar & dec_builder & rev_enc_builder & fwd_enc_builder;
}
};
int main(int argc, char** argv) {
dynet::initialize(argc, argv);
if (argc != 3 && argc != 4) {
cerr << "Usage: " << argv[0] << " corpus.txt dev.txt [model.params]\n";
return 1;
}
kSOS = d.convert("<s>");
kEOS = d.convert("</s>");
vector<vector<int>> training, dev;
string line;
int tlc = 0;
int ttoks = 0;
cerr << "Reading training data from " << argv[1] << "...\n";
{
ifstream in(argv[1]);
assert(in);
while(getline(in, line)) {
++tlc;
training.push_back(read_sentence(line, &d));
ttoks += training.back().size();
if (training.back().front() != kSOS && training.back().back() != kEOS) {
cerr << "Training sentence in " << argv[1] << ":" << tlc << " didn't start or end with <s>, </s>\n";
abort();
}
}
cerr << tlc << " lines, " << ttoks << " tokens, " << d.size() << " types\n";
}
d.freeze(); // no new word types allowed
INPUT_VOCAB_SIZE = d.size();
OUTPUT_VOCAB_SIZE = d.size();
int dlc = 0;
int dtoks = 0;
cerr << "Reading dev data from " << argv[2] << "...\n";
{
ifstream in(argv[2]);
assert(in);
while(getline(in, line)) {
++dlc;
dev.push_back(read_sentence(line, &devd));
dtoks += dev.back().size();
if (dev.back().front() != kSOS && dev.back().back() != kEOS) {
cerr << "Dev sentence in " << argv[2] << ":" << dlc << " didn't start or end with <s>, </s>\n";
abort();
}
}
cerr << dlc << " lines, " << dtoks << " tokens\n";
}
ostringstream os;
os << "bilm"
<< '_' << LAYERS
<< '_' << INPUT_DIM
<< '_' << HIDDEN_DIM
<< "-pid" << getpid() << ".params";
const string fname = os.str();
cerr << "Parameters will be written to: " << fname << endl;
double best = 9e+99;
Model model;
bool use_momentum = false;
Trainer* sgd = nullptr;
if (use_momentum)
sgd = new MomentumSGDTrainer(&model);
else
sgd = new SimpleSGDTrainer(&model);
//RNNBuilder rnn(LAYERS, INPUT_DIM, HIDDEN_DIM, &model);
//EncoderDecoder<SimpleRNNBuilder> lm(model);
EncoderDecoder<LSTMBuilder> lm;
if (argc == 4) {
string fname = argv[3];
ifstream in(fname);
boost::archive::text_iarchive ia(in);
ia >> model;
}
else {
lm = EncoderDecoder<LSTMBuilder>(model);
}
unsigned report_every_i = 50;
unsigned dev_every_i_reports = 10;
unsigned si = training.size();
vector<unsigned> order(training.size());
for (unsigned i = 0; i < order.size(); ++i) order[i] = i;
bool first = true;
int report = 0;
unsigned lines = 0;
while(1) {
Timer iteration("completed in");
double loss = 0;
unsigned chars = 0;
for (unsigned i = 0; i < report_every_i; ++i) {
if (si == training.size()) {
si = 0;
if (first) { first = false; } else { sgd->update_epoch(); }
cerr << "**SHUFFLE\n";
random_shuffle(order.begin(), order.end());
}
// build graph for this instance
ComputationGraph cg;
auto& sent = training[order[si]];
chars += sent.size() - 1;
++si;
Expression loss_expr = lm.BuildGraph(sent, sent, cg);
//cg.print_graphviz();
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
sgd->update();
++lines;
}
sgd->status();
cerr << " E = " << (loss / chars) << " ppl=" << exp(loss / chars) << ' ';
#if 0
lm.RandomSample();
#endif
// show score on dev data?
report++;
if (report % dev_every_i_reports == 0) {
double dloss = 0;
int dchars = 0;
for (auto& sent : dev) {
ComputationGraph cg;
Expression loss_expr = lm.BuildGraph(sent, sent, cg);
dloss += as_scalar(cg.forward(loss_expr));
dchars += sent.size() - 1;
}
if (dloss < best) {
best = dloss;
ofstream out(fname);
boost::archive::text_oarchive oa(out);
oa << model << lm;
}
cerr << "\n***DEV [epoch=" << (lines / (double)training.size()) << "] E = " << (dloss / dchars) << " ppl=" << exp(dloss / dchars) << ' ';
}
}
delete sgd;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ポート・マッピング・オーダー型 @n
ポートの機能設定において、どのピンを利用するかを、選択する「型」
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2021 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ポート・マッピング・オーダー型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class port_map_order {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ポート・マッピング・オーダー型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ORDER : uint8_t {
BYPASS, ///< ポートマップの設定をバイパスする場合
FIRST, ///< 第1候補
SECOND, ///< 第2候補
THIRD, ///< 第3候補
FOURTH, ///< 第4候補
FIFTH, ///< 第5候補
SIXTH, ///< 第6候補
SEVENTH, ///< 第7候補
EIGHTH, ///< 第8候補
NINTH, ///< 第9候補
TENTH, ///< 第10候補
FIRST_I2C, ///< SCI ポートを簡易 I2C として使う場合、第1候補
SECOND_I2C, ///< SCI ポートを簡易 I2C として使う場合、第2候補
THIRD_I2C, ///< SCI ポートを簡易 I2C として使う場合、第3候補
FIRST_SPI, ///< SCI ポートを簡易 SPI として使う場合、第1候補
SECOND_SPI, ///< SCI ポートを簡易 SPI として使う場合、第2候補
THIRD_SPI, ///< SCI ポートを簡易 SPI として使う場合、第3候補
FIRST_MII, ///< ETHERC MII 接続、第1候補
SECOND_MII, ///< ETHERC MII 接続、第2候補
FIRST_RMII, ///< ETHERC RMII 接続、第1候補
SECOND_RMII, ///< ETHERC RMII 接続、第2候補
LOCAL0, ///< 独自の特殊な設定0
LOCAL1, ///< 独自の特殊な設定1
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief SCI ポート・マッピング・グループ @n
CTS/RTS はどちらか片方しか利用出来ない
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct sci_port_t {
ORDER cts_; ///< CTSx 端子の選択権
ORDER rts_; ///< RTSx 端子の選択権
ORDER rxd_; ///< RXDx 端子の選択権
ORDER sck_; ///< SCKx 端子の選択権
ORDER txd_; ///< TXDx 端子の選択権
constexpr sci_port_t(ORDER rxd = ORDER::BYPASS, ORDER txd = ORDER::BYPASS) noexcept :
cts_(ORDER::BYPASS), rts_(ORDER::BYPASS),
rxd_(rxd), sck_(ORDER::BYPASS), txd_(txd)
{ }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief USB ポート型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class USB_PORT : uint8_t {
VBUS, ///< VBUS input
EXICEN, ///< EXICEN output
VBUSEN, ///< VBUSEN output
OVRCURA, ///< OVRCURA input
OVRCURB, ///< OVRCURB input
ID, ///< ID input
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER RMII 型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ETHER_RMII : uint8_t {
REF50CK, ///< REF50CK input
CRS_DV, ///< CRS_DV input
TXD0, ///< TXD0 output
TXD1, ///< TXD1 output
RXD0, ///< RXD0 input
RXD1, ///< RXD1 input
TXD_EN, ///< TXD_EN output
RX_ER, ///< RX_ER input
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER MII 型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ETHER_MII : uint8_t {
CRS, ///< REF50CK input
RX_DV, ///< CRS_DV input
EX_OUT, ///< EX_OUT output
LINKSTA, ///< LINKSTA input
ETXD0, ///< ETXD0 output
ETXD1, ///< ETXD1 output
ETXD2, ///< ETXD2 output
ETXD3, ///< ETXD3 output
ERXD0, ///< ERXD0 input
ERXD1, ///< ERXD1 input
ERXD2, ///< ERXD2 input
ERXD3, ///< ERXD3 input
TX_EN, ///< TX_EN output
TX_ER, ///< TX_ER input
RX_ER, ///< RX_ER input
TX_CLK, ///< TX_CLK input
RX_CLK, ///< RX_CLK input
COL, ///< COL input
WOL, ///< WOL output
MDC, ///< MDC output
MDIO, ///< MDIO input/output
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER RMII ポート・マッピング・グループ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct ether_rmii_t {
ORDER ref50ck_;
ORDER crs_dv_;
ORDER txd0_;
ORDER txd1_;
ORDER rxd0_;
ORDER rxd1_;
ORDER txd_en_;
ORDER rx_er_;
ORDER mdc_;
ORDER mdio_;
ether_rmii_t() noexcept :
ref50ck_(ORDER::BYPASS),
crs_dv_(ORDER::BYPASS),
txd0_(ORDER::BYPASS),
txd1_(ORDER::BYPASS),
rxd0_(ORDER::BYPASS),
rxd1_(ORDER::BYPASS),
txd_en_(ORDER::BYPASS),
rx_er_(ORDER::BYPASS),
mdc_(ORDER::BYPASS),
mdio_(ORDER::BYPASS)
{ }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER MII ポート・マッピング・グループ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct ether_mii_t {
ORDER crs_;
ORDER rx_dv_;
ORDER exout_;
ORDER linksta_;
ORDER etxd0_;
ORDER etxd1_;
ORDER etxd2_;
ORDER etxd3_;
ORDER erxd0_;
ORDER erxd1_;
ORDER erxd2_;
ORDER erxd3_;
ORDER tx_en_;
ORDER tx_er_;
ORDER rx_er_;
ORDER tx_clk_;
ORDER rx_clk_;
ORDER col_;
ORDER wol_;
ORDER mdc_;
ORDER mdio_;
ether_mii_t() noexcept :
crs_(ORDER::BYPASS),
rx_dv_(ORDER::BYPASS),
exout_(ORDER::BYPASS),
linksta_(ORDER::BYPASS),
etxd0_(ORDER::BYPASS),
etxd1_(ORDER::BYPASS),
etxd2_(ORDER::BYPASS),
etxd3_(ORDER::BYPASS),
erxd0_(ORDER::BYPASS),
erxd1_(ORDER::BYPASS),
erxd2_(ORDER::BYPASS),
erxd3_(ORDER::BYPASS),
tx_en_(ORDER::BYPASS),
tx_er_(ORDER::BYPASS),
rx_er_(ORDER::BYPASS),
tx_clk_(ORDER::BYPASS),
rx_clk_(ORDER::BYPASS),
col_(ORDER::BYPASS),
wol_(ORDER::BYPASS),
mdc_(ORDER::BYPASS),
mdio_(ORDER::BYPASS)
{ }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ポート・マッピング・ルネサス型 @n
ルネサス社が提供するボードに対する型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class RENESAS : uint8_t {
RX72N_ENVISION_KIT, ///< RX72N Envision Kit に対する設定
};
};
}<commit_msg>Update: cleanup, CHANNEL type<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ポート・マッピング・オーダー型 @n
ポートの機能設定において、どのピンを利用するかを、選択する「型」
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2021 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ポート・マッピング・オーダー型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class port_map_order {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ポート・マッピング・オーダー型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ORDER : uint8_t {
BYPASS, ///< ポートマップの設定をバイパスする場合
FIRST, ///< 第1候補
SECOND, ///< 第2候補
THIRD, ///< 第3候補
FOURTH, ///< 第4候補
FIFTH, ///< 第5候補
SIXTH, ///< 第6候補
SEVENTH, ///< 第7候補
EIGHTH, ///< 第8候補
NINTH, ///< 第9候補
TENTH, ///< 第10候補
FIRST_I2C, ///< SCI ポートを簡易 I2C として使う場合、第1候補
SECOND_I2C, ///< SCI ポートを簡易 I2C として使う場合、第2候補
THIRD_I2C, ///< SCI ポートを簡易 I2C として使う場合、第3候補
FIRST_SPI, ///< SCI ポートを簡易 SPI として使う場合、第1候補
SECOND_SPI, ///< SCI ポートを簡易 SPI として使う場合、第2候補
THIRD_SPI, ///< SCI ポートを簡易 SPI として使う場合、第3候補
FIRST_MII, ///< ETHERC MII 接続、第1候補
SECOND_MII, ///< ETHERC MII 接続、第2候補
FIRST_RMII, ///< ETHERC RMII 接続、第1候補
SECOND_RMII, ///< ETHERC RMII 接続、第2候補
LOCAL0, ///< 独自の特殊な設定0
LOCAL1, ///< 独自の特殊な設定1
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief SCI ポート・マッピング・グループ @n
CTS/RTS はどちらか片方しか利用出来ない
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct sci_port_t {
ORDER cts_; ///< CTSx 端子の選択権
ORDER rts_; ///< RTSx 端子の選択権
ORDER rxd_; ///< RXDx 端子の選択権
ORDER sck_; ///< SCKx 端子の選択権
ORDER txd_; ///< TXDx 端子の選択権
constexpr sci_port_t(ORDER rxd = ORDER::BYPASS, ORDER txd = ORDER::BYPASS) noexcept :
cts_(ORDER::BYPASS), rts_(ORDER::BYPASS),
rxd_(rxd), sck_(ORDER::BYPASS), txd_(txd)
{ }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief タイマー・チャネル型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class CHANNEL : uint8_t {
A, ///< MTUx A (MTIOCxA), GPTWx A (GTIOCxA)
B, ///< MTUx B (MTIOCxB), GPTWx B (GTIOCxB)
C, ///< MTUx C (MTIOCxC)
D, ///< MTUx D (MTIOCxD)
U, ///< MTUy U (MTICyU)
V, ///< MTUy V (MTICyV)
W, ///< MTUy W (MTICyW)
CLK_A, ///< MTCLKA
CLK_B, ///< MTCLKB
CLK_C, ///< MTCLKC
CLK_D, ///< MTCLKD
NONE, ///< 無効なチャネル
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief USB ポート型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class USB_PORT : uint8_t {
VBUS, ///< VBUS input
EXICEN, ///< EXICEN output
VBUSEN, ///< VBUSEN output
OVRCURA, ///< OVRCURA input
OVRCURB, ///< OVRCURB input
ID, ///< ID input
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER RMII 型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ETHER_RMII : uint8_t {
REF50CK, ///< REF50CK input
CRS_DV, ///< CRS_DV input
TXD0, ///< TXD0 output
TXD1, ///< TXD1 output
RXD0, ///< RXD0 input
RXD1, ///< RXD1 input
TXD_EN, ///< TXD_EN output
RX_ER, ///< RX_ER input
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER MII 型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class ETHER_MII : uint8_t {
CRS, ///< REF50CK input
RX_DV, ///< CRS_DV input
EX_OUT, ///< EX_OUT output
LINKSTA, ///< LINKSTA input
ETXD0, ///< ETXD0 output
ETXD1, ///< ETXD1 output
ETXD2, ///< ETXD2 output
ETXD3, ///< ETXD3 output
ERXD0, ///< ERXD0 input
ERXD1, ///< ERXD1 input
ERXD2, ///< ERXD2 input
ERXD3, ///< ERXD3 input
TX_EN, ///< TX_EN output
TX_ER, ///< TX_ER input
RX_ER, ///< RX_ER input
TX_CLK, ///< TX_CLK input
RX_CLK, ///< RX_CLK input
COL, ///< COL input
WOL, ///< WOL output
MDC, ///< MDC output
MDIO, ///< MDIO input/output
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER RMII ポート・マッピング・グループ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct ether_rmii_t {
ORDER ref50ck_;
ORDER crs_dv_;
ORDER txd0_;
ORDER txd1_;
ORDER rxd0_;
ORDER rxd1_;
ORDER txd_en_;
ORDER rx_er_;
ORDER mdc_;
ORDER mdio_;
ether_rmii_t() noexcept :
ref50ck_(ORDER::BYPASS),
crs_dv_(ORDER::BYPASS),
txd0_(ORDER::BYPASS),
txd1_(ORDER::BYPASS),
rxd0_(ORDER::BYPASS),
rxd1_(ORDER::BYPASS),
txd_en_(ORDER::BYPASS),
rx_er_(ORDER::BYPASS),
mdc_(ORDER::BYPASS),
mdio_(ORDER::BYPASS)
{ }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ETHER MII ポート・マッピング・グループ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct ether_mii_t {
ORDER crs_;
ORDER rx_dv_;
ORDER exout_;
ORDER linksta_;
ORDER etxd0_;
ORDER etxd1_;
ORDER etxd2_;
ORDER etxd3_;
ORDER erxd0_;
ORDER erxd1_;
ORDER erxd2_;
ORDER erxd3_;
ORDER tx_en_;
ORDER tx_er_;
ORDER rx_er_;
ORDER tx_clk_;
ORDER rx_clk_;
ORDER col_;
ORDER wol_;
ORDER mdc_;
ORDER mdio_;
ether_mii_t() noexcept :
crs_(ORDER::BYPASS),
rx_dv_(ORDER::BYPASS),
exout_(ORDER::BYPASS),
linksta_(ORDER::BYPASS),
etxd0_(ORDER::BYPASS),
etxd1_(ORDER::BYPASS),
etxd2_(ORDER::BYPASS),
etxd3_(ORDER::BYPASS),
erxd0_(ORDER::BYPASS),
erxd1_(ORDER::BYPASS),
erxd2_(ORDER::BYPASS),
erxd3_(ORDER::BYPASS),
tx_en_(ORDER::BYPASS),
tx_er_(ORDER::BYPASS),
rx_er_(ORDER::BYPASS),
tx_clk_(ORDER::BYPASS),
rx_clk_(ORDER::BYPASS),
col_(ORDER::BYPASS),
wol_(ORDER::BYPASS),
mdc_(ORDER::BYPASS),
mdio_(ORDER::BYPASS)
{ }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ポート・マッピング・ルネサス型 @n
ルネサス社が提供するボードに対する型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class RENESAS : uint8_t {
RX72N_ENVISION_KIT, ///< RX72N Envision Kit に対する設定
};
};
}<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.