text
stringlengths 54
60.6k
|
|---|
<commit_before>// Copyright 2012 the V8 project 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:
//
// * 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 Google Inc. 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.
#include "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 22
#define BUILD_NUMBER 6
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<commit_msg>Prepare push to trunk. Now working on version 3.22.7.<commit_after>// Copyright 2012 the V8 project 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:
//
// * 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 Google Inc. 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.
#include "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 22
#define BUILD_NUMBER 7
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<|endoftext|>
|
<commit_before>
#include "viewer.h"
nanogui::Screen *screen = nullptr;
Control control;
Loader loader;
float width = 800;
float height = 800;
bool mouseDown = false;
bool orthographic = false;
bool wireframe = false;
float cameraViewAngle = 45.0;
float cameraNear = 1.0;
float cameraFar = 100.0;
float lineWidth = 0.5f;
float cameraZoom = 3.0f;
float modelZoom = 3.0f;
Eigen::Matrix4f viewMatrix = Eigen::Matrix4f::Identity();
Eigen::Matrix4f projMatrix = Eigen::Matrix4f::Identity();
Eigen::Matrix4f modelMatrix = Eigen::Matrix4f::Identity();
Eigen::Quaternionf arcballQuat = Eigen::Quaternionf::Identity();
Eigen::Vector3f center(0, 1, 0);
Eigen::Vector4f lineColor(1.0f, 1.0f, 1.0f, 1.0f);
Eigen::Vector3f cameraEye(0, 0, 5);
Eigen::Vector3f cameraCenter(0, 1, 0);
Eigen::Vector3f cameraUp(0, 1, 0);
Eigen::Vector3f modelTranslation(0, 0, 0);
Eigen::Vector4f viewport(0, 0, 800, 800);
float currentMouseX;
float currentMouseY;
float mouseDownX;
float mouseDownY;
float mouseDownZ;
Eigen::Quaternionf mouseDownRotation;
void Viewer::init() {
glfwInit();
glfwSetTime(0);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 0);
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GLFW_ALPHA_BITS, 8);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
// glEnable(GL_DEPTH_TEST);
// glEnable(GL_LIGHTING);
window = glfwCreateWindow(width, height, "CAD app", nullptr, nullptr);
glfwMakeContextCurrent(window);
glViewport(0, 0, width, height);
glfwSwapInterval(0);
glfwSwapBuffers(window);
int windowWidth, windowHeight;
glfwGetWindowSize(window, &windowWidth, &windowHeight);
screen = new nanogui::Screen();
screen->initialize(window, true);
nanogui::FormHelper *gui = new nanogui::FormHelper(screen);
nanogui::ref<nanogui::Window> guiWindow = gui->addWindow(Eigen::Vector2i(10, 10), "Main Menu");
gui->addGroup("Workspace");
gui->addButton("Load", [&]() { this->load(); });
// gui->addButton("Save", [&]() { this->save(); });
gui->addVariable("Wireframe", wireframe);
screen->setVisible(true);
screen->performLayout();
}
void Viewer::load() {
std::string filename = nanogui::file_dialog({
{"obj", "Wavefront OBJ"}
}, false);
std::cout << filename << std::endl;
if (filename.empty()) {
return;
}
Eigen::MatrixXf V;
Eigen::MatrixXi F;
loader.loadObj(filename, V, F);
mesh.set(V, F);
// this->mesh.setUv(vertexUvs, faceUvs);
// core.align_camera_center(data.V,data.F);
}
void Viewer::save() {
std::cout << "save" << std::endl;
}
void Viewer::computeCameraMatries() {
modelMatrix = Eigen::Matrix4f::Identity();
viewMatrix = Eigen::Matrix4f::Identity();
projMatrix = Eigen::Matrix4f::Identity();
// Set view parameters
viewMatrix = control.lookAt(cameraEye, cameraCenter, cameraUp);
// Set projection paramters
if (orthographic) {
float length = (cameraEye - cameraCenter).norm();
float h = tan(cameraViewAngle/360.0 * M_PI) * (length);
float left = -h * width / height;
float right = h * width / height;
float bottom = -h;
float top = h;
projMatrix = control.ortho(left, right, bottom, top, cameraNear, cameraFar);
} else {
float fH = tan(cameraViewAngle / 360.0 * M_PI) * cameraNear;
float fW = fH * width / height;
float left = -fW;
float right = fW;
float bottom = -fH;
float top = fH;
projMatrix = control.frustum(left, right, bottom, top, cameraNear, cameraFar);
}
// Set model parameters
modelMatrix = control.quatToMatrix(arcballQuat);
modelMatrix.topLeftCorner(3,3) *= cameraZoom;
modelMatrix.topLeftCorner(3,3) *= modelZoom;
modelMatrix.col(3).head(3) += modelMatrix.topLeftCorner(3,3)*modelTranslation;
}
void Viewer::launch() {
init();
setCallbacks();
std::cout << "Compiling shaders .. ";
std::cout.flush();
shaderMesh.initFromFiles("shader_mesh",
"../src/shader_mesh.vert",
"../src/shader_mesh.frag",
"../src/shader_mesh.geom");
shaderWireframe.initFromFiles("shader_wireframe",
"../src/shader_wireframe.vert",
"../src/shader_wireframe.frag");
std::cout << "done." << std::endl;
std::string filename = "../bunny.obj";
Eigen::MatrixXf V;
Eigen::MatrixXi F;
loader.loadObj(filename, V, F);
mesh.set(V, F);
while (glfwWindowShouldClose(window) == 0 && glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS) {
glfwPollEvents();
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
float ratio;
int frameWidth, frameHeight;
glfwGetFramebufferSize(window, &frameWidth, &frameHeight);
ratio = frameWidth / (float)frameHeight;
glViewport(0, 0, frameWidth, frameHeight);
// Set transformaition parameters
computeCameraMatries();
Eigen::Vector3f lightPosition(0.0f, 0.30f, 5.0f);
Eigen::Vector4f civ = (viewMatrix * modelMatrix).inverse() * Eigen::Vector4f(0.0f, 0.0f, 0.0f, 1.0f);
Eigen::Vector3f cameraLocal = Eigen::Vector3f(civ.head(3));
Eigen::Vector3f baseColor(0.4f, 0.4f, 0.4f);
Eigen::Vector3f specularColor(1.0f, 1.0f, 1.0f);
shaderMesh.bind();
// vertex shader
shaderMesh.uploadIndices(mesh.F);
shaderMesh.uploadAttrib("position", mesh.V);
shaderMesh.uploadAttrib("normal", mesh.N);
// geometry shader
shaderMesh.setUniform("model", modelMatrix);
shaderMesh.setUniform("view", viewMatrix);
shaderMesh.setUniform("proj", projMatrix);
shaderMesh.setUniform("light_position", lightPosition);
shaderMesh.setUniform("camera_local", cameraLocal);
// fragment shader
shaderMesh.setUniform("show_uvs", 0.0f);
shaderMesh.setUniform("base_color", baseColor);
shaderMesh.setUniform("specular_color", specularColor);
// shaderMesh.setUniform("fixed_color", Eigen::Vector4f(1.0, 1.0, 1.0, 1.0));
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0, 1.0);
shaderMesh.drawIndexed(GL_TRIANGLES, 0, mesh.F.cols());
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_LINE_SMOOTH);
shaderWireframe.bind();
shaderWireframe.uploadAttrib("position", mesh.V);
shaderWireframe.setUniform("color", baseColor);
shaderWireframe.setUniform("mvp", Eigen::Matrix4f(projMatrix * viewMatrix * modelMatrix));
shaderWireframe.drawIndexed(GL_LINES, 0, mesh.F.cols());
glfwPostEmptyEvent();
// Send texture paramters
/*
if (wireframe) {
glEnable(GL_LINE_SMOOTH);
glLineWidth(lineWidth);
glUniform4f(fixedColor, lineColor[0], lineColor[1],
lineColor[2], 1.0f);
opengl.drawMesh(false);
glUniform4f(fixedColor, 0.0f, 0.0f, 0.0f, 0.0f);
} else {
glUniform1f(textureFactor, 1.0f);
opengl.drawMesh(true);
glUniform1f(textureFactor, 0.0f);
}
*/
screen->drawContents();
screen->drawWidgets();
glfwSwapBuffers(window);
}
glfwTerminate();
}
void Viewer::debug() {
GLShader mShader;
mShader.init(
"a_simple_shader",
"#version 330\n"
"uniform mat4 modelViewProj;\n"
"in vec3 position;\n"
"void main() {\n"
" gl_Position = modelViewProj * vec4(position, 1.0);\n"
"}",
"#version 330\n"
"out vec4 color;\n"
"uniform float intensity;\n"
"void main() {\n"
" color = vec4(vec3(intensity), 1.0);\n"
"}"
);
Eigen::MatrixXi indices(3, 2);
indices.col(0) << 0, 1, 2;
indices.col(1) << 2, 3, 0;
Eigen::MatrixXf positions(3, 4);
positions.col(0) << -1, -1, 0;
positions.col(1) << 1, -1, 0;
positions.col(2) << 1, 1, 0;
positions.col(3) << -1, 1, 0;
mShader.bind();
mShader.uploadIndices(indices);
mShader.uploadAttrib("position", positions);
mShader.setUniform("intensity", 0.5f);
Eigen::Matrix4f mvp;
mvp.setIdentity();
mvp.topLeftCorner<3,3>() = Eigen::Matrix3f(Eigen::AngleAxisf((float) glfwGetTime(), Eigen::Vector3f::UnitZ())) * 0.25f;
mvp.row(0) *= (float) width / (float) height;
mShader.setUniform("modelViewProj", mvp);
mShader.drawIndexed(GL_TRIANGLES, 0, 2);
}
void Viewer::setCallbacks() {
glfwSetKeyCallback(window, [](GLFWwindow *, int key, int scancode, int action, int mods) {
screen->keyCallbackEvent(key, scancode, action, mods);
});
glfwSetCharCallback(window, [](GLFWwindow *, unsigned int codepoint) {
screen->charCallbackEvent(codepoint);
});
glfwSetDropCallback(window, [](GLFWwindow *, int count, const char **filenames) {
screen->dropCallbackEvent(count, filenames);
});
glfwSetMouseButtonCallback(window, [](GLFWwindow *, int button, int action, int modifiers) {
screen->mouseButtonCallbackEvent(button, action, modifiers);
if (action == GLFW_PRESS) {
mouseDown = true;
Eigen::Vector3f coord = control.project(center, modelMatrix, projMatrix, viewMatrix, viewport);
mouseDownX = currentMouseX;
mouseDownY = currentMouseY;
mouseDownZ = coord[2];
mouseDownRotation = arcballQuat.normalized();
} else {
mouseDown = false;
}
// mouseMode = "ROTATION";
});
glfwSetCursorPosCallback(window, [](GLFWwindow *, double x, double y) {
screen->cursorPosCallbackEvent(x, y);
float mouseX = x;
float mouseY = y;
currentMouseX = x;
currentMouseY = y;
double speed = 2.0;
if (mouseDown) {
std::cout << Eigen::Vector4f(mouseDownX, mouseDownY, mouseX, mouseY) << std::endl;
Eigen::Quaternionf diffRotation = control.motion(width, height, mouseX, mouseY, mouseDownX, mouseDownY, speed);
arcballQuat = diffRotation * mouseDownRotation;
}
});
glfwSetScrollCallback(window, [](GLFWwindow *, double x, double y) {
screen->scrollCallbackEvent(x, y);
float deltaY = y;
std::cout << deltaY << std::endl;
if (deltaY != 0) {
float mult = (1.0 + ((deltaY>0) ? 1.0 : -1.0) * 0.05);
const float minZoom = 0.1f;
cameraZoom = (cameraZoom * mult > minZoom ? cameraZoom * mult : minZoom);
}
});
glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int width, int height) {
screen->resizeCallbackEvent(width, height);
});
}
<commit_msg>Add depth test<commit_after>
#include "viewer.h"
nanogui::Screen *screen = nullptr;
Control control;
Loader loader;
float width = 800;
float height = 800;
bool mouseDown = false;
bool orthographic = false;
bool wireframe = false;
float cameraViewAngle = 45.0;
float cameraNear = 1.0;
float cameraFar = 100.0;
float lineWidth = 0.5f;
float cameraZoom = 3.0f;
float modelZoom = 3.0f;
Eigen::Matrix4f viewMatrix = Eigen::Matrix4f::Identity();
Eigen::Matrix4f projMatrix = Eigen::Matrix4f::Identity();
Eigen::Matrix4f modelMatrix = Eigen::Matrix4f::Identity();
Eigen::Quaternionf arcballQuat = Eigen::Quaternionf::Identity();
Eigen::Vector3f center(0, 1, 0);
Eigen::Vector4f lineColor(1.0f, 1.0f, 1.0f, 1.0f);
Eigen::Vector3f cameraEye(0, 0, 5);
Eigen::Vector3f cameraCenter(0, 1, 0);
Eigen::Vector3f cameraUp(0, 1, 0);
Eigen::Vector3f modelTranslation(0, 0, 0);
Eigen::Vector4f viewport(0, 0, 800, 800);
float currentMouseX;
float currentMouseY;
float mouseDownX;
float mouseDownY;
float mouseDownZ;
Eigen::Quaternionf mouseDownRotation;
void Viewer::init() {
glfwInit();
glfwSetTime(0);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 0);
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GLFW_ALPHA_BITS, 8);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
// glEnable(GL_DEPTH_TEST);
// glEnable(GL_LIGHTING);
window = glfwCreateWindow(width, height, "CAD app", nullptr, nullptr);
glfwMakeContextCurrent(window);
glViewport(0, 0, width, height);
glfwSwapInterval(0);
glfwSwapBuffers(window);
int windowWidth, windowHeight;
glfwGetWindowSize(window, &windowWidth, &windowHeight);
screen = new nanogui::Screen();
screen->initialize(window, true);
nanogui::FormHelper *gui = new nanogui::FormHelper(screen);
nanogui::ref<nanogui::Window> guiWindow = gui->addWindow(Eigen::Vector2i(10, 10), "Main Menu");
gui->addGroup("Workspace");
gui->addButton("Load", [&]() { this->load(); });
// gui->addButton("Save", [&]() { this->save(); });
gui->addVariable("Wireframe", wireframe);
screen->setVisible(true);
screen->performLayout();
}
void Viewer::load() {
std::string filename = nanogui::file_dialog({
{"obj", "Wavefront OBJ"}
}, false);
std::cout << filename << std::endl;
if (filename.empty()) {
return;
}
Eigen::MatrixXf V;
Eigen::MatrixXi F;
loader.loadObj(filename, V, F);
mesh.set(V, F);
// this->mesh.setUv(vertexUvs, faceUvs);
// core.align_camera_center(data.V,data.F);
}
void Viewer::save() {
std::cout << "save" << std::endl;
}
void Viewer::computeCameraMatries() {
modelMatrix = Eigen::Matrix4f::Identity();
viewMatrix = Eigen::Matrix4f::Identity();
projMatrix = Eigen::Matrix4f::Identity();
// Set view parameters
viewMatrix = control.lookAt(cameraEye, cameraCenter, cameraUp);
// Set projection paramters
if (orthographic) {
float length = (cameraEye - cameraCenter).norm();
float h = tan(cameraViewAngle/360.0 * M_PI) * (length);
float left = -h * width / height;
float right = h * width / height;
float bottom = -h;
float top = h;
projMatrix = control.ortho(left, right, bottom, top, cameraNear, cameraFar);
} else {
float fH = tan(cameraViewAngle / 360.0 * M_PI) * cameraNear;
float fW = fH * width / height;
float left = -fW;
float right = fW;
float bottom = -fH;
float top = fH;
projMatrix = control.frustum(left, right, bottom, top, cameraNear, cameraFar);
}
// Set model parameters
modelMatrix = control.quatToMatrix(arcballQuat);
modelMatrix.topLeftCorner(3,3) *= cameraZoom;
modelMatrix.topLeftCorner(3,3) *= modelZoom;
modelMatrix.col(3).head(3) += modelMatrix.topLeftCorner(3,3)*modelTranslation;
}
void Viewer::launch() {
init();
setCallbacks();
std::cout << "Compiling shaders .. ";
std::cout.flush();
shaderMesh.initFromFiles("shader_mesh",
"../src/shader_mesh.vert",
"../src/shader_mesh.frag",
"../src/shader_mesh.geom");
shaderWireframe.initFromFiles("shader_wireframe",
"../src/shader_wireframe.vert",
"../src/shader_wireframe.frag");
std::cout << "done." << std::endl;
std::string filename = "../bunny.obj";
Eigen::MatrixXf V;
Eigen::MatrixXi F;
loader.loadObj(filename, V, F);
mesh.set(V, F);
while (glfwWindowShouldClose(window) == 0 && glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS) {
glfwPollEvents();
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float ratio;
int frameWidth, frameHeight;
glfwGetFramebufferSize(window, &frameWidth, &frameHeight);
ratio = frameWidth / (float)frameHeight;
glViewport(0, 0, frameWidth, frameHeight);
// Set transformaition parameters
computeCameraMatries();
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
glLineWidth(1.0f);
Eigen::Vector3f lightPosition(0.0f, 0.30f, 5.0f);
Eigen::Vector4f civ = (viewMatrix * modelMatrix).inverse() * Eigen::Vector4f(0.0f, 0.0f, 0.0f, 1.0f);
Eigen::Vector3f cameraLocal = Eigen::Vector3f(civ.head(3));
Eigen::Vector3f baseColor(0.4f, 0.4f, 0.4f);
Eigen::Vector3f specularColor(1.0f, 1.0f, 1.0f);
shaderMesh.bind();
// vertex shader
shaderMesh.uploadIndices(mesh.F);
shaderMesh.uploadAttrib("position", mesh.V);
shaderMesh.uploadAttrib("normal", mesh.N);
// geometry shader
shaderMesh.setUniform("model", modelMatrix);
shaderMesh.setUniform("view", viewMatrix);
shaderMesh.setUniform("proj", projMatrix);
shaderMesh.setUniform("light_position", lightPosition);
shaderMesh.setUniform("camera_local", cameraLocal);
// fragment shader
shaderMesh.setUniform("show_uvs", 0.0f);
shaderMesh.setUniform("base_color", baseColor);
shaderMesh.setUniform("specular_color", specularColor);
// shaderMesh.setUniform("fixed_color", Eigen::Vector4f(1.0, 1.0, 1.0, 1.0));
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0, 1.0);
shaderMesh.drawIndexed(GL_TRIANGLES, 0, mesh.F.cols());
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_LINE_SMOOTH);
shaderWireframe.bind();
shaderWireframe.uploadAttrib("position", mesh.V);
shaderWireframe.setUniform("color", baseColor);
shaderWireframe.setUniform("mvp", Eigen::Matrix4f(projMatrix * viewMatrix * modelMatrix));
shaderWireframe.drawIndexed(GL_LINES, 0, mesh.F.cols());
glfwPostEmptyEvent();
// Send texture paramters
/*
if (wireframe) {
glEnable(GL_LINE_SMOOTH);
glLineWidth(lineWidth);
glUniform4f(fixedColor, lineColor[0], lineColor[1],
lineColor[2], 1.0f);
opengl.drawMesh(false);
glUniform4f(fixedColor, 0.0f, 0.0f, 0.0f, 0.0f);
} else {
glUniform1f(textureFactor, 1.0f);
opengl.drawMesh(true);
glUniform1f(textureFactor, 0.0f);
}
*/
screen->drawContents();
screen->drawWidgets();
glfwSwapBuffers(window);
}
glfwTerminate();
}
void Viewer::debug() {
GLShader mShader;
mShader.init(
"a_simple_shader",
"#version 330\n"
"uniform mat4 modelViewProj;\n"
"in vec3 position;\n"
"void main() {\n"
" gl_Position = modelViewProj * vec4(position, 1.0);\n"
"}",
"#version 330\n"
"out vec4 color;\n"
"uniform float intensity;\n"
"void main() {\n"
" color = vec4(vec3(intensity), 1.0);\n"
"}"
);
Eigen::MatrixXi indices(3, 2);
indices.col(0) << 0, 1, 2;
indices.col(1) << 2, 3, 0;
Eigen::MatrixXf positions(3, 4);
positions.col(0) << -1, -1, 0;
positions.col(1) << 1, -1, 0;
positions.col(2) << 1, 1, 0;
positions.col(3) << -1, 1, 0;
mShader.bind();
mShader.uploadIndices(indices);
mShader.uploadAttrib("position", positions);
mShader.setUniform("intensity", 0.5f);
Eigen::Matrix4f mvp;
mvp.setIdentity();
mvp.topLeftCorner<3,3>() = Eigen::Matrix3f(Eigen::AngleAxisf((float) glfwGetTime(), Eigen::Vector3f::UnitZ())) * 0.25f;
mvp.row(0) *= (float) width / (float) height;
mShader.setUniform("modelViewProj", mvp);
mShader.drawIndexed(GL_TRIANGLES, 0, 2);
}
void Viewer::setCallbacks() {
glfwSetKeyCallback(window, [](GLFWwindow *, int key, int scancode, int action, int mods) {
screen->keyCallbackEvent(key, scancode, action, mods);
});
glfwSetCharCallback(window, [](GLFWwindow *, unsigned int codepoint) {
screen->charCallbackEvent(codepoint);
});
glfwSetDropCallback(window, [](GLFWwindow *, int count, const char **filenames) {
screen->dropCallbackEvent(count, filenames);
});
glfwSetMouseButtonCallback(window, [](GLFWwindow *, int button, int action, int modifiers) {
screen->mouseButtonCallbackEvent(button, action, modifiers);
if (action == GLFW_PRESS) {
mouseDown = true;
Eigen::Vector3f coord = control.project(center, modelMatrix, projMatrix, viewMatrix, viewport);
mouseDownX = currentMouseX;
mouseDownY = currentMouseY;
mouseDownZ = coord[2];
mouseDownRotation = arcballQuat.normalized();
} else {
mouseDown = false;
}
// mouseMode = "ROTATION";
});
glfwSetCursorPosCallback(window, [](GLFWwindow *, double x, double y) {
screen->cursorPosCallbackEvent(x, y);
float mouseX = x;
float mouseY = y;
currentMouseX = x;
currentMouseY = y;
double speed = 2.0;
if (mouseDown) {
std::cout << Eigen::Vector4f(mouseDownX, mouseDownY, mouseX, mouseY) << std::endl;
Eigen::Quaternionf diffRotation = control.motion(width, height, mouseX, mouseY, mouseDownX, mouseDownY, speed);
arcballQuat = diffRotation * mouseDownRotation;
}
});
glfwSetScrollCallback(window, [](GLFWwindow *, double x, double y) {
screen->scrollCallbackEvent(x, y);
float deltaY = y;
std::cout << deltaY << std::endl;
if (deltaY != 0) {
float mult = (1.0 + ((deltaY>0) ? 1.0 : -1.0) * 0.05);
const float minZoom = 0.1f;
cameraZoom = (cameraZoom * mult > minZoom ? cameraZoom * mult : minZoom);
}
});
glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int width, int height) {
screen->resizeCallbackEvent(width, height);
});
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "Sleep.h"
#include "ThreadPool.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
class ThreadPool::MyRunnable_ : public IRunnable {
public:
MyRunnable_ (ThreadPool& threadPool)
: fThreadPool_ (threadPool)
, fCurTask_ ()
, fNextTask_ ()
, fCurTaskUpdateCritSection_ ()
{
}
public:
ThreadPool::TaskType GetCurrentTask () const
{
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
// THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK
// Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either
Assert (fCurTask_.IsNull () or fNextTask_.IsNull ()); // one or both must be null
return fCurTask_.IsNull ()? fNextTask_ : fCurTask_;
}
public:
virtual void Run () override
{
// For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability
// Keep grabbing new tasks, and running them
while (true) {
{
fThreadPool_.WaitForNextTask_ (&fNextTask_); // This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
Assert (not fNextTask_.IsNull ());
Assert (fCurTask_.IsNull ());
fCurTask_ = fNextTask_;
fNextTask_.clear ();
Assert (not fCurTask_.IsNull ());
Assert (fNextTask_.IsNull ());
}
try {
fCurTask_->Run ();
fCurTask_.clear ();
}
catch (const ThreadAbortException&) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
throw; // cancel this thread
}
catch (...) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
// other excpetions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT/IGNORE
}
}
}
private:
ThreadPool& fThreadPool_;
mutable CriticalSection fCurTaskUpdateCritSection_;
ThreadPool::TaskType fCurTask_;
ThreadPool::TaskType fNextTask_;
public:
DECLARE_USE_BLOCK_ALLOCATION(MyRunnable_);
};
/*
********************************************************************************
********************************* Execution::ThreadPool ************************
********************************************************************************
*/
ThreadPool::ThreadPool (unsigned int nThreads)
: fCriticalSection_ ()
, fAborted_ (false)
, fThreads_ ()
, fTasks_ ()
, fTasksAdded_ ()
{
SetPoolSize (nThreads);
}
unsigned int ThreadPool::GetPoolSize () const
{
AutoCriticalSection critSection (fCriticalSection_);
return fThreads_.size ();
}
void ThreadPool::SetPoolSize (unsigned int poolSize)
{
Require (not fAborted_);
AutoCriticalSection critSection (fCriticalSection_);
fThreads_.reserve (poolSize);
while (poolSize > fThreads_.size ()) {
fThreads_.push_back (mkThread_ ());
}
if (poolSize < fThreads_.size ()) {
AssertNotImplemented ();
// MUST STOP THREADS and WAIT FOR THEM TO BE DONE (OR STORE THEM SOMEPLACE ELSE - NO - I THINK MUST ABORTANDWAIT(). Unsure.
// For now - just assert!!!
// TODO:
// (1) HOIRRIBLE - NOW
fThreads_.resize (poolSize); // remove some off the end. OK if they are running?
}
}
void ThreadPool::AddTask (const TaskType& task)
{
Require (not fAborted_);
{
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.push_back (task);
}
// Notify any waiting threads to wakeup and claim the next task
fTasksAdded_.Set ();
}
void ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)
{
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
fTasks_.erase (i);
return;
}
}
}
// If we got here - its NOT in the task Q, so maybe its already running.
//
//
// TODO:
// We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.
// But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK
// actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for soemthing
// quite rare.
//
// Anyhow SB OK for now to just not allow aborting a task which has already started....
Thread thread2Kill;
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> ct = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == ct) {
thread2Kill = *i;
*i = mkThread_ ();
break;
}
}
}
if (not thread2Kill.GetStatus () != Thread::eNull) {
thread2Kill.AbortAndWaitForDone (timeout);
}
}
bool ThreadPool::IsPresent (const TaskType& task) const
{
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::const_iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
return true;
}
}
}
return IsRunning (task);
}
bool ThreadPool::IsRunning (const TaskType& task) const
{
Require (not task.IsNull ());
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> rTask = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == rTask) {
return true;
}
}
}
return false;
}
void ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const
{
// Inefficient / VERY SLOPPY impl
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
while (true) {
if (not IsPresent (task)) {
return;
}
Time::DurationSecondsType remaining = timeout - Time::GetTickCount ();
if (remaining <= 0.0) {
DoThrow (WaitTimedOutException ());
}
Execution::Sleep (min (remaining, 1.0));
}
}
vector<ThreadPool::TaskType> ThreadPool::GetTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fTasks_.size () + fThreads_.size ());
result.insert (result.begin (), fTasks_.begin (), fTasks_.end ()); // copy pending tasks
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
vector<ThreadPool::TaskType> ThreadPool::GetRunningTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fThreads_.size ());
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
size_t ThreadPool::GetTasksCount () const
{
size_t count = 0;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
count += fTasks_.size ();
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
count++;
}
}
}
return count;
}
void ThreadPool::WaitForDone (Time::DurationSecondsType timeout) const
{
Require (fAborted_);
{
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->WaitForDone (timeout - Time::GetTickCount ());
}
}
}
void ThreadPool::Abort ()
{
fAborted_ = true;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.clear ();
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->Abort ();
}
}
}
void ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)
{
Abort ();
WaitForDone (timeout);
}
// THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool
void ThreadPool::WaitForNextTask_ (TaskType* result)
{
RequireNotNull (result);
if (fAborted_) {
Execution::DoThrow (ThreadAbortException ());
}
while (true) {
{
AutoCriticalSection critSection (fCriticalSection_);
if (not fTasks_.empty ()) {
*result = fTasks_.front ();
fTasks_.pop_front ();
DbgTrace ("ThreadPool::WaitForNextTask_ () is starting a new task");
return;
}
}
// Prevent spinwaiting... This event is SET when any new item arrives
fTasksAdded_.Wait ();
}
}
Thread ThreadPool::mkThread_ ()
{
Thread t = Thread (SharedPtr<IRunnable> (new ThreadPool::MyRunnable_ (*this))); // ADD MY THREADOBJ
t.SetThreadName (L"Thread Pool");
t.Start ();
return t;
}
<commit_msg>a few Debug::TraceContextBumper and DbgTrace messages checked in (but most commented out) for threadPool debugging<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "Sleep.h"
#include "ThreadPool.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
class ThreadPool::MyRunnable_ : public IRunnable {
public:
MyRunnable_ (ThreadPool& threadPool)
: fThreadPool_ (threadPool)
, fCurTask_ ()
, fNextTask_ ()
, fCurTaskUpdateCritSection_ ()
{
}
public:
ThreadPool::TaskType GetCurrentTask () const
{
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
// THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK
// Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either
Assert (fCurTask_.IsNull () or fNextTask_.IsNull ()); // one or both must be null
return fCurTask_.IsNull ()? fNextTask_ : fCurTask_;
}
public:
virtual void Run () override
{
// For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability
// Keep grabbing new tasks, and running them
while (true) {
{
fThreadPool_.WaitForNextTask_ (&fNextTask_); // This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
Assert (not fNextTask_.IsNull ());
Assert (fCurTask_.IsNull ());
fCurTask_ = fNextTask_;
fNextTask_.clear ();
Assert (not fCurTask_.IsNull ());
Assert (fNextTask_.IsNull ());
}
try {
fCurTask_->Run ();
fCurTask_.clear ();
}
catch (const ThreadAbortException&) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
throw; // cancel this thread
}
catch (...) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
// other excpetions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT/IGNORE
}
}
}
private:
ThreadPool& fThreadPool_;
mutable CriticalSection fCurTaskUpdateCritSection_;
ThreadPool::TaskType fCurTask_;
ThreadPool::TaskType fNextTask_;
public:
DECLARE_USE_BLOCK_ALLOCATION(MyRunnable_);
};
/*
********************************************************************************
********************************* Execution::ThreadPool ************************
********************************************************************************
*/
ThreadPool::ThreadPool (unsigned int nThreads)
: fCriticalSection_ ()
, fAborted_ (false)
, fThreads_ ()
, fTasks_ ()
, fTasksAdded_ ()
{
SetPoolSize (nThreads);
}
unsigned int ThreadPool::GetPoolSize () const
{
AutoCriticalSection critSection (fCriticalSection_);
return fThreads_.size ();
}
void ThreadPool::SetPoolSize (unsigned int poolSize)
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::SetPoolSize"));
Require (not fAborted_);
AutoCriticalSection critSection (fCriticalSection_);
fThreads_.reserve (poolSize);
while (poolSize > fThreads_.size ()) {
fThreads_.push_back (mkThread_ ());
}
if (poolSize < fThreads_.size ()) {
AssertNotImplemented ();
// MUST STOP THREADS and WAIT FOR THEM TO BE DONE (OR STORE THEM SOMEPLACE ELSE - NO - I THINK MUST ABORTANDWAIT(). Unsure.
// For now - just assert!!!
// TODO:
// (1) HOIRRIBLE - NOW
fThreads_.resize (poolSize); // remove some off the end. OK if they are running?
}
}
void ThreadPool::AddTask (const TaskType& task)
{
//Debug::TraceContextBumper ctx (TSTR ("ThreadPool::AddTask"));
Require (not fAborted_);
{
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.push_back (task);
}
// Notify any waiting threads to wakeup and claim the next task
fTasksAdded_.Set ();
}
void ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::AbortTask"));
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
fTasks_.erase (i);
return;
}
}
}
// If we got here - its NOT in the task Q, so maybe its already running.
//
//
// TODO:
// We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.
// But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK
// actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for soemthing
// quite rare.
//
// Anyhow SB OK for now to just not allow aborting a task which has already started....
Thread thread2Kill;
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> ct = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == ct) {
thread2Kill = *i;
*i = mkThread_ ();
break;
}
}
}
if (not thread2Kill.GetStatus () != Thread::eNull) {
thread2Kill.AbortAndWaitForDone (timeout);
}
}
bool ThreadPool::IsPresent (const TaskType& task) const
{
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::const_iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
return true;
}
}
}
return IsRunning (task);
}
bool ThreadPool::IsRunning (const TaskType& task) const
{
Require (not task.IsNull ());
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> rTask = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == rTask) {
return true;
}
}
}
return false;
}
void ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::WaitForTask"));
// Inefficient / VERY SLOPPY impl
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
while (true) {
if (not IsPresent (task)) {
return;
}
Time::DurationSecondsType remaining = timeout - Time::GetTickCount ();
if (remaining <= 0.0) {
DoThrow (WaitTimedOutException ());
}
Execution::Sleep (min (remaining, 1.0));
}
}
vector<ThreadPool::TaskType> ThreadPool::GetTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fTasks_.size () + fThreads_.size ());
result.insert (result.begin (), fTasks_.begin (), fTasks_.end ()); // copy pending tasks
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
vector<ThreadPool::TaskType> ThreadPool::GetRunningTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fThreads_.size ());
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
size_t ThreadPool::GetTasksCount () const
{
size_t count = 0;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
count += fTasks_.size ();
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
count++;
}
}
}
return count;
}
void ThreadPool::WaitForDone (Time::DurationSecondsType timeout) const
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::WaitForDone"));
Require (fAborted_);
{
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->WaitForDone (endAt - Time::GetTickCount ());
}
}
}
void ThreadPool::Abort ()
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::Abort"));
fAborted_ = true;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.clear ();
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->Abort ();
}
}
}
void ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)
{
Abort ();
WaitForDone (timeout);
}
// THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool
void ThreadPool::WaitForNextTask_ (TaskType* result)
{
RequireNotNull (result);
if (fAborted_) {
Execution::DoThrow (ThreadAbortException ());
}
while (true) {
{
AutoCriticalSection critSection (fCriticalSection_);
if (not fTasks_.empty ()) {
*result = fTasks_.front ();
fTasks_.pop_front ();
DbgTrace ("ThreadPool::WaitForNextTask_ () is starting a new task");
return;
}
}
// Prevent spinwaiting... This event is SET when any new item arrives
//DbgTrace ("ThreadPool::WaitForNextTask_ () - about to wait for added tasks");
fTasksAdded_.Wait ();
//DbgTrace ("ThreadPool::WaitForNextTask_ () - completed wait for added tasks");
}
}
Thread ThreadPool::mkThread_ ()
{
Thread t = Thread (SharedPtr<IRunnable> (new ThreadPool::MyRunnable_ (*this))); // ADD MY THREADOBJ
t.SetThreadName (L"Thread Pool");
t.Start ();
return t;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "selxCropperComponent.h"
#include "selxCheckTemplateProperties.h"
#include "itkImageFileWriter.h"
namespace selx
{
template< int Dimensionality, class TPixel >
CropperComponent< Dimensionality, TPixel >::CropperComponent( const std::string & name,
LoggerImpl & logger ) : Superclass( name, logger ) {
this->m_LabelGeometryImageFilter
= LabelGeometryImageFilterType::New();
this->m_LabelGeometryImageFilter->CalculateOrientedBoundingBoxOn();
this->m_RegionOfInterestImageFilter
= RegionOfInterestImageFilterType::New();
this->m_Pad = 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageInterface< Dimensionality, TPixel >::Pointer component )
{
this->m_Image = component->GetItkImage();
this->m_RegionOfInterestImageFilter->SetInput(this->m_Image);
return 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMaskInterface< Dimensionality, unsigned char >::Pointer component )
{
this->m_Mask = component->GetItkImageMask();
return 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedMaskInterface< Dimensionality, unsigned char >::Pointer component )
{
this->m_Mask = component->GetItkImageFixedMask();
return 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingMaskInterface< Dimensionality, unsigned char >::Pointer component )
{
this->m_Mask = component->GetItkImageMovingMask();
return 0;
}
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImagePointer
CropperComponent< Dimensionality, TPixel >::GetItkImage()
{
return this->m_RegionOfInterestImageFilter->GetOutput();
}
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImagePointer
CropperComponent< Dimensionality, TPixel >::GetItkImageFixed()
{
return this->GetItkImage();
};
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImagePointer
CropperComponent< Dimensionality, TPixel >::GetItkImageMoving()
{
return this->GetItkImage();
};
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImageDomainPointer
CropperComponent< Dimensionality, TPixel >
::GetItkImageDomainFixed()
{
// Implicitly casted to domain (itk::ImageBase)
return this->m_RegionOfInterestImageFilter->GetOutput();
}
template< int Dimensionality, class TPixel >
void
CropperComponent< Dimensionality, TPixel >::BeforeUpdate()
{
this->m_Image->UpdateOutputInformation();
this->m_Mask->UpdateOutputInformation();
// Output information must be generated before downstream components are run
this->m_LabelGeometryImageFilter->SetInput(this->m_Mask);
this->m_LabelGeometryImageFilter->Update();
auto boundingBox = this->m_LabelGeometryImageFilter->GetBoundingBox(1);
typename itk::Index< Dimensionality > start;
start[0] = std::max(boundingBox.GetElement(0) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(0)));
start[1] = std::max(boundingBox.GetElement(2) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(1)));
if( Dimensionality > 2 ) start[2] = std::max(boundingBox.GetElement(4) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(2)));
if( Dimensionality > 3 ) start[3] = std::max(boundingBox.GetElement(6) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(3)));
{
std::stringstream ss;
ss << this->m_Image->GetLargestPossibleRegion();
this->m_Logger.Log(LogLevel::INF, "{0}: Got image with {1}", this->m_Name, ss.str());
}
typename itk::Size< Dimensionality > size;
size[0] = std::min(boundingBox.GetElement(1) - start[0] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(0)) - start[0]);
size[1] = std::min(boundingBox.GetElement(3) - start[1] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(1)) - start[1]);
if( Dimensionality > 2 ) size[2] = std::min(boundingBox.GetElement(5) - start[2] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(2)) - start[2]);
if( Dimensionality > 3 ) size[3] = std::min(boundingBox.GetElement(7) - start[3] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(3)) - start[3]);
typename ItkImageType::RegionType region(start, size);
{
std::stringstream ss;
ss << region;
this->m_Logger.Log(LogLevel::INF, "{0}: Cropping image to {1}", this->m_Name, ss.str());
}
this->m_RegionOfInterestImageFilter->SetRegionOfInterest(region);
}
template< int Dimensionality, class TPixel >
void
CropperComponent< Dimensionality, TPixel >::Update()
{
}
template< int Dimensionality, class TPixel >
bool
CropperComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
if( status == CriterionStatus::Satisfied )
{
return true;
}
else if( status == CriterionStatus::Failed )
{
return false;
}
if( criterion.first == "Pad" ) {
this->m_Pad = std::stoi( criterion.second[0] );
return true;
}
return false;
};
template< int Dimensionality, class TPixel >
bool
CropperComponent< Dimensionality, TPixel >
::ConnectionsSatisfied() {
if (!this->InterfaceAcceptor<itkImageInterface<Dimensionality, TPixel >>::GetAccepted()) {
return false;
}
if (!this->InterfaceAcceptor<itkImageMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&
!this->InterfaceAcceptor<itkImageFixedMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&
!this->InterfaceAcceptor<itkImageMovingMaskInterface<Dimensionality, unsigned char >>::GetAccepted()) {
return false;
}
return true;
}
}
<commit_msg>COMP: Fixed VS errors CropperComponent::BeforeUpdate()<commit_after>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "selxCropperComponent.h"
#include "selxCheckTemplateProperties.h"
#include "itkImageFileWriter.h"
namespace selx
{
template< int Dimensionality, class TPixel >
CropperComponent< Dimensionality, TPixel >::CropperComponent( const std::string & name,
LoggerImpl & logger ) : Superclass( name, logger ) {
this->m_LabelGeometryImageFilter
= LabelGeometryImageFilterType::New();
this->m_LabelGeometryImageFilter->CalculateOrientedBoundingBoxOn();
this->m_RegionOfInterestImageFilter
= RegionOfInterestImageFilterType::New();
this->m_Pad = 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageInterface< Dimensionality, TPixel >::Pointer component )
{
this->m_Image = component->GetItkImage();
this->m_RegionOfInterestImageFilter->SetInput(this->m_Image);
return 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMaskInterface< Dimensionality, unsigned char >::Pointer component )
{
this->m_Mask = component->GetItkImageMask();
return 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedMaskInterface< Dimensionality, unsigned char >::Pointer component )
{
this->m_Mask = component->GetItkImageFixedMask();
return 0;
}
template< int Dimensionality, class TPixel >
int
CropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingMaskInterface< Dimensionality, unsigned char >::Pointer component )
{
this->m_Mask = component->GetItkImageMovingMask();
return 0;
}
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImagePointer
CropperComponent< Dimensionality, TPixel >::GetItkImage()
{
return this->m_RegionOfInterestImageFilter->GetOutput();
}
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImagePointer
CropperComponent< Dimensionality, TPixel >::GetItkImageFixed()
{
return this->GetItkImage();
};
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImagePointer
CropperComponent< Dimensionality, TPixel >::GetItkImageMoving()
{
return this->GetItkImage();
};
template< int Dimensionality, class TPixel >
typename CropperComponent< Dimensionality, TPixel >::ItkImageDomainPointer
CropperComponent< Dimensionality, TPixel >
::GetItkImageDomainFixed()
{
// Implicitly casted to domain (itk::ImageBase)
return this->m_RegionOfInterestImageFilter->GetOutput();
}
template< int Dimensionality, class TPixel >
void
CropperComponent< Dimensionality, TPixel >::BeforeUpdate()
{
this->m_Image->UpdateOutputInformation();
this->m_Mask->UpdateOutputInformation();
// Output information must be generated before downstream components are run
this->m_LabelGeometryImageFilter->SetInput(this->m_Mask);
this->m_LabelGeometryImageFilter->Update();
const auto boundingBox = this->m_LabelGeometryImageFilter->GetBoundingBox(1);
const auto& largestPossibleRegion = this->m_Image->GetLargestPossibleRegion();
{
std::stringstream ss;
ss << largestPossibleRegion;
this->m_Logger.Log(LogLevel::INF, "{0}: Got image with {1}", this->m_Name, ss.str());
}
itk::Index< Dimensionality > start;
itk::Size< Dimensionality > size;
for (unsigned i{ 0 }; i < Dimensionality; ++i)
{
start[i] = std::max<itk::IndexValueType>(
boundingBox.GetElement(2 * i) - this->m_Pad, largestPossibleRegion.GetIndex(i));
size[i] = std::min<itk::IndexValueType>(
boundingBox.GetElement(2 * i + 1) - start[i] + 1 + this->m_Pad, largestPossibleRegion.GetSize(i) - start[i]);
}
const typename ItkImageType::RegionType croppedRegion(start, size);
{
std::stringstream ss;
ss << croppedRegion;
this->m_Logger.Log(LogLevel::INF, "{0}: Cropping image to {1}", this->m_Name, ss.str());
}
this->m_RegionOfInterestImageFilter->SetRegionOfInterest(croppedRegion);
}
template< int Dimensionality, class TPixel >
void
CropperComponent< Dimensionality, TPixel >::Update()
{
}
template< int Dimensionality, class TPixel >
bool
CropperComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
if( status == CriterionStatus::Satisfied )
{
return true;
}
else if( status == CriterionStatus::Failed )
{
return false;
}
if( criterion.first == "Pad" ) {
this->m_Pad = std::stoi( criterion.second[0] );
return true;
}
return false;
};
template< int Dimensionality, class TPixel >
bool
CropperComponent< Dimensionality, TPixel >
::ConnectionsSatisfied() {
if (!this->InterfaceAcceptor<itkImageInterface<Dimensionality, TPixel >>::GetAccepted()) {
return false;
}
if (!this->InterfaceAcceptor<itkImageMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&
!this->InterfaceAcceptor<itkImageFixedMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&
!this->InterfaceAcceptor<itkImageMovingMaskInterface<Dimensionality, unsigned char >>::GetAccepted()) {
return false;
}
return true;
}
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreRoot.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreWindowEventUtilities.h"
#include "OgreGLRenderSystemCommon.h"
#include "OgreAndroidEGLSupport.h"
#include "OgreAndroidEGLWindow.h"
#include "OgreViewport.h"
#include <iostream>
#include <algorithm>
#include <climits>
namespace Ogre {
AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport)
: EGLWindow(glsupport),
mMaxBufferSize(32),
mMinBufferSize(16),
mMaxDepthSize(16),
mMaxStencilSize(0),
mMSAA(0),
mCSAA(0),
mPreserveContext(false)
{
}
void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height )
{
// We don't have a native window.... but I think all android windows are origined
left = top = 0;
}
void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)
{
}
void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )
{
}
void AndroidEGLWindow::reposition( int left, int top )
{
}
void AndroidEGLWindow::resize(uint width, uint height)
{
}
void AndroidEGLWindow::windowMovedOrResized()
{
if(mActive)
{
// When using GPU rendering for Android UI the os creates a context in the main thread
// Now we have 2 choices create OGRE in its own thread or set our context current before doing
// anything else. I put this code here because this function called before any rendering is done.
// Because the events for screen rotation / resizing did not worked on all devices it is the best way
// to query the correct dimensions.
mContext->setCurrent();
eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);
// Notify viewports of resize
ViewportList::iterator it = mViewportList.begin();
while( it != mViewportList.end() )
(*it++).second->_updateDimensions();
}
}
void AndroidEGLWindow::switchFullScreen(bool fullscreen)
{
}
void AndroidEGLWindow::create(const String& name, uint width, uint height,
bool fullScreen, const NameValuePairList *miscParams)
{
mName = name;
mWidth = width;
mHeight = height;
mLeft = 0;
mTop = 0;
mIsFullScreen = fullScreen;
void* eglContext = NULL;
AConfiguration* config = NULL;
bool preserveContextOpt = false;
if (miscParams)
{
NameValuePairList::const_iterator opt;
NameValuePairList::const_iterator end = miscParams->end();
if ((opt = miscParams->find("currentGLContext")) != end &&
StringConverter::parseBool(opt->second))
{
eglContext = eglGetCurrentContext();
if (!eglContext)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"currentGLContext was specified with no current GL context",
"EGLWindow::create");
}
mEglSurface = eglGetCurrentSurface(EGL_DRAW);
mEglDisplay = eglGetCurrentDisplay();
}
if((opt = miscParams->find("externalWindowHandle")) != end)
{
mWindow = (ANativeWindow*)(Ogre::StringConverter::parseSizeT(opt->second));
}
if((opt = miscParams->find("androidConfig")) != end)
{
config = (AConfiguration*)(Ogre::StringConverter::parseSizeT(opt->second));
}
int ctxHandle = -1;
if((opt = miscParams->find("externalGLContext")) != end)
{
mIsExternalGLControl = true;
ctxHandle = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("maxColourBufferSize")) != end)
{
mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("maxDepthBufferSize")) != end)
{
mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("maxStencilBufferSize")) != end)
{
mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("minColourBufferSize")) != end)
{
mMinBufferSize = Ogre::StringConverter::parseInt(opt->second);
if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize;
}
if((opt = miscParams->find("MSAA")) != end)
{
mMSAA = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("CSAA")) != end)
{
mCSAA = Ogre::StringConverter::parseInt(opt->second);
}
if ((opt = miscParams->find("preserveContext")) != end &&
StringConverter::parseBool(opt->second))
{
preserveContextOpt = true;
}
}
initNativeCreatedWindow(miscParams);
if (mEglSurface)
{
mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height);
}
if (!mEglConfig && eglContext)
{
mEglConfig = mGLSupport->getGLConfigFromContext(eglContext);
if (!mEglConfig)
{
// This should never happen.
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Unexpected failure to determine a EGLFBConfig",
"EGLWindow::create");
}
}
mIsExternal = (mEglSurface != 0);
if (!mEglConfig)
{
_createInternalResources(mWindow, config);
mHwGamma = false;
}
mContext = createEGLContext();
mContext->setCurrent();
eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);
EGL_CHECK_ERROR
mActive = true;
mVisible = true;
mClosed = false;
mPreserveContext = preserveContextOpt;
}
void AndroidEGLWindow::_destroyInternalResources()
{
if(mClosed)
return;
if (!mPreserveContext)
{
mContext->setCurrent();
static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->notifyOnContextLost();
mContext->_destroyInternalResources();
}
eglDestroySurface(mEglDisplay, mEglSurface);
EGL_CHECK_ERROR
eglTerminate(mEglDisplay);
EGL_CHECK_ERROR
mEglDisplay = 0;
mEglSurface = 0;
mActive = false;
mVisible = false;
mClosed = true;
}
void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config)
{
mWindow = window;
if (mPreserveContext)
{
mEglDisplay = mGLSupport->getGLDisplay();
mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);
static_cast<EGLContext*>(mContext)->_updateInternalResources(mEglDisplay, mEglConfig, mEglSurface);
}
else
{
int minAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BUFFER_SIZE, mMinBufferSize,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
int maxAttribs[] = {
EGL_BUFFER_SIZE, mMaxBufferSize,
EGL_DEPTH_SIZE, mMaxDepthSize,
EGL_STENCIL_SIZE, mMaxStencilSize,
EGL_NONE
};
bool bAASuccess = false;
if (mCSAA)
{
try
{
int CSAAminAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BUFFER_SIZE, mMinBufferSize,
EGL_DEPTH_SIZE, 16,
EGL_COVERAGE_BUFFERS_NV, 1,
EGL_COVERAGE_SAMPLES_NV, mCSAA,
EGL_NONE
};
int CSAAmaxAttribs[] = {
EGL_BUFFER_SIZE, mMaxBufferSize,
EGL_DEPTH_SIZE, mMaxDepthSize,
EGL_STENCIL_SIZE, mMaxStencilSize,
EGL_COVERAGE_BUFFERS_NV, 1,
EGL_COVERAGE_SAMPLES_NV, mCSAA,
EGL_NONE
};
mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs);
bAASuccess = true;
}
catch (Exception& e)
{
LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting CSAA failed");
}
}
if (mMSAA && !bAASuccess)
{
try
{
int MSAAminAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BUFFER_SIZE, mMinBufferSize,
EGL_DEPTH_SIZE, 16,
EGL_SAMPLE_BUFFERS, 1,
EGL_SAMPLES, mMSAA,
EGL_NONE
};
int MSAAmaxAttribs[] = {
EGL_BUFFER_SIZE, mMaxBufferSize,
EGL_DEPTH_SIZE, mMaxDepthSize,
EGL_STENCIL_SIZE, mMaxStencilSize,
EGL_SAMPLE_BUFFERS, 1,
EGL_SAMPLES, mMSAA,
EGL_NONE
};
mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs);
bAASuccess = true;
}
catch (Exception& e)
{
LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting MSAA failed");
}
}
mEglDisplay = mGLSupport->getGLDisplay();
if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);
EGLint format;
eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format);
EGL_CHECK_ERROR
ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format);
mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);
if (config)
{
bool isLandscape = (int)AConfiguration_getOrientation(config) == 2;
mGLSupport->setConfigOption("Orientation", isLandscape ? "Landscape" : "Portrait");
}
}
if(mContext)
{
mActive = true;
mVisible = true;
mClosed = false;
if (!mPreserveContext)
{
mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL);
static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this);
}
}
}
}
<commit_msg>fix build with NDK11+: add missing include<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreRoot.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreWindowEventUtilities.h"
#include "OgreGLRenderSystemCommon.h"
#include "OgreAndroidEGLSupport.h"
#include "OgreAndroidEGLWindow.h"
#include "OgreViewport.h"
#include <android/native_window.h>
#include <iostream>
#include <algorithm>
#include <climits>
namespace Ogre {
AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport)
: EGLWindow(glsupport),
mMaxBufferSize(32),
mMinBufferSize(16),
mMaxDepthSize(16),
mMaxStencilSize(0),
mMSAA(0),
mCSAA(0),
mPreserveContext(false)
{
}
void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height )
{
// We don't have a native window.... but I think all android windows are origined
left = top = 0;
}
void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)
{
}
void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )
{
}
void AndroidEGLWindow::reposition( int left, int top )
{
}
void AndroidEGLWindow::resize(uint width, uint height)
{
}
void AndroidEGLWindow::windowMovedOrResized()
{
if(mActive)
{
// When using GPU rendering for Android UI the os creates a context in the main thread
// Now we have 2 choices create OGRE in its own thread or set our context current before doing
// anything else. I put this code here because this function called before any rendering is done.
// Because the events for screen rotation / resizing did not worked on all devices it is the best way
// to query the correct dimensions.
mContext->setCurrent();
eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);
// Notify viewports of resize
ViewportList::iterator it = mViewportList.begin();
while( it != mViewportList.end() )
(*it++).second->_updateDimensions();
}
}
void AndroidEGLWindow::switchFullScreen(bool fullscreen)
{
}
void AndroidEGLWindow::create(const String& name, uint width, uint height,
bool fullScreen, const NameValuePairList *miscParams)
{
mName = name;
mWidth = width;
mHeight = height;
mLeft = 0;
mTop = 0;
mIsFullScreen = fullScreen;
void* eglContext = NULL;
AConfiguration* config = NULL;
bool preserveContextOpt = false;
if (miscParams)
{
NameValuePairList::const_iterator opt;
NameValuePairList::const_iterator end = miscParams->end();
if ((opt = miscParams->find("currentGLContext")) != end &&
StringConverter::parseBool(opt->second))
{
eglContext = eglGetCurrentContext();
if (!eglContext)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"currentGLContext was specified with no current GL context",
"EGLWindow::create");
}
mEglSurface = eglGetCurrentSurface(EGL_DRAW);
mEglDisplay = eglGetCurrentDisplay();
}
if((opt = miscParams->find("externalWindowHandle")) != end)
{
mWindow = (ANativeWindow*)(Ogre::StringConverter::parseSizeT(opt->second));
}
if((opt = miscParams->find("androidConfig")) != end)
{
config = (AConfiguration*)(Ogre::StringConverter::parseSizeT(opt->second));
}
int ctxHandle = -1;
if((opt = miscParams->find("externalGLContext")) != end)
{
mIsExternalGLControl = true;
ctxHandle = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("maxColourBufferSize")) != end)
{
mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("maxDepthBufferSize")) != end)
{
mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("maxStencilBufferSize")) != end)
{
mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("minColourBufferSize")) != end)
{
mMinBufferSize = Ogre::StringConverter::parseInt(opt->second);
if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize;
}
if((opt = miscParams->find("MSAA")) != end)
{
mMSAA = Ogre::StringConverter::parseInt(opt->second);
}
if((opt = miscParams->find("CSAA")) != end)
{
mCSAA = Ogre::StringConverter::parseInt(opt->second);
}
if ((opt = miscParams->find("preserveContext")) != end &&
StringConverter::parseBool(opt->second))
{
preserveContextOpt = true;
}
}
initNativeCreatedWindow(miscParams);
if (mEglSurface)
{
mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height);
}
if (!mEglConfig && eglContext)
{
mEglConfig = mGLSupport->getGLConfigFromContext(eglContext);
if (!mEglConfig)
{
// This should never happen.
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Unexpected failure to determine a EGLFBConfig",
"EGLWindow::create");
}
}
mIsExternal = (mEglSurface != 0);
if (!mEglConfig)
{
_createInternalResources(mWindow, config);
mHwGamma = false;
}
mContext = createEGLContext();
mContext->setCurrent();
eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);
EGL_CHECK_ERROR
mActive = true;
mVisible = true;
mClosed = false;
mPreserveContext = preserveContextOpt;
}
void AndroidEGLWindow::_destroyInternalResources()
{
if(mClosed)
return;
if (!mPreserveContext)
{
mContext->setCurrent();
static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->notifyOnContextLost();
mContext->_destroyInternalResources();
}
eglDestroySurface(mEglDisplay, mEglSurface);
EGL_CHECK_ERROR
eglTerminate(mEglDisplay);
EGL_CHECK_ERROR
mEglDisplay = 0;
mEglSurface = 0;
mActive = false;
mVisible = false;
mClosed = true;
}
void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config)
{
mWindow = window;
if (mPreserveContext)
{
mEglDisplay = mGLSupport->getGLDisplay();
mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);
static_cast<EGLContext*>(mContext)->_updateInternalResources(mEglDisplay, mEglConfig, mEglSurface);
}
else
{
int minAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BUFFER_SIZE, mMinBufferSize,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
int maxAttribs[] = {
EGL_BUFFER_SIZE, mMaxBufferSize,
EGL_DEPTH_SIZE, mMaxDepthSize,
EGL_STENCIL_SIZE, mMaxStencilSize,
EGL_NONE
};
bool bAASuccess = false;
if (mCSAA)
{
try
{
int CSAAminAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BUFFER_SIZE, mMinBufferSize,
EGL_DEPTH_SIZE, 16,
EGL_COVERAGE_BUFFERS_NV, 1,
EGL_COVERAGE_SAMPLES_NV, mCSAA,
EGL_NONE
};
int CSAAmaxAttribs[] = {
EGL_BUFFER_SIZE, mMaxBufferSize,
EGL_DEPTH_SIZE, mMaxDepthSize,
EGL_STENCIL_SIZE, mMaxStencilSize,
EGL_COVERAGE_BUFFERS_NV, 1,
EGL_COVERAGE_SAMPLES_NV, mCSAA,
EGL_NONE
};
mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs);
bAASuccess = true;
}
catch (Exception& e)
{
LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting CSAA failed");
}
}
if (mMSAA && !bAASuccess)
{
try
{
int MSAAminAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BUFFER_SIZE, mMinBufferSize,
EGL_DEPTH_SIZE, 16,
EGL_SAMPLE_BUFFERS, 1,
EGL_SAMPLES, mMSAA,
EGL_NONE
};
int MSAAmaxAttribs[] = {
EGL_BUFFER_SIZE, mMaxBufferSize,
EGL_DEPTH_SIZE, mMaxDepthSize,
EGL_STENCIL_SIZE, mMaxStencilSize,
EGL_SAMPLE_BUFFERS, 1,
EGL_SAMPLES, mMSAA,
EGL_NONE
};
mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs);
bAASuccess = true;
}
catch (Exception& e)
{
LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting MSAA failed");
}
}
mEglDisplay = mGLSupport->getGLDisplay();
if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);
EGLint format;
eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format);
EGL_CHECK_ERROR
ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format);
mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);
if (config)
{
bool isLandscape = (int)AConfiguration_getOrientation(config) == 2;
mGLSupport->setConfigOption("Orientation", isLandscape ? "Landscape" : "Portrait");
}
}
if(mContext)
{
mActive = true;
mVisible = true;
mClosed = false;
if (!mPreserveContext)
{
mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL);
static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this);
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013-2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "seasocks/ToString.h"
#include "catch.hpp"
using namespace seasocks;
TEST_CASE("insensitiveToLocale", "[toStringTests]") {
CHECK(toString("1234") == "1234");
auto prev = std::locale::global(std::locale("en_US.utf8"));
CHECK(toString("1234") == "1234"); // locale-dependent could have been 1,234
std::locale::global(std::locale(""));
CHECK(toString("1234") == "1234"); // locale-dependent could have been 1,234
std::locale::global(prev);
}
<commit_msg>Fix the tests for toString so they really show bug 28 was fixed. Closes #28<commit_after>// Copyright (c) 2013-2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "seasocks/ToString.h"
#include "catch.hpp"
using namespace seasocks;
TEST_CASE("insensitiveToLocale", "[toStringTests]") {
CHECK(toString(1234) == "1234");
auto prev = std::locale::global(std::locale("en_US.utf8"));
CHECK(toString(1234) == "1234"); // locale-dependent could have been 1,234
std::locale::global(std::locale(""));
CHECK(toString(1234) == "1234"); // locale-dependent could have been 1,234
std::locale::global(prev);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#include <libpc/filters/ChipperIterator.hpp>
namespace libpc { namespace filters {
ChipperSequentialIterator::ChipperSequentialIterator(Chipper const& filter)
: libpc::FilterSequentialIterator(filter)
, m_chipper(filter)
, m_currentBlockId(0)
, m_currentPointCount(0)
{
const_cast<Chipper&>(m_chipper).Chip();
return;
}
boost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)
{
return naiveSkipImpl(count);
}
boost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& buffer)
{
// The client has asked us for dstData.getCapacity() points.
// We will read from our previous stage until we get that amount (or
// until the previous stage runs out of points).
buffer.setNumPoints(0);
if (m_currentBlockId == m_chipper.GetBlockCount())
return 0; // we're done.
filters::chipper::Block const& block = m_chipper.GetBlock(m_currentBlockId);
std::size_t numPointsThisBlock = block.GetIDs().size();
m_currentPointCount = m_currentPointCount + numPointsThisBlock;
if (buffer.getCapacity() < numPointsThisBlock)
{
// FIXME: Expand the buffer?
throw libpc_error("Buffer not large enough to hold block!");
}
block.GetBuffer(m_chipper.getPrevStage(), buffer, m_currentBlockId);
// FIXME: Set the PointBuffer's Bounds
buffer.setSpatialBounds(block.GetBounds());
m_currentBlockId++;
return numPointsThisBlock;
}
bool ChipperSequentialIterator::atEndImpl() const
{
// we don't have a fixed point point --
// we are at the end only when our source is at the end
const SequentialIterator& iter = getPrevIterator();
return iter.atEnd();
}
// boost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)
// {
// getPrevIterator().skip(count);
// return count;
// }
//
//
// bool ChipperSequentialIterator::atEndImpl() const
// {
// return getPrevIterator().atEnd();
// }
//
//
// boost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& data)
// {
// const boost::uint32_t numRead = getPrevIterator().read(data);
// // const boost::uint32_t cacheBlockSize = m_filter.getCacheBlockSize();
// //
// // const boost::uint64_t currentPointIndex = getIndex();
// //
// // // for now, we only read from the cache if they are asking for one point
// // // (this avoids the problem of an N-point request needing more than one
// // // cached block to satisfy it)
// // if (data.getCapacity() != 1)
// // {
// // const boost::uint32_t numRead = getPrevIterator().read(data);
// //
// // // if they asked for a full block and we got a full block,
// // // and the block we got is properly aligned and not already cached,
// // // then let's cache it!
// // const bool isCacheable = (data.getCapacity() == cacheBlockSize) &&
// // (numRead == cacheBlockSize) &&
// // (currentPointIndex % cacheBlockSize == 0);
// // if (isCacheable && (m_filter.lookupInCache(currentPointIndex) == NULL))
// // {
// // m_filter.addToCache(currentPointIndex, data);
// // }
// //
// // m_filter.updateStats(numRead, data.getCapacity());
// //
// // return numRead;
// // }
// //
// // // they asked for just one point -- first, check Mister Cache
// // const PointBuffer* block = m_filter.lookupInCache(currentPointIndex);
// // if (block != NULL)
// // {
// // // A hit! A palpable hit!
// // data.copyPointFast(0, currentPointIndex % cacheBlockSize, *block);
// //
// // m_filter.updateStats(0, 1);
// //
// // return 1;
// // }
// //
// // // Not in the cache, so do a normal read :-(
// // const boost::uint32_t numRead = getPrevIterator().read(data);
// // m_filter.updateStats(numRead, numRead);
//
// return numRead;
// }
//
} } // namespaces
<commit_msg>hop out of readImpl before resetting the buffer's count to 0<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#include <libpc/filters/ChipperIterator.hpp>
namespace libpc { namespace filters {
ChipperSequentialIterator::ChipperSequentialIterator(Chipper const& filter)
: libpc::FilterSequentialIterator(filter)
, m_chipper(filter)
, m_currentBlockId(0)
, m_currentPointCount(0)
{
const_cast<Chipper&>(m_chipper).Chip();
return;
}
boost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)
{
return naiveSkipImpl(count);
}
boost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& buffer)
{
// The client has asked us for dstData.getCapacity() points.
// We will read from our previous stage until we get that amount (or
// until the previous stage runs out of points).
if (m_currentBlockId == m_chipper.GetBlockCount())
return 0; // we're done.
buffer.setNumPoints(0);
filters::chipper::Block const& block = m_chipper.GetBlock(m_currentBlockId);
std::size_t numPointsThisBlock = block.GetIDs().size();
m_currentPointCount = m_currentPointCount + numPointsThisBlock;
if (buffer.getCapacity() < numPointsThisBlock)
{
// FIXME: Expand the buffer?
throw libpc_error("Buffer not large enough to hold block!");
}
block.GetBuffer(m_chipper.getPrevStage(), buffer, m_currentBlockId);
// FIXME: Set the PointBuffer's Bounds
buffer.setSpatialBounds(block.GetBounds());
m_currentBlockId++;
return numPointsThisBlock;
}
bool ChipperSequentialIterator::atEndImpl() const
{
// we don't have a fixed point point --
// we are at the end only when our source is at the end
const SequentialIterator& iter = getPrevIterator();
return iter.atEnd();
}
// boost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)
// {
// getPrevIterator().skip(count);
// return count;
// }
//
//
// bool ChipperSequentialIterator::atEndImpl() const
// {
// return getPrevIterator().atEnd();
// }
//
//
// boost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& data)
// {
// const boost::uint32_t numRead = getPrevIterator().read(data);
// // const boost::uint32_t cacheBlockSize = m_filter.getCacheBlockSize();
// //
// // const boost::uint64_t currentPointIndex = getIndex();
// //
// // // for now, we only read from the cache if they are asking for one point
// // // (this avoids the problem of an N-point request needing more than one
// // // cached block to satisfy it)
// // if (data.getCapacity() != 1)
// // {
// // const boost::uint32_t numRead = getPrevIterator().read(data);
// //
// // // if they asked for a full block and we got a full block,
// // // and the block we got is properly aligned and not already cached,
// // // then let's cache it!
// // const bool isCacheable = (data.getCapacity() == cacheBlockSize) &&
// // (numRead == cacheBlockSize) &&
// // (currentPointIndex % cacheBlockSize == 0);
// // if (isCacheable && (m_filter.lookupInCache(currentPointIndex) == NULL))
// // {
// // m_filter.addToCache(currentPointIndex, data);
// // }
// //
// // m_filter.updateStats(numRead, data.getCapacity());
// //
// // return numRead;
// // }
// //
// // // they asked for just one point -- first, check Mister Cache
// // const PointBuffer* block = m_filter.lookupInCache(currentPointIndex);
// // if (block != NULL)
// // {
// // // A hit! A palpable hit!
// // data.copyPointFast(0, currentPointIndex % cacheBlockSize, *block);
// //
// // m_filter.updateStats(0, 1);
// //
// // return 1;
// // }
// //
// // // Not in the cache, so do a normal read :-(
// // const boost::uint32_t numRead = getPrevIterator().read(data);
// // m_filter.updateStats(numRead, numRead);
//
// return numRead;
// }
//
} } // namespaces
<|endoftext|>
|
<commit_before>/* See other files here for the LICENCE that applies here. */
/*
Template for new files, replace word "template" and later delete this line here.
*/
#ifndef INCLUDE_OT_NEWCLI_template
#define INCLUDE_OT_NEWCLI_template
#include "lib_common1.hpp"
namespace nOT {
INJECT_OT_COMMON_USING_NAMESPACE_COMMON_1; // <=== namespaces
/** Global options to run this program main() Eg used for developer's special options like +setdemo +setdebug.
This is NOT for all the other options that are parsed and executed by program. */
class cRunOptions {
public:
enum tRunMode { ///< Type of run mode - is this normal, or demonstration etc.
eRunModeCurrent=1, ///< currently developed version
eRunModeDemo, ///< best currently available Demo of something nice
eRunModeNormal, ///< do the normal things that the program should do
};
private:
tRunMode mRunMode; ///< selected run mode
bool mDebug; // turn debug on, Eg: +debug without it probably nothing will be written to debug (maybe just error etc)
bool mDebugSendToFile; // send to file, Eg: for +debugfile ; also turns on debug
bool mDebugSendToCerr; // send to cerr, Eg: for +debugcerr ; also turns on debug
// if debug is set but not any other DebugSend* then we will default to sending to debugcerr
bool mDoRunDebugshow;
public:
const tRunMode getTRunMode() { return mRunMode; }
const bool getDebug() { return mDebug; }
const bool getDebugSendToFile() { return mDebugSendToFile; }
const bool getDebugSendToCerr() { return mDebugSendToCerr; }
const bool getDoRunDebugshow() { return mDoRunDebugshow; }
cRunOptions();
vector<string> ExecuteRunoptionsAndRemoveThem(const vector<string> & args);
void Exec(const string & runoption); // eg: Exec("+debug");
void Normalize();
};
extern cRunOptions gRunOptions;
}; // namespace nOT
#endif
<commit_msg>[detail] include guard name in runoptions<commit_after>/* See other files here for the LICENCE that applies here. */
/*
Template for new files, replace word "template" and later delete this line here.
*/
#ifndef INCLUDE_OT_NEWCLI_runoptions_hpp
#define INCLUDE_OT_NEWCLI_runoptions_hpp
#include "lib_common1.hpp"
namespace nOT {
INJECT_OT_COMMON_USING_NAMESPACE_COMMON_1; // <=== namespaces
/** Global options to run this program main() Eg used for developer's special options like +setdemo +setdebug.
This is NOT for all the other options that are parsed and executed by program. */
class cRunOptions {
public:
enum tRunMode { ///< Type of run mode - is this normal, or demonstration etc.
eRunModeCurrent=1, ///< currently developed version
eRunModeDemo, ///< best currently available Demo of something nice
eRunModeNormal, ///< do the normal things that the program should do
};
private:
tRunMode mRunMode; ///< selected run mode
bool mDebug; // turn debug on, Eg: +debug without it probably nothing will be written to debug (maybe just error etc)
bool mDebugSendToFile; // send to file, Eg: for +debugfile ; also turns on debug
bool mDebugSendToCerr; // send to cerr, Eg: for +debugcerr ; also turns on debug
// if debug is set but not any other DebugSend* then we will default to sending to debugcerr
bool mDoRunDebugshow;
public:
const tRunMode getTRunMode() { return mRunMode; }
const bool getDebug() { return mDebug; }
const bool getDebugSendToFile() { return mDebugSendToFile; }
const bool getDebugSendToCerr() { return mDebugSendToCerr; }
const bool getDoRunDebugshow() { return mDoRunDebugshow; }
cRunOptions();
vector<string> ExecuteRunoptionsAndRemoveThem(const vector<string> & args);
void Exec(const string & runoption); // eg: Exec("+debug");
void Normalize();
};
extern cRunOptions gRunOptions;
}; // namespace nOT
#endif
<|endoftext|>
|
<commit_before>/* This file is part of the UniSet project
* Copyright (c) 2009 Free Software Foundation, Inc.
* Copyright (c) 2009 Ivan Donchevskiy
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Ivan Donchevskiy
* \date $Date: 2009/07/15 15:55:00 $
* \version $Id: Jrn.h,v 1.0 2009/07/15 15:55:00 vpashka Exp $
*/
// --------------------------------------------------------------------------
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "Storages.h"
#include "UniXML.h"
void testTable1(void)
{
char *chr=new char[20];
char *val=new char[40];
TableStorage *t;
t = new TableStorage("table.test", 40, 1220, 0);
int i;
for(i=0;i<20;i++)
{
chr[0]=i;
sprintf(val,"%d",i);
t->AddRow(chr,val);
}
printf("elements with values=keys added:\n");
for(i=0;i<40;i++)
{
chr[0]=i;
if(t->FindKeyValue(chr,val)!=0) printf("%s, ",val);
}
printf("\n");
for(i=9;i<15;i++)
{
chr[0]=i;
t->DelRow(chr);
}
printf("elements with keys from 9 to 14 deleted\n");
for(i=9;i<15;i++)
{
chr[0]=i;
sprintf(val,"%d",i+40);
t->AddRow(chr,val);
}
printf("elements with keys from 9 to 14 with values=key+40 added, all elements:\n");
for(i=0;i<40;i++)
{
chr[0]=i;
if(t->FindKeyValue(chr,val)!=0) printf("%s, ",val);
}
printf("\n");
}
void testTable2(void)
{
char *val=new char[40];
TableBlockStorage *t;
t = new TableBlockStorage("big_file.test", 4, 40, 20000, 5,28,0,true);
int i;
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d\n",t->GetCurBlock());
for(i=1;i<11;i++)
{
sprintf(val,"%d",i);
t->AddRow((char*)&i,val);
}
printf("current block = %d, elements with values=keys added:\n",t->GetCurBlock());
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d, rewriting first 7 with values=keys+10\n",t->GetCurBlock());
for(i=1;i<8;i++)
{
sprintf(val,"%d",i+10);
t->AddRow(&i,val);
}
printf("deleteing 8-10 elements\n");
for(i=8;i<11;i++)
{
t->DelRow(&i);
}
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d, rewriting 3-10 elements with values=keys+40\n",t->GetCurBlock());
for(i=3;i<11;i++)
{
sprintf(val,"%d",i+40);
t->AddRow(&i,val);
}
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d\n",t->GetCurBlock());
strcpy(val,"new block");
i=9;
t->AddRow(&i,val);
for(i=1;i<20;i++)
{
if(t->FindKeyValue((char*)&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d\n",t->GetCurBlock());
printf("after reopen:\n");
t->Open("big_file.test", 4, 40, 20000, 5,28,0);
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d\n",t->GetCurBlock());
delete t;
}
void testJournal1(void)
{
CycleStorage *j;
int i;
char *str = new char[30];
printf("journal test 1\n");
j = new CycleStorage("big_file.test",30,1000000,20000,true);
for(i=1;i<33000;i++)
{
sprintf(str,"%d",i);
j->AddRow(str);
}
printf("\nfirst 30 elements:\n");
for(i=0;i<30;i++)
{
if(j->ReadRow(i,str))
printf("%s\n",str);
}
printf("test of 2 classes working in 1 file together\n");
TableBlockStorage *t = new TableBlockStorage("big_file.test", 4, 40, 20000, 5,28,0);
char *val = new char[40];
for(i=1;i<20;i++)
{
if(t->FindKeyValue((char*)&i,val)!=0) printf("%s, ",val);
}
printf("\ncurrent block = %d\n\n",t->GetCurBlock());
printf("\nfirst 30 elements after deleting first 20:\n");
for(i=0;i<20;i++)
{
j->DelRow(i);
}
for(i=0;i<30;i++)
{
if(j->ReadRow(i,str))
printf("%s\n",str);
}
printf("\nfirst 20 after adding 10 elements\n");
for(i=10001;i<10011;i++)
{
sprintf(str,"%d",i);
j->AddRow(str);
}
for(i=0;i<20;i++)
{
if(j->ReadRow(i,str))
printf("%s\n",str);
}
printf("\nthe same after reopen:\n");
delete j;
j = new CycleStorage();
j->Open("big_file.test",30,1000000,20000);
for(i=0;i<20;i++)
{
if(j->ReadRow(i,str))
printf("%s\n",str);
}
printf("\n");
delete t;
delete j;
}
void testJournal2(void)
{
CycleStorage *j;
int i,k;
char *str = (char*)malloc(30);
j = new CycleStorage("big_file.test",30,1000000,20000);
printf("journal test 2 - checking number of iterations to find head/tail\n");
printf("iterations = %d\n",j->GetIter());
for(i=0;i<20;i++)
{
for(k=1000;k<3000;k++)
{
sprintf(str,"%d",k);
j->AddRow(str);
}
j->Open("big_file.test",30,1000000,20000);
printf("iterations = %d\n",j->GetIter());
}
printf("\n");
delete j;
}
int main(int args, char **argv)
{
//testTable1();
testTable2();
testJournal1();
testJournal2();
return 0;
}<commit_msg>/Utilities improovements in JrnTest<commit_after>/* This file is part of the UniSet project
* Copyright (c) 2009 Free Software Foundation, Inc.
* Copyright (c) 2009 Ivan Donchevskiy
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Ivan Donchevskiy
* \date $Date: 2009/07/15 15:55:00 $
* \version $Id: Jrn.h,v 1.0 2009/07/15 15:55:00 vpashka Exp $
*/
// --------------------------------------------------------------------------
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "Storages.h"
#include "UniXML.h"
void testTable1(void)
{
char *chr=new char[20];
char *val=new char[40];
TableStorage *t;
t = new TableStorage("table.test", 40, 1220, 0);
int i;
for(i=0;i<20;i++)
{
chr[0]=i;
sprintf(val,"%d",i);
t->AddRow(chr,val);
}
printf("elements with values=keys added:\n");
for(i=0;i<40;i++)
{
chr[0]=i;
if(t->FindKeyValue(chr,val)!=0) printf("%s, ",val);
}
printf("\n");
for(i=9;i<15;i++)
{
chr[0]=i;
t->DelRow(chr);
}
printf("elements with keys from 9 to 14 deleted\n");
for(i=9;i<15;i++)
{
chr[0]=i;
sprintf(val,"%d",i+40);
t->AddRow(chr,val);
}
printf("elements with keys from 9 to 14 with values=key+40 added, all elements:\n");
for(i=0;i<40;i++)
{
chr[0]=i;
if(t->FindKeyValue(chr,val)!=0) printf("%s, ",val);
}
printf("\n");
}
bool testTable2(void)
{
char *val=new char[40];
TableBlockStorage *t;
t = new TableBlockStorage();
t->Create("big_file.test", 4, 40, 20000, 5,28,0);
int i;
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
printf("\n");
if(t->GetCurBlock()!=0)
{
delete t;
return false;
}
for(i=1;i<11;i++)
{
sprintf(val,"%d",i);
t->AddRow((char*)&i,val);
}
if(t->GetCurBlock()!=0)
{
delete t;
return false;
}
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
if(val[0]==0)
{
delete t;
return false;
}
}
printf("\n");
if(t->GetCurBlock()!=0)
{
delete t;
return false;
}
for(i=1;i<8;i++)
{
sprintf(val,"%d",i+10);
t->AddRow(&i,val);
}
printf("deleteing 8-10 elements\n");
for(i=8;i<11;i++)
{
t->DelRow(&i);
}
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0)
{
printf("%s, ",val);
if((i > 7)&&(i <11))
{
delete t;
return false;
}
}
if((val[0] == 0)&&(i < 8))
{
delete t;
return false;
}
}
printf("\nrewriting 3-10 elements with values=keys+40\n");
if(t->GetCurBlock()!=0)
{
delete t;
return false;
}
for(i=3;i<11;i++)
{
sprintf(val,"%d",i+40);
t->AddRow(&i,val);
}
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
if((atoi(val) != i+40) && (i>2) && (i<11))
{
delete t;
return false;
}
if((atoi(val) != i+10) && (i<3))
{
delete t;
return false;
}
}
if(t->GetCurBlock()!=0)
{
delete t;
return false;
}
strcpy(val,"new block");
i=9;
t->AddRow(&i,val);
for(i=1;i<20;i++)
{
if(t->FindKeyValue((char*)&i,val)!=0) printf("%s, ",val);
}
if(t->GetCurBlock()!=1)
{
delete t;
return false;
}
printf("after reopen:\n");
t->Open("big_file.test", 4, 40, 20000, 5,28,0);
for(i=1;i<20;i++)
{
if(t->FindKeyValue(&i,val)!=0) printf("%s, ",val);
}
if(t->GetCurBlock()!=1)
{
delete t;
return false;
}
delete t;
return true;
}
bool testJournal1(void)
{
CycleStorage *j;
int i,k=0;
char *str = new char[30];
printf("journal test 1\n");
j = new CycleStorage("big_file.test",30,1000000,20000,true);
for(i=1;i<33000;i++)
{
sprintf(str,"%d",i);
j->AddRow(str);
}
printf("first 30 elements:\n");
for(i=0;i<30;i++)
{
if(j->ReadRow(i,str))
{
printf("%s\n",str);
k++;
}
}
if(k < 30)
{
delete j;
return false;
}
k = 0;
printf("test of 2 classes working in 1 file together\n");
TableBlockStorage *t = new TableBlockStorage("big_file.test", 4, 40, 20000, 5,28,0);
char *val = new char[40];
for(i=1;i<20;i++)
{
if(t->FindKeyValue((char*)&i,val)!=0) printf("%s, ",val);
if((atoi(val) != i+10) && (i<3))
{
delete t;
delete j;
return false;
}
}
printf("\nfirst 30 elements after deleting first 20:\n");
for(i=0;i<20;i++)
{
j->DelRow(i);
}
for(i=0;i<30;i++)
{
if(j->ReadRow(i,str))
{
printf("%s\n",str);
k++;
}
}
if(k != 10)
{
delete t;
delete j;
return false;
}
k = 0;
printf("first 20 after adding 10 elements\n");
for(i=10001;i<10011;i++)
{
sprintf(str,"%d",i);
j->AddRow(str);
}
for(i=0;i<20;i++)
{
if(j->ReadRow(i,str))
{
printf("%s\n",str);
k++;
}
}
if(k != 10)
{
delete t;
delete j;
return false;
}
k = 0;
printf("the same after reopen:\n");
delete j;
j = new CycleStorage();
j->Open("big_file.test",30,1000000,20000);
for(i=0;i<20;i++)
{
if(j->ReadRow(i,str))
{
printf("%s\n",str);
k++;
}
}
if(k != 10)
{
delete t;
delete j;
return false;
}
k = 0;
printf("the same after reopen:\n");
delete j;
j = new CycleStorage();
j->Open("big_file.test",30,1000000,20000);
for(i=0;i<20;i++)
{
if(j->ReadRow(i,str))
{
printf("%s\n",str);
k++;
}
}
if(k != 10)
{
delete t;
delete j;
//return false;
}
delete t;
delete j;
return true;
}
void testJournal2(void)
{
CycleStorage *j;
int i,k;
char *str = (char*)malloc(30);
j = new CycleStorage("big_file.test",30,1000000,20000);
printf("journal test 2 - checking number of iterations to find head/tail\n");
printf("iterations = %d\n",j->GetIter());
for(i=0;i<20;i++)
{
for(k=1000;k<3000;k++)
{
sprintf(str,"%d",k);
j->AddRow(str);
}
j->Open("big_file.test",30,1000000,20000);
printf("iterations = %d\n",j->GetIter());
}
printf("\n");
delete j;
}
int main(int args, char **argv)
{
//testTable1();
bool ok = true;
if(testTable2())
printf("\nTest for TableBlockStorage passed\n\n");
else
{
printf("\nTest for TableBlockStorage failed\n\n");
ok = false;
}
if(testJournal1())
printf("\nTest1 for CycleStorage passed\n\n");
else
{
printf("\nTest for CycleStorage failed\n\n");
ok = false;
}
if(ok)
{
testJournal2();
printf("TEST PASSED :)\n");
}
else
printf("TEST FAILED :(\n");
return 0;
}<|endoftext|>
|
<commit_before>#include "stdafx.h"
TexMan texMan;
#ifndef _MSC_VER
static GLuint LoadTextureViaOS(const char* name)
{
jclass myview = jniEnv->FindClass(boundJavaClass);
jmethodID method = method = jniEnv->GetStaticMethodID(myview, "loadTexture", "(Ljava/lang/String;)I");
if (method == 0) {
return 0;
}
return jniEnv->CallStaticIntMethod(myview, method, jniEnv->NewStringUTF(name));
}
#endif
#ifdef _MSC_VER
using std::min;
using std::max;
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
static GLuint LoadTextureViaOS(const char* name)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
WCHAR wc[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));
Gdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);
int w = (int)image->GetWidth();
int h = (int)image->GetHeight();
Gdiplus::Rect rc(0, 0, w, h);
Gdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;
image->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);
std::vector<uint32_t> col;
col.resize(w * h);
for (int y = 0; y < h; y++) {
memcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);
for (int x = 0; x < w; x++) {
uint32_t& c = col[y * w + x];
c = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);
}
}
image->UnlockBits(bitmapData);
delete bitmapData;
delete image;
Gdiplus::GdiplusShutdown(gdiplusToken);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
#endif
struct DDSHeader {
uint32_t h3[3];
uint32_t h, w;
uint32_t h2[2];
uint32_t mipCnt;
uint32_t h13[13];
uint32_t fourcc, bitsPerPixel, rMask, gMask, bMask, aMask;
};
static void bitScanForward(uint32_t* result, uint32_t mask)
{
// DWORD dwd;
// _BitScanForward(&dwd, mask);
// *result = dwd;
for (int i = 0; i < 32; i++) {
if (mask & (1 << i)) {
*result = i;
return;
}
}
*result = 0;
}
static GLuint CreateTextureFromRowDDS(const void* img, int size)
{
const DDSHeader* hdr = (DDSHeader*)img;
int w = (int)hdr->w;
int h = (int)hdr->h;
const uint32_t* im = (uint32_t*)img + 128 / 4;
std::vector<uint32_t> col;
uint32_t rShift, gShift, bShift, aShift;
bitScanForward(&rShift, hdr->rMask);
bitScanForward(&gShift, hdr->gMask);
bitScanForward(&bShift, hdr->bMask);
bitScanForward(&aShift, hdr->aMask);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
uint32_t c = *im++;
col.push_back(
((hdr->aMask & c) >> aShift << 24) +
((hdr->bMask & c) >> bShift << 16) +
((hdr->gMask & c) >> gShift << 8) +
((hdr->rMask & c) >> rShift));
}
}
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
static GLuint LoadDDSTexture(const char* name)
{
int size;
GLuint texture = 0;
void* img = LoadFile(name, &size);
if (!img) {
aflog("LoadDDSTexture failed! %s", name);
return 0;
}
const DDSHeader* hdr = (DDSHeader*)img;
GLenum format;
int blockSize = 16;
switch (hdr->fourcc) {
case 0x31545844: //'1TXD':
format = 0x83F1; // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
blockSize = 8;
break;
// case 0x33545844; //'3TXD':
// format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
// break;
// case 0x35545844; //'5TXD':
// format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
// break;
default:
texture = CreateTextureFromRowDDS(img, size);
goto END;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
{
int texSize = blockSize * ((hdr->w + 3) / 4) * ((hdr->h + 3) / 4);
glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, hdr->w, hdr->h, 0, texSize, (char*)img + 128);
}
glBindTexture(GL_TEXTURE_2D, 0);
END:
free(img);
return texture;
}
static GLuint LoadTexture(const char* name)
{
int len = strlen(name);
if (len > 4 && !stricmp(name + len - 4, ".dds")) {
return LoadDDSTexture(name);
} else {
return LoadTextureViaOS(name);
}
}
static GLuint CreateWhiteTexture()
{
uint32_t col = 0xffffffff;
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
static GLuint CreateDynamicTexture(int w, int h)
{
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
TexMan::TMID TexMan::CreateDynamicTexture(const char* name, int w, int h)
{
auto it = nameToId.find(name);
if (it != nameToId.end())
{
return it->second;
}
return nameToId[name] = ::CreateDynamicTexture(w, h);
}
TexMan::TMID TexMan::Create(const char *name)
{
NameToId::iterator it = nameToId.find(name);
if (it != nameToId.end())
{
return it->second;
}
return nameToId[name] = LoadTexture(name);
}
TexMan::TMID TexMan::CreateWhiteTexture()
{
const std::string name = "$WHITE";
NameToId::iterator it = nameToId.find(name);
if (it != nameToId.end())
{
return it->second;
}
return nameToId[name] = ::CreateWhiteTexture();
}
void TexMan::Destroy()
{
for (NameToId::iterator it = nameToId.begin(); it != nameToId.end(); ++it)
{
GLuint id[1] = { it->second };
glDeleteTextures(1, id);
}
nameToId.clear();
}
void TexMan::Write(TMID id, const void* buf, int w, int h)
{
glBindTexture(GL_TEXTURE_2D, id);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
w,
h,
GL_RGBA,
GL_UNSIGNED_BYTE,
buf
);
glBindTexture(GL_TEXTURE_2D, 0);
}
<commit_msg>put min/max into Gdiplus<commit_after>#include "stdafx.h"
TexMan texMan;
#ifndef _MSC_VER
static GLuint LoadTextureViaOS(const char* name)
{
jclass myview = jniEnv->FindClass(boundJavaClass);
jmethodID method = method = jniEnv->GetStaticMethodID(myview, "loadTexture", "(Ljava/lang/String;)I");
if (method == 0) {
return 0;
}
return jniEnv->CallStaticIntMethod(myview, method, jniEnv->NewStringUTF(name));
}
#endif
#ifdef _MSC_VER
namespace Gdiplus {
using std::min;
using std::max;
}
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
static GLuint LoadTextureViaOS(const char* name)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);
WCHAR wc[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));
Gdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);
int w = (int)image->GetWidth();
int h = (int)image->GetHeight();
Gdiplus::Rect rc(0, 0, w, h);
Gdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;
image->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);
std::vector<uint32_t> col;
col.resize(w * h);
for (int y = 0; y < h; y++) {
memcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);
for (int x = 0; x < w; x++) {
uint32_t& c = col[y * w + x];
c = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);
}
}
image->UnlockBits(bitmapData);
delete bitmapData;
delete image;
Gdiplus::GdiplusShutdown(gdiplusToken);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
#endif
struct DDSHeader {
uint32_t h3[3];
uint32_t h, w;
uint32_t h2[2];
uint32_t mipCnt;
uint32_t h13[13];
uint32_t fourcc, bitsPerPixel, rMask, gMask, bMask, aMask;
};
static void bitScanForward(uint32_t* result, uint32_t mask)
{
// DWORD dwd;
// _BitScanForward(&dwd, mask);
// *result = dwd;
for (int i = 0; i < 32; i++) {
if (mask & (1 << i)) {
*result = i;
return;
}
}
*result = 0;
}
static GLuint CreateTextureFromRowDDS(const void* img, int size)
{
const DDSHeader* hdr = (DDSHeader*)img;
int w = (int)hdr->w;
int h = (int)hdr->h;
const uint32_t* im = (uint32_t*)img + 128 / 4;
std::vector<uint32_t> col;
uint32_t rShift, gShift, bShift, aShift;
bitScanForward(&rShift, hdr->rMask);
bitScanForward(&gShift, hdr->gMask);
bitScanForward(&bShift, hdr->bMask);
bitScanForward(&aShift, hdr->aMask);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
uint32_t c = *im++;
col.push_back(
((hdr->aMask & c) >> aShift << 24) +
((hdr->bMask & c) >> bShift << 16) +
((hdr->gMask & c) >> gShift << 8) +
((hdr->rMask & c) >> rShift));
}
}
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
static GLuint LoadDDSTexture(const char* name)
{
int size;
GLuint texture = 0;
void* img = LoadFile(name, &size);
if (!img) {
aflog("LoadDDSTexture failed! %s", name);
return 0;
}
const DDSHeader* hdr = (DDSHeader*)img;
GLenum format;
int blockSize = 16;
switch (hdr->fourcc) {
case 0x31545844: //'1TXD':
format = 0x83F1; // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
blockSize = 8;
break;
// case 0x33545844; //'3TXD':
// format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
// break;
// case 0x35545844; //'5TXD':
// format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
// break;
default:
texture = CreateTextureFromRowDDS(img, size);
goto END;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
{
int texSize = blockSize * ((hdr->w + 3) / 4) * ((hdr->h + 3) / 4);
glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, hdr->w, hdr->h, 0, texSize, (char*)img + 128);
}
glBindTexture(GL_TEXTURE_2D, 0);
END:
free(img);
return texture;
}
static GLuint LoadTexture(const char* name)
{
int len = strlen(name);
if (len > 4 && !stricmp(name + len - 4, ".dds")) {
return LoadDDSTexture(name);
} else {
return LoadTextureViaOS(name);
}
}
static GLuint CreateWhiteTexture()
{
uint32_t col = 0xffffffff;
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
static GLuint CreateDynamicTexture(int w, int h)
{
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
}
TexMan::TMID TexMan::CreateDynamicTexture(const char* name, int w, int h)
{
auto it = nameToId.find(name);
if (it != nameToId.end())
{
return it->second;
}
return nameToId[name] = ::CreateDynamicTexture(w, h);
}
TexMan::TMID TexMan::Create(const char *name)
{
NameToId::iterator it = nameToId.find(name);
if (it != nameToId.end())
{
return it->second;
}
return nameToId[name] = LoadTexture(name);
}
TexMan::TMID TexMan::CreateWhiteTexture()
{
const std::string name = "$WHITE";
NameToId::iterator it = nameToId.find(name);
if (it != nameToId.end())
{
return it->second;
}
return nameToId[name] = ::CreateWhiteTexture();
}
void TexMan::Destroy()
{
for (NameToId::iterator it = nameToId.begin(); it != nameToId.end(); ++it)
{
GLuint id[1] = { it->second };
glDeleteTextures(1, id);
}
nameToId.clear();
}
void TexMan::Write(TMID id, const void* buf, int w, int h)
{
glBindTexture(GL_TEXTURE_2D, id);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
w,
h,
GL_RGBA,
GL_UNSIGNED_BYTE,
buf
);
glBindTexture(GL_TEXTURE_2D, 0);
}
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse_price.h"
using namespace std;
namespace bohrium {
/* The default fuse model */
static const FusePriceModel default_price_model = UNIQUE_VIEWS;
/* The current selected fuse model */
static FusePriceModel selected_price_model = NUM_OF_PRICE_MODELS;
/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/
/* Returns the bytes in a bh_view */
inline static uint64_t bytes_in_view(const bh_view &v)
{
assert (!bh_is_constant(&v));
return bh_nelements_nbcast(&v) * bh_type_size(v.base->type);
}
/* The cost of a kernel is the sum of unique views read and written */
static uint64_t cost_unique(const bh_ir_kernel &k)
{
set<bh_view> unique_views;
unique_views.insert(k.get_input_set().begin(), k.get_input_set().end());
unique_views.insert(k.get_output_set().begin(), k.get_output_set().end());
uint64_t sum = 0;
for(const bh_view &v: k.get_input_set())
sum += bytes_in_view(v);
for(const bh_view &v: k.get_output_set())
sum += bytes_in_view(v);
return sum;
}
static uint64_t savings_unique(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_unique(k1) + cost_unique(k2);
uint64_t new_cost = cost_unique(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
/*
static uint64_t savings_unique_old(const bh_ir_kernel &a, const bh_ir_kernel &b)
{
int64_t price_drop = 0;
//Subtract inputs in 'a' that comes from 'b' or is already an input in 'b'
for(const bh_view &i: a.get_input_set())
{
for(const bh_view &o: b.get_output_set())
{
if(bh_view_aligned(&i, &o))
price_drop += bytes_in_view(i);
}
for(const bh_view &o: b.get_input_set())
{
if(bh_view_aligned(&i, &o))
price_drop += bytes_in_view(i);
}
}
//Subtract outputs from 'b' that are discared in 'a'
for(const bh_view &o: b.get_output_set())
{
for(uint64_t a_instr_idx: a.instr_indexes())
{
const bh_instruction &a_instr = a.bhir->instr_list[a_instr_idx];
if(a_instr.opcode == BH_DISCARD and a_instr.operand[0].base == o.base)
{
price_drop += bytes_in_view(o);
break;
}
}
}
return price_drop;
}
*/
/* The cost of a kernel is 'number of instruction' * 3 - 'number of temp arrays' */
static uint64_t cost_temp_elemination(const bh_ir_kernel &k)
{
return k.instr_indexes().size() * 3 - k.get_temps().size();
}
static uint64_t savings_temp_elemination(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_temp_elemination(k1) + cost_temp_elemination(k2);
uint64_t new_cost = cost_temp_elemination(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
static uint64_t cost_max_share(const bh_ir_kernel &k)
{
if(k.instr_indexes().size() == 0)
return 0;
uint64_t shared_access = 0;
for(uint64_t instr_idx=0; instr_idx < k.bhir->instr_list.size(); ++instr_idx)
{
const bh_instruction &instr = k.bhir->instr_list[instr_idx];
//Check if the instruction is in this kernel
if(std::find(k.instr_indexes().begin(), k.instr_indexes().end(), instr_idx) != k.instr_indexes().end())
continue;
//Let's count the number of inputs in this kernel that reads the output of 'instr'
for(uint64_t krn_idx: k.instr_indexes())
{
if(krn_idx < instr_idx)
continue;
const bh_instruction &krn_instr = k.bhir->instr_list[krn_idx];
const int nop = bh_operands(krn_instr.opcode);
for(int i=1; i<nop; ++i)
{
const bh_view &read = krn_instr.operand[i];
if(bh_is_constant(&read))
continue;
if(read.base->nelem <= 1)
continue; //We ignore 1-sized arrays
if(instr.operand[0] == read)
++shared_access;
}
}
//Let's count the number of shared inputs
for(uint64_t krn_idx: k.instr_indexes())
{
const bh_instruction &krn_instr = k.bhir->instr_list[krn_idx];
for(int i=1; i < bh_operands(instr.opcode); ++i)
{
if(bh_is_constant(&instr.operand[i]))
continue;
for(int j=1; j < bh_operands(krn_instr.opcode); ++j)
{
if(bh_is_constant(&krn_instr.operand[j]))
continue;
if(krn_instr.operand[j].base->nelem <= 1)
continue; //We ignore 1-sized arrays
if(instr.operand[i] == krn_instr.operand[j])
++shared_access;
}
}
}
}
return shared_access;
}
static uint64_t savings_max_share(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_max_share(k1) + cost_max_share(k2);
uint64_t new_cost = cost_max_share(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
static uint64_t cost_amos(const bh_ir_kernel &k)
{
uint64_t N = k.bhir->instr_list.size();
if(k.instr_indexes().size() == 0)
return 0;
uint64_t loop_overhead = 1;
uint64_t not_tmp = k.get_parameters().size();
uint64_t shared_access = cost_max_share(k);
return loop_overhead+not_tmp*N+shared_access*N*N;
}
static uint64_t savings_amos(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_amos(k1) + cost_amos(k2);
uint64_t new_cost = cost_amos(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/
FusePriceModel fuse_get_selected_price_model()
{
using namespace boost;
if(selected_price_model != NUM_OF_PRICE_MODELS)
return selected_price_model;
string default_model;
fuse_price_model_text(default_price_model, default_model);
//Check enviroment variable
const char *env = getenv("BH_PRICE_MODEL");
if(env != NULL)
{
string e(env);
//Iterate through the 'FusePriceModel' enum and find the enum that matches
//the enviroment variable string 'e'
for(FusePriceModel m = UNIQUE_VIEWS; m < NUM_OF_PRICE_MODELS; m = FusePriceModel(m + 1))
{
string model;
fuse_price_model_text(m, model);
if(iequals(e, model))
{
return m;
}
}
cerr << "[FUSE] WARNING: unknown price model: '" << e;
cerr << "', using the default model '" << default_model << "' instead" << endl;
setenv("BH_PRICE_MODEL", default_model.c_str(), 1);
}
return default_price_model;
}
void fuse_price_model_text(FusePriceModel price_model, string &output)
{
switch(price_model)
{
case UNIQUE_VIEWS:
output = "unique_views";
break;
case TEMP_ELEMINATION:
output = "temp_elemination";
break;
case MAX_SHARE:
output = "max_share";
break;
case AMOS:
output = "amos";
break;
default:
output = "unknown";
}
}
uint64_t kernel_cost(const bh_ir_kernel &kernel)
{
switch(selected_price_model)
{
case NUM_OF_PRICE_MODELS:
selected_price_model = fuse_get_selected_price_model();
return kernel_cost(kernel);
case UNIQUE_VIEWS:
return cost_unique(kernel);
case TEMP_ELEMINATION:
return cost_temp_elemination(kernel);
case MAX_SHARE:
return cost_max_share(kernel);
case AMOS:
return cost_amos(kernel);
default:
throw runtime_error("No price module is selected!");
}
}
uint64_t kernel_cost_unique_views(const bh_ir_kernel &kernel)
{
return cost_unique(kernel);
}
uint64_t cost_savings(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
switch(selected_price_model)
{
case NUM_OF_PRICE_MODELS:
selected_price_model = fuse_get_selected_price_model();
return cost_savings(k1, k2);
case UNIQUE_VIEWS:
return savings_unique(k1, k2);
case TEMP_ELEMINATION:
return savings_temp_elemination(k1, k2);
case MAX_SHARE:
return savings_max_share(k1, k2);
case AMOS:
return savings_amos(k1, k2);
default:
throw runtime_error("No price module is selected!");
}
}
} //namespace bohrium
<commit_msg>fuse-price: reimplemented the MAX_SHARE price model<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse_price.h"
using namespace std;
namespace bohrium {
/* The default fuse model */
static const FusePriceModel default_price_model = UNIQUE_VIEWS;
/* The current selected fuse model */
static FusePriceModel selected_price_model = NUM_OF_PRICE_MODELS;
/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/
/* Returns the bytes in a bh_view */
inline static uint64_t bytes_in_view(const bh_view &v)
{
assert (!bh_is_constant(&v));
return bh_nelements_nbcast(&v) * bh_type_size(v.base->type);
}
/* The cost of a kernel is the sum of unique views read and written */
static uint64_t cost_unique(const bh_ir_kernel &k)
{
set<bh_view> unique_views;
unique_views.insert(k.get_input_set().begin(), k.get_input_set().end());
unique_views.insert(k.get_output_set().begin(), k.get_output_set().end());
uint64_t sum = 0;
for(const bh_view &v: k.get_input_set())
sum += bytes_in_view(v);
for(const bh_view &v: k.get_output_set())
sum += bytes_in_view(v);
return sum;
}
static uint64_t savings_unique(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_unique(k1) + cost_unique(k2);
uint64_t new_cost = cost_unique(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
/*
static uint64_t savings_unique_old(const bh_ir_kernel &a, const bh_ir_kernel &b)
{
int64_t price_drop = 0;
//Subtract inputs in 'a' that comes from 'b' or is already an input in 'b'
for(const bh_view &i: a.get_input_set())
{
for(const bh_view &o: b.get_output_set())
{
if(bh_view_aligned(&i, &o))
price_drop += bytes_in_view(i);
}
for(const bh_view &o: b.get_input_set())
{
if(bh_view_aligned(&i, &o))
price_drop += bytes_in_view(i);
}
}
//Subtract outputs from 'b' that are discared in 'a'
for(const bh_view &o: b.get_output_set())
{
for(uint64_t a_instr_idx: a.instr_indexes())
{
const bh_instruction &a_instr = a.bhir->instr_list[a_instr_idx];
if(a_instr.opcode == BH_DISCARD and a_instr.operand[0].base == o.base)
{
price_drop += bytes_in_view(o);
break;
}
}
}
return price_drop;
}
*/
/* The cost of a kernel is 'number of instruction' * 3 - 'number of temp arrays' */
static uint64_t cost_temp_elemination(const bh_ir_kernel &k)
{
return k.instr_indexes().size() * 3 - k.get_temps().size();
}
static uint64_t savings_temp_elemination(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_temp_elemination(k1) + cost_temp_elemination(k2);
uint64_t new_cost = cost_temp_elemination(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
static uint64_t cost_max_share(const bh_ir_kernel &k)
{
if(k.instr_indexes().size() == 0)
return 0;
uint64_t shared_access = 0;
for(uint64_t krn_idx: k.instr_indexes())
{
const bh_instruction &krn_instr = k.bhir->instr_list[krn_idx];
if(bh_opcode_is_system(krn_instr.opcode))
continue;
//Find which instructions that reads and writes to arrays "visible" to
//the instruction 'krn_idx'
multiset<bh_view> read_access, read_access_outside;
set<bh_view> write_access, write_access_outside;;
for(uint64_t instr_idx=0; instr_idx < krn_idx; ++instr_idx)
{
const bh_instruction &instr = k.bhir->instr_list[instr_idx];
if(bh_opcode_is_system(instr.opcode))
continue;
//Check if the instruction is in this kernel
bool instr_in_kernel = false;
if(std::find(k.instr_indexes().begin(),
k.instr_indexes().end(), instr_idx) != k.instr_indexes().end())
instr_in_kernel = true;
for(int i=bh_operands(instr.opcode)-1; i>=0; --i)
{
const bh_view &v = instr.operand[i];
if(bh_is_constant(&v))
continue;
if(i > 0)
{
read_access.insert(v);
if(not instr_in_kernel)
read_access_outside.insert(v);
}
else
{
write_access.insert(v);
read_access.erase(v);
if(not instr_in_kernel)
{
write_access_outside.insert(v);
}
else
write_access_outside.erase(v);
read_access_outside.erase(v);
}
}
}
for(int i=1; i < bh_operands(krn_instr.opcode); ++i)
{
const bh_view &v = krn_instr.operand[i];
if(bh_is_constant(&v))
continue;
if(write_access_outside.find(v) != write_access_outside.end())
shared_access++;
shared_access += read_access_outside.count(v);
}
}
return shared_access;
}
static uint64_t savings_max_share(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_max_share(k1) + cost_max_share(k2);
uint64_t new_cost = cost_max_share(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
static uint64_t cost_amos(const bh_ir_kernel &k)
{
uint64_t N = k.bhir->instr_list.size();
if(k.instr_indexes().size() == 0)
return 0;
uint64_t loop_overhead = 1;
uint64_t not_tmp = k.get_parameters().size();
uint64_t shared_access = cost_max_share(k);
return loop_overhead+not_tmp*N+shared_access*N*N;
}
static uint64_t savings_amos(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
bh_ir_kernel tmp = k1;
for(uint64_t instr_idx: k2.instr_indexes())
{
tmp.add_instr(instr_idx);
}
uint64_t old_cost = cost_amos(k1) + cost_amos(k2);
uint64_t new_cost = cost_amos(tmp);
assert(old_cost >= new_cost);
return old_cost - new_cost;
}
/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/
FusePriceModel fuse_get_selected_price_model()
{
using namespace boost;
if(selected_price_model != NUM_OF_PRICE_MODELS)
return selected_price_model;
string default_model;
fuse_price_model_text(default_price_model, default_model);
//Check enviroment variable
const char *env = getenv("BH_PRICE_MODEL");
if(env != NULL)
{
string e(env);
//Iterate through the 'FusePriceModel' enum and find the enum that matches
//the enviroment variable string 'e'
for(FusePriceModel m = UNIQUE_VIEWS; m < NUM_OF_PRICE_MODELS; m = FusePriceModel(m + 1))
{
string model;
fuse_price_model_text(m, model);
if(iequals(e, model))
{
return m;
}
}
cerr << "[FUSE] WARNING: unknown price model: '" << e;
cerr << "', using the default model '" << default_model << "' instead" << endl;
setenv("BH_PRICE_MODEL", default_model.c_str(), 1);
}
return default_price_model;
}
void fuse_price_model_text(FusePriceModel price_model, string &output)
{
switch(price_model)
{
case UNIQUE_VIEWS:
output = "unique_views";
break;
case TEMP_ELEMINATION:
output = "temp_elemination";
break;
case MAX_SHARE:
output = "max_share";
break;
case AMOS:
output = "amos";
break;
default:
output = "unknown";
}
}
uint64_t kernel_cost(const bh_ir_kernel &kernel)
{
switch(selected_price_model)
{
case NUM_OF_PRICE_MODELS:
selected_price_model = fuse_get_selected_price_model();
return kernel_cost(kernel);
case UNIQUE_VIEWS:
return cost_unique(kernel);
case TEMP_ELEMINATION:
return cost_temp_elemination(kernel);
case MAX_SHARE:
return cost_max_share(kernel);
case AMOS:
return cost_amos(kernel);
default:
throw runtime_error("No price module is selected!");
}
}
uint64_t kernel_cost_unique_views(const bh_ir_kernel &kernel)
{
return cost_unique(kernel);
}
uint64_t cost_savings(const bh_ir_kernel &k1, const bh_ir_kernel &k2)
{
switch(selected_price_model)
{
case NUM_OF_PRICE_MODELS:
selected_price_model = fuse_get_selected_price_model();
return cost_savings(k1, k2);
case UNIQUE_VIEWS:
return savings_unique(k1, k2);
case TEMP_ELEMINATION:
return savings_temp_elemination(k1, k2);
case MAX_SHARE:
return savings_max_share(k1, k2);
case AMOS:
return savings_amos(k1, k2);
default:
throw runtime_error("No price module is selected!");
}
}
} //namespace bohrium
<|endoftext|>
|
<commit_before>#ifndef PERCEPTRON_H
#define PERCEPTRON_H
#include <sstream>
#include <vector>
#include <numeric> // inner_product
#include <algorithm> // transform
#include <functional> // plus, minus
#include <assert.h>
#include <cmath> // sqrt
#include <initializer_list>
#include "randomgen.hh"
#include "classifier.hh"
#include "activation.hh"
using namespace std;
using epoch_parameter = function<double(int)>;
epoch_parameter const_epoch_parameter(double eta) {
return [eta](int) { return eta; };
}
using Weights = vector<double>;
class APerceptron {
/// induced local field of activation potential $v_k$, page 11
virtual double inducedLocalField(const Input &x) = 0;
/// neuron's output (activation function applied to the induced local field)
virtual double output(const Input &x) = 0;
/// neuron's weights; weights[0] is bias
virtual Weights getWeights() const = 0;
};
class Perceptron : public APerceptron, public BinaryClassifier {
private:
double bias;
vector<double> weights;
const ActivationFunction &activationFunction;
void trainConverge_addSample(Input input, double output, double eta) {
double y = this->output(input);
double xfactor = eta * (output - y);
bias += xfactor * 1.0;
transform(
weights.begin(), weights.end(), input.begin(),
weights.begin() /* output */,
[&xfactor](double w_i, double x_i) { return w_i + xfactor * x_i; });
}
void trainBatch_addBatch(LabeledSet batch, double eta) {
for (auto sample : batch) {
double d = sample.output[0]; // desired output
Input x = sample.input;
bias += eta * 1.0 * d;
transform(x.begin(), x.end(), weights.begin(), weights.begin(),
[d, eta](double x_i, double w_i) {
return w_i + eta * x_i * d;
});
}
}
public:
Perceptron(int n, const ActivationFunction &af = defaultSignum)
: bias(0), weights(n), activationFunction(af) {}
virtual double inducedLocalField(const Input &x) {
assert(x.size() == weights.size());
return inner_product(weights.begin(), weights.end(), x.begin(), bias);
}
virtual double output(const Input &x) {
return activationFunction(inducedLocalField(x));
}
virtual bool classify(const Input &x) { return output(x) > 0; }
/// perceptron convergence algorithm (Table 1.1)
void trainConverge(const LabeledSet &trainSet, int epochs,
double eta = 1.0) {
return trainConverge(trainSet, epochs, const_epoch_parameter(eta));
}
/// perceptron convergence algorithm (Table 1.1)
void trainConverge(const LabeledSet &trainSet, int epochs,
epoch_parameter eta) {
assert(trainSet.getOutputSize() == 1);
for (int epoch = 0; epoch < epochs; ++epoch) {
double etaval = eta(epoch);
for (auto sample : trainSet) {
trainConverge_addSample(sample.input, sample.output[0], etaval);
}
}
}
/// batch-training algorithm (Sec 1.6, Eq. 1.42)
void trainBatch(const LabeledSet &trainSet, int epochs, double eta = 1.0) {
return trainBatch(trainSet, epochs, const_epoch_parameter(eta));
}
/// batch-training algorithm (Sec 1.6, Eq. 1.42)
void trainBatch(const LabeledSet &trainSet, int epochs,
epoch_parameter eta) {
assert(trainSet.getOutputSize() == 1);
assert(trainSet.getInputSize() == weights.size());
LabeledPairPredicate isMisclassified =
[this](const Input &in, const Output &out) {
return (this->output(in)) * out[0] <= 0;
};
// \nabla J(w) = \sum_{\vec{x}(n) \in H} ( - \vec{x}(n) d(n) ) (1.40)
// w(n+1) = w(n) - eta(n) \nabla J(w) (1.42)
for (int epoch = 0; epoch < epochs; ++epoch) {
double etaval = eta(epoch);
// a new batch
LabeledSet misclassifiedSet = trainSet.filter(isMisclassified);
// sum cost gradient over the entire bactch
trainBatch_addBatch(misclassifiedSet, etaval);
}
}
virtual vector<double> getWeights() const {
vector<double> biasAndWeights(weights);
biasAndWeights.insert(biasAndWeights.begin(), bias);
return biasAndWeights;
}
string fmt() {
ostringstream ss;
for (auto it : getWeights()) {
ss << " " << it;
}
return ss.str();
}
};
ostream &operator<<(ostream &out, const vector<double> &xs);
/**
A basic perceptron, without built-in training facilities, with
reasonable defaults to be used within `PerceptronsLayers`.
*/
class BasicPerceptron : public APerceptron {
private:
Weights weights; // weights[0] is bias
const ActivationFunction &activationFunction;
// remember the last input and internal parameters to use them
// again in the back-propagation step
double lastInducedLocalField; // v_j = \sum w_i y_i
double lastActivationValue; // y_j = \phi (v_j)
double lastActivationGradient; // y_j = \phi^\prime (v_j)
double lastLocalGradient; // delta_j = \phi^\prime(v_j) e_j
public:
BasicPerceptron(int n, const ActivationFunction &af = defaultTanh)
: weights(n + 1), activationFunction(af) {}
// one-sided Xavier initialization
// see http://andyljones.tumblr.com/post/110998971763/
void init(unique_ptr<rng_type> &rng) {
int n_in = weights.size()-1;
double sigma = n_in > 0 ? sqrt(1.0/n_in) : 1.0;
uniform_real_distribution<double> nd(-sigma, sigma);
generate(weights.begin(), weights.end(), [&nd, &rng] {
double w = nd(*rng.get());
return w;
});
}
virtual double inducedLocalField(const Input &x) {
double bias = weights[0];
auto weights_2nd = next(weights.begin());
return inner_product(weights_2nd, weights.end(), x.begin(), bias);
}
virtual double output(const Input &x) {
double v = inducedLocalField(x);
lastInducedLocalField = v;
lastActivationValue = activationFunction(v);
lastActivationGradient = activationFunction.derivative(v);
return lastActivationValue;
}
virtual Weights getWeights() const {
return weights;
}
void adjustWeights(Weights deltaW) {
assert(deltaW.size() == weights.size());
for (size_t i = 0; i < weights.size(); ++i) {
weights[i] += deltaW[i];
}
}
struct BPResult {
Weights weightCorrection;
double localGradient;
};
// Page 134. Equation (4.27) defines weight correction
//
// $$ \Delta w_{ji} (n) =
// \eta
// \times
// \delta_j (n)
// \times
// y_{i} (n) $$
//
// where $w_{ji}$ is the synaptic weight connecting neuron $i$ to neuron $j$,
// $\eta$ is learning rate, $delta_j (n)$ is the local [error] gradient,
// $y_{i}$ is the input signal of the neuron $i$, $n$ is the epoch number
//
// The local gradient is the product of the activation function derivative
// and the error signal.
//
// Return a vector of weight corrections and the local gradient value.
//
// The method should be called _after_ `forwardPass`
BPResult backwardPass(const Input &inputs, double errorSignal,
double learningRate) {
assert(inputs.size() + 1 == weights.size());
size_t nInputs = weights.size();
double localGradient = lastActivationGradient * errorSignal;
double multiplier = learningRate * localGradient;
Weights delta_W(nInputs, multiplier);
for (size_t i = 0; i < inputs.size(); ++i) {
delta_W[i + 1] *= inputs[i];
}
lastLocalGradient = localGradient;
return BPResult{delta_W, localGradient};
}
};
/// A fully connected layer of perceptrons.
class PerceptronsLayer {
private:
unsigned int nInputs;
unsigned int nNeurons;
vector<BasicPerceptron> neurons;
Output lastOutput;
public:
PerceptronsLayer(unsigned int nInputs = 0, unsigned int nOutputs = 0,
const ActivationFunction &af = defaultTanh)
: nInputs(nInputs), nNeurons(nOutputs),
neurons(nOutputs, BasicPerceptron(nInputs, af)),
lastOutput(nOutputs) {}
void init(unique_ptr<rng_type> &rng) {
for (size_t i = 0; i < neurons.size(); ++i) {
neurons[i].init(rng);
}
}
void adjustWeights(vector<Weights> weightDeltas) {
assert(nNeurons == weightDeltas.size());
for (size_t i = 0; i < neurons.size(); ++i) {
neurons[i].adjustWeights(weightDeltas[i]);
}
}
// Pages 132-133.
// Return a vector of outputs.
Output forwardPass(const Input &inputs) {
for (auto i = 0u; i < nNeurons; ++i) {
lastOutput[i] = neurons[i].output(inputs);
}
return lastOutput;
}
struct BPResult {
Output propagatedErrorSignal;
vector<Weights> weightCorrections;
};
// Page 134. Update synaptic weights.
//
// Return a vector of back-propagated error signal
//
// $$ e_j = \sum_k \delta_k w_{kj} $$
//
// where $e_j$ is an error propagated from all downstream neurons to the
// neuron $j$, $\delta_k$ is the local gradient of the downstream neurons
// $k$, $w_{kj}$ is the synaptic weight of the $j$-th input of the
// downstream neuron $k$.
//
// The method should be called _after_ `forwardPass`
BPResult backwardPass(const Input &inputs, const Output &errorSignals,
double learningRate) {
assert(errorSignals.size() == neurons.size());
auto eta = learningRate;
vector<Weights> weightDeltas(0);
Weights propagatedErrorSignals(nInputs, 0.0);
for (auto k = 0u; k < nNeurons; ++k) {
auto error_k = errorSignals[k];
auto r = neurons[k].backwardPass(inputs, error_k, eta);
Weights delta_Wk = r.weightCorrection;
double delta_k = r.localGradient;
Weights Wk = neurons[k].getWeights();
for (auto j = 0u; j < nInputs; ++j) {
propagatedErrorSignals[j] += delta_k * Wk[j + 1];
}
weightDeltas.push_back(delta_Wk);
}
return BPResult{propagatedErrorSignals, weightDeltas};
}
friend ostream &operator<<(ostream &out, const PerceptronsLayer &net);
};
/// Multiple layers of perceptrons stack one upon another.
class PerceptronsNetwork {
private:
vector<PerceptronsLayer> layers;
public:
PerceptronsNetwork(initializer_list<unsigned int> shape,
const ActivationFunction &af = defaultTanh)
: layers(0) {
auto pIn = shape.begin();
auto pOut = next(pIn);
for (; pOut != shape.end(); ++pIn, ++pOut) {
PerceptronsLayer layer(*pIn, *pOut, af);
layers.push_back(layer);
}
}
void init(unique_ptr<rng_type> &rng) {
for (auto i = 0u; i < layers.size(); ++i) {
layers[i].init(rng);
}
}
friend ostream &operator<<(ostream &out, const PerceptronsNetwork &net);
};
ostream &operator<<(ostream &out, const PerceptronsLayer &layer) {
size_t n = layer.neurons.size();
for (size_t j = 0; j < n; ++j) {
if (j == 0) {
out << "[";
} else {
out << " ";
}
out << layer.neurons[j].getWeights();
if (j >= n - 1) {
out << "]";
} else {
out << ",\n";
}
}
return out;
}
ostream &operator<<(ostream &out, const PerceptronsNetwork &net) {
for (PerceptronsLayer l : net.layers) {
out << l << "\n";
}
return out;
}
ostream &operator<<(ostream &out, const vector<double> &xs) {
int n = xs.size();
out << "[ ";
for (int i = 0; i < n - 1; ++i) {
out << xs[i] << ", ";
}
out << xs[n - 1] << " ]";
return out;
}
#endif /* PERCEPTRON_H */
<commit_msg>edit method comment (backwardPass)<commit_after>#ifndef PERCEPTRON_H
#define PERCEPTRON_H
#include <sstream>
#include <vector>
#include <numeric> // inner_product
#include <algorithm> // transform
#include <functional> // plus, minus
#include <assert.h>
#include <cmath> // sqrt
#include <initializer_list>
#include "randomgen.hh"
#include "classifier.hh"
#include "activation.hh"
using namespace std;
using epoch_parameter = function<double(int)>;
epoch_parameter const_epoch_parameter(double eta) {
return [eta](int) { return eta; };
}
using Weights = vector<double>;
class APerceptron {
/// induced local field of activation potential $v_k$, page 11
virtual double inducedLocalField(const Input &x) = 0;
/// neuron's output (activation function applied to the induced local field)
virtual double output(const Input &x) = 0;
/// neuron's weights; weights[0] is bias
virtual Weights getWeights() const = 0;
};
class Perceptron : public APerceptron, public BinaryClassifier {
private:
double bias;
vector<double> weights;
const ActivationFunction &activationFunction;
void trainConverge_addSample(Input input, double output, double eta) {
double y = this->output(input);
double xfactor = eta * (output - y);
bias += xfactor * 1.0;
transform(
weights.begin(), weights.end(), input.begin(),
weights.begin() /* output */,
[&xfactor](double w_i, double x_i) { return w_i + xfactor * x_i; });
}
void trainBatch_addBatch(LabeledSet batch, double eta) {
for (auto sample : batch) {
double d = sample.output[0]; // desired output
Input x = sample.input;
bias += eta * 1.0 * d;
transform(x.begin(), x.end(), weights.begin(), weights.begin(),
[d, eta](double x_i, double w_i) {
return w_i + eta * x_i * d;
});
}
}
public:
Perceptron(int n, const ActivationFunction &af = defaultSignum)
: bias(0), weights(n), activationFunction(af) {}
virtual double inducedLocalField(const Input &x) {
assert(x.size() == weights.size());
return inner_product(weights.begin(), weights.end(), x.begin(), bias);
}
virtual double output(const Input &x) {
return activationFunction(inducedLocalField(x));
}
virtual bool classify(const Input &x) { return output(x) > 0; }
/// perceptron convergence algorithm (Table 1.1)
void trainConverge(const LabeledSet &trainSet, int epochs,
double eta = 1.0) {
return trainConverge(trainSet, epochs, const_epoch_parameter(eta));
}
/// perceptron convergence algorithm (Table 1.1)
void trainConverge(const LabeledSet &trainSet, int epochs,
epoch_parameter eta) {
assert(trainSet.getOutputSize() == 1);
for (int epoch = 0; epoch < epochs; ++epoch) {
double etaval = eta(epoch);
for (auto sample : trainSet) {
trainConverge_addSample(sample.input, sample.output[0], etaval);
}
}
}
/// batch-training algorithm (Sec 1.6, Eq. 1.42)
void trainBatch(const LabeledSet &trainSet, int epochs, double eta = 1.0) {
return trainBatch(trainSet, epochs, const_epoch_parameter(eta));
}
/// batch-training algorithm (Sec 1.6, Eq. 1.42)
void trainBatch(const LabeledSet &trainSet, int epochs,
epoch_parameter eta) {
assert(trainSet.getOutputSize() == 1);
assert(trainSet.getInputSize() == weights.size());
LabeledPairPredicate isMisclassified =
[this](const Input &in, const Output &out) {
return (this->output(in)) * out[0] <= 0;
};
// \nabla J(w) = \sum_{\vec{x}(n) \in H} ( - \vec{x}(n) d(n) ) (1.40)
// w(n+1) = w(n) - eta(n) \nabla J(w) (1.42)
for (int epoch = 0; epoch < epochs; ++epoch) {
double etaval = eta(epoch);
// a new batch
LabeledSet misclassifiedSet = trainSet.filter(isMisclassified);
// sum cost gradient over the entire bactch
trainBatch_addBatch(misclassifiedSet, etaval);
}
}
virtual vector<double> getWeights() const {
vector<double> biasAndWeights(weights);
biasAndWeights.insert(biasAndWeights.begin(), bias);
return biasAndWeights;
}
string fmt() {
ostringstream ss;
for (auto it : getWeights()) {
ss << " " << it;
}
return ss.str();
}
};
ostream &operator<<(ostream &out, const vector<double> &xs);
/**
A basic perceptron, without built-in training facilities, with
reasonable defaults to be used within `PerceptronsLayers`.
*/
class BasicPerceptron : public APerceptron {
private:
Weights weights; // weights[0] is bias
const ActivationFunction &activationFunction;
// remember the last input and internal parameters to use them
// again in the back-propagation step
double lastInducedLocalField; // v_j = \sum w_i y_i
double lastActivationValue; // y_j = \phi (v_j)
double lastActivationGradient; // y_j = \phi^\prime (v_j)
double lastLocalGradient; // delta_j = \phi^\prime(v_j) e_j
public:
BasicPerceptron(int n, const ActivationFunction &af = defaultTanh)
: weights(n + 1), activationFunction(af) {}
// one-sided Xavier initialization
// see http://andyljones.tumblr.com/post/110998971763/
void init(unique_ptr<rng_type> &rng) {
int n_in = weights.size()-1;
double sigma = n_in > 0 ? sqrt(1.0/n_in) : 1.0;
uniform_real_distribution<double> nd(-sigma, sigma);
generate(weights.begin(), weights.end(), [&nd, &rng] {
double w = nd(*rng.get());
return w;
});
}
virtual double inducedLocalField(const Input &x) {
double bias = weights[0];
auto weights_2nd = next(weights.begin());
return inner_product(weights_2nd, weights.end(), x.begin(), bias);
}
virtual double output(const Input &x) {
double v = inducedLocalField(x);
lastInducedLocalField = v;
lastActivationValue = activationFunction(v);
lastActivationGradient = activationFunction.derivative(v);
return lastActivationValue;
}
virtual Weights getWeights() const {
return weights;
}
void adjustWeights(Weights deltaW) {
assert(deltaW.size() == weights.size());
for (size_t i = 0; i < weights.size(); ++i) {
weights[i] += deltaW[i];
}
}
struct BPResult {
Weights weightCorrection;
double localGradient;
};
// Page 134. Equation (4.27) defines weight correction
//
// $$ \Delta w_{ji} (n) =
// \eta
// \times
// \delta_j (n)
// \times
// y_{i} (n) $$
//
// where $w_{ji}$ is the synaptic weight connecting neuron $i$ to neuron $j$,
// $\eta$ is learning rate, $delta_j (n)$ is the local [error] gradient,
// $y_{i}$ is the input signal of the neuron $i$, $n$ is the epoch number
//
// The local gradient is the product of the activation function derivative
// and the error signal.
//
// Return a vector of weight corrections and the local gradient value.
//
// The method should be called _after_ `forwardPass`
BPResult backwardPass(const Input &inputs, double errorSignal,
double learningRate) {
assert(inputs.size() + 1 == weights.size());
size_t nInputs = weights.size();
double localGradient = lastActivationGradient * errorSignal;
double multiplier = learningRate * localGradient;
Weights delta_W(nInputs, multiplier);
for (size_t i = 0; i < inputs.size(); ++i) {
delta_W[i + 1] *= inputs[i];
}
lastLocalGradient = localGradient;
return BPResult{delta_W, localGradient};
}
};
/// A fully connected layer of perceptrons.
class PerceptronsLayer {
private:
unsigned int nInputs;
unsigned int nNeurons;
vector<BasicPerceptron> neurons;
Output lastOutput;
public:
PerceptronsLayer(unsigned int nInputs = 0, unsigned int nOutputs = 0,
const ActivationFunction &af = defaultTanh)
: nInputs(nInputs), nNeurons(nOutputs),
neurons(nOutputs, BasicPerceptron(nInputs, af)),
lastOutput(nOutputs) {}
void init(unique_ptr<rng_type> &rng) {
for (size_t i = 0; i < neurons.size(); ++i) {
neurons[i].init(rng);
}
}
void adjustWeights(vector<Weights> weightDeltas) {
assert(nNeurons == weightDeltas.size());
for (size_t i = 0; i < neurons.size(); ++i) {
neurons[i].adjustWeights(weightDeltas[i]);
}
}
// Pages 132-133.
// Return a vector of outputs.
Output forwardPass(const Input &inputs) {
for (auto i = 0u; i < nNeurons; ++i) {
lastOutput[i] = neurons[i].output(inputs);
}
return lastOutput;
}
struct BPResult {
Output propagatedErrorSignal;
vector<Weights> weightCorrections;
};
// Page 134. Calculate back-propagated error signal and corrections to
// synaptic weights.
//
// $$ e_j = \sum_k \delta_k w_{kj} $$
//
// where $e_j$ is an error propagated from all downstream neurons to the
// neuron $j$, $\delta_k$ is the local gradient of the downstream neurons
// $k$, $w_{kj}$ is the synaptic weight of the $j$-th input of the
// downstream neuron $k$.
//
// The method should be called _after_ `forwardPass`
BPResult backwardPass(const Input &inputs, const Output &errorSignals,
double learningRate) {
assert(errorSignals.size() == neurons.size());
auto eta = learningRate;
vector<Weights> weightDeltas(0);
Weights propagatedErrorSignals(nInputs, 0.0);
for (auto k = 0u; k < nNeurons; ++k) {
auto error_k = errorSignals[k];
auto r = neurons[k].backwardPass(inputs, error_k, eta);
Weights delta_Wk = r.weightCorrection;
double delta_k = r.localGradient;
Weights Wk = neurons[k].getWeights();
for (auto j = 0u; j < nInputs; ++j) {
propagatedErrorSignals[j] += delta_k * Wk[j + 1];
}
weightDeltas.push_back(delta_Wk);
}
return BPResult{propagatedErrorSignals, weightDeltas};
}
friend ostream &operator<<(ostream &out, const PerceptronsLayer &net);
};
/// Multiple layers of perceptrons stack one upon another.
class PerceptronsNetwork {
private:
vector<PerceptronsLayer> layers;
public:
PerceptronsNetwork(initializer_list<unsigned int> shape,
const ActivationFunction &af = defaultTanh)
: layers(0) {
auto pIn = shape.begin();
auto pOut = next(pIn);
for (; pOut != shape.end(); ++pIn, ++pOut) {
PerceptronsLayer layer(*pIn, *pOut, af);
layers.push_back(layer);
}
}
void init(unique_ptr<rng_type> &rng) {
for (auto i = 0u; i < layers.size(); ++i) {
layers[i].init(rng);
}
}
friend ostream &operator<<(ostream &out, const PerceptronsNetwork &net);
};
ostream &operator<<(ostream &out, const PerceptronsLayer &layer) {
size_t n = layer.neurons.size();
for (size_t j = 0; j < n; ++j) {
if (j == 0) {
out << "[";
} else {
out << " ";
}
out << layer.neurons[j].getWeights();
if (j >= n - 1) {
out << "]";
} else {
out << ",\n";
}
}
return out;
}
ostream &operator<<(ostream &out, const PerceptronsNetwork &net) {
for (PerceptronsLayer l : net.layers) {
out << l << "\n";
}
return out;
}
ostream &operator<<(ostream &out, const vector<double> &xs) {
int n = xs.size();
out << "[ ";
for (int i = 0; i < n - 1; ++i) {
out << xs[i] << ", ";
}
out << xs[n - 1] << " ]";
return out;
}
#endif /* PERCEPTRON_H */
<|endoftext|>
|
<commit_before>/*
* A filtered_socket class that offloads the actual filtering to a
* worker thread.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_THREAD_SOCKET_FILTER_HXX
#define BENG_PROXY_THREAD_SOCKET_FILTER_HXX
#include "thread_job.hxx"
#include "event/DeferEvent.hxx"
#include "event/TimerEvent.hxx"
#include "SliceFifoBuffer.hxx"
#include <mutex>
typedef struct _GError GError;
struct SocketFilter;
struct FilteredSocket;
struct ThreadSocketFilter;
class ThreadQueue;
class ThreadSocketFilterHandler {
public:
virtual ~ThreadSocketFilterHandler() {}
/**
* Called in the main thread before Run() is scheduled.
*/
virtual void PreRun(ThreadSocketFilter &) {}
/**
* Do the work. This is run in an unspecified worker thread. The
* given #ThreadSocketFilter's mutex may be used for protection.
*
* This method may throw exceptions, which will be forwarded to
* BufferedSocketHandler::error().
*/
virtual void Run(ThreadSocketFilter &f) = 0;
/**
* Called in the main thread after one or more run() calls have
* finished successfully.
*/
virtual void PostRun(ThreadSocketFilter &) {}
};
/**
* A module for #filtered_socket that moves the filter to a thread
* pool (see #thread_job).
*/
struct ThreadSocketFilter final : ThreadJob {
ThreadQueue &queue;
FilteredSocket *socket;
/**
* The actual filter. If this is NULL, then this object behaves
* just like #BufferedSocket.
*/
ThreadSocketFilterHandler *const handler;
BoundMethod<void()> handshake_callback{nullptr};
/**
* This event moves a call out of the current stack frame. It is
* used by ScheduleWrite() to avoid calling InvokeWrite()
* directly.
*/
DeferEvent defer_event;
/**
*
*/
TimerEvent handshake_timeout_event;
bool busy = false, done_pending = false;
bool connected = true;
/**
* Does the handler expect more data? It announced this by
* returning BUFFERED_MORE.
*/
bool expect_more = false;
bool postponed_remaining = false;
bool postponed_end = false;
/**
* Set to true when the thread queue hasn't yet released the
* #thread_job. The object will be destroyed in the "done"
* callback.
*/
bool postponed_destroy = false;
/**
* True when the client has called
* filtered_socket_schedule_read().
*/
bool want_read = false;
/**
* Was _schedule_read() forwarded?
*/
bool read_scheduled = false;
/**
* True when the client has called
* filtered_socket_schedule_write().
*/
bool want_write = false;
/**
* True when #ThreadSocketFilterHandler's internal output buffers
* are empty. Set by #ThreadSocketFilterHandler::run() before
* returning.
*
* Protected by #mutex.
*/
bool drained = true;
/**
* True when no more input can be decrypted by
* #ThreadSocketFilterHandler. Will be set to true by
* #ThreadSocketFilterHandler.
*
* Protected by #mutex.
*/
bool input_eof = false;
/**
* Schedule the job again? This can be used to fix up things that
* can only be done in the main thread.
*
* Protected by #mutex.
*/
bool again = false;
/**
* True during the initial handshake. Will be set to false by the
* #ThreadSocketFilterHandler. It is used to control the
* #handshake_timeout_event.
*
* Protected by #mutex.
*
* TODO: this is only a kludge for the stable branch. Reimplement
* properly.
*/
bool handshaking = true;
struct timeval read_timeout_buffer;
const struct timeval *read_timeout = nullptr;
std::mutex mutex;
/**
* If this is set, an exception was caught inside the thread, and
* shall be forwarded to the main thread.
*/
std::exception_ptr error;
/**
* A buffer of input data that was not yet handled by the filter.
* It will be passed to the filter, and after that, it will go to
* #decrypted_input.
*
* This gets fed from buffered_socket::input. We need another
* buffer because buffered_socket is not thread-safe, while this
* buffer is protected by the #mutex.
*/
SliceFifoBuffer encrypted_input;
/**
* A buffer of input data that was handled by the filter. It will
* be passed to the handler.
*/
SliceFifoBuffer decrypted_input;
/**
* A buffer of output data that was not yet handled by the filter.
* Once it was filtered, it will be written to #encrypted_output.
*/
SliceFifoBuffer plain_output;
/**
* A buffer of output data that has been filtered already, and
* will be written to the socket.
*/
SliceFifoBuffer encrypted_output;
ThreadSocketFilter(EventLoop &_event_loop,
ThreadQueue &queue,
ThreadSocketFilterHandler *handler);
ThreadSocketFilter(const ThreadSocketFilter &) = delete;
~ThreadSocketFilter();
void SetHandshakeCallback(BoundMethod<void()> callback);
/**
* Schedule a Run() call in a worker thread.
*/
void Schedule();
/**
* @return false if the object has been destroyed
*/
bool SubmitDecryptedInput();
/**
* @return the number of bytes appended to #plain_output
*/
size_t LockWritePlainOutput(const void *data, size_t size);
/* virtual methods from class ThreadJob */
void Run() final;
void Done() final;
private:
void ClosedPrematurely();
bool CheckRead(std::unique_lock<std::mutex> &lock);
bool CheckWrite(std::unique_lock<std::mutex> &lock);
void HandshakeTimeoutCallback();
/**
* Called in the main thread before scheduling a Run() call in a
* worker thread.
*/
void PreRun();
/**
* Called in the main thread after one or more Run() calls have
* finished successfully.
*/
void PostRun();
/**
* This event moves a call out of the current stack frame. It is
* used by ScheduleWrite() to avoid calling InvokeWrite()
* directly.
*/
void OnDeferred();
};
extern const SocketFilter thread_socket_filter;
#endif
<commit_msg>thread_socket_filter: remove obsolete GError declaration<commit_after>/*
* A filtered_socket class that offloads the actual filtering to a
* worker thread.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_THREAD_SOCKET_FILTER_HXX
#define BENG_PROXY_THREAD_SOCKET_FILTER_HXX
#include "thread_job.hxx"
#include "event/DeferEvent.hxx"
#include "event/TimerEvent.hxx"
#include "SliceFifoBuffer.hxx"
#include <mutex>
struct SocketFilter;
struct FilteredSocket;
struct ThreadSocketFilter;
class ThreadQueue;
class ThreadSocketFilterHandler {
public:
virtual ~ThreadSocketFilterHandler() {}
/**
* Called in the main thread before Run() is scheduled.
*/
virtual void PreRun(ThreadSocketFilter &) {}
/**
* Do the work. This is run in an unspecified worker thread. The
* given #ThreadSocketFilter's mutex may be used for protection.
*
* This method may throw exceptions, which will be forwarded to
* BufferedSocketHandler::error().
*/
virtual void Run(ThreadSocketFilter &f) = 0;
/**
* Called in the main thread after one or more run() calls have
* finished successfully.
*/
virtual void PostRun(ThreadSocketFilter &) {}
};
/**
* A module for #filtered_socket that moves the filter to a thread
* pool (see #thread_job).
*/
struct ThreadSocketFilter final : ThreadJob {
ThreadQueue &queue;
FilteredSocket *socket;
/**
* The actual filter. If this is NULL, then this object behaves
* just like #BufferedSocket.
*/
ThreadSocketFilterHandler *const handler;
BoundMethod<void()> handshake_callback{nullptr};
/**
* This event moves a call out of the current stack frame. It is
* used by ScheduleWrite() to avoid calling InvokeWrite()
* directly.
*/
DeferEvent defer_event;
/**
*
*/
TimerEvent handshake_timeout_event;
bool busy = false, done_pending = false;
bool connected = true;
/**
* Does the handler expect more data? It announced this by
* returning BUFFERED_MORE.
*/
bool expect_more = false;
bool postponed_remaining = false;
bool postponed_end = false;
/**
* Set to true when the thread queue hasn't yet released the
* #thread_job. The object will be destroyed in the "done"
* callback.
*/
bool postponed_destroy = false;
/**
* True when the client has called
* filtered_socket_schedule_read().
*/
bool want_read = false;
/**
* Was _schedule_read() forwarded?
*/
bool read_scheduled = false;
/**
* True when the client has called
* filtered_socket_schedule_write().
*/
bool want_write = false;
/**
* True when #ThreadSocketFilterHandler's internal output buffers
* are empty. Set by #ThreadSocketFilterHandler::run() before
* returning.
*
* Protected by #mutex.
*/
bool drained = true;
/**
* True when no more input can be decrypted by
* #ThreadSocketFilterHandler. Will be set to true by
* #ThreadSocketFilterHandler.
*
* Protected by #mutex.
*/
bool input_eof = false;
/**
* Schedule the job again? This can be used to fix up things that
* can only be done in the main thread.
*
* Protected by #mutex.
*/
bool again = false;
/**
* True during the initial handshake. Will be set to false by the
* #ThreadSocketFilterHandler. It is used to control the
* #handshake_timeout_event.
*
* Protected by #mutex.
*
* TODO: this is only a kludge for the stable branch. Reimplement
* properly.
*/
bool handshaking = true;
struct timeval read_timeout_buffer;
const struct timeval *read_timeout = nullptr;
std::mutex mutex;
/**
* If this is set, an exception was caught inside the thread, and
* shall be forwarded to the main thread.
*/
std::exception_ptr error;
/**
* A buffer of input data that was not yet handled by the filter.
* It will be passed to the filter, and after that, it will go to
* #decrypted_input.
*
* This gets fed from buffered_socket::input. We need another
* buffer because buffered_socket is not thread-safe, while this
* buffer is protected by the #mutex.
*/
SliceFifoBuffer encrypted_input;
/**
* A buffer of input data that was handled by the filter. It will
* be passed to the handler.
*/
SliceFifoBuffer decrypted_input;
/**
* A buffer of output data that was not yet handled by the filter.
* Once it was filtered, it will be written to #encrypted_output.
*/
SliceFifoBuffer plain_output;
/**
* A buffer of output data that has been filtered already, and
* will be written to the socket.
*/
SliceFifoBuffer encrypted_output;
ThreadSocketFilter(EventLoop &_event_loop,
ThreadQueue &queue,
ThreadSocketFilterHandler *handler);
ThreadSocketFilter(const ThreadSocketFilter &) = delete;
~ThreadSocketFilter();
void SetHandshakeCallback(BoundMethod<void()> callback);
/**
* Schedule a Run() call in a worker thread.
*/
void Schedule();
/**
* @return false if the object has been destroyed
*/
bool SubmitDecryptedInput();
/**
* @return the number of bytes appended to #plain_output
*/
size_t LockWritePlainOutput(const void *data, size_t size);
/* virtual methods from class ThreadJob */
void Run() final;
void Done() final;
private:
void ClosedPrematurely();
bool CheckRead(std::unique_lock<std::mutex> &lock);
bool CheckWrite(std::unique_lock<std::mutex> &lock);
void HandshakeTimeoutCallback();
/**
* Called in the main thread before scheduling a Run() call in a
* worker thread.
*/
void PreRun();
/**
* Called in the main thread after one or more Run() calls have
* finished successfully.
*/
void PostRun();
/**
* This event moves a call out of the current stack frame. It is
* used by ScheduleWrite() to avoid calling InvokeWrite()
* directly.
*/
void OnDeferred();
};
extern const SocketFilter thread_socket_filter;
#endif
<|endoftext|>
|
<commit_before>/*
* jcom.oscinstance
* External for Jamoma: retrieve instance numbers or ids from osc messages
* By Trond Lossius, Copyright 2005
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "Jamoma.h"
#define MAX_MESS_SIZE 2048
typedef struct _oscinstance{ ///< Data Structure for this object
t_object ob; ///< REQUIRED: Our object
void *outlet0; ///< Leftmost outlet, passing osc messages
void *outlet1; ///< 2nd outlet, passing instance number or ID
void *outlet2; ///< 3rd outlet, passing the arguments of incomming OSC messages
void *outlet_overflow; ///< The rightmost outlet: This outlet doubles as the dumpout outlet
} t_oscinstance;
/** The jcom.oscinstance constructor */
void *oscinstance_new(t_symbol *s, long argc, t_atom *argv);
/** Provide assistance strings in the patcher window. */
void oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst);
/** Method for bang input. */
void oscinstance_bang(t_oscinstance *x);
/** Method for int input. */
void oscinstance_int(t_oscinstance *x, long n);
/** Method for int float. */
void oscinstance_float(t_oscinstance *x, double f);
/** Method for anything else, including OSC messages. */
void oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);
//void oscinstance_list(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);
// Globals
t_class *oscinstance_class; // Required: Global pointer for our class
/************************************************************************************/
// Main() Function
int main(void) // main recieves a copy of the Max function macros table
{
long attrflags = 0;
t_class *c;
t_object *attr;
jamoma_init();
common_symbols_init();
c = class_new("jcom.oscinstance",(method)oscinstance_new, (method)0L, sizeof(t_oscinstance), (method)0L, A_GIMME, 0);
class_addmethod(c, (method)oscinstance_bang, "bang", 0);
class_addmethod(c, (method)oscinstance_int, "int", A_DEFLONG, 0L);
class_addmethod(c, (method)oscinstance_float, "float", A_DEFFLOAT, 0L);
class_addmethod(c, (method)oscinstance_symbol, "list", A_GIMME, 0L);
class_addmethod(c, (method)oscinstance_symbol, "anything", A_GIMME, 0L);
class_addmethod(c, (method)oscinstance_assist, "assist", A_CANT, 0L);
class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT,0);
// Finalize our class
class_register(CLASS_BOX, c);
oscinstance_class = c;
return 0;
}
/************************************************************************************/
// Object Life
void *oscinstance_new(t_symbol *s, long argc, t_atom *argv)
{
t_oscinstance *x = (t_oscinstance *)object_alloc(oscinstance_class);
if(x){
x->outlet_overflow = outlet_new(x, 0); // overflow outlet
object_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow); // dumpout
x->outlet2 = outlet_new(x, 0); // Create Outlet
x->outlet1 = outlet_new(x, 0); // Create Outlet
x->outlet0 = outlet_new(x, 0); // Create Outlet
}
return (x); // return the pointer to our new instantiation
}
/************************************************************************************/
// Methods bound to input/inlets
// Method for Assistance Messages
void oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst)
{
if(msg==1) // Inlet
strcpy(dst, "Input");
else if(msg==2){ // Outlets
if(arg == 0)
strcpy(dst, "OSC message with instance info stripped");
else if (arg == 1)
strcpy(dst, "OSC instance number or ID");
else
strcpy(dst, "dumpout / overflow from non-matching input");
}
}
void oscinstance_bang(t_oscinstance *x)
{
outlet_bang(x->outlet_overflow);
}
// INT INPUT
void oscinstance_int(t_oscinstance *x, long n)
{
outlet_int(x->outlet_overflow, n);
}
// FLOAT INPUT
void oscinstance_float(t_oscinstance *x, double f)
{
outlet_float(x->outlet_overflow, f);
}
// SYMBOL INPUT
void oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv)
{
char input[MAX_MESS_SIZE]; // our input string
char *input2 = input; // pointer to our input string
char *dot;
char *slash;
t_symbol *instance;
char *instanceEnd;
t_symbol *output;
t_symbol *osc = NULL;
long i;
strcpy(input, msg->s_name);
// This object only deals with OSC messages
if(!*input2 == '/') {
goto spillover;
}
input2++; // jump past the leading slash
dot = strchr(input2, '.'); // look for dot
if (dot == NULL)
goto spillover;
slash = strchr(input2, '/'); // checking for additional osc branches
if ( slash == 0) {
*dot = NULL;
osc = gensym(input2-1); // reintroduce the leading slash
instance = gensym(dot+1);
}
else {
if ( slash<dot )
goto spillover; // there are instances, but not in the leading branch
*dot = NULL;
*slash = NULL; // temporarily remove the slash
instance = gensym(dot+1);
*slash = '/'; // put slash back in
strcat(input, slash); // remove the instance part and concatenate
osc = gensym(input2-1); // reintroduce the leading slash
}
// Output from 3rd outlet: The arguments of the OSC message
// We have to check what message to return.
// The message received has no arguments:
if (argc == 0) {
outlet_bang(x->outlet2);
}
// The message received has one argument only:
else if (argc==1) {
// int argument
if (argv->a_type==A_LONG)
outlet_int(x->outlet2,argv->a_w.w_long);
// float argument
else if (argv->a_type==A_FLOAT)
outlet_float(x->outlet2,argv->a_w.w_float);
// something else
else if (argv->a_type==A_SYM)
outlet_anything(x->outlet2,argv->a_w.w_sym,0,0);
}
// There are two or more arguments: check if first is A_SYM
else {
if (argv->a_type==A_SYM) {
output = argv->a_w.w_sym;
argc--;
argv++;
}
else
output = _sym_list;
outlet_anything(x->outlet2, output, argc , argv);
}
// Output from 2nd outlet: Instance. Check if the instance is an integer (long):
i = strtol (instance->s_name,&instanceEnd,10);
if (instance->s_name[0] != '\n' && (*instanceEnd == '\n' || *instanceEnd == '\0'))
outlet_int(x->outlet1, i);
else
outlet_anything(x->outlet1, instance, NULL, 0L);
// Output from 1st outlet: OC name with instance removed
outlet_anything(x->outlet0, osc, NULL, 0L);
return;
spillover:
outlet_anything(x->outlet_overflow, msg, argc , argv);
return;
}
<commit_msg>corrected the labeling of the 3rd and 4th outlet <commit_after>/*
* jcom.oscinstance
* External for Jamoma: retrieve instance numbers or ids from osc messages
* By Trond Lossius, Copyright 2005
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "Jamoma.h"
#define MAX_MESS_SIZE 2048
typedef struct _oscinstance{ ///< Data Structure for this object
t_object ob; ///< REQUIRED: Our object
void *outlet0; ///< Leftmost outlet, passing osc messages
void *outlet1; ///< 2nd outlet, passing instance number or ID
void *outlet2; ///< 3rd outlet, passing the arguments of incomming OSC messages
void *outlet_overflow; ///< The rightmost outlet: This outlet doubles as the dumpout outlet
} t_oscinstance;
/** The jcom.oscinstance constructor */
void *oscinstance_new(t_symbol *s, long argc, t_atom *argv);
/** Provide assistance strings in the patcher window. */
void oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst);
/** Method for bang input. */
void oscinstance_bang(t_oscinstance *x);
/** Method for int input. */
void oscinstance_int(t_oscinstance *x, long n);
/** Method for int float. */
void oscinstance_float(t_oscinstance *x, double f);
/** Method for anything else, including OSC messages. */
void oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);
//void oscinstance_list(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);
// Globals
t_class *oscinstance_class; // Required: Global pointer for our class
/************************************************************************************/
// Main() Function
int main(void) // main recieves a copy of the Max function macros table
{
long attrflags = 0;
t_class *c;
t_object *attr;
jamoma_init();
common_symbols_init();
c = class_new("jcom.oscinstance",(method)oscinstance_new, (method)0L, sizeof(t_oscinstance), (method)0L, A_GIMME, 0);
class_addmethod(c, (method)oscinstance_bang, "bang", 0);
class_addmethod(c, (method)oscinstance_int, "int", A_DEFLONG, 0L);
class_addmethod(c, (method)oscinstance_float, "float", A_DEFFLOAT, 0L);
class_addmethod(c, (method)oscinstance_symbol, "list", A_GIMME, 0L);
class_addmethod(c, (method)oscinstance_symbol, "anything", A_GIMME, 0L);
class_addmethod(c, (method)oscinstance_assist, "assist", A_CANT, 0L);
class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT,0);
// Finalize our class
class_register(CLASS_BOX, c);
oscinstance_class = c;
return 0;
}
/************************************************************************************/
// Object Life
void *oscinstance_new(t_symbol *s, long argc, t_atom *argv)
{
t_oscinstance *x = (t_oscinstance *)object_alloc(oscinstance_class);
if(x){
x->outlet_overflow = outlet_new(x, 0); // overflow outlet
object_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow); // dumpout
x->outlet2 = outlet_new(x, 0); // Create Outlet
x->outlet1 = outlet_new(x, 0); // Create Outlet
x->outlet0 = outlet_new(x, 0); // Create Outlet
}
return (x); // return the pointer to our new instantiation
}
/************************************************************************************/
// Methods bound to input/inlets
// Method for Assistance Messages
void oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst)
{
if(msg==1) // Inlet
strcpy(dst, "Input");
else if(msg==2){ // Outlets
if(arg == 0)
strcpy(dst, "OSC message with instance info stripped");
else if (arg == 1)
strcpy(dst, "OSC instance number or ID");
else if (arg == 2)
strcpy(dst, "parameter value");
else
strcpy(dst, "dumpout / overflow from non-matching input");
}
}
void oscinstance_bang(t_oscinstance *x)
{
outlet_bang(x->outlet_overflow);
}
// INT INPUT
void oscinstance_int(t_oscinstance *x, long n)
{
outlet_int(x->outlet_overflow, n);
}
// FLOAT INPUT
void oscinstance_float(t_oscinstance *x, double f)
{
outlet_float(x->outlet_overflow, f);
}
// SYMBOL INPUT
void oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv)
{
char input[MAX_MESS_SIZE]; // our input string
char *input2 = input; // pointer to our input string
char *dot;
char *slash;
t_symbol *instance;
char *instanceEnd;
t_symbol *output;
t_symbol *osc = NULL;
long i;
strcpy(input, msg->s_name);
// This object only deals with OSC messages
if(!*input2 == '/') {
goto spillover;
}
input2++; // jump past the leading slash
dot = strchr(input2, '.'); // look for dot
if (dot == NULL)
goto spillover;
slash = strchr(input2, '/'); // checking for additional osc branches
if ( slash == 0) {
*dot = NULL;
osc = gensym(input2-1); // reintroduce the leading slash
instance = gensym(dot+1);
}
else {
if ( slash<dot )
goto spillover; // there are instances, but not in the leading branch
*dot = NULL;
*slash = NULL; // temporarily remove the slash
instance = gensym(dot+1);
*slash = '/'; // put slash back in
strcat(input, slash); // remove the instance part and concatenate
osc = gensym(input2-1); // reintroduce the leading slash
}
// Output from 3rd outlet: The arguments of the OSC message
// We have to check what message to return.
// The message received has no arguments:
if (argc == 0) {
outlet_bang(x->outlet2);
}
// The message received has one argument only:
else if (argc==1) {
// int argument
if (argv->a_type==A_LONG)
outlet_int(x->outlet2,argv->a_w.w_long);
// float argument
else if (argv->a_type==A_FLOAT)
outlet_float(x->outlet2,argv->a_w.w_float);
// something else
else if (argv->a_type==A_SYM)
outlet_anything(x->outlet2,argv->a_w.w_sym,0,0);
}
// There are two or more arguments: check if first is A_SYM
else {
if (argv->a_type==A_SYM) {
output = argv->a_w.w_sym;
argc--;
argv++;
}
else
output = _sym_list;
outlet_anything(x->outlet2, output, argc , argv);
}
// Output from 2nd outlet: Instance. Check if the instance is an integer (long):
i = strtol (instance->s_name,&instanceEnd,10);
if (instance->s_name[0] != '\n' && (*instanceEnd == '\n' || *instanceEnd == '\0'))
outlet_int(x->outlet1, i);
else
outlet_anything(x->outlet1, instance, NULL, 0L);
// Output from 1st outlet: OC name with instance removed
outlet_anything(x->outlet0, osc, NULL, 0L);
return;
spillover:
outlet_anything(x->outlet_overflow, msg, argc , argv);
return;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ServerSocket.h"
#include "SocketError.h"
#ifdef HAVE_WINSOCK2_H
#include <Winsock2.h>
#include <Ws2tcpip.h>
#include <sys/stat.h>
#define stat _stat
#else
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/types.h>
#include <assert.h>
#include <string>
using namespace activemq::network;
#ifdef HAVE_WINSOCK2_H
// Static socket initializer needed for winsock
ServerSocket::StaticServerSocketInitializer::StaticServerSocketInitializer () {
socketInitError = NULL;
const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version
WSAData temp;
if( WSAStartup(version_needed, &temp )){
clear();
socketInitError = new SocketException ( __FILE__, __LINE__,
"winsock.dll was not found");
}
}
ServerSocket::StaticServerSocketInitializer::~StaticServerSocketInitializer () {
clear();
WSACleanup();
}
// Create static instance of the socket initializer.
ServerSocket::StaticServerSocketInitializer
ServerSocket::staticSocketInitializer;
#endif
////////////////////////////////////////////////////////////////////////////////
ServerSocket::ServerSocket()
{
socketHandle = Socket::INVALID_SOCKET_HANDLE;
#if defined(HAVE_WINSOCK2_H)
if( ServerSocket::staticSocketInitializer.getSocketInitError() != NULL ) {
throw *ServerSocket::staticSocketInitializer.getSocketInitError();
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
ServerSocket::~ServerSocket()
{
// No shutdown, just close - dont want blocking destructor.
close();
}
////////////////////////////////////////////////////////////////////////////////
void ServerSocket::bind( const char* host, int port ) throw ( SocketException )
{
bind (host, port, SOMAXCONN);
}
////////////////////////////////////////////////////////////////////////////////
void ServerSocket::bind( const char* host,
int port,
int backlog ) throw ( SocketException )
{
if(isBound()) {
throw SocketException ( __FILE__, __LINE__,
"ServerSocket::bind - Socket already bound" );
}
// Create the socket.
socketHandle = ::socket(AF_INET, SOCK_STREAM, 0 );
if( socketHandle < 0) {
socketHandle = Socket::INVALID_SOCKET_HANDLE;
throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str());
}
// Verify the port value.
if( port <= 0 || port > 65535 ) {
throw SocketException( __FILE__, __LINE__,
"ServerSocket::bind - Port out of range: %d", port );
}
sockaddr_in bind_addr;
bind_addr.sin_family = AF_INET;
bind_addr.sin_port = htons((short)port);
bind_addr.sin_addr.s_addr = 0; // To be set later down...
memset(&bind_addr.sin_zero, 0, sizeof(bind_addr.sin_zero));
int status;
// Resolve name
#if defined(HAVE_STRUCT_ADDRINFO)
::addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = PF_INET;
struct addrinfo *res_ptr = NULL;
status = ::getaddrinfo(host, NULL, &hints, &res_ptr);
if( status != 0 || res_ptr == NULL) {
throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );
}
assert(res_ptr->ai_addr->sa_family == AF_INET);
// Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.
assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);
bind_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;
freeaddrinfo(res_ptr);
#else
struct ::hostent *he = ::gethostbyname(host);
if( he == NULL ) {
throw SocketException( __FILE__, __LINE__, "Failed to resolve hostname" );
}
bind_addr.sin_addr.s_addr = *((in_addr_t *)he->h_addr);
#endif
// Set the socket to reuse the address.
int value = 1;
::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) );
status = ::bind(socketHandle,
reinterpret_cast<sockaddr*>(&bind_addr), sizeof( bind_addr ));
if( status < 0 ){
close();
throw SocketException ( __FILE__, __LINE__,
"ServerSocket::bind - %s", SocketError::getErrorString().c_str() );
}
status = ::listen( socketHandle, (int)backlog );
if( status < 0 ) {
close();
throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );
}
}
////////////////////////////////////////////////////////////////////////////////
void ServerSocket::close() throw (cms::CMSException){
if( isBound() ) {
#if !defined(HAVE_WINSOCK2_H)
::close( socketHandle );
#else
::closesocket( socketHandle );
#endif
socketHandle = Socket::INVALID_SOCKET_HANDLE;
}
}
////////////////////////////////////////////////////////////////////////////////
bool ServerSocket::isBound() const {
return this->socketHandle != Socket::INVALID_SOCKET_HANDLE;
}
////////////////////////////////////////////////////////////////////////////////
Socket* ServerSocket::accept() throw (SocketException)
{
struct sockaddr_in temp;
#if !defined(HAVE_WINSOCK2_H)
socklen_t temp_len = sizeof( sockaddr_in );
#else
int temp_len = sizeof( sockaddr_in );
#endif
SocketHandle ss_socket_handle =
::accept( socketHandle, reinterpret_cast<struct sockaddr*>(&temp), &temp_len );
if( ss_socket_handle < 0 ) {
throw SocketException( __FILE__, __LINE__,
"ServerSocket::accept- %s", SocketError::getErrorString().c_str() );
}
return new TcpSocket( ss_socket_handle );
}
<commit_msg>AMQCPP-107 - adding handling of signal interruptions to ServerSocket<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ServerSocket.h"
#include "SocketError.h"
#ifdef HAVE_WINSOCK2_H
#include <Winsock2.h>
#include <Ws2tcpip.h>
#include <sys/stat.h>
#define stat _stat
#else
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/types.h>
#include <assert.h>
#include <string>
using namespace activemq::network;
#ifdef HAVE_WINSOCK2_H
// Static socket initializer needed for winsock
ServerSocket::StaticServerSocketInitializer::StaticServerSocketInitializer () {
socketInitError = NULL;
const WORD version_needed = MAKEWORD(2,2); // lo-order byte: major version
WSAData temp;
if( WSAStartup(version_needed, &temp )){
clear();
socketInitError = new SocketException ( __FILE__, __LINE__,
"winsock.dll was not found");
}
}
ServerSocket::StaticServerSocketInitializer::~StaticServerSocketInitializer () {
clear();
WSACleanup();
}
// Create static instance of the socket initializer.
ServerSocket::StaticServerSocketInitializer
ServerSocket::staticSocketInitializer;
#endif
////////////////////////////////////////////////////////////////////////////////
ServerSocket::ServerSocket()
{
socketHandle = Socket::INVALID_SOCKET_HANDLE;
#if defined(HAVE_WINSOCK2_H)
if( ServerSocket::staticSocketInitializer.getSocketInitError() != NULL ) {
throw *ServerSocket::staticSocketInitializer.getSocketInitError();
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
ServerSocket::~ServerSocket()
{
// No shutdown, just close - dont want blocking destructor.
close();
}
////////////////////////////////////////////////////////////////////////////////
void ServerSocket::bind( const char* host, int port ) throw ( SocketException )
{
bind (host, port, SOMAXCONN);
}
////////////////////////////////////////////////////////////////////////////////
void ServerSocket::bind( const char* host,
int port,
int backlog ) throw ( SocketException )
{
if(isBound()) {
throw SocketException ( __FILE__, __LINE__,
"ServerSocket::bind - Socket already bound" );
}
// Create the socket.
socketHandle = ::socket(AF_INET, SOCK_STREAM, 0 );
if( socketHandle < 0) {
socketHandle = Socket::INVALID_SOCKET_HANDLE;
throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str());
}
// Verify the port value.
if( port <= 0 || port > 65535 ) {
throw SocketException( __FILE__, __LINE__,
"ServerSocket::bind - Port out of range: %d", port );
}
sockaddr_in bind_addr;
bind_addr.sin_family = AF_INET;
bind_addr.sin_port = htons((short)port);
bind_addr.sin_addr.s_addr = 0; // To be set later down...
memset(&bind_addr.sin_zero, 0, sizeof(bind_addr.sin_zero));
int status;
// Resolve name
#if defined(HAVE_STRUCT_ADDRINFO)
::addrinfo hints;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = PF_INET;
struct addrinfo *res_ptr = NULL;
status = ::getaddrinfo(host, NULL, &hints, &res_ptr);
if( status != 0 || res_ptr == NULL) {
throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );
}
assert(res_ptr->ai_addr->sa_family == AF_INET);
// Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.
assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);
bind_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;
freeaddrinfo(res_ptr);
#else
struct ::hostent *he = ::gethostbyname(host);
if( he == NULL ) {
throw SocketException( __FILE__, __LINE__, "Failed to resolve hostname" );
}
bind_addr.sin_addr.s_addr = *((in_addr_t *)he->h_addr);
#endif
// Set the socket to reuse the address.
int value = 1;
::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) );
status = ::bind(socketHandle,
reinterpret_cast<sockaddr*>(&bind_addr), sizeof( bind_addr ));
if( status < 0 ){
close();
throw SocketException ( __FILE__, __LINE__,
"ServerSocket::bind - %s", SocketError::getErrorString().c_str() );
}
status = ::listen( socketHandle, (int)backlog );
if( status < 0 ) {
close();
throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );
}
}
////////////////////////////////////////////////////////////////////////////////
void ServerSocket::close() throw (cms::CMSException){
if( isBound() ) {
#if !defined(HAVE_WINSOCK2_H)
::close( socketHandle );
#else
::closesocket( socketHandle );
#endif
socketHandle = Socket::INVALID_SOCKET_HANDLE;
}
}
////////////////////////////////////////////////////////////////////////////////
bool ServerSocket::isBound() const {
return this->socketHandle != Socket::INVALID_SOCKET_HANDLE;
}
////////////////////////////////////////////////////////////////////////////////
Socket* ServerSocket::accept() throw (SocketException)
{
struct sockaddr_in temp;
#if !defined(HAVE_WINSOCK2_H)
socklen_t temp_len = sizeof( sockaddr_in );
#else
int temp_len = sizeof( sockaddr_in );
#endif
SocketHandle ss_socket_handle = NULL;
// Loop to ignore any signal interruptions that occur during the operation.
do {
ss_socket_handle = ::accept( socketHandle,
reinterpret_cast<struct sockaddr*>(&temp),
&temp_len );
} while( ss_socket_handle < 0 &&
SocketError::getErrorCode() == SocketError::INTERRUPTED );
if( ss_socket_handle < 0 ) {
throw SocketException( __FILE__, __LINE__,
"ServerSocket::accept- %s", SocketError::getErrorString().c_str() );
}
return new TcpSocket( ss_socket_handle );
}
<|endoftext|>
|
<commit_before>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <termios.h>
#include <sys/ioctl.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#include <map>
#include <functional>
#include <experimental/optional>
#include "History.hpp"
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::string printBuffer;
thread_local std::string::iterator printBufferPos;
using namespace yb;
thread_local History history;
thread_local History::const_iterator historyPos;
static char arrowIndicator = 0;
using ReadSignature = ssize_t (*)(int, void*, size_t);
using Char = unsigned char;
using CharOpt = std::experimental::optional<Char>;
CharOpt newlineHandler(Char);
CharOpt tabHandler(Char);
CharOpt backspaceHandler(Char);
CharOpt regularCHarHandler(Char);
CharOpt arrowHandler1(Char);
CharOpt arrowHandler2(Char);
CharOpt arrowHandler3(Char);
thread_local std::map<Char, std::function<CharOpt(Char)>> handlers = {
{0x06, tabHandler},
{0x0d, newlineHandler},
{0x17, newlineHandler}, // TODO: this should delete one word
{0x1b, arrowHandler1},
{0x5b, arrowHandler2},
{0x43, arrowHandler3},
{0x7f, backspaceHandler}
};
int getCursorPosition(int &x, int &y) {
int retVal = -1;
fd_set stdInSet;
struct timeval time;
struct termios rawTermios, oldTermios;
tcgetattr(STDIN_FILENO, &oldTermios);
rawTermios = oldTermios;
rawTermios.c_lflag &= ~ICANON;
rawTermios.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &rawTermios);
printf("\033[6n");
fflush(stdout);
FD_ZERO(&stdInSet);
FD_SET(STDIN_FILENO, &stdInSet);
time.tv_sec = 0;
time.tv_usec = 100000;
if (select(STDIN_FILENO + 1, &stdInSet, NULL, NULL, &time) == 1)
if (scanf("\033[%d;%dR", &x, &y) == 2)
retVal = 0;
tcsetattr(STDIN_FILENO, TCSADRAIN, &oldTermios);
return retVal;
}
int getTerminalWidth() {
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
return w.ws_col;
}
void clearTerminalLine() {
// TODO: get info about terminal width and current cursor position
// and fix below loops
int col, row, width;
if (getCursorPosition(row, col)) return;
width = getTerminalWidth();
for (int i = 0; i < width - col; i++)
printf(" ");
fflush(stdout);
for (int i = 0; i < width - col; i++)
cursor_backward(1);
}
std::string findCompletion(History::const_iterator start, const std::string &pattern) {
for (auto it = start - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.end();
return pattern;
}
void printCompletion(History::const_iterator startIterator, int offset) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
clearTerminalLine();
if (offset)
cursor_forward(offset);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + offset);
fflush(stdout);
}
CharOpt newlineHandler(Char) {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
return {};
}
CharOpt backspaceHandler(Char) {
if (lineBufferPos != lineBuffer.begin()) {
*(--lineBufferPos) = 0;
}
return {};
}
CharOpt regularCharHandler(Char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.end(), 1);
return {};
}
CharOpt tabHandler(Char) {
printCompletion(historyPos, 0);
return Char{0}; // TODO: this does not seem to work.
}
CharOpt arrowHandler1(Char) {
arrowIndicator = 1;
return {};
}
CharOpt arrowHandler2(Char c) {
if (arrowIndicator == 1) {
arrowIndicator = 2;
return {};
}
else {
return regularCharHandler(c);
}
}
CharOpt arrowHandler3(Char c) {
CharOpt return_value = {};
if (arrowIndicator == 2) {
arrowIndicator = 0;
}
else {
return_value = regularCharHandler(c);
}
try {
printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());
printBufferPos = printBuffer.begin();
} catch (...) {
// FIXME:
}
return return_value;
}
static unsigned char yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
history.read(std::string{getenv("HOME")} + "/.bash_history");
auto handler = handlers[c];
// TODO(Mrokkk): There would be a problem with processing all escape codes
// that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).
// It would be thoughtful if we just disable our yebash if any of these codes would
// occur and reenable it after a newline
CharOpt cReturned = c;
if (handler) {
handler(c);
}
else {
if (c < 0x20) {
newlineHandler(c);
}
else {
regularCharHandler(c);
}
}
if (static_cast<bool>(cReturned)) {
return cReturned.value();
}
return c;
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
static thread_local ReadSignature realRead = nullptr;
if (fd == 0) { // TODO: make it look good
if (printBuffer.length()) {
// Return printBuffer to bash one char at time
*reinterpret_cast<char *>(buf) = *printBufferPos;
*lineBufferPos++ = *printBufferPos++;
if (printBufferPos == printBuffer.end()) {
printBuffer.erase(printBuffer.begin(), printBuffer.end());
}
return 1;
}
}
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0 && isatty(fileno(stdin)))
*reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<commit_msg>Improve clearing line<commit_after>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <termios.h>
#include <sys/ioctl.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#include <map>
#include <functional>
#include <experimental/optional>
#include "History.hpp"
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::string printBuffer;
thread_local std::string::iterator printBufferPos;
using namespace yb;
thread_local History history;
thread_local History::const_iterator historyPos;
static char arrowIndicator = 0;
using ReadSignature = ssize_t (*)(int, void*, size_t);
using Char = unsigned char;
using CharOpt = std::experimental::optional<Char>;
CharOpt newlineHandler(Char);
CharOpt tabHandler(Char);
CharOpt backspaceHandler(Char);
CharOpt regularCHarHandler(Char);
CharOpt arrowHandler1(Char);
CharOpt arrowHandler2(Char);
CharOpt arrowHandler3(Char);
thread_local std::map<Char, std::function<CharOpt(Char)>> handlers = {
{0x06, tabHandler},
{0x0d, newlineHandler},
{0x17, newlineHandler}, // TODO: this should delete one word
{0x1b, arrowHandler1},
{0x5b, arrowHandler2},
{0x43, arrowHandler3},
{0x7f, backspaceHandler}
};
int getCursorPosition() {
int retVal = 0, x, y;
fd_set stdInSet;
struct timeval time;
struct termios rawTermios, oldTermios;
tcgetattr(STDIN_FILENO, &oldTermios);
rawTermios = oldTermios;
rawTermios.c_lflag &= ~ICANON;
rawTermios.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &rawTermios);
printf("\033[6n");
fflush(stdout);
FD_ZERO(&stdInSet);
FD_SET(STDIN_FILENO, &stdInSet);
time.tv_sec = 0;
time.tv_usec = 100000;
if (select(STDIN_FILENO + 1, &stdInSet, NULL, NULL, &time) == 1)
if (scanf("\033[%d;%dR", &x, &y) == 2)
retVal = y;
tcsetattr(STDIN_FILENO, TCSADRAIN, &oldTermios);
return retVal;
}
int getTerminalWidth() {
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
return w.ws_col;
}
void clearTerminalLine() {
int pos, width;
if (!(pos = getCursorPosition())) return;
width = getTerminalWidth();
for (int i = 0; i < width - pos; i++)
printf(" ");
fflush(stdout);
for (int i = 0; i < width - pos; i++)
cursor_backward(1);
}
std::string findCompletion(History::const_iterator start, const std::string &pattern) {
for (auto it = start - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.end();
return pattern;
}
void printCompletion(History::const_iterator startIterator, int offset) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
clearTerminalLine();
if (offset)
cursor_forward(offset);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + offset);
fflush(stdout);
}
CharOpt newlineHandler(Char) {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
return {};
}
CharOpt backspaceHandler(Char) {
if (lineBufferPos != lineBuffer.begin()) {
*(--lineBufferPos) = 0;
}
return {};
}
CharOpt regularCharHandler(Char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.end(), 1);
return {};
}
CharOpt tabHandler(Char) {
printCompletion(historyPos, 0);
return Char{0}; // TODO: this does not seem to work.
}
CharOpt arrowHandler1(Char) {
arrowIndicator = 1;
return {};
}
CharOpt arrowHandler2(Char c) {
if (arrowIndicator == 1) {
arrowIndicator = 2;
return {};
}
else {
return regularCharHandler(c);
}
}
CharOpt arrowHandler3(Char c) {
CharOpt return_value = {};
if (arrowIndicator == 2) {
arrowIndicator = 0;
}
else {
return_value = regularCharHandler(c);
}
try {
printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());
printBufferPos = printBuffer.begin();
} catch (...) {
// FIXME:
}
return return_value;
}
static unsigned char yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
history.read(std::string{getenv("HOME")} + "/.bash_history");
auto handler = handlers[c];
// TODO(Mrokkk): There would be a problem with processing all escape codes
// that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).
// It would be thoughtful if we just disable our yebash if any of these codes would
// occur and reenable it after a newline
CharOpt cReturned = c;
if (handler) {
handler(c);
}
else {
if (c < 0x20) {
newlineHandler(c);
}
else {
regularCharHandler(c);
}
}
if (static_cast<bool>(cReturned)) {
return cReturned.value();
}
return c;
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
static thread_local ReadSignature realRead = nullptr;
if (fd == 0) { // TODO: make it look good
if (printBuffer.length()) {
// Return printBuffer to bash one char at time
*reinterpret_cast<char *>(buf) = *printBufferPos;
*lineBufferPos++ = *printBufferPos++;
if (printBufferPos == printBuffer.end()) {
printBuffer.erase(printBuffer.begin(), printBuffer.end());
}
return 1;
}
}
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0 && isatty(fileno(stdin)))
*reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBayesianClassifierImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkBayesianClassifierImageFilter.h"
#include "itkBayesianClassifierInitializationImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "../IO/itkPipelineMonitorImageFilter.h"
int itkBayesianClassifierImageFilterTest(int argc, char* argv[] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile numberOfClasses smoothingIterations" << std::endl;
return EXIT_FAILURE;
}
// setup reader
const unsigned int Dimension = 2;
typedef unsigned char InputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef unsigned char LabelType;
typedef float PriorType;
typedef float PosteriorType;
typedef itk::BayesianClassifierInitializationImageFilter< InputImageType >
BayesianInitializerType;
BayesianInitializerType::Pointer bayesianInitializer = BayesianInitializerType::New();
bayesianInitializer->SetInput( reader->GetOutput() );
bayesianInitializer->SetNumberOfClasses( atoi( argv[3] ) );
typedef BayesianInitializerType::OutputImageType InitialLabelImageType;
typedef itk::BayesianClassifierImageFilter<
InitialLabelImageType, LabelType, PosteriorType, PriorType > ClassifierFilterType;
ClassifierFilterType::Pointer filter = ClassifierFilterType::New();
filter->SetInput( bayesianInitializer->GetOutput() );
//
// Exercise Set/GetNumberOfSmoothingIterations()
//
filter->SetNumberOfSmoothingIterations( 1 );
if( filter->GetNumberOfSmoothingIterations() != 1 )
{
std::cerr << "Error in Set/GetNumberOfSmoothingIterations()" << std::endl;
return EXIT_FAILURE;
}
filter->SetNumberOfSmoothingIterations( 19 );
if( filter->GetNumberOfSmoothingIterations() != 19 )
{
std::cerr << "Error in Set/GetNumberOfSmoothingIterations()" << std::endl;
return EXIT_FAILURE;
}
filter->SetNumberOfSmoothingIterations( 0 );
filter->SetNumberOfSmoothingIterations( atoi( argv[4] ));
typedef ClassifierFilterType::ExtractedComponentImageType ExtractedComponentImageType;
typedef itk::GradientAnisotropicDiffusionImageFilter<
ExtractedComponentImageType, ExtractedComponentImageType > SmoothingFilterType;
SmoothingFilterType::Pointer smoother = SmoothingFilterType::New();
smoother->SetNumberOfIterations( 1 );
smoother->SetTimeStep( 0.125 );
smoother->SetConductanceParameter( 3 );
filter->SetSmoothingFilter( smoother );
//
// Exercise Set/GetSmoothingFilter()
//
if( filter->GetSmoothingFilter().GetPointer() != smoother.GetPointer() )
{
std::cerr << "Error in Set/GetSmoothingFilter()" << std::endl;
return EXIT_FAILURE;
}
filter->SetSmoothingFilter( NULL );
if( filter->GetSmoothingFilter().GetPointer() != NULL )
{
std::cerr << "Error in Set/GetSmoothingFilter()" << std::endl;
return EXIT_FAILURE;
}
filter->SetSmoothingFilter( smoother );
typedef itk::PipelineMonitorImageFilter<InputImageType> MonitorFilterType;
MonitorFilterType::Pointer monitor = MonitorFilterType::New();
monitor->SetInput(filter->GetOutput());
typedef ClassifierFilterType::OutputImageType ClassifierOutputImageType;
typedef itk::Image< unsigned char, Dimension > OutputImageType;
typedef itk::RescaleIntensityImageFilter<
ClassifierOutputImageType, OutputImageType > RescalerType;
RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetInput( monitor->GetOutput() );
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
writer->SetInput( rescaler->GetOutput() );
try
{
filter->Update();
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught: " << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if (!monitor->VerifyAllIputCanNotStream())
{
std::cout << "pipeline did not execute as expected!" << std::endl;
return EXIT_FAILURE;
}
filter->Print( std::cout );
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Adding a code for exercising the SetPriors() method.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBayesianClassifierImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkBayesianClassifierImageFilter.h"
#include "itkBayesianClassifierInitializationImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "../IO/itkPipelineMonitorImageFilter.h"
int itkBayesianClassifierImageFilterTest(int argc, char* argv[] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile numberOfClasses smoothingIterations" << std::endl;
return EXIT_FAILURE;
}
// setup reader
const unsigned int Dimension = 2;
typedef unsigned char InputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef unsigned char LabelType;
typedef float PriorType;
typedef float PosteriorType;
typedef itk::BayesianClassifierInitializationImageFilter< InputImageType >
BayesianInitializerType;
BayesianInitializerType::Pointer bayesianInitializer = BayesianInitializerType::New();
bayesianInitializer->SetInput( reader->GetOutput() );
bayesianInitializer->SetNumberOfClasses( atoi( argv[3] ) );
typedef BayesianInitializerType::OutputImageType InitialLabelImageType;
typedef itk::BayesianClassifierImageFilter<
InitialLabelImageType, LabelType, PosteriorType, PriorType > ClassifierFilterType;
ClassifierFilterType::Pointer filter = ClassifierFilterType::New();
filter->SetInput( bayesianInitializer->GetOutput() );
//
// Exercise Set/GetNumberOfSmoothingIterations()
//
filter->SetNumberOfSmoothingIterations( 1 );
if( filter->GetNumberOfSmoothingIterations() != 1 )
{
std::cerr << "Error in Set/GetNumberOfSmoothingIterations()" << std::endl;
return EXIT_FAILURE;
}
filter->SetNumberOfSmoothingIterations( 19 );
if( filter->GetNumberOfSmoothingIterations() != 19 )
{
std::cerr << "Error in Set/GetNumberOfSmoothingIterations()" << std::endl;
return EXIT_FAILURE;
}
filter->SetNumberOfSmoothingIterations( 0 );
filter->SetNumberOfSmoothingIterations( atoi( argv[4] ));
typedef ClassifierFilterType::ExtractedComponentImageType ExtractedComponentImageType;
typedef itk::GradientAnisotropicDiffusionImageFilter<
ExtractedComponentImageType, ExtractedComponentImageType > SmoothingFilterType;
SmoothingFilterType::Pointer smoother = SmoothingFilterType::New();
smoother->SetNumberOfIterations( 1 );
smoother->SetTimeStep( 0.125 );
smoother->SetConductanceParameter( 3 );
filter->SetSmoothingFilter( smoother );
//
// Exercise Set/GetSmoothingFilter()
//
if( filter->GetSmoothingFilter().GetPointer() != smoother.GetPointer() )
{
std::cerr << "Error in Set/GetSmoothingFilter()" << std::endl;
return EXIT_FAILURE;
}
filter->SetSmoothingFilter( NULL );
if( filter->GetSmoothingFilter().GetPointer() != NULL )
{
std::cerr << "Error in Set/GetSmoothingFilter()" << std::endl;
return EXIT_FAILURE;
}
filter->SetSmoothingFilter( smoother );
typedef itk::PipelineMonitorImageFilter<InputImageType> MonitorFilterType;
MonitorFilterType::Pointer monitor = MonitorFilterType::New();
monitor->SetInput(filter->GetOutput());
typedef ClassifierFilterType::OutputImageType ClassifierOutputImageType;
typedef itk::Image< unsigned char, Dimension > OutputImageType;
typedef itk::RescaleIntensityImageFilter<
ClassifierOutputImageType, OutputImageType > RescalerType;
RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetInput( monitor->GetOutput() );
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
writer->SetInput( rescaler->GetOutput() );
try
{
filter->Update();
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught: " << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if (!monitor->VerifyAllIputCanNotStream())
{
std::cout << "pipeline did not execute as expected!" << std::endl;
return EXIT_FAILURE;
}
filter->Print( std::cout );
std::cout << "Test passed." << std::endl;
typedef ClassifierFilterType::PriorsImageType PriorsImageType;
const InputImageType * inputImage = reader->GetOutput();
PriorsImageType::Pointer priorsImage = PriorsImageType::New();
priorsImage->CopyInformation( inputImage );
priorsImage->SetRegions( inputImage->GetLargestPossibleRegion() );
priorsImage->SetNumberOfComponentsPerPixel(5);
priorsImage->Allocate();
filter->SetPriors( priorsImage );
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#pragma once
#ifndef REPLACER_HPP
#define REPLACER_HPP
#include <QString>
#include "tags/textwidget.hpp"
#include "tags/report.hpp"
namespace qtreports
{
namespace detail
{
/*! @~russian
@brief Класс, заменяющий параметры на реальные значения.
Класс, заменяющий параметры на реальные значения в тэгах,
производных от TextWidget
*/
class Replacer {
public:
Replacer();
~Replacer();
/*! @~russian
Возвращает текст с подставленными значениями параметров.
@param[in] text Исходный текст
@param[in] report Указатель на отчет
*/
QString replaceParameters( const QString & text, const ReportPtr & report );
/*! @~russian
Заменяет текст виджета текстом с подставленными значениями параметров.
Перегружанная функция, предоставленная для удобства.
@param[in] widget Указатель на виджет
@param[in] report Указатель на отчет
*/
bool replaceParametersInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report );
/*! @~russian
Заменяет текст всех виджетов секции текстом с подставленными значениями параметров.
Перегружанная функция, предоставленная для удобства.
@param[in] section Указатель на секцию
@param[in] report Указатель на отчет
*/
bool replaceParametersInSection( const SectionPtr & section, const ReportPtr & report );
/*! @~russian
Заменяет текст всех виджетов с текстом в отчете
текстом с подставленными значениями параметров.
Перегружанная функция, предоставленная для удобства.
@param[in] report Указатель на отчет
*/
bool replaceParameters( const ReportPtr & report );
/*! @~russian
Возвращает текст с подставленными значениями полей из источника данных.
@param[in] report Указатель на отчет
@param[in] text Исходный текст
@param[in] i Текущая строка
*/
QString replaceField( const QString & text, const ReportPtr & report, int i );
/*! @~russian
Заменяет текст виджета текстом с подставленными значениями полей из источника данных.
Перегружанная функция, предоставленная для удобства.
@param[in] widget Указатель на виджет
@param[in] report Указатель на отчет
@param[in] i Текущая строка
*/
bool replaceFieldInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report, int i );
/*! @~russian
Заменяет текст всех виджетов секции
текстом с подставленными значениями полей из источника данных.
Перегружанная функция, предоставленная для удобства.
@param[in] section Указатель на секцию
@param[in] report Указатель на отчет
@param[in] i Текущая строка
*/
bool replaceFieldInSection( const SectionPtr & section, const ReportPtr & report, int i );
/*! @~russian
Заменяет текст всех виджетов секции
текстом с подставленными значениями.
Перегружанная функция, предоставленная для удобства.
@param[in] section Указатель на секцию
@param[in] report Указатель на отчет
@param[in] i Текущая строка
*/
bool replace( const SectionPtr & section, const ReportPtr & report, int i );
const QString getLastError() const;
private:
QString m_lastError;
};
}
}
#endif // REPLACER_HPP
<commit_msg>Full doc<commit_after>#pragma once
#ifndef REPLACER_HPP
#define REPLACER_HPP
#include <QString>
#include "tags/textwidget.hpp"
#include "tags/report.hpp"
namespace qtreports
{
namespace detail
{
/*! @~russian
@brief Класс, заменяющий параметры на реальные значения.
Класс, заменяющий параметры на реальные значения в тэгах,
производных от TextWidget
*/
class Replacer {
public:
Replacer();
~Replacer();
/*! @~russian
Возвращает текст с подставленными значениями параметров.
@param[in] text Исходный текст
@param[in] report Указатель на отчет
*/
QString replaceParameters( const QString & text, const ReportPtr & report );
/*! @~russian
Заменяет текст виджета текстом с подставленными значениями параметров.
Перегружанная функция, предоставленная для удобства.
@param[in] widget Указатель на виджет
@param[in] report Указатель на отчет
*/
bool replaceParametersInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report );
/*! @~russian
Заменяет текст всех виджетов секции текстом с подставленными значениями параметров.
Перегружанная функция, предоставленная для удобства.
@param[in] section Указатель на секцию
@param[in] report Указатель на отчет
*/
bool replaceParametersInSection( const SectionPtr & section, const ReportPtr & report );
/*! @~russian
Заменяет текст всех виджетов с текстом в отчете
текстом с подставленными значениями параметров.
Перегружанная функция, предоставленная для удобства.
@param[in] report Указатель на отчет
*/
bool replaceParameters( const ReportPtr & report );
/*! @~russian
Возвращает текст с подставленными значениями полей из источника данных.
@param[in] report Указатель на отчет
@param[in] text Исходный текст
@param[in] i Текущая строка
*/
QString replaceField( const QString & text, const ReportPtr & report, int i );
/*! @~russian
Заменяет текст виджета текстом с подставленными значениями полей из источника данных.
Перегружанная функция, предоставленная для удобства.
@param[in] widget Указатель на виджет
@param[in] report Указатель на отчет
@param[in] i Текущая строка
*/
bool replaceFieldInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report, int i );
/*! @~russian
Заменяет текст всех виджетов секции
текстом с подставленными значениями полей из источника данных.
Перегружанная функция, предоставленная для удобства.
@param[in] section Указатель на секцию
@param[in] report Указатель на отчет
@param[in] i Текущая строка
*/
bool replaceFieldInSection( const SectionPtr & section, const ReportPtr & report, int i );
/*! @~russian
Заменяет текст всех виджетов секции
текстом с подставленными значениями.
Перегружанная функция, предоставленная для удобства.
@param[in] section Указатель на секцию
@param[in] report Указатель на отчет
@param[in] i Текущая строка
*/
bool replace( const SectionPtr & section, const ReportPtr & report, int i );
/*! @~russian
Возвращает описание последней произошедшей ошибки.
*/
const QString getLastError() const;
private:
QString m_lastError;
};
}
}
#endif // REPLACER_HPP
<|endoftext|>
|
<commit_before>//
// WinAPI
//
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <SetupAPI.h>
#include <Shlwapi.h>
#include <initguid.h>
#include <winioctl.h>
#include "XUSB.h"
//
// STL
//
#include <string>
#include <codecvt>
#include <locale>
#include <map>
#include <iostream>
#include <fstream>
//
// JSON
//
#include <json/json.h>
//
// Hooking
//
#include <detours/detours.h>
//
// Logging
//
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/fmt/bin_to_hex.h>
using convert_t = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_t, wchar_t> strconverter;
std::once_flag g_init;
std::string g_dllDir;
static decltype(SetupDiEnumDeviceInterfaces) *real_SetupDiEnumDeviceInterfaces = SetupDiEnumDeviceInterfaces;
static decltype(DeviceIoControl) *real_DeviceIoControl = DeviceIoControl;
static decltype(CreateFileA) *real_CreateFileA = CreateFileA;
static decltype(CreateFileW) *real_CreateFileW = CreateFileW;
static decltype(WriteFile)* real_WriteFile = WriteFile;
static decltype(CloseHandle)* real_CloseHandle = CloseHandle;
static decltype(GetOverlappedResult)* real_GetOverlappedResult = GetOverlappedResult;
static std::map<HANDLE, std::string> g_handleToPath;
static std::map<DWORD, std::string> g_ioctlMap;
//
// Hooks SetupDiEnumDeviceInterfaces() API
//
BOOL WINAPI DetourSetupDiEnumDeviceInterfaces(
HDEVINFO DeviceInfoSet,
PSP_DEVINFO_DATA DeviceInfoData,
const GUID* InterfaceClassGuid,
DWORD MemberIndex,
PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("SetupDiEnumDeviceInterfaces");
auto retval = real_SetupDiEnumDeviceInterfaces(DeviceInfoSet, DeviceInfoData, InterfaceClassGuid, MemberIndex,
DeviceInterfaceData);
_logger->info("InterfaceClassGuid = {{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}, "
"success = {}, error = 0x{:08X}",
InterfaceClassGuid->Data1, InterfaceClassGuid->Data2, InterfaceClassGuid->Data3,
InterfaceClassGuid->Data4[0], InterfaceClassGuid->Data4[1], InterfaceClassGuid->Data4[2],
InterfaceClassGuid->Data4[3],
InterfaceClassGuid->Data4[4], InterfaceClassGuid->Data4[5], InterfaceClassGuid->Data4[6],
InterfaceClassGuid->Data4[7],
retval ? "true" : "false",
retval ? ERROR_SUCCESS : GetLastError());
return retval;
}
//
// Hooks CreateFileA() API
//
HANDLE WINAPI DetourCreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileA");
std::string path(lpFileName);
const bool isOfInterest = (path.rfind("\\\\", 0) == 0);
const auto handle = real_CreateFileA(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile
);
if (isOfInterest && handle != INVALID_HANDLE_VALUE)
{
g_handleToPath[handle] = path;
_logger->info("handle = {}, lpFileName = {}", handle, path);
}
return handle;
}
//
// Hooks CreateFileW() API
//
HANDLE WINAPI DetourCreateFileW(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileW");
std::string path(strconverter.to_bytes(lpFileName));
const bool isOfInterest = (path.rfind("\\\\", 0) == 0);
const auto handle = real_CreateFileW(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile
);
if (isOfInterest && handle != INVALID_HANDLE_VALUE)
{
g_handleToPath[handle] = path;
_logger->info("handle = {}, lpFileName = {}", handle, path);
}
return handle;
}
//
// Hooks WriteFile() API
//
BOOL WINAPI DetourWriteFile(
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("WriteFile");
const PUCHAR charInBuf = PUCHAR(lpBuffer);
DWORD tmpBytesWritten;
const auto ret = real_WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, &tmpBytesWritten, lpOverlapped);
const auto error = GetLastError();
if (lpNumberOfBytesWritten)
*lpNumberOfBytesWritten = tmpBytesWritten;
std::string path = "Unknown";
if (g_handleToPath.count(hFile))
{
path = g_handleToPath[hFile];
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return ret;
}
#endif
const auto bufSize = std::min(nNumberOfBytesToWrite, tmpBytesWritten);
const std::vector<char> inBuffer(charInBuf, charInBuf + bufSize);
// Prevent the logger from causing a crash via exception when it double-detours WriteFile
try
{
_logger->info("success = {}, lastError = 0x{:08X}, path = {} ({:04d}) -> {:Xpn}",
ret ? "true" : "false",
ret ? ERROR_SUCCESS : error,
path,
bufSize,
spdlog::to_hex(inBuffer)
);
}
catch (...)
{ }
return ret;
}
BOOL DetourCloseHandle(
HANDLE hObject
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CloseHandle");
const auto ret = real_CloseHandle(hObject);
std::string path = "Unknown";
if (g_handleToPath.count(hObject))
{
path = g_handleToPath[hObject];
g_handleToPath.erase(hObject);
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return ret;
}
#endif
_logger->info("handle = {}, path = {}", hObject, path);
return ret;
}
BOOL WINAPI DetourGetOverlappedResult(
HANDLE hFile,
LPOVERLAPPED lpOverlapped,
LPDWORD lpNumberOfBytesTransferred,
BOOL bWait
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("GetOverlappedResult");
DWORD tmpBytesTransferred;
const auto ret = real_GetOverlappedResult(hFile, lpOverlapped, &tmpBytesTransferred, bWait);
const auto error = GetLastError();
if (lpNumberOfBytesTransferred)
*lpNumberOfBytesTransferred = tmpBytesTransferred;
std::string path = "Unknown";
if (g_handleToPath.count(hFile))
{
path = g_handleToPath[hFile];
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return ret;
}
#endif
_logger->info("success = {}, lastError = 0x{:08X}, bytesTransferred = {}, path = {}",
ret ? "true" : "false",
ret ? ERROR_SUCCESS : error,
tmpBytesTransferred,
path
);
return ret;
}
//
// Hooks DeviceIoControl() API
//
BOOL WINAPI DetourDeviceIoControl(
HANDLE hDevice,
DWORD dwIoControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("DeviceIoControl");
const PUCHAR charInBuf = static_cast<PUCHAR>(lpInBuffer);
const std::vector<char> inBuffer(charInBuf, charInBuf + nInBufferSize);
DWORD tmpBytesReturned;
const auto retval = real_DeviceIoControl(
hDevice,
dwIoControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
&tmpBytesReturned, // might be null, use our own variable
lpOverlapped
);
if (lpBytesReturned)
*lpBytesReturned = tmpBytesReturned;
std::string path = "Unknown";
if (g_handleToPath.count(hDevice))
{
path = g_handleToPath[hDevice];
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return retval;
}
#endif
if (g_ioctlMap.count(dwIoControlCode))
{
_logger->info("[I] [{}] path = {} ({:04d}) -> {:Xpn}",
g_ioctlMap[dwIoControlCode],
path,
nInBufferSize,
spdlog::to_hex(inBuffer)
);
}
if (lpOutBuffer && nOutBufferSize > 0)
{
const PUCHAR charOutBuf = static_cast<PUCHAR>(lpOutBuffer);
const auto bufSize = std::min(nOutBufferSize, tmpBytesReturned);
const std::vector<char> outBuffer(charOutBuf, charOutBuf + bufSize);
if (g_ioctlMap.count(dwIoControlCode))
{
_logger->info("[O] [{}] path = {} ({:04d}) -> {:Xpn}",
g_ioctlMap[dwIoControlCode],
path,
bufSize,
spdlog::to_hex(outBuffer)
);
}
}
return retval;
}
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
BOOL WINAPI DllMain(HINSTANCE dll_handle, DWORD reason, LPVOID reserved)
{
if (DetourIsHelperProcess())
{
return TRUE;
}
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
CHAR dllPath[MAX_PATH];
GetModuleFileNameA((HINSTANCE)&__ImageBase, dllPath, MAX_PATH);
PathRemoveFileSpecA(dllPath);
g_dllDir = std::string(dllPath);
auto logger = spdlog::basic_logger_mt(
"XInputHooker",
g_dllDir + "\\XInputHooker.log"
);
#if _DEBUG
spdlog::set_level(spdlog::level::debug);
logger->flush_on(spdlog::level::debug);
#else
logger->flush_on(spdlog::level::info);
#endif
set_default_logger(logger);
//
// Load known IOCTL code definitions
//
Json::Value root;
std::ifstream ifs(g_dllDir + "\\ioctls.json");
ifs >> root;
for (auto& i : root)
{
g_ioctlMap[std::stoul(i["HexValue"].asString(), nullptr, 16)] = i["Ioctl"].asString();
}
}
DisableThreadLibraryCalls(dll_handle);
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);
DetourAttach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);
DetourAttach((PVOID*)&real_CreateFileA, DetourCreateFileA);
DetourAttach((PVOID*)&real_CreateFileW, DetourCreateFileW);
DetourAttach((PVOID*)&real_WriteFile, DetourWriteFile);
DetourAttach((PVOID*)&real_CloseHandle, DetourCloseHandle);
DetourAttach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);
DetourTransactionCommit();
break;
case DLL_PROCESS_DETACH:
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);
DetourDetach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);
DetourDetach((PVOID*)&real_CreateFileA, DetourCreateFileA);
DetourDetach((PVOID*)&real_CreateFileW, DetourCreateFileW);
DetourDetach((PVOID*)&real_WriteFile, DetourWriteFile);
DetourDetach((PVOID*)&real_CloseHandle, DetourCloseHandle);
DetourDetach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);
DetourTransactionCommit();
break;
}
return TRUE;
}
<commit_msg>Log path and error code if CreateFile fails<commit_after>//
// WinAPI
//
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <SetupAPI.h>
#include <Shlwapi.h>
#include <initguid.h>
#include <winioctl.h>
#include "XUSB.h"
//
// STL
//
#include <string>
#include <codecvt>
#include <locale>
#include <map>
#include <iostream>
#include <fstream>
//
// JSON
//
#include <json/json.h>
//
// Hooking
//
#include <detours/detours.h>
//
// Logging
//
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/fmt/bin_to_hex.h>
using convert_t = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_t, wchar_t> strconverter;
std::once_flag g_init;
std::string g_dllDir;
static decltype(SetupDiEnumDeviceInterfaces) *real_SetupDiEnumDeviceInterfaces = SetupDiEnumDeviceInterfaces;
static decltype(DeviceIoControl) *real_DeviceIoControl = DeviceIoControl;
static decltype(CreateFileA) *real_CreateFileA = CreateFileA;
static decltype(CreateFileW) *real_CreateFileW = CreateFileW;
static decltype(WriteFile)* real_WriteFile = WriteFile;
static decltype(CloseHandle)* real_CloseHandle = CloseHandle;
static decltype(GetOverlappedResult)* real_GetOverlappedResult = GetOverlappedResult;
static std::map<HANDLE, std::string> g_handleToPath;
static std::map<DWORD, std::string> g_ioctlMap;
//
// Hooks SetupDiEnumDeviceInterfaces() API
//
BOOL WINAPI DetourSetupDiEnumDeviceInterfaces(
HDEVINFO DeviceInfoSet,
PSP_DEVINFO_DATA DeviceInfoData,
const GUID* InterfaceClassGuid,
DWORD MemberIndex,
PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("SetupDiEnumDeviceInterfaces");
auto retval = real_SetupDiEnumDeviceInterfaces(DeviceInfoSet, DeviceInfoData, InterfaceClassGuid, MemberIndex,
DeviceInterfaceData);
_logger->info("InterfaceClassGuid = {{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}, "
"success = {}, error = 0x{:08X}",
InterfaceClassGuid->Data1, InterfaceClassGuid->Data2, InterfaceClassGuid->Data3,
InterfaceClassGuid->Data4[0], InterfaceClassGuid->Data4[1], InterfaceClassGuid->Data4[2],
InterfaceClassGuid->Data4[3],
InterfaceClassGuid->Data4[4], InterfaceClassGuid->Data4[5], InterfaceClassGuid->Data4[6],
InterfaceClassGuid->Data4[7],
retval ? "true" : "false",
retval ? ERROR_SUCCESS : GetLastError());
return retval;
}
//
// Hooks CreateFileA() API
//
HANDLE WINAPI DetourCreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileA");
std::string path(lpFileName);
const bool isOfInterest = (path.rfind("\\\\", 0) == 0);
const auto handle = real_CreateFileA(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile
);
if (isOfInterest)
{
if (handle != INVALID_HANDLE_VALUE)
{
g_handleToPath[handle] = path;
_logger->info("handle = {}, lpFileName = {}", handle, path);
}
else
{
_logger->info("lpFileName = {}, lastError = {}", path, GetLastError());
}
}
return handle;
}
//
// Hooks CreateFileW() API
//
HANDLE WINAPI DetourCreateFileW(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CreateFileW");
std::string path(strconverter.to_bytes(lpFileName));
const bool isOfInterest = (path.rfind("\\\\", 0) == 0);
const auto handle = real_CreateFileW(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile
);
if (isOfInterest)
{
if (handle != INVALID_HANDLE_VALUE)
{
g_handleToPath[handle] = path;
_logger->info("handle = {}, lpFileName = {}", handle, path);
}
else
{
_logger->info("lpFileName = {}, lastError = {}", path, GetLastError());
}
}
return handle;
}
//
// Hooks WriteFile() API
//
BOOL WINAPI DetourWriteFile(
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("WriteFile");
const PUCHAR charInBuf = PUCHAR(lpBuffer);
DWORD tmpBytesWritten;
const auto ret = real_WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, &tmpBytesWritten, lpOverlapped);
const auto error = GetLastError();
if (lpNumberOfBytesWritten)
*lpNumberOfBytesWritten = tmpBytesWritten;
std::string path = "Unknown";
if (g_handleToPath.count(hFile))
{
path = g_handleToPath[hFile];
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return ret;
}
#endif
const auto bufSize = std::min(nNumberOfBytesToWrite, tmpBytesWritten);
const std::vector<char> inBuffer(charInBuf, charInBuf + bufSize);
// Prevent the logger from causing a crash via exception when it double-detours WriteFile
try
{
_logger->info("success = {}, lastError = 0x{:08X}, path = {} ({:04d}) -> {:Xpn}",
ret ? "true" : "false",
ret ? ERROR_SUCCESS : error,
path,
bufSize,
spdlog::to_hex(inBuffer)
);
}
catch (...)
{ }
return ret;
}
BOOL DetourCloseHandle(
HANDLE hObject
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("CloseHandle");
const auto ret = real_CloseHandle(hObject);
std::string path = "Unknown";
if (g_handleToPath.count(hObject))
{
path = g_handleToPath[hObject];
g_handleToPath.erase(hObject);
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return ret;
}
#endif
_logger->info("handle = {}, path = {}", hObject, path);
return ret;
}
BOOL WINAPI DetourGetOverlappedResult(
HANDLE hFile,
LPOVERLAPPED lpOverlapped,
LPDWORD lpNumberOfBytesTransferred,
BOOL bWait
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("GetOverlappedResult");
DWORD tmpBytesTransferred;
const auto ret = real_GetOverlappedResult(hFile, lpOverlapped, &tmpBytesTransferred, bWait);
const auto error = GetLastError();
if (lpNumberOfBytesTransferred)
*lpNumberOfBytesTransferred = tmpBytesTransferred;
std::string path = "Unknown";
if (g_handleToPath.count(hFile))
{
path = g_handleToPath[hFile];
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return ret;
}
#endif
_logger->info("success = {}, lastError = 0x{:08X}, bytesTransferred = {}, path = {}",
ret ? "true" : "false",
ret ? ERROR_SUCCESS : error,
tmpBytesTransferred,
path
);
return ret;
}
//
// Hooks DeviceIoControl() API
//
BOOL WINAPI DetourDeviceIoControl(
HANDLE hDevice,
DWORD dwIoControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped
)
{
std::shared_ptr<spdlog::logger> _logger = spdlog::get("XInputHooker")->clone("DeviceIoControl");
const PUCHAR charInBuf = static_cast<PUCHAR>(lpInBuffer);
const std::vector<char> inBuffer(charInBuf, charInBuf + nInBufferSize);
DWORD tmpBytesReturned;
const auto retval = real_DeviceIoControl(
hDevice,
dwIoControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
&tmpBytesReturned, // might be null, use our own variable
lpOverlapped
);
if (lpBytesReturned)
*lpBytesReturned = tmpBytesReturned;
std::string path = "Unknown";
if (g_handleToPath.count(hDevice))
{
path = g_handleToPath[hDevice];
}
#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES
else
{
// Ignore unknown handles
return retval;
}
#endif
if (g_ioctlMap.count(dwIoControlCode))
{
_logger->info("[I] [{}] path = {} ({:04d}) -> {:Xpn}",
g_ioctlMap[dwIoControlCode],
path,
nInBufferSize,
spdlog::to_hex(inBuffer)
);
}
if (lpOutBuffer && nOutBufferSize > 0)
{
const PUCHAR charOutBuf = static_cast<PUCHAR>(lpOutBuffer);
const auto bufSize = std::min(nOutBufferSize, tmpBytesReturned);
const std::vector<char> outBuffer(charOutBuf, charOutBuf + bufSize);
if (g_ioctlMap.count(dwIoControlCode))
{
_logger->info("[O] [{}] path = {} ({:04d}) -> {:Xpn}",
g_ioctlMap[dwIoControlCode],
path,
bufSize,
spdlog::to_hex(outBuffer)
);
}
}
return retval;
}
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
BOOL WINAPI DllMain(HINSTANCE dll_handle, DWORD reason, LPVOID reserved)
{
if (DetourIsHelperProcess())
{
return TRUE;
}
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
CHAR dllPath[MAX_PATH];
GetModuleFileNameA((HINSTANCE)&__ImageBase, dllPath, MAX_PATH);
PathRemoveFileSpecA(dllPath);
g_dllDir = std::string(dllPath);
auto logger = spdlog::basic_logger_mt(
"XInputHooker",
g_dllDir + "\\XInputHooker.log"
);
#if _DEBUG
spdlog::set_level(spdlog::level::debug);
logger->flush_on(spdlog::level::debug);
#else
logger->flush_on(spdlog::level::info);
#endif
set_default_logger(logger);
//
// Load known IOCTL code definitions
//
Json::Value root;
std::ifstream ifs(g_dllDir + "\\ioctls.json");
ifs >> root;
for (auto& i : root)
{
g_ioctlMap[std::stoul(i["HexValue"].asString(), nullptr, 16)] = i["Ioctl"].asString();
}
}
DisableThreadLibraryCalls(dll_handle);
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);
DetourAttach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);
DetourAttach((PVOID*)&real_CreateFileA, DetourCreateFileA);
DetourAttach((PVOID*)&real_CreateFileW, DetourCreateFileW);
DetourAttach((PVOID*)&real_WriteFile, DetourWriteFile);
DetourAttach((PVOID*)&real_CloseHandle, DetourCloseHandle);
DetourAttach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);
DetourTransactionCommit();
break;
case DLL_PROCESS_DETACH:
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);
DetourDetach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);
DetourDetach((PVOID*)&real_CreateFileA, DetourCreateFileA);
DetourDetach((PVOID*)&real_CreateFileW, DetourCreateFileW);
DetourDetach((PVOID*)&real_WriteFile, DetourWriteFile);
DetourDetach((PVOID*)&real_CloseHandle, DetourCloseHandle);
DetourDetach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);
DetourTransactionCommit();
break;
}
return TRUE;
}
<|endoftext|>
|
<commit_before>#include "group_shared.hpp"
#include <cassert>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
using namespace tightdb;
// Pre-declare local functions
char* concat_strings(const char* str1, const char* str2);
struct tightdb::ReadCount {
uint32_t version;
uint32_t count;
};
struct tightdb::SharedInfo {
pthread_mutex_t readmutex;
pthread_mutex_t writemutex;
uint64_t filesize;
uint32_t infosize;
uint64_t current_top;
uint32_t current_version;
uint32_t capacity; // -1 so it can also be used as mask
uint32_t put_pos;
uint32_t get_pos;
ReadCount readers[32]; // has to be power of two
};
// Does not work for windows yet
#ifndef _MSC_VER
SharedGroup::SharedGroup(const char* filename) : m_group(filename, false), m_info(NULL), m_isValid(false), m_version(-1)
{
if (!m_group.is_valid()) return;
// Open shared coordination buffer
const char* const path = concat_strings(filename, ".lock");
const int fd = open(path, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
free((void*)path);
if (fd < 0) return;
// Get size
struct stat statbuf;
if (fstat(fd, &statbuf) < 0) {
close(fd);
return;
}
size_t len = statbuf.st_size;
// Handle empty files (first user)
bool needInit = false;
if (len == 0) {
// Create new file
len = sizeof(SharedInfo);
ftruncate(fd, len);
needInit = true;
}
// Map to memory
void* const p = mmap(0, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
close(fd); // no loner need file discriptor
if (p == (void*)-1) return;
m_info = (SharedInfo*)p;
if (needInit) {
pthread_mutex_lock(&m_info->readmutex);
{
const SlabAlloc& alloc = m_group.get_allocator();
m_info->filesize = alloc.GetFileLen();
m_info->infosize = (uint32_t)len;
m_info->current_top = alloc.GetTopRef();;
m_info->current_version = 0;
m_info->capacity = 32-1;
m_info->put_pos = 0;
m_info->get_pos = 0;
}
pthread_mutex_unlock(&m_info->readmutex);
}
m_isValid = true;
}
SharedGroup::~SharedGroup()
{
if (m_info) {
munmap((void*)m_info, m_info->infosize);
}
}
const Group& SharedGroup::start_read()
{
size_t new_topref = 0;
size_t new_filesize = 0;
pthread_mutex_lock(&m_info->readmutex);
{
// Get the current top ref
new_topref = m_info->current_top;
new_filesize = m_info->filesize;
m_version = m_info->current_version;
// Update reader list
if (ringbuf_is_empty()) {
const ReadCount r2 = {m_info->current_version, 1};
ringbuf_put(r2);
}
else {
ReadCount& r = ringbuf_get_last();
if (r.version == m_info->current_version)
++(r.count);
else {
const ReadCount r2 = {m_info->current_version, 1};
ringbuf_put(r2);
}
}
}
pthread_mutex_unlock(&m_info->readmutex);
// Make sure the group is up-to-date
m_group.update_from_shared(new_topref, new_filesize);
return m_group;
}
void SharedGroup::end_read()
{
assert(m_version != (uint32_t)-1);
pthread_mutex_lock(&m_info->readmutex);
{
// Find entry for current version
const size_t ndx = ringbuf_find(m_version);
assert(ndx != (size_t)-1);
ReadCount& r = ringbuf_get(ndx);
// Decrement count and remove as many entries as possible
if (r.count == 1 && ringbuf_is_first(ndx)) {
ringbuf_remove_first();
while (!ringbuf_is_empty() && ringbuf_get_first().count == 0) {
ringbuf_remove_first();
}
}
else {
assert(r.count > 0);
--r.count;
}
}
pthread_mutex_unlock(&m_info->readmutex);
m_version = (uint32_t)-1;
}
Group& SharedGroup::start_write()
{
// Get write lock
// Note that this will not get released until we call
// end_write().
pthread_mutex_lock(&m_info->writemutex);
// Get the current top ref
const size_t new_topref = m_info->current_top;
const size_t new_filesize = m_info->filesize;
// Make sure the group is up-to-date
// zero ref means that the file has just been created
if (new_topref != 0) {
m_group.update_from_shared(new_topref, new_filesize);
}
return m_group;
}
void SharedGroup::end_write()
{
m_group.commit();
// Get the current top ref
const SlabAlloc& alloc = m_group.get_allocator();
const size_t new_topref = alloc.GetTopRef();
const size_t new_filesize = alloc.GetFileLen();
// Update reader info
pthread_mutex_lock(&m_info->readmutex);
{
m_info->current_top = new_topref;
m_info->filesize = new_filesize;
++m_info->current_version;
}
pthread_mutex_unlock(&m_info->readmutex);
// Release write lock
pthread_mutex_unlock(&m_info->writemutex);
}
bool SharedGroup::ringbuf_is_empty() const
{
return (ringbuf_size() == 0);
}
size_t SharedGroup::ringbuf_size() const
{
return ((m_info->put_pos - m_info->get_pos) & m_info->capacity);
}
size_t SharedGroup::ringbuf_capacity() const
{
return m_info->capacity+1;
}
bool SharedGroup::ringbuf_is_first(size_t ndx) const {
return (ndx == m_info->get_pos);
}
ReadCount& SharedGroup::ringbuf_get(size_t ndx)
{
return m_info->readers[ndx];
}
ReadCount& SharedGroup::ringbuf_get_first()
{
return m_info->readers[m_info->get_pos];
}
ReadCount& SharedGroup::ringbuf_get_last()
{
const uint32_t lastPos = (m_info->put_pos - 1) & m_info->capacity;
return m_info->readers[lastPos];
}
void SharedGroup::ringbuf_remove_first() {
m_info->get_pos = (m_info->get_pos + 1) & m_info->capacity;
}
void SharedGroup::ringbuf_put(const ReadCount& v)
{
const bool isFull = (ringbuf_size() == (m_info->capacity+1));
if(isFull) {
//TODO: expand buffer
assert(false);
}
m_info->readers[m_info->put_pos] = v;
m_info->put_pos = (m_info->put_pos + 1) & m_info->capacity;
}
size_t SharedGroup::ringbuf_find(uint32_t version) const
{
uint32_t pos = m_info->get_pos;
while (pos != m_info->put_pos) {
const ReadCount& r = m_info->readers[pos];
if (r.version == version)
return pos;
pos = (pos + 1) & m_info->capacity;
}
return (size_t)-1;
}
void SharedGroup::test_ringbuf()
{
assert(ringbuf_is_empty());
const ReadCount rc = {1, 1};
ringbuf_put(rc);
assert(ringbuf_size() == 1);
ringbuf_remove_first();
assert(ringbuf_is_empty());
// Fill buffer
const size_t capacity = ringbuf_capacity();
for (size_t i = 0; i < capacity; ++i) {
const ReadCount r = {1, (uint32_t)i};
ringbuf_put(r);
assert(ringbuf_get_last().count == i);
}
for (size_t i = 0; i < 32; ++i) {
const ReadCount& r = ringbuf_get_first();
assert(r.count == i);
ringbuf_remove_first();
}
assert(ringbuf_is_empty());
}
#endif //_MSV_VER
// Support methods
char* concat_strings(const char* str1, const char* str2) {
const size_t len1 = strlen(str1);
const size_t len2 = strlen(str2) + 1; // includes terminating null
char* const s = (char*)malloc(len1 + len2);
memcpy(s, str1, len1);
memcpy(s + len1, str2, len2);
return s;
}<commit_msg>Elimination of a couple of warnings<commit_after>#include "group_shared.hpp"
#include <cassert>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
using namespace tightdb;
// Pre-declare local functions
char* concat_strings(const char* str1, const char* str2);
struct tightdb::ReadCount {
uint32_t version;
uint32_t count;
};
struct tightdb::SharedInfo {
pthread_mutex_t readmutex;
pthread_mutex_t writemutex;
uint64_t filesize;
uint32_t infosize;
uint64_t current_top;
uint32_t current_version;
uint32_t capacity; // -1 so it can also be used as mask
uint32_t put_pos;
uint32_t get_pos;
ReadCount readers[32]; // has to be power of two
};
// Does not work for windows yet
#ifndef _MSC_VER
SharedGroup::SharedGroup(const char* filename) : m_group(filename, false), m_info(NULL), m_isValid(false), m_version(-1)
{
if (!m_group.is_valid()) return;
// Open shared coordination buffer
const char* const path = concat_strings(filename, ".lock");
const int fd = open(path, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
free((void*)path);
if (fd < 0) return;
// Get size
struct stat statbuf;
if (fstat(fd, &statbuf) < 0) {
close(fd);
return;
}
size_t len = statbuf.st_size;
// Handle empty files (first user)
bool needInit = false;
if (len == 0) {
// Create new file
len = sizeof(SharedInfo);
int r = ftruncate(fd, len);
static_cast<void>(r); // FIXME: We should probably check for error here!
needInit = true;
}
// Map to memory
void* const p = mmap(0, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
close(fd); // no loner need file discriptor
if (p == (void*)-1) return;
m_info = (SharedInfo*)p;
if (needInit) {
pthread_mutex_lock(&m_info->readmutex);
{
const SlabAlloc& alloc = m_group.get_allocator();
m_info->filesize = alloc.GetFileLen();
m_info->infosize = (uint32_t)len;
m_info->current_top = alloc.GetTopRef();;
m_info->current_version = 0;
m_info->capacity = 32-1;
m_info->put_pos = 0;
m_info->get_pos = 0;
}
pthread_mutex_unlock(&m_info->readmutex);
}
m_isValid = true;
}
SharedGroup::~SharedGroup()
{
if (m_info) {
munmap((void*)m_info, m_info->infosize);
}
}
const Group& SharedGroup::start_read()
{
size_t new_topref = 0;
size_t new_filesize = 0;
pthread_mutex_lock(&m_info->readmutex);
{
// Get the current top ref
new_topref = m_info->current_top;
new_filesize = m_info->filesize;
m_version = m_info->current_version;
// Update reader list
if (ringbuf_is_empty()) {
const ReadCount r2 = {m_info->current_version, 1};
ringbuf_put(r2);
}
else {
ReadCount& r = ringbuf_get_last();
if (r.version == m_info->current_version)
++(r.count);
else {
const ReadCount r2 = {m_info->current_version, 1};
ringbuf_put(r2);
}
}
}
pthread_mutex_unlock(&m_info->readmutex);
// Make sure the group is up-to-date
m_group.update_from_shared(new_topref, new_filesize);
return m_group;
}
void SharedGroup::end_read()
{
assert(m_version != (uint32_t)-1);
pthread_mutex_lock(&m_info->readmutex);
{
// Find entry for current version
const size_t ndx = ringbuf_find(m_version);
assert(ndx != (size_t)-1);
ReadCount& r = ringbuf_get(ndx);
// Decrement count and remove as many entries as possible
if (r.count == 1 && ringbuf_is_first(ndx)) {
ringbuf_remove_first();
while (!ringbuf_is_empty() && ringbuf_get_first().count == 0) {
ringbuf_remove_first();
}
}
else {
assert(r.count > 0);
--r.count;
}
}
pthread_mutex_unlock(&m_info->readmutex);
m_version = (uint32_t)-1;
}
Group& SharedGroup::start_write()
{
// Get write lock
// Note that this will not get released until we call
// end_write().
pthread_mutex_lock(&m_info->writemutex);
// Get the current top ref
const size_t new_topref = m_info->current_top;
const size_t new_filesize = m_info->filesize;
// Make sure the group is up-to-date
// zero ref means that the file has just been created
if (new_topref != 0) {
m_group.update_from_shared(new_topref, new_filesize);
}
return m_group;
}
void SharedGroup::end_write()
{
m_group.commit();
// Get the current top ref
const SlabAlloc& alloc = m_group.get_allocator();
const size_t new_topref = alloc.GetTopRef();
const size_t new_filesize = alloc.GetFileLen();
// Update reader info
pthread_mutex_lock(&m_info->readmutex);
{
m_info->current_top = new_topref;
m_info->filesize = new_filesize;
++m_info->current_version;
}
pthread_mutex_unlock(&m_info->readmutex);
// Release write lock
pthread_mutex_unlock(&m_info->writemutex);
}
bool SharedGroup::ringbuf_is_empty() const
{
return (ringbuf_size() == 0);
}
size_t SharedGroup::ringbuf_size() const
{
return ((m_info->put_pos - m_info->get_pos) & m_info->capacity);
}
size_t SharedGroup::ringbuf_capacity() const
{
return m_info->capacity+1;
}
bool SharedGroup::ringbuf_is_first(size_t ndx) const {
return (ndx == m_info->get_pos);
}
ReadCount& SharedGroup::ringbuf_get(size_t ndx)
{
return m_info->readers[ndx];
}
ReadCount& SharedGroup::ringbuf_get_first()
{
return m_info->readers[m_info->get_pos];
}
ReadCount& SharedGroup::ringbuf_get_last()
{
const uint32_t lastPos = (m_info->put_pos - 1) & m_info->capacity;
return m_info->readers[lastPos];
}
void SharedGroup::ringbuf_remove_first() {
m_info->get_pos = (m_info->get_pos + 1) & m_info->capacity;
}
void SharedGroup::ringbuf_put(const ReadCount& v)
{
const bool isFull = (ringbuf_size() == (m_info->capacity+1));
if(isFull) {
//TODO: expand buffer
assert(false);
}
m_info->readers[m_info->put_pos] = v;
m_info->put_pos = (m_info->put_pos + 1) & m_info->capacity;
}
size_t SharedGroup::ringbuf_find(uint32_t version) const
{
uint32_t pos = m_info->get_pos;
while (pos != m_info->put_pos) {
const ReadCount& r = m_info->readers[pos];
if (r.version == version)
return pos;
pos = (pos + 1) & m_info->capacity;
}
return (size_t)-1;
}
void SharedGroup::test_ringbuf()
{
assert(ringbuf_is_empty());
const ReadCount rc = {1, 1};
ringbuf_put(rc);
assert(ringbuf_size() == 1);
ringbuf_remove_first();
assert(ringbuf_is_empty());
// Fill buffer
const size_t capacity = ringbuf_capacity();
for (size_t i = 0; i < capacity; ++i) {
const ReadCount r = {1, (uint32_t)i};
ringbuf_put(r);
assert(ringbuf_get_last().count == i);
}
for (size_t i = 0; i < 32; ++i) {
const ReadCount& r = ringbuf_get_first();
assert(r.count == i);
static_cast<void>(r);
ringbuf_remove_first();
}
assert(ringbuf_is_empty());
}
#endif //_MSV_VER
// Support methods
char* concat_strings(const char* str1, const char* str2) {
const size_t len1 = strlen(str1);
const size_t len2 = strlen(str2) + 1; // includes terminating null
char* const s = (char*)malloc(len1 + len2);
memcpy(s, str1, len1);
memcpy(s + len1, str2, len2);
return s;
}
<|endoftext|>
|
<commit_before><commit_msg>Modified output of filters-test.cxx to CSV<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filedlg2.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:13:20 $
*
* 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 _FILEDLG2_HXX
#define _FILEDLG2_HXX
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _FSYS_HXX //autogen
#include <tools/fsys.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen wg. PushButton
#include <vcl/button.hxx>
#endif
#ifndef _VCL_UNOHELP_HXX
#include <vcl/unohelp.hxx>
#endif
class FixedText;
class Edit;
class ListBox;
class ListBox;
class Button;
class PathDialog;
class FileDialog;
class ImpPathDialog;
struct ImpFilterItem
{
String aName;
String aMask;
ImpFilterItem( const String & rFilter, const String & rMask )
{
aName = rFilter;
aMask = rMask;
}
};
DECLARE_LIST( ImpFilterList, ImpFilterItem* )
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif // _SV_LSTBOX_HXX
class KbdListBox : public ListBox
{
public:
KbdListBox( Window* pParent, WinBits nStyle = WB_BORDER )
: ListBox ( pParent, nStyle )
{};
virtual long PreNotify( NotifyEvent& rNEvt );
};
class ImpPathDialog
{
friend class ImpFileDialog;
private:
PathDialog* pSvPathDialog;
Edit* pEdit;
FixedText* pDirTitel;
KbdListBox* pDirList;
FixedText* pDirPath;
ListBox* pDriveList;
FixedText* pDriveTitle;
PushButton* pLoadBtn;
PushButton* pOkBtn;
PushButton* pCancelBtn;
PushButton* pHomeBtn;
PushButton* pNewDirBtn;
USHORT nOwnChilds;
DirEntry aPath; // aktuell angewaehlter Pfad
USHORT nDirCount; // Anzahl der Verzeichnis-
// Verschachtelungen
::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCollator >
xCollator;
protected:
virtual void UpdateEntries( const BOOL bWithDirs );
void UpdateDirs( const DirEntry& rTmpPath );
BOOL IsFileOk( const DirEntry& rDirEntry );
void InitControls();
DECL_LINK( SelectHdl, ListBox * );
DECL_LINK( DblClickHdl, ListBox * );
DECL_LINK( ClickHdl, Button * );
public:
ImpPathDialog( PathDialog* pDlg, WinBits nWinBits, RESOURCE_TYPE nType, BOOL bCreateDir );
virtual ~ImpPathDialog();
virtual void SetPath( const String& rPath );
virtual void SetPath( const Edit& rEdit );
virtual String GetPath() const;
virtual void PreExecute();
virtual void PostExecute();
PathDialog* GetPathDialog() const { return pSvPathDialog; }
void SetOkButtonText( const String& rText ) { pOkBtn->SetText( rText ); }
void SetCancelButtonText( const String& rText ) { pCancelBtn->SetText( rText ); }
};
class ImpFileDialog : public ImpPathDialog
{
private:
FixedText* pFileTitel;
ListBox* pFileList;
FixedText* pTypeTitel;
ListBox* pTypeList;
WildCard aMask; // aktuelle Maske
ImpFilterList aFilterList; // Filterliste
USHORT nCurFilter; // aktueller Filter
BOOL bOpen; // TRUE = Open; FALSE = SAVEAS
protected:
void InitControls();
String ExtendFileName( DirEntry aEntry ) const;
DECL_LINK( SelectHdl, ListBox * );
DECL_LINK( DblClickHdl, ListBox * );
DECL_LINK( ClickHdl, Button * );
virtual void UpdateEntries( const BOOL bWithDirs );
BOOL IsFileOk( const DirEntry& rDirEntry );
public:
ImpFileDialog( PathDialog* pDlg, WinBits nWinBits, RESOURCE_TYPE nType );
virtual ~ImpFileDialog();
void AddFilter( const String& rFilter, const String& rMask );
void RemoveFilter( const String& rFilter );
void RemoveAllFilter();
void SetCurFilter( const String& rFilter );
String GetCurFilter() const;
USHORT GetFilterCount() const { return (USHORT)aFilterList.Count(); }
inline String GetFilterName( USHORT nPos ) const;
inline String GetFilterType( USHORT nPos ) const;
virtual void SetPath( const String& rPath );
virtual void SetPath( const Edit& rEdit );
virtual String GetPath() const;
virtual void PreExecute();
FileDialog* GetFileDialog() const { return (FileDialog*)GetPathDialog(); }
};
inline String ImpFileDialog::GetFilterName( USHORT nPos ) const
{
String aName;
ImpFilterItem* pItem = aFilterList.GetObject( nPos );
if ( pItem )
aName = pItem->aName;
return aName;
}
inline String ImpFileDialog::GetFilterType( USHORT nPos ) const
{
String aMask;
ImpFilterItem* pItem = aFilterList.GetObject( nPos );
if ( pItem )
aMask = pItem->aMask;
return aMask;
}
class ImpSvFileDlg
{
private:
ImpPathDialog* pDlg;
public:
ImpSvFileDlg() { pDlg = 0; }
~ImpSvFileDlg() { delete pDlg; }
ImpPathDialog* GetDialog() const { return pDlg; }
void CreateDialog( PathDialog* pCreateFrom, WinBits nStyle, RESOURCE_TYPE nType, BOOL bCreate );
void SetOkButtonText( const String& rText ) { pDlg->SetOkButtonText( rText ); } // ihr habts ja nicht anders gewollt
void SetCancelButtonText( const String& rText ) { pDlg->SetCancelButtonText( rText ); }
};
#endif // _FILEDLG2_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.3.62); FILE MERGED 2005/11/15 17:54:29 pl 1.3.62.1: #i55991# removed warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filedlg2.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 20:59:47 $
*
* 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 _FILEDLG2_HXX
#define _FILEDLG2_HXX
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _FSYS_HXX //autogen
#include <tools/fsys.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen wg. PushButton
#include <vcl/button.hxx>
#endif
#ifndef _VCL_UNOHELP_HXX
#include <vcl/unohelp.hxx>
#endif
class FixedText;
class Edit;
class ListBox;
class ListBox;
class Button;
class PathDialog;
class FileDialog;
class ImpPathDialog;
struct ImpFilterItem
{
String aName;
String aMask;
ImpFilterItem( const String & rFilter, const String & rMask )
{
aName = rFilter;
aMask = rMask;
}
};
DECLARE_LIST( ImpFilterList, ImpFilterItem* )
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif // _SV_LSTBOX_HXX
class KbdListBox : public ListBox
{
public:
KbdListBox( Window* pParent, WinBits nStyle = WB_BORDER )
: ListBox ( pParent, nStyle )
{};
virtual long PreNotify( NotifyEvent& rNEvt );
};
class ImpPathDialog
{
friend class ImpFileDialog;
private:
PathDialog* pSvPathDialog;
Edit* pEdit;
FixedText* pDirTitel;
KbdListBox* pDirList;
FixedText* pDirPath;
ListBox* pDriveList;
FixedText* pDriveTitle;
PushButton* pLoadBtn;
PushButton* pOkBtn;
PushButton* pCancelBtn;
PushButton* pHomeBtn;
PushButton* pNewDirBtn;
USHORT nOwnChilds;
DirEntry aPath; // aktuell angewaehlter Pfad
USHORT nDirCount; // Anzahl der Verzeichnis-
// Verschachtelungen
::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCollator >
xCollator;
protected:
virtual void UpdateEntries( const BOOL bWithDirs );
void UpdateDirs( const DirEntry& rTmpPath );
BOOL IsFileOk( const DirEntry& rDirEntry );
void InitControls();
DECL_LINK( SelectHdl, ListBox * );
DECL_LINK( DblClickHdl, ListBox * );
DECL_LINK( ClickHdl, Button * );
public:
ImpPathDialog( PathDialog* pDlg, RESOURCE_TYPE nType, BOOL bCreateDir );
virtual ~ImpPathDialog();
virtual void SetPath( const String& rPath );
virtual void SetPath( const Edit& rEdit );
virtual String GetPath() const;
virtual void PreExecute();
virtual void PostExecute();
PathDialog* GetPathDialog() const { return pSvPathDialog; }
void SetOkButtonText( const String& rText ) { pOkBtn->SetText( rText ); }
void SetCancelButtonText( const String& rText ) { pCancelBtn->SetText( rText ); }
};
class ImpFileDialog : public ImpPathDialog
{
private:
FixedText* pFileTitel;
ListBox* pFileList;
FixedText* pTypeTitel;
ListBox* pTypeList;
WildCard aMask; // aktuelle Maske
ImpFilterList aFilterList; // Filterliste
USHORT nCurFilter; // aktueller Filter
BOOL bOpen; // TRUE = Open; FALSE = SAVEAS
protected:
void InitControls();
String ExtendFileName( DirEntry aEntry ) const;
DECL_LINK( SelectHdl, ListBox * );
DECL_LINK( DblClickHdl, ListBox * );
DECL_LINK( ClickHdl, Button * );
virtual void UpdateEntries( const BOOL bWithDirs );
BOOL IsFileOk( const DirEntry& rDirEntry );
public:
ImpFileDialog( PathDialog* pDlg, WinBits nStyle, RESOURCE_TYPE nType );
virtual ~ImpFileDialog();
void AddFilter( const String& rFilter, const String& rMask );
void RemoveFilter( const String& rFilter );
void RemoveAllFilter();
void SetCurFilter( const String& rFilter );
String GetCurFilter() const;
USHORT GetFilterCount() const { return (USHORT)aFilterList.Count(); }
inline String GetFilterName( USHORT nPos ) const;
inline String GetFilterType( USHORT nPos ) const;
virtual void SetPath( const String& rPath );
virtual void SetPath( const Edit& rEdit );
virtual String GetPath() const;
virtual void PreExecute();
FileDialog* GetFileDialog() const { return (FileDialog*)GetPathDialog(); }
};
inline String ImpFileDialog::GetFilterName( USHORT nPos ) const
{
String aName;
ImpFilterItem* pItem = aFilterList.GetObject( nPos );
if ( pItem )
aName = pItem->aName;
return aName;
}
inline String ImpFileDialog::GetFilterType( USHORT nPos ) const
{
String aFilterMask;
ImpFilterItem* pItem = aFilterList.GetObject( nPos );
if ( pItem )
aFilterMask = pItem->aMask;
return aFilterMask;
}
class ImpSvFileDlg
{
private:
ImpPathDialog* pDlg;
public:
ImpSvFileDlg() { pDlg = 0; }
~ImpSvFileDlg() { delete pDlg; }
ImpPathDialog* GetDialog() const { return pDlg; }
void CreateDialog( PathDialog* pCreateFrom, WinBits nStyle, RESOURCE_TYPE nType, BOOL bCreate );
void SetOkButtonText( const String& rText ) { pDlg->SetOkButtonText( rText ); } // ihr habts ja nicht anders gewollt
void SetCancelButtonText( const String& rText ) { pDlg->SetCancelButtonText( rText ); }
};
#endif // _FILEDLG2_HXX
<|endoftext|>
|
<commit_before><commit_msg>sw: dump ruby text in nodes dump<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************/
/* message_queue.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "message_queue.h"
#include "global_config.h"
#include "script_language.h"
MessageQueue *MessageQueue::singleton = NULL;
MessageQueue *MessageQueue::get_singleton() {
return singleton;
}
Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
_THREAD_SAFE_METHOD_
int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
type = ObjectDB::get_instance(p_id)->get_class();
print_line("failed method: " + type + ":" + p_method + " target ID: " + itos(p_id));
statistics();
}
ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
Message *msg = memnew_placement(&buffer[buffer_end], Message);
msg->args = p_argcount;
msg->instance_ID = p_id;
msg->target = p_method;
msg->type = TYPE_CALL;
if (p_show_error)
msg->type |= FLAG_SHOW_ERROR;
buffer_end += sizeof(Message);
for (int i = 0; i < p_argcount; i++) {
Variant *v = memnew_placement(&buffer[buffer_end], Variant);
buffer_end += sizeof(Variant);
*v = *p_args[i];
}
return OK;
}
Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
int argc = 0;
for (int i = 0; i < VARIANT_ARG_MAX; i++) {
if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
return push_call(p_id, p_method, argptr, argc, false);
}
Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
_THREAD_SAFE_METHOD_
uint8_t room_needed = sizeof(Message) + sizeof(Variant);
if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
type = ObjectDB::get_instance(p_id)->get_class();
print_line("failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id));
statistics();
}
ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
Message *msg = memnew_placement(&buffer[buffer_end], Message);
msg->args = 1;
msg->instance_ID = p_id;
msg->target = p_prop;
msg->type = TYPE_SET;
buffer_end += sizeof(Message);
Variant *v = memnew_placement(&buffer[buffer_end], Variant);
buffer_end += sizeof(Variant);
*v = p_value;
return OK;
}
Error MessageQueue::push_notification(ObjectID p_id, int p_notification) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
uint8_t room_needed = sizeof(Message);
if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
type = ObjectDB::get_instance(p_id)->get_class();
print_line("failed notification: " + itos(p_notification) + " target ID: " + itos(p_id));
statistics();
}
ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
Message *msg = memnew_placement(&buffer[buffer_end], Message);
msg->type = TYPE_NOTIFICATION;
msg->instance_ID = p_id;
//msg->target;
msg->notification = p_notification;
buffer_end += sizeof(Message);
return OK;
}
Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) {
return push_call(p_object->get_instance_ID(), p_method, VARIANT_ARG_PASS);
}
Error MessageQueue::push_notification(Object *p_object, int p_notification) {
return push_notification(p_object->get_instance_ID(), p_notification);
}
Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
return push_set(p_object->get_instance_ID(), p_prop, p_value);
}
void MessageQueue::statistics() {
Map<StringName, int> set_count;
Map<int, int> notify_count;
Map<StringName, int> call_count;
int null_count = 0;
uint32_t read_pos = 0;
while (read_pos < buffer_end) {
Message *message = (Message *)&buffer[read_pos];
Object *target = ObjectDB::get_instance(message->instance_ID);
if (target != NULL) {
switch (message->type & FLAG_MASK) {
case TYPE_CALL: {
if (!call_count.has(message->target))
call_count[message->target] = 0;
call_count[message->target]++;
} break;
case TYPE_NOTIFICATION: {
if (!notify_count.has(message->notification))
notify_count[message->notification] = 0;
notify_count[message->notification]++;
} break;
case TYPE_SET: {
if (!set_count.has(message->target))
set_count[message->target] = 0;
set_count[message->target]++;
} break;
}
//object was deleted
//WARN_PRINT("Object was deleted while awaiting a callback")
//should it print a warning?
} else {
null_count++;
}
read_pos += sizeof(Message);
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
read_pos += sizeof(Variant) * message->args;
}
print_line("TOTAL BYTES: " + itos(buffer_end));
print_line("NULL count: " + itos(null_count));
for (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) {
print_line("SET " + E->key() + ": " + itos(E->get()));
}
for (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) {
print_line("CALL " + E->key() + ": " + itos(E->get()));
}
for (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) {
print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get()));
}
}
bool MessageQueue::print() {
#if 0
uint32_t read_pos=0;
while (read_pos < buffer_end ) {
Message *message = (Message*)&buffer[ read_pos ];
Object *target = ObjectDB::get_instance(message->instance_ID);
String cname;
String cfunc;
if (target==NULL) {
//object was deleted
//WARN_PRINT("Object was deleted while awaiting a callback")
//should it print a warning?
} else if (message->notification>=0) {
// messages don't expect a return value
cfunc="notification # "+itos(message->notification);
cname=target->get_type();
} else if (!message->target.empty()) {
cfunc="property: "+message->target;
cname=target->get_type();
} else if (message->target) {
cfunc=String(message->target)+"()";
cname=target->get_type();
}
read_pos+=sizeof(Message);
if (message->type!=TYPE_NOTIFICATION)
read_pos+=sizeof(Variant)*message->args;
}
#endif
return false;
}
int MessageQueue::get_max_buffer_usage() const {
return buffer_max_used;
}
void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) {
const Variant **argptrs = NULL;
if (p_argcount) {
argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
for (int i = 0; i < p_argcount; i++) {
argptrs[i] = &p_args[i];
}
}
Variant::CallError ce;
p_target->call(p_func, argptrs, p_argcount, ce);
if (p_show_error && ce.error != Variant::CallError::CALL_OK) {
ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce));
}
}
void MessageQueue::flush() {
if (buffer_end > buffer_max_used) {
buffer_max_used = buffer_end;
//statistics();
}
uint32_t read_pos = 0;
//using reverse locking strategy
_THREAD_SAFE_LOCK_
while (read_pos < buffer_end) {
_THREAD_SAFE_UNLOCK_
//lock on each interation, so a call can re-add itself to the message queue
Message *message = (Message *)&buffer[read_pos];
Object *target = ObjectDB::get_instance(message->instance_ID);
if (target != NULL) {
switch (message->type & FLAG_MASK) {
case TYPE_CALL: {
Variant *args = (Variant *)(message + 1);
// messages don't expect a return value
_call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR);
for (int i = 0; i < message->args; i++) {
args[i].~Variant();
}
} break;
case TYPE_NOTIFICATION: {
// messages don't expect a return value
target->notification(message->notification);
} break;
case TYPE_SET: {
Variant *arg = (Variant *)(message + 1);
// messages don't expect a return value
target->set(message->target, *arg);
arg->~Variant();
} break;
}
}
uint32_t advance = sizeof(Message);
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
advance += sizeof(Variant) * message->args;
message->~Message();
_THREAD_SAFE_LOCK_
read_pos += advance;
}
buffer_end = 0; // reset buffer
_THREAD_SAFE_UNLOCK_
}
MessageQueue::MessageQueue() {
ERR_FAIL_COND(singleton != NULL);
singleton = this;
buffer_end = 0;
buffer_max_used = 0;
buffer_size = GLOBAL_DEF("memory/buffers/message_queue_max_size_kb", DEFAULT_QUEUE_SIZE_KB);
buffer_size *= 1024;
buffer = memnew_arr(uint8_t, buffer_size);
}
MessageQueue::~MessageQueue() {
uint32_t read_pos = 0;
while (read_pos < buffer_end) {
Message *message = (Message *)&buffer[read_pos];
Variant *args = (Variant *)(message + 1);
int argc = message->args;
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
for (int i = 0; i < argc; i++)
args[i].~Variant();
}
message->~Message();
read_pos += sizeof(Message);
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
read_pos += sizeof(Variant) * message->args;
}
singleton = NULL;
memdelete_arr(buffer);
}
<commit_msg>Better explain out of memory error in message queue<commit_after>/*************************************************************************/
/* message_queue.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "message_queue.h"
#include "global_config.h"
#include "script_language.h"
MessageQueue *MessageQueue::singleton = NULL;
MessageQueue *MessageQueue::get_singleton() {
return singleton;
}
Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
_THREAD_SAFE_METHOD_
int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
type = ObjectDB::get_instance(p_id)->get_class();
print_line("failed method: " + type + ":" + p_method + " target ID: " + itos(p_id));
statistics();
ERR_EXPLAIN("Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings");
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
}
Message *msg = memnew_placement(&buffer[buffer_end], Message);
msg->args = p_argcount;
msg->instance_ID = p_id;
msg->target = p_method;
msg->type = TYPE_CALL;
if (p_show_error)
msg->type |= FLAG_SHOW_ERROR;
buffer_end += sizeof(Message);
for (int i = 0; i < p_argcount; i++) {
Variant *v = memnew_placement(&buffer[buffer_end], Variant);
buffer_end += sizeof(Variant);
*v = *p_args[i];
}
return OK;
}
Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
int argc = 0;
for (int i = 0; i < VARIANT_ARG_MAX; i++) {
if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
return push_call(p_id, p_method, argptr, argc, false);
}
Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
_THREAD_SAFE_METHOD_
uint8_t room_needed = sizeof(Message) + sizeof(Variant);
if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
type = ObjectDB::get_instance(p_id)->get_class();
print_line("failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id));
statistics();
ERR_EXPLAIN("Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings");
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
}
Message *msg = memnew_placement(&buffer[buffer_end], Message);
msg->args = 1;
msg->instance_ID = p_id;
msg->target = p_prop;
msg->type = TYPE_SET;
buffer_end += sizeof(Message);
Variant *v = memnew_placement(&buffer[buffer_end], Variant);
buffer_end += sizeof(Variant);
*v = p_value;
return OK;
}
Error MessageQueue::push_notification(ObjectID p_id, int p_notification) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
uint8_t room_needed = sizeof(Message);
if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
type = ObjectDB::get_instance(p_id)->get_class();
print_line("failed notification: " + itos(p_notification) + " target ID: " + itos(p_id));
statistics();
ERR_EXPLAIN("Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings");
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
}
Message *msg = memnew_placement(&buffer[buffer_end], Message);
msg->type = TYPE_NOTIFICATION;
msg->instance_ID = p_id;
//msg->target;
msg->notification = p_notification;
buffer_end += sizeof(Message);
return OK;
}
Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) {
return push_call(p_object->get_instance_ID(), p_method, VARIANT_ARG_PASS);
}
Error MessageQueue::push_notification(Object *p_object, int p_notification) {
return push_notification(p_object->get_instance_ID(), p_notification);
}
Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
return push_set(p_object->get_instance_ID(), p_prop, p_value);
}
void MessageQueue::statistics() {
Map<StringName, int> set_count;
Map<int, int> notify_count;
Map<StringName, int> call_count;
int null_count = 0;
uint32_t read_pos = 0;
while (read_pos < buffer_end) {
Message *message = (Message *)&buffer[read_pos];
Object *target = ObjectDB::get_instance(message->instance_ID);
if (target != NULL) {
switch (message->type & FLAG_MASK) {
case TYPE_CALL: {
if (!call_count.has(message->target))
call_count[message->target] = 0;
call_count[message->target]++;
} break;
case TYPE_NOTIFICATION: {
if (!notify_count.has(message->notification))
notify_count[message->notification] = 0;
notify_count[message->notification]++;
} break;
case TYPE_SET: {
if (!set_count.has(message->target))
set_count[message->target] = 0;
set_count[message->target]++;
} break;
}
//object was deleted
//WARN_PRINT("Object was deleted while awaiting a callback")
//should it print a warning?
} else {
null_count++;
}
read_pos += sizeof(Message);
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
read_pos += sizeof(Variant) * message->args;
}
print_line("TOTAL BYTES: " + itos(buffer_end));
print_line("NULL count: " + itos(null_count));
for (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) {
print_line("SET " + E->key() + ": " + itos(E->get()));
}
for (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) {
print_line("CALL " + E->key() + ": " + itos(E->get()));
}
for (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) {
print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get()));
}
}
bool MessageQueue::print() {
#if 0
uint32_t read_pos=0;
while (read_pos < buffer_end ) {
Message *message = (Message*)&buffer[ read_pos ];
Object *target = ObjectDB::get_instance(message->instance_ID);
String cname;
String cfunc;
if (target==NULL) {
//object was deleted
//WARN_PRINT("Object was deleted while awaiting a callback")
//should it print a warning?
} else if (message->notification>=0) {
// messages don't expect a return value
cfunc="notification # "+itos(message->notification);
cname=target->get_type();
} else if (!message->target.empty()) {
cfunc="property: "+message->target;
cname=target->get_type();
} else if (message->target) {
cfunc=String(message->target)+"()";
cname=target->get_type();
}
read_pos+=sizeof(Message);
if (message->type!=TYPE_NOTIFICATION)
read_pos+=sizeof(Variant)*message->args;
}
#endif
return false;
}
int MessageQueue::get_max_buffer_usage() const {
return buffer_max_used;
}
void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) {
const Variant **argptrs = NULL;
if (p_argcount) {
argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
for (int i = 0; i < p_argcount; i++) {
argptrs[i] = &p_args[i];
}
}
Variant::CallError ce;
p_target->call(p_func, argptrs, p_argcount, ce);
if (p_show_error && ce.error != Variant::CallError::CALL_OK) {
ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce));
}
}
void MessageQueue::flush() {
if (buffer_end > buffer_max_used) {
buffer_max_used = buffer_end;
//statistics();
}
uint32_t read_pos = 0;
//using reverse locking strategy
_THREAD_SAFE_LOCK_
while (read_pos < buffer_end) {
_THREAD_SAFE_UNLOCK_
//lock on each interation, so a call can re-add itself to the message queue
Message *message = (Message *)&buffer[read_pos];
Object *target = ObjectDB::get_instance(message->instance_ID);
if (target != NULL) {
switch (message->type & FLAG_MASK) {
case TYPE_CALL: {
Variant *args = (Variant *)(message + 1);
// messages don't expect a return value
_call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR);
for (int i = 0; i < message->args; i++) {
args[i].~Variant();
}
} break;
case TYPE_NOTIFICATION: {
// messages don't expect a return value
target->notification(message->notification);
} break;
case TYPE_SET: {
Variant *arg = (Variant *)(message + 1);
// messages don't expect a return value
target->set(message->target, *arg);
arg->~Variant();
} break;
}
}
uint32_t advance = sizeof(Message);
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
advance += sizeof(Variant) * message->args;
message->~Message();
_THREAD_SAFE_LOCK_
read_pos += advance;
}
buffer_end = 0; // reset buffer
_THREAD_SAFE_UNLOCK_
}
MessageQueue::MessageQueue() {
ERR_FAIL_COND(singleton != NULL);
singleton = this;
buffer_end = 0;
buffer_max_used = 0;
buffer_size = GLOBAL_DEF("memory/buffers/message_queue_max_size_kb", DEFAULT_QUEUE_SIZE_KB);
buffer_size *= 1024;
buffer = memnew_arr(uint8_t, buffer_size);
}
MessageQueue::~MessageQueue() {
uint32_t read_pos = 0;
while (read_pos < buffer_end) {
Message *message = (Message *)&buffer[read_pos];
Variant *args = (Variant *)(message + 1);
int argc = message->args;
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
for (int i = 0; i < argc; i++)
args[i].~Variant();
}
message->~Message();
read_pos += sizeof(Message);
if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
read_pos += sizeof(Variant) * message->args;
}
singleton = NULL;
memdelete_arr(buffer);
}
<|endoftext|>
|
<commit_before>// Gridding algoithm, adopted from bilateral_grid demo app.
// There's nothing left from bilateral_grid except ideas and typical Halide idioms.
#include "Halide.h"
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
ImageParam UVW(Float(64), 4); // second dimension is used for U, V and W parts. So it should be Nx3 sized.
// Constant supersample factor.
Expr supersampleFactor = 8;
// The Omega - telescope view angle.
Expr Omega = pi/2;
// Two dimensional image for prolate spheroidal wave function. Last dimension is fixed to 2.
ImageParam PSWF(Float(64),3);
Var pswfKernelHalf("pswfKernelHalf");
// pswf kernel image height and width are odd, 2N+1. To recover the half, and not to overflow image bounds,
// we first subtract 1 and only then divide by 2. It have to work for 2N+1 and is safe for even values.
// (albeit incorrect).
pswfKernelHalf = (PSWF.extent(0)-1) / 2;
// Iterator within UVW triples.
RDom uvwRange (0, UVW.extent(0), 0, UVW.extent(1), 0, UVW.extent(2));
Var timestep("timestep");
Var baseline("baseline");
Var channel("channel");
baseline = uvwRange.x;
timestep = uvmRange.y;
timestep = uvwRange.z;
// fetch the values.
Var U("U");
U = UVW(baseline, timestep, channel, 0);
Var V("V");
V = UVW(baseline, timestep, channel, 1);
Var W("W");
W = UVW(baseline, timestep, channel, 2);
Expr intU = cast<int>U;
Expr intV = case<int>V;
Expr supersampleU = cast<int>(supersampleFactor*(U - intU));
Expr supersampleV = cast<int>(supersampleFactor*(V - intV));
// Computation of kernel width.
Expr onePercent = 0.01;
Expr wOmegaBy2 = W*Omega/2;
Expr GKernelWidth = sqrt(wOmegaBy2*(wOmegaBy2 + pi*onePercent/sqrt(w)));
Expr GKernelWidthInt = cast<int>(GKernelWidth+0.5);
// Range over kernel space. It is two dimensional, to account for U and V.
RDom GUVRange (-GKernelWidthInt, GKernelWidthInt+1, -GKernelWidthInt, GKernelWidthInt+1);
Var GU("GU");
Var GV("GV");
GU = GUVRange.x;
GV = GUVRange.y;
// Range over PSWF space.
RDom pswfRange(-pswfKernelHalf, pswfKernelHalf+1, -pswfKernelHalf, pswfKernelHalf+1);
Var PSWFU("PSWFU");
Var PSWFV("PSWFV");
PSWFU = pswfRange.x;
PSWFV = pswfRange.y;
// The G kernel.
Func G("G");
// !!! XXX FIXME !!! XXX FIXME
G(GU,GV) = 1-G*0.01-U*0.01;
// The computation of the result.
Func result("result");
var rU("rU");
Var rV("rV");
// computing the result
rU = intU + GU+PSWFU;
rU = intV + GV+PSWFV;
result(rU, rV) = 0.0;
result(rU, rV) += PSWF(PSWFU, PSWFV)*G(GU,GV); // This product can be cached. We also can drop assignment to zero and only update image.
return 0;
}
<commit_msg>Gridding mostly done, going to compile and test.<commit_after>// Gridding algoithm, adopted from bilateral_grid demo app.
// There's nothing left from bilateral_grid except ideas and typical Halide idioms.
#include "Halide.h"
#include <stdio.h>
using namespace Halide;
int main(int argc, char **argv) {
ImageParam UVW(Float(64), 4); // second dimension is used for U, V and W parts. So it should be Nx3 sized.
// Constant supersample factor.
Expr supersampleFactor = 8;
// The Omega - telescope view angle.
Expr Omega = pi/2;
// Two dimensional image for prolate spheroidal wave function. Last dimension is fixed to 2.
ImageParam PSWF(Float(64),3);
Var pswfKernelHalf("pswfKernelHalf");
// pswf kernel image height and width are odd, 2N+1. To recover the half, and not to overflow image bounds,
// we first subtract 1 and only then divide by 2. It have to work for 2N+1 and is safe for even values.
// (albeit incorrect).
pswfKernelHalf = (PSWF.extent(0)-1) / 2;
// Iterator within UVW triples.
RDom uvwRange (0, UVW.extent(0), 0, UVW.extent(1), 0, UVW.extent(2));
Var timestep("timestep");
Var baseline("baseline");
Var channel("channel");
baseline = uvwRange.x;
timestep = uvmRange.y;
timestep = uvwRange.z;
// fetch the values.
Var U("U");
U = UVW(baseline, timestep, channel, 0);
Var V("V");
V = UVW(baseline, timestep, channel, 1);
Var W("W");
W = UVW(baseline, timestep, channel, 2);
Expr intU = cast<int>U;
Expr intV = case<int>V;
Expr supersampleU = cast<int>(supersampleFactor*(U - intU));
Expr supersampleV = cast<int>(supersampleFactor*(V - intV));
// Computation of kernel width.
Expr onePercent = 0.01;
Expr wOmegaBy2 = W*Omega/2;
Expr GKernelWidth = sqrt(wOmegaBy2*(wOmegaBy2 + pi*onePercent/sqrt(w)));
Expr GKernelWidthInt = cast<int>(GKernelWidth+0.5);
// Range over kernel space. It is two dimensional, to account for U and V.
RDom GUVRange (-GKernelWidthInt, GKernelWidthInt+1, -GKernelWidthInt, GKernelWidthInt+1);
Var GU("GU");
Var GV("GV");
GU = GUVRange.x;
GV = GUVRange.y;
// Range over PSWF space.
RDom pswfRange(-pswfKernelHalf, pswfKernelHalf+1, -pswfKernelHalf, pswfKernelHalf+1);
Var PSWFU("PSWFU");
Var PSWFV("PSWFV");
PSWFU = pswfRange.x;
PSWFV = pswfRange.y;
// The G kernel.
Func G("G");
// !!! XXX FIXME !!! XXX FIXME
G(GU,GV) = 1-G*0.01-U*0.01;
// The computation of the result.
Func gridding("gridding");
var rU("rU");
Var rV("rV");
// computing the result
rU = intU + GU+PSWFU;
rU = intV + GV+PSWFV;
gridding(rU, rV) = 0.0;
gridding(rU, rV) += PSWF(PSWFU, PSWFV)*G(GU,GV); // This product can be cached. We also can drop assignment to zero and only update image.
Target compile_target = get_target_from_environment();
gridding.compile_to_file("gridding_compiled", UVW, PSWF, compile_target);
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Page Break: Make the line control thicker to ease fade in/out<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009 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 "native_client/src/include/portability.h"
#if NACL_OSX
#include <crt_externs.h>
#endif
#ifdef _WIN64 /* TODO(gregoryd): remove this when win64 issues are fixed */
#define NACL_NO_INLINE
#endif
EXTERN_C_BEGIN
#include "native_client/src/shared/platform/nacl_sync.h"
#include "native_client/src/shared/platform/nacl_sync_checked.h"
#include "native_client/src/trusted/service_runtime/nacl_globals.h"
#include "native_client/src/trusted/service_runtime/expiration.h"
#include "native_client/src/trusted/service_runtime/nacl_app.h"
#include "native_client/src/trusted/service_runtime/nacl_all_modules.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h"
EXTERN_C_END
int verbosity = 0;
#ifdef __GNUC__
/*
* GDB's canonical overlay managment routine.
* We need its symbol in the symbol table so don't inline it.
* TODO(dje): add some explanation for the non-GDB person.
*/
static void __attribute__ ((noinline)) _ovly_debug_event (void) {
/*
* The asm volatile is here as instructed by the GCC docs.
* It's not enough to declare a function noinline.
* GCC will still look inside the function to see if it's worth calling.
*/
asm volatile ("");
}
#endif
static void StopForDebuggerInit(const struct NaClApp *state) {
/* Put xlate_base in a place where gdb can find it. */
nacl_global_xlate_base = state->mem_start;
#ifdef __GNUC__
_ovly_debug_event();
#endif
}
int SelMain(const int desc, const NaClHandle handle) {
char *av[1];
int ac = 1;
char **envp;
struct NaClApp state;
char *nacl_file = 0;
int main_thread_only = 1;
int export_addr_to = -2;
struct NaClApp *nap;
NaClErrorCode errcode;
int ret_code = 1;
#if NACL_OSX
// Mac dynamic libraries cannot access the environ variable directly.
envp = *_NSGetEnviron();
#else
extern char **environ;
envp = environ;
#endif
NaClAllModulesInit();
/* used to be -P */
NaClSrpcFileDescriptor = desc;
/* used to be -X */
export_addr_to = desc;
/* to be passed to NaClMain, eventually... */
av[0] = const_cast<char*>("NaClMain");
if (!NaClAppCtor(&state)) {
fprintf(stderr, "Error while constructing app state\n");
goto done_file_dtor;
}
state.restrict_to_main_thread = main_thread_only;
nap = &state;
errcode = LOAD_OK;
/* import IMC handle - used to be "-i" */
NaClAddImcHandle(nap, handle, desc);
/*
* in order to report load error to the browser plugin through the
* secure command channel, we do not immediate jump to cleanup code
* on error. rather, we continue processing (assuming earlier
* errors do not make it inappropriate) until the secure command
* channel is set up, and then bail out.
*/
/*
* Ensure this operating system platform is supported.
*/
if (!NaClOsIsSupported()) {
errcode = LOAD_UNSUPPORTED_OS_PLATFORM;
nap->module_load_status = errcode;
fprintf(stderr, "Error while loading \"%s\": %s\n",
nacl_file,
NaClErrorString(errcode));
}
/* Give debuggers a well known point at which xlate_base is known. */
StopForDebuggerInit(&state);
/*
* If export_addr_to is set to a non-negative integer, we create a
* bound socket and socket address pair and bind the former to
* descriptor 3 and the latter to descriptor 4. The socket address
* is written out to the export_addr_to descriptor.
*
* The service runtime also accepts a connection on the bound socket
* and spawns a secure command channel thread to service it.
*
* If export_addr_to is -1, we only create the bound socket and
* socket address pair, and we do not export to an IMC socket. This
* use case is typically only used in testing, where we only "dump"
* the socket address to stdout or similar channel.
*/
if (-2 < export_addr_to) {
NaClCreateServiceSocket(nap);
if (0 <= export_addr_to) {
NaClSendServiceAddressTo(nap, export_addr_to);
/*
* NB: spawns a thread that uses the command channel. we do
* this after NaClAppLoadFile so that NaClApp object is more
* fully populated. Hereafter any changes to nap should be done
* while holding locks.
*/
NaClSecureCommandChannel(nap);
}
}
NaClXMutexLock(&nap->mu);
nap->module_load_status = LOAD_OK;
NaClXCondVarBroadcast(&nap->cv);
NaClXMutexUnlock(&nap->mu);
if (NULL != nap->secure_channel) {
/*
* wait for start_module RPC call on secure channel thread.
*/
NaClWaitForModuleStartStatusCall(nap);
}
/*
* error reporting done; can quit now if there was an error earlier.
*/
if (LOAD_OK != errcode) {
goto done;
}
/*
* only nap->ehdrs.e_entry is usable, no symbol table is
* available.
*/
if (!NaClCreateMainThread(nap,
ac,
av,
envp)) {
fprintf(stderr, "creating main thread failed\n");
goto done;
}
ret_code = NaClWaitForMainThreadToExit(nap);
/*
* exit_group or equiv kills any still running threads while module
* addr space is still valid. otherwise we'd have to kill threads
* before we clean up the address space.
*/
return ret_code;
done:
fflush(stdout);
NaClAppDtor(&state);
done_file_dtor:
fflush(stdout);
NaClAllModulesFini();
return ret_code;
}
<commit_msg>Make _ovly_debug_event extern "C" for nacl-gdb<commit_after>// Copyright (c) 2009 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 "native_client/src/include/portability.h"
#if NACL_OSX
#include <crt_externs.h>
#endif
#ifdef _WIN64 /* TODO(gregoryd): remove this when win64 issues are fixed */
#define NACL_NO_INLINE
#endif
EXTERN_C_BEGIN
#include "native_client/src/shared/platform/nacl_sync.h"
#include "native_client/src/shared/platform/nacl_sync_checked.h"
#include "native_client/src/trusted/service_runtime/nacl_globals.h"
#include "native_client/src/trusted/service_runtime/expiration.h"
#include "native_client/src/trusted/service_runtime/nacl_app.h"
#include "native_client/src/trusted/service_runtime/nacl_all_modules.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h"
EXTERN_C_END
int verbosity = 0;
#ifdef __GNUC__
/*
* GDB's canonical overlay managment routine.
* We need its symbol in the symbol table so don't inline it.
* Note: _ovly_debug_event has to be an unmangled 'C' style symbol.
* TODO(dje): add some explanation for the non-GDB person.
*/
EXTERN_C_BEGIN
static void __attribute__ ((noinline)) _ovly_debug_event (void) {
/*
* The asm volatile is here as instructed by the GCC docs.
* It's not enough to declare a function noinline.
* GCC will still look inside the function to see if it's worth calling.
*/
asm volatile ("");
}
EXTERN_C_END
#endif
static void StopForDebuggerInit(const struct NaClApp *state) {
/* Put xlate_base in a place where gdb can find it. */
nacl_global_xlate_base = state->mem_start;
#ifdef __GNUC__
_ovly_debug_event();
#endif
}
int SelMain(const int desc, const NaClHandle handle) {
char *av[1];
int ac = 1;
char **envp;
struct NaClApp state;
char *nacl_file = 0;
int main_thread_only = 1;
int export_addr_to = -2;
struct NaClApp *nap;
NaClErrorCode errcode;
int ret_code = 1;
#if NACL_OSX
// Mac dynamic libraries cannot access the environ variable directly.
envp = *_NSGetEnviron();
#else
extern char **environ;
envp = environ;
#endif
NaClAllModulesInit();
/* used to be -P */
NaClSrpcFileDescriptor = desc;
/* used to be -X */
export_addr_to = desc;
/* to be passed to NaClMain, eventually... */
av[0] = const_cast<char*>("NaClMain");
if (!NaClAppCtor(&state)) {
fprintf(stderr, "Error while constructing app state\n");
goto done_file_dtor;
}
state.restrict_to_main_thread = main_thread_only;
nap = &state;
errcode = LOAD_OK;
/* import IMC handle - used to be "-i" */
NaClAddImcHandle(nap, handle, desc);
/*
* in order to report load error to the browser plugin through the
* secure command channel, we do not immediate jump to cleanup code
* on error. rather, we continue processing (assuming earlier
* errors do not make it inappropriate) until the secure command
* channel is set up, and then bail out.
*/
/*
* Ensure this operating system platform is supported.
*/
if (!NaClOsIsSupported()) {
errcode = LOAD_UNSUPPORTED_OS_PLATFORM;
nap->module_load_status = errcode;
fprintf(stderr, "Error while loading \"%s\": %s\n",
nacl_file,
NaClErrorString(errcode));
}
/* Give debuggers a well known point at which xlate_base is known. */
StopForDebuggerInit(&state);
/*
* If export_addr_to is set to a non-negative integer, we create a
* bound socket and socket address pair and bind the former to
* descriptor 3 and the latter to descriptor 4. The socket address
* is written out to the export_addr_to descriptor.
*
* The service runtime also accepts a connection on the bound socket
* and spawns a secure command channel thread to service it.
*
* If export_addr_to is -1, we only create the bound socket and
* socket address pair, and we do not export to an IMC socket. This
* use case is typically only used in testing, where we only "dump"
* the socket address to stdout or similar channel.
*/
if (-2 < export_addr_to) {
NaClCreateServiceSocket(nap);
if (0 <= export_addr_to) {
NaClSendServiceAddressTo(nap, export_addr_to);
/*
* NB: spawns a thread that uses the command channel. we do
* this after NaClAppLoadFile so that NaClApp object is more
* fully populated. Hereafter any changes to nap should be done
* while holding locks.
*/
NaClSecureCommandChannel(nap);
}
}
NaClXMutexLock(&nap->mu);
nap->module_load_status = LOAD_OK;
NaClXCondVarBroadcast(&nap->cv);
NaClXMutexUnlock(&nap->mu);
if (NULL != nap->secure_channel) {
/*
* wait for start_module RPC call on secure channel thread.
*/
NaClWaitForModuleStartStatusCall(nap);
}
/*
* error reporting done; can quit now if there was an error earlier.
*/
if (LOAD_OK != errcode) {
goto done;
}
/*
* only nap->ehdrs.e_entry is usable, no symbol table is
* available.
*/
if (!NaClCreateMainThread(nap,
ac,
av,
envp)) {
fprintf(stderr, "creating main thread failed\n");
goto done;
}
ret_code = NaClWaitForMainThreadToExit(nap);
/*
* exit_group or equiv kills any still running threads while module
* addr space is still valid. otherwise we'd have to kill threads
* before we clean up the address space.
*/
return ret_code;
done:
fflush(stdout);
NaClAppDtor(&state);
done_file_dtor:
fflush(stdout);
NaClAllModulesFini();
return ret_code;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021
— Vladimír Vondruš <mosra@centrum.cz>
2021 — Pablo Escobar <mail@rvrs.in>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
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 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 <Corrade/Containers/Array.h>
#include <Corrade/Containers/StringView.h>
#include <Corrade/Utility/Assert.h>
#include <Corrade/PluginManager/Manager.h>
#include <Magnum/Magnum.h>
#include <Magnum/ImageView.h>
#include <Magnum/PixelFormat.h>
#include <Magnum/Math/Color.h>
#include <Magnum/ShaderTools/AbstractConverter.h>
#include <Magnum/Trade/AbstractImageConverter.h>
#include <Magnum/Vk/Assert.h>
#include <Magnum/Vk/BufferCreateInfo.h>
#include <Magnum/Vk/CommandBuffer.h>
#include <Magnum/Vk/CommandPoolCreateInfo.h>
#include <Magnum/Vk/DeviceCreateInfo.h>
#include <Magnum/Vk/DeviceProperties.h>
#include <Magnum/Vk/Fence.h>
#include <Magnum/Vk/FramebufferCreateInfo.h>
#include <Magnum/Vk/ImageCreateInfo.h>
#include <Magnum/Vk/ImageViewCreateInfo.h>
#include <Magnum/Vk/InstanceCreateInfo.h>
#include <Magnum/Vk/Memory.h>
#include <Magnum/Vk/Queue.h>
#include <Magnum/Vk/RenderPassCreateInfo.h>
#include <Magnum/Vk/ShaderCreateInfo.h>
#include <MagnumExternal/Vulkan/flextVkGlobal.h>
using namespace Corrade::Containers::Literals;
using namespace Magnum;
using namespace Magnum::Math::Literals;
int main(int argc, char** argv) {
/* Create an instance */
Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv}
.setApplicationInfo("Magnum Vulkan Triangle Example"_s, {})};
/* Create a device with a graphics queue */
Vk::Queue queue{NoCreate};
Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)}
.addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue})};
/* Allocate a command buffer */
Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{
device.properties().pickQueueFamily(Vk::QueueFlag::Graphics)}};
Vk::CommandBuffer cmd = commandPool.allocate();
device.populateGlobalFunctionPointers();
/* Render pass */
Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{}
.setAttachments({
Vk::AttachmentDescription{PixelFormat::RGBA8Srgb,
Vk::AttachmentLoadOperation::Clear,
Vk::AttachmentStoreOperation::Store,
Vk::ImageLayout::Undefined,
Vk::ImageLayout::ColorAttachment
}
})
.addSubpass(Vk::SubpassDescription{}
.setColorAttachments({
Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment}
})
)
};
/* Framebuffer image. Allocate with linear tiling as we want to download it
later. */
Vk::Image image{NoCreate};
{
Vk::ImageCreateInfo2D info{Vk::ImageUsage::ColorAttachment,
PixelFormat::RGBA8Srgb, {800, 600}, 1};
info->tiling = VK_IMAGE_TILING_LINEAR;
image = Vk::Image{device, info, Vk::MemoryFlag::HostVisible};
}
Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}};
/* Vertex buffer */
Vk::Buffer buffer{device, Vk::BufferCreateInfo{
Vk::BufferUsage::VertexBuffer,
3*2*4*4 /* Three vertices, each is four-element pos & color */
}, Vk::MemoryFlag::HostVisible};
{
/* Fill the data */
/** @todo arrayCast for an array rvalue */
Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map();
auto view = Containers::arrayCast<Vector4>(data);
view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; /* Left vertex, red color */
view[1] = 0xff0000ff_srgbaf;
view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; /* Right vertex, green color */
view[3] = 0x00ff00ff_srgbaf;
view[4] = { 0.0f, 0.5f, 0.0f, 1.0f}; /* Top vertex, blue color */
view[5] = 0x0000ffff_srgbaf;
}
/* Framebuffer */
Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, {
color
}, {800, 600}}};
/* Create the shader */
constexpr Containers::StringView assembly = R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
; Function %1 is vertex shader and has %12, %13 as input and %15, %16 as output
OpEntryPoint Vertex %1 "ver" %12 %13 %gl_Position %16
; Function %2 is fragment shader and has %5 as input and %6 as output
OpEntryPoint Fragment %2 "fra" %5 %6
OpExecutionMode %2 OriginUpperLeft
; Input/output layouts
OpDecorate %12 Location 0
OpDecorate %13 Location 1
OpDecorate %gl_Position BuiltIn Position
OpDecorate %16 Location 0
OpDecorate %5 Location 0
OpDecorate %6 Location 0
; Types
%void = OpTypeVoid
%8 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Input_v4float = OpTypePointer Input %v4float
%12 = OpVariable %_ptr_Input_v4float Input
%13 = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_Position = OpVariable %_ptr_Output_v4float Output
%16 = OpVariable %_ptr_Output_v4float Output
%5 = OpVariable %_ptr_Input_v4float Input
%6 = OpVariable %_ptr_Output_v4float Output
; %1 = void ver()
%1 = OpFunction %void None %8
%33 = OpLabel
%30 = OpLoad %v4float %12
%31 = OpLoad %v4float %13
OpStore %gl_Position %30
OpStore %16 %31
OpReturn
OpFunctionEnd
; %2 = void fra()
%2 = OpFunction %void None %8
%34 = OpLabel
%32 = OpLoad %v4float %5
OpStore %6 %32
OpReturn
OpFunctionEnd
)"_s;
Vk::Shader shader{device, Vk::ShaderCreateInfo{
CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION(
PluginManager::Manager<ShaderTools::AbstractConverter>{}.loadAndInstantiate("SpirvAssemblyToSpirvShaderConverter")
)->convertDataToData({}, assembly))}};
/* Pipeline layout */
VkPipelineLayout pipelineLayout;
{
VkPipelineLayoutCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
info.setLayoutCount = 0;
info.pushConstantRangeCount = 0;
MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreatePipelineLayout(device, &info, nullptr, &pipelineLayout));
}
/* Create a graphics pipeline */
VkPipeline pipeline;
{
VkVertexInputBindingDescription binding{};
binding.binding = 0;
binding.stride = 2*4*4;
VkVertexInputAttributeDescription attributes[2]{};
attributes[0].location = 0; /* position attribute */
attributes[0].binding = binding.binding;
attributes[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributes[0].offset = 0;
attributes[1].location = 1; /* color attribute */
attributes[1].binding = binding.binding;
attributes[1].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributes[1].offset = 4*4;
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &binding;
vertexInputInfo.vertexAttributeDescriptionCount = 2;
vertexInputInfo.pVertexAttributeDescriptions = attributes;
VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};
inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkViewport viewport{};
viewport.width = 800.0f;
viewport.height = 600.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{{}, {800, 600}};
VkPipelineViewportStateCreateInfo viewportInfo{};
viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportInfo.viewportCount = 1;
viewportInfo.pViewports = &viewport;
viewportInfo.scissorCount = 1;
viewportInfo.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizationInfo{};
rasterizationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizationInfo.lineWidth = 1.0f;
/* the zero-filled defaults are good enough apparently */
VkPipelineMultisampleStateCreateInfo multisampleInfo{};
multisampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState blend{};
blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT|
VK_COLOR_COMPONENT_G_BIT|
VK_COLOR_COMPONENT_B_BIT|
VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlendInfo.attachmentCount = 1;
colorBlendInfo.pAttachments = &blend;
VkPipelineShaderStageCreateInfo stages[2]{};
stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
stages[0].module = shader;
stages[0].pName = "ver";
stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stages[1].module = shader;
stages[1].pName = "fra";
VkGraphicsPipelineCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
info.stageCount = 2;
info.pStages = stages;
info.pVertexInputState = &vertexInputInfo;
info.pInputAssemblyState = &inputAssemblyInfo;
info.pViewportState = &viewportInfo;
info.pRasterizationState = &rasterizationInfo;
info.pMultisampleState = &multisampleInfo;
info.pColorBlendState = &colorBlendInfo;
info.layout = pipelineLayout;
info.renderPass = renderPass;
info.subpass = 0;
MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreateGraphicsPipelines(device, nullptr, 1, &info, nullptr, &pipeline));
}
/* Begin recording */
cmd.begin();
/* Begin a render pass. Converts the framebuffer attachment from Undefined
to ColorAttachment layout and clears it. */
cmd.beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer}
.clearColor(0, 0x1f1f1f_srgbf));
/* Bind the pipeline */
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
/* Bind the vertex buffer */
{
const VkDeviceSize offset = 0;
const VkBuffer handle = buffer;
vkCmdBindVertexBuffers(cmd, 0, 1, &handle, &offset);
}
/* Draw the triangle */
vkCmdDraw(cmd, 3, 1, 0, 0);
/* End recording */
cmd.endRenderPass()
.end();
/* Submit the command buffer and wait until done */
Vk::Fence fence{device};
queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}, fence);
fence.wait();
/* Read the image back */
CORRADE_INTERNAL_ASSERT_EXPRESSION(
PluginManager::Manager<Trade::AbstractImageConverter>{}
.loadAndInstantiate("AnyImageConverter")
)->exportToFile(ImageView2D{
PixelFormat::RGBA8Unorm, {800, 600},
image.dedicatedMemory().mapRead()}, "image.png");
Debug{} << "Saved an image to image.png";
/* Clean up */
vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
}
<commit_msg>triangle-vulkan: minor formatting.<commit_after>/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021
— Vladimír Vondruš <mosra@centrum.cz>
2021 — Pablo Escobar <mail@rvrs.in>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
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 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 <Corrade/Containers/Array.h>
#include <Corrade/Containers/StringView.h>
#include <Corrade/Utility/Assert.h>
#include <Corrade/PluginManager/Manager.h>
#include <Magnum/Magnum.h>
#include <Magnum/ImageView.h>
#include <Magnum/PixelFormat.h>
#include <Magnum/Math/Color.h>
#include <Magnum/ShaderTools/AbstractConverter.h>
#include <Magnum/Trade/AbstractImageConverter.h>
#include <Magnum/Vk/Assert.h>
#include <Magnum/Vk/BufferCreateInfo.h>
#include <Magnum/Vk/CommandBuffer.h>
#include <Magnum/Vk/CommandPoolCreateInfo.h>
#include <Magnum/Vk/DeviceCreateInfo.h>
#include <Magnum/Vk/DeviceProperties.h>
#include <Magnum/Vk/Fence.h>
#include <Magnum/Vk/FramebufferCreateInfo.h>
#include <Magnum/Vk/ImageCreateInfo.h>
#include <Magnum/Vk/ImageViewCreateInfo.h>
#include <Magnum/Vk/InstanceCreateInfo.h>
#include <Magnum/Vk/Memory.h>
#include <Magnum/Vk/Queue.h>
#include <Magnum/Vk/RenderPassCreateInfo.h>
#include <Magnum/Vk/ShaderCreateInfo.h>
#include <MagnumExternal/Vulkan/flextVkGlobal.h>
using namespace Corrade::Containers::Literals;
using namespace Magnum;
using namespace Magnum::Math::Literals;
int main(int argc, char** argv) {
/* Create an instance */
Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv}
.setApplicationInfo("Magnum Vulkan Triangle Example"_s, {})};
/* Create a device with a graphics queue */
Vk::Queue queue{NoCreate};
Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)}
.addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue})};
/* Allocate a command buffer */
Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{
device.properties().pickQueueFamily(Vk::QueueFlag::Graphics)}};
Vk::CommandBuffer cmd = commandPool.allocate();
device.populateGlobalFunctionPointers();
/* Render pass */
Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{}
.setAttachments({
Vk::AttachmentDescription{PixelFormat::RGBA8Srgb,
Vk::AttachmentLoadOperation::Clear,
Vk::AttachmentStoreOperation::Store,
Vk::ImageLayout::Undefined,
Vk::ImageLayout::ColorAttachment
}
})
.addSubpass(Vk::SubpassDescription{}
.setColorAttachments({
Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment}
})
)
};
/* Framebuffer image. Allocate with linear tiling as we want to download it
later. */
Vk::Image image{NoCreate};
{
Vk::ImageCreateInfo2D info{Vk::ImageUsage::ColorAttachment,
PixelFormat::RGBA8Srgb, {800, 600}, 1};
info->tiling = VK_IMAGE_TILING_LINEAR;
image = Vk::Image{device, info, Vk::MemoryFlag::HostVisible};
}
Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}};
/* Vertex buffer */
Vk::Buffer buffer{device, Vk::BufferCreateInfo{
Vk::BufferUsage::VertexBuffer,
3*2*4*4 /* Three vertices, each is four-element pos & color */
}, Vk::MemoryFlag::HostVisible};
{
/* Fill the data */
/** @todo arrayCast for an array rvalue */
Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map();
auto view = Containers::arrayCast<Vector4>(data);
view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; /* Left vertex, red color */
view[1] = 0xff0000ff_srgbaf;
view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; /* Right vertex, green color */
view[3] = 0x00ff00ff_srgbaf;
view[4] = { 0.0f, 0.5f, 0.0f, 1.0f}; /* Top vertex, blue color */
view[5] = 0x0000ffff_srgbaf;
}
/* Framebuffer */
Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, {
color
}, {800, 600}}};
/* Create the shader */
constexpr Containers::StringView assembly = R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
; Function %1 is vertex shader and has %12, %13 as input and %15, %16 as output
OpEntryPoint Vertex %1 "ver" %12 %13 %gl_Position %16
; Function %2 is fragment shader and has %5 as input and %6 as output
OpEntryPoint Fragment %2 "fra" %5 %6
OpExecutionMode %2 OriginUpperLeft
; Input/output layouts
OpDecorate %12 Location 0
OpDecorate %13 Location 1
OpDecorate %gl_Position BuiltIn Position
OpDecorate %16 Location 0
OpDecorate %5 Location 0
OpDecorate %6 Location 0
; Types
%void = OpTypeVoid
%8 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Input_v4float = OpTypePointer Input %v4float
%12 = OpVariable %_ptr_Input_v4float Input
%13 = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_Position = OpVariable %_ptr_Output_v4float Output
%16 = OpVariable %_ptr_Output_v4float Output
%5 = OpVariable %_ptr_Input_v4float Input
%6 = OpVariable %_ptr_Output_v4float Output
; %1 = void ver()
%1 = OpFunction %void None %8
%33 = OpLabel
%30 = OpLoad %v4float %12
%31 = OpLoad %v4float %13
OpStore %gl_Position %30
OpStore %16 %31
OpReturn
OpFunctionEnd
; %2 = void fra()
%2 = OpFunction %void None %8
%34 = OpLabel
%32 = OpLoad %v4float %5
OpStore %6 %32
OpReturn
OpFunctionEnd
)"_s;
Vk::Shader shader{device, Vk::ShaderCreateInfo{
CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION(
PluginManager::Manager<ShaderTools::AbstractConverter>{}.loadAndInstantiate("SpirvAssemblyToSpirvShaderConverter")
)->convertDataToData({}, assembly))}};
/* Pipeline layout */
VkPipelineLayout pipelineLayout;
{
VkPipelineLayoutCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
info.setLayoutCount = 0;
info.pushConstantRangeCount = 0;
MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreatePipelineLayout(device, &info, nullptr, &pipelineLayout));
}
/* Create a graphics pipeline */
VkPipeline pipeline;
{
VkVertexInputBindingDescription binding{};
binding.binding = 0;
binding.stride = 2*4*4;
VkVertexInputAttributeDescription attributes[2]{};
attributes[0].location = 0; /* position attribute */
attributes[0].binding = binding.binding;
attributes[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributes[0].offset = 0;
attributes[1].location = 1; /* color attribute */
attributes[1].binding = binding.binding;
attributes[1].format = VK_FORMAT_R32G32B32A32_SFLOAT;
attributes[1].offset = 4*4;
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.pVertexBindingDescriptions = &binding;
vertexInputInfo.vertexAttributeDescriptionCount = 2;
vertexInputInfo.pVertexAttributeDescriptions = attributes;
VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};
inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkViewport viewport{};
viewport.width = 800.0f;
viewport.height = 600.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{{}, {800, 600}};
VkPipelineViewportStateCreateInfo viewportInfo{};
viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportInfo.viewportCount = 1;
viewportInfo.pViewports = &viewport;
viewportInfo.scissorCount = 1;
viewportInfo.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizationInfo{};
rasterizationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizationInfo.lineWidth = 1.0f;
/* the zero-filled defaults are good enough apparently */
VkPipelineMultisampleStateCreateInfo multisampleInfo{};
multisampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState blend{};
blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT|
VK_COLOR_COMPONENT_G_BIT|
VK_COLOR_COMPONENT_B_BIT|
VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlendInfo.attachmentCount = 1;
colorBlendInfo.pAttachments = &blend;
VkPipelineShaderStageCreateInfo stages[2]{};
stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
stages[0].module = shader;
stages[0].pName = "ver";
stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stages[1].module = shader;
stages[1].pName = "fra";
VkGraphicsPipelineCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
info.stageCount = 2;
info.pStages = stages;
info.pVertexInputState = &vertexInputInfo;
info.pInputAssemblyState = &inputAssemblyInfo;
info.pViewportState = &viewportInfo;
info.pRasterizationState = &rasterizationInfo;
info.pMultisampleState = &multisampleInfo;
info.pColorBlendState = &colorBlendInfo;
info.layout = pipelineLayout;
info.renderPass = renderPass;
info.subpass = 0;
MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreateGraphicsPipelines(device, nullptr, 1, &info, nullptr, &pipeline));
}
/* Begin recording */
cmd.begin();
/* Begin a render pass. Converts the framebuffer attachment from Undefined
to ColorAttachment layout and clears it. */
cmd.beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer}
.clearColor(0, 0x1f1f1f_srgbf)
);
/* Bind the pipeline */
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
/* Bind the vertex buffer */
{
const VkDeviceSize offset = 0;
const VkBuffer handle = buffer;
vkCmdBindVertexBuffers(cmd, 0, 1, &handle, &offset);
}
/* Draw the triangle */
vkCmdDraw(cmd, 3, 1, 0, 0);
/* End recording */
cmd.endRenderPass()
.end();
/* Submit the command buffer and wait until done */
Vk::Fence fence{device};
queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}, fence);
fence.wait();
/* Read the image back */
CORRADE_INTERNAL_ASSERT_EXPRESSION(
PluginManager::Manager<Trade::AbstractImageConverter>{}
.loadAndInstantiate("AnyImageConverter")
)->exportToFile(ImageView2D{
PixelFormat::RGBA8Unorm, {800, 600},
image.dedicatedMemory().mapRead()}, "image.png");
Debug{} << "Saved an image to image.png";
/* Clean up */
vkDestroyPipeline(device, pipeline, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
}
<|endoftext|>
|
<commit_before>/*
** SelfPortrait API
** See Copyright Notice in lua_utils.h
*/
#include "test_utils.h"
#include <stdexcept>
#include "str_conversion.h"
#include <cxxtest/TestSuite.h>
//#include <dlfcn.h>
using namespace std;
namespace LuaUtils {
void addTestFunctionsAndPaths(lua_State* L)
{
lua_atpanic(L, atPanicThrow);
luaL_openlibs(L);
lua_pushcfunction(L, ts_fail);
lua_setglobal(L, "TS_FAIL");
lua_pushcfunction(L, ts_trace);
lua_setglobal(L, "TS_TRACE");
lua_pushcfunction(L, ts_warn);
lua_setglobal(L, "TS_WARN");
lua_getglobal(L, "package");
luaL_checktype(L, 1, LUA_TTABLE);
// for cxxtest.lua
lua_getfield(L, 1, "path");
lua_pushstring(L, ";");
lua_pushstring(L, srcpath().c_str());
lua_pushstring(L, "/?.lua");
lua_concat(L, 4);
lua_setfield(L, 1, "path");
// for libluacppreflect
lua_getfield(L, 1, "cpath");
lua_pushstring(L, ";");
lua_pushstring(L, binpath().c_str());
lua_pushstring(L, "/../lua_module/?.so");
lua_pushstring(L, ";");
lua_pushstring(L, binpath().c_str());
lua_pushstring(L, "/../lua_module/?.dll"); // don't want to mess with platform DEFINEs
lua_concat(L, 7);
lua_setfield(L, 1, "cpath");
// Uncomment this to prevent the unloading of the library
// When the library is unloaded valgrind cannot translate function addresses to names
// in the stacktrace
//std::string library_path = fmt_str("%1/../lua_module/libluaselfportrait.so", binpath());
//void* handle = dlopen(library_path.c_str(), RTLD_NOW);
}
int atPanicThrow(lua_State* L) {
throw std::runtime_error(strconv::fmt_str("Error during execution of Lua code:\n%1", lua_tostring(L, -1)));
return 0;
}
int ts_fail(lua_State* L) {
const int nargs = lua_gettop(L);
if (nargs == 3) {
CxxTest::TestTracker::tracker().failedTest( luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );
} else if (nargs >= 1) {
lua_Debug debug;
lua_getstack(L, 1, &debug);
lua_getinfo(L, "Sl", &debug);
CxxTest::TestTracker::tracker().failedTest( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );
} else {
luaL_error(L, "TS_FAIL called with an illegal number of arguments");
}
return 0;
}
int ts_trace(lua_State* L) {
const int nargs = lua_gettop(L);
if (nargs == 3) {
CxxTest::TestTracker::tracker().trace(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );
} else if (nargs >= 1) {
lua_Debug debug;
lua_getstack(L, 1, &debug);
lua_getinfo(L, "Sl", &debug);
CxxTest::TestTracker::tracker().trace( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );
} else {
luaL_error(L, "TS_TRACE called with an illegal number of arguments");
}
return 0;
}
int ts_warn(lua_State* L) {
const int nargs = lua_gettop(L);
if (nargs == 3) {
CxxTest::TestTracker::tracker().warning(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );
} else if (nargs >= 1) {
lua_Debug debug;
lua_getstack(L, 1, &debug);
lua_getinfo(L, "Sl", &debug);
CxxTest::TestTracker::tracker().warning( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );
} else {
luaL_error(L, "TS_WARN called with an illegal number of arguments");
}
return 0;
}
}
<commit_msg>Remove duplicate lua_openlibs that resets package.path<commit_after>/*
** SelfPortrait API
** See Copyright Notice in lua_utils.h
*/
#include "test_utils.h"
#include <stdexcept>
#include "str_conversion.h"
#include <cxxtest/TestSuite.h>
//#include <dlfcn.h>
using namespace std;
namespace LuaUtils {
void addTestFunctionsAndPaths(lua_State* L)
{
lua_atpanic(L, atPanicThrow);
lua_pushcfunction(L, ts_fail);
lua_setglobal(L, "TS_FAIL");
lua_pushcfunction(L, ts_trace);
lua_setglobal(L, "TS_TRACE");
lua_pushcfunction(L, ts_warn);
lua_setglobal(L, "TS_WARN");
lua_getglobal(L, "package");
luaL_checktype(L, 1, LUA_TTABLE);
// for cxxtest.lua
lua_getfield(L, 1, "path");
lua_pushstring(L, ";");
lua_pushstring(L, srcpath().c_str());
lua_pushstring(L, "/?.lua");
lua_concat(L, 4);
lua_setfield(L, 1, "path");
// for libluacppreflect
lua_getfield(L, 1, "cpath");
lua_pushstring(L, ";");
lua_pushstring(L, binpath().c_str());
lua_pushstring(L, "/../lua_module/?.so");
lua_pushstring(L, ";");
lua_pushstring(L, binpath().c_str());
lua_pushstring(L, "/../lua_module/?.dll"); // don't want to mess with platform DEFINEs
lua_concat(L, 7);
lua_setfield(L, 1, "cpath");
// Uncomment this to prevent the unloading of the library
// When the library is unloaded valgrind cannot translate function addresses to names
// in the stacktrace
//std::string library_path = fmt_str("%1/../lua_module/libluaselfportrait.so", binpath());
//void* handle = dlopen(library_path.c_str(), RTLD_NOW);
}
int atPanicThrow(lua_State* L) {
throw std::runtime_error(strconv::fmt_str("Error during execution of Lua code:\n%1", lua_tostring(L, -1)));
return 0;
}
int ts_fail(lua_State* L) {
const int nargs = lua_gettop(L);
if (nargs == 3) {
CxxTest::TestTracker::tracker().failedTest( luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );
} else if (nargs >= 1) {
lua_Debug debug;
lua_getstack(L, 1, &debug);
lua_getinfo(L, "Sl", &debug);
CxxTest::TestTracker::tracker().failedTest( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );
} else {
luaL_error(L, "TS_FAIL called with an illegal number of arguments");
}
return 0;
}
int ts_trace(lua_State* L) {
const int nargs = lua_gettop(L);
if (nargs == 3) {
CxxTest::TestTracker::tracker().trace(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );
} else if (nargs >= 1) {
lua_Debug debug;
lua_getstack(L, 1, &debug);
lua_getinfo(L, "Sl", &debug);
CxxTest::TestTracker::tracker().trace( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );
} else {
luaL_error(L, "TS_TRACE called with an illegal number of arguments");
}
return 0;
}
int ts_warn(lua_State* L) {
const int nargs = lua_gettop(L);
if (nargs == 3) {
CxxTest::TestTracker::tracker().warning(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );
} else if (nargs >= 1) {
lua_Debug debug;
lua_getstack(L, 1, &debug);
lua_getinfo(L, "Sl", &debug);
CxxTest::TestTracker::tracker().warning( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );
} else {
luaL_error(L, "TS_WARN called with an illegal number of arguments");
}
return 0;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "errors.hpp"
#include <boost/make_shared.hpp>
#include "buffer_cache/buffer_cache.hpp"
#include "containers/iterators.hpp"
#include "memcached/protocol.hpp"
#include "rdb_protocol/protocol.hpp"
#include "serializer/config.hpp"
#include "serializer/translator.hpp"
#include "unittest/gtest.hpp"
#include "unittest/dummy_namespace_interface.hpp"
namespace unittest {
namespace {
void run_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t *)> fun) {
order_source_t order_source;
/* Pick shards */
std::vector<rdb_protocol_t::region_t> shards;
shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::none, store_key_t(), key_range_t::open, store_key_t("n"))));
shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::closed, store_key_t("n"), key_range_t::none, store_key_t() )));
boost::ptr_vector<mock::temp_file_t> temp_files;
for (size_t i = 0; i < shards.size(); ++i) {
temp_files.push_back(new mock::temp_file_t("/tmp/rdb_unittest.XXXXXX"));
}
scoped_ptr_t<io_backender_t> io_backender;
make_io_backender(aio_default, &io_backender);
scoped_array_t<scoped_ptr_t<serializer_t> > serializers(shards.size());
for (size_t i = 0; i < shards.size(); ++i) {
filepath_file_opener_t file_opener(temp_files[i].name(), io_backender.get());
standard_serializer_t::create(&file_opener,
standard_serializer_t::static_config_t());
serializers[i].init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(),
&file_opener,
&get_global_perfmon_collection()));
}
boost::ptr_vector<rdb_protocol_t::store_t> underlying_stores;
rdb_protocol_t::context_t ctx;
for (size_t i = 0; i < shards.size(); ++i) {
underlying_stores.push_back(new rdb_protocol_t::store_t(serializers[i].get(), temp_files[i].name(), GIGABYTE, true, &get_global_perfmon_collection(), &ctx));
}
boost::ptr_vector<store_view_t<rdb_protocol_t> > stores;
for (size_t i = 0; i < shards.size(); ++i) {
stores.push_back(new store_subview_t<rdb_protocol_t>(&underlying_stores[i], shards[i]));
}
/* Set up namespace interface */
dummy_namespace_interface_t<rdb_protocol_t> nsi(shards, stores.c_array(), &order_source);
fun(&nsi, &order_source);
}
void run_in_thread_pool_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t*)> fun) {
mock::run_in_thread_pool(boost::bind(&run_with_namespace_interface, fun));
}
} /* anonymous namespace */
/* `SetupTeardown` makes sure that it can start and stop without anything going
horribly wrong */
void run_setup_teardown_test(UNUSED namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *) {
/* Do nothing */
}
TEST(RDBProtocol, SetupTeardown) {
run_in_thread_pool_with_namespace_interface(&run_setup_teardown_test);
}
/* `GetSet` tests basic get and set operations */
void run_get_set_test(namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *osource) {
boost::shared_ptr<scoped_cJSON_t> data(new scoped_cJSON_t(cJSON_CreateNull()));
{
rdb_protocol_t::write_t write(rdb_protocol_t::point_write_t(store_key_t("a"), data));
rdb_protocol_t::write_response_t response;
cond_t interruptor;
nsi->write(write, &response, osource->check_in("unittest::run_get_set_test(rdb_protocol.cc-A)"), &interruptor);
if (rdb_protocol_t::point_write_response_t *maybe_point_write_response_t = boost::get<rdb_protocol_t::point_write_response_t>(&response.response)) {
EXPECT_EQ(maybe_point_write_response_t->result, STORED);
} else {
ADD_FAILURE() << "got wrong type of result back";
}
}
{
rdb_protocol_t::read_t read(rdb_protocol_t::point_read_t(store_key_t("a")));
rdb_protocol_t::read_response_t response;
cond_t interruptor;
nsi->read(read, &response, osource->check_in("unittest::run_get_set_test(rdb_protocol.cc-B)"), &interruptor);
if (rdb_protocol_t::point_read_response_t *maybe_point_read_response = boost::get<rdb_protocol_t::point_read_response_t>(&response.response)) {
EXPECT_TRUE(maybe_point_read_response->data->get() != NULL);
EXPECT_TRUE(cJSON_Equal(data->get(), maybe_point_read_response->data->get()));
} else {
ADD_FAILURE() << "got wrong result back";
}
}
}
TEST(RDBProtocol, GetSet) {
run_in_thread_pool_with_namespace_interface(&run_get_set_test);
}
} /* namespace unittest */
<commit_msg>Make rdb_protocol unittest work.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "errors.hpp"
#include <boost/make_shared.hpp>
#include "buffer_cache/buffer_cache.hpp"
#include "clustering/administration/metadata.hpp"
#include "containers/iterators.hpp"
#include "memcached/protocol.hpp"
#include "rdb_protocol/protocol.hpp"
#include "rpc/semilattice/semilattice_manager.hpp"
#include "serializer/config.hpp"
#include "serializer/translator.hpp"
#include "unittest/dummy_namespace_interface.hpp"
#include "unittest/gtest.hpp"
#include "rpc/directory/read_manager.hpp"
namespace unittest {
namespace {
void run_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t *)> fun) {
order_source_t order_source;
/* Pick shards */
std::vector<rdb_protocol_t::region_t> shards;
shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::none, store_key_t(), key_range_t::open, store_key_t("n"))));
shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::closed, store_key_t("n"), key_range_t::none, store_key_t() )));
boost::ptr_vector<mock::temp_file_t> temp_files;
for (size_t i = 0; i < shards.size(); ++i) {
temp_files.push_back(new mock::temp_file_t("/tmp/rdb_unittest.XXXXXX"));
}
scoped_ptr_t<io_backender_t> io_backender;
make_io_backender(aio_default, &io_backender);
scoped_array_t<scoped_ptr_t<serializer_t> > serializers(shards.size());
for (size_t i = 0; i < shards.size(); ++i) {
filepath_file_opener_t file_opener(temp_files[i].name(), io_backender.get());
standard_serializer_t::create(&file_opener,
standard_serializer_t::static_config_t());
serializers[i].init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(),
&file_opener,
&get_global_perfmon_collection()));
}
boost::ptr_vector<rdb_protocol_t::store_t> underlying_stores;
/* Create some structures for the rdb_protocol_t::context_t, warning some
* boilerplate is about to follow, avert your eyes if you have a weak
* stomach for such things. */
extproc::spawner_t::info_t spawner_info;
extproc::spawner_t::create(&spawner_info);
extproc::pool_group_t pool_group(&spawner_info, extproc::pool_group_t::DEFAULTS);
int port = mock::randport();
connectivity_cluster_t c;
semilattice_manager_t<cluster_semilattice_metadata_t> slm(&c, cluster_semilattice_metadata_t());
connectivity_cluster_t::run_t cr(&c, mock::get_unittest_addresses(), port, &slm, 0, NULL);
int port2 = mock::randport();
connectivity_cluster_t c2;
directory_read_manager_t<cluster_directory_metadata_t> read_manager(&c2);
connectivity_cluster_t::run_t cr2(&c2, mock::get_unittest_addresses(), port2, &read_manager, 0, NULL);
rdb_protocol_t::context_t ctx(&pool_group, NULL, slm.get_root_view(), &read_manager, generate_uuid());
for (size_t i = 0; i < shards.size(); ++i) {
underlying_stores.push_back(new rdb_protocol_t::store_t(serializers[i].get(), temp_files[i].name(), GIGABYTE, true, &get_global_perfmon_collection(), &ctx));
}
boost::ptr_vector<store_view_t<rdb_protocol_t> > stores;
for (size_t i = 0; i < shards.size(); ++i) {
stores.push_back(new store_subview_t<rdb_protocol_t>(&underlying_stores[i], shards[i]));
}
/* Set up namespace interface */
dummy_namespace_interface_t<rdb_protocol_t> nsi(shards, stores.c_array(), &order_source);
fun(&nsi, &order_source);
}
void run_in_thread_pool_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t*)> fun) {
mock::run_in_thread_pool(boost::bind(&run_with_namespace_interface, fun));
}
} /* anonymous namespace */
/* `SetupTeardown` makes sure that it can start and stop without anything going
horribly wrong */
void run_setup_teardown_test(UNUSED namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *) {
/* Do nothing */
}
TEST(RDBProtocol, SetupTeardown) {
run_in_thread_pool_with_namespace_interface(&run_setup_teardown_test);
}
/* `GetSet` tests basic get and set operations */
void run_get_set_test(namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *osource) {
boost::shared_ptr<scoped_cJSON_t> data(new scoped_cJSON_t(cJSON_CreateNull()));
{
rdb_protocol_t::write_t write(rdb_protocol_t::point_write_t(store_key_t("a"), data));
rdb_protocol_t::write_response_t response;
cond_t interruptor;
nsi->write(write, &response, osource->check_in("unittest::run_get_set_test(rdb_protocol.cc-A)"), &interruptor);
if (rdb_protocol_t::point_write_response_t *maybe_point_write_response_t = boost::get<rdb_protocol_t::point_write_response_t>(&response.response)) {
EXPECT_EQ(maybe_point_write_response_t->result, STORED);
} else {
ADD_FAILURE() << "got wrong type of result back";
}
}
{
rdb_protocol_t::read_t read(rdb_protocol_t::point_read_t(store_key_t("a")));
rdb_protocol_t::read_response_t response;
cond_t interruptor;
nsi->read(read, &response, osource->check_in("unittest::run_get_set_test(rdb_protocol.cc-B)"), &interruptor);
if (rdb_protocol_t::point_read_response_t *maybe_point_read_response = boost::get<rdb_protocol_t::point_read_response_t>(&response.response)) {
EXPECT_TRUE(maybe_point_read_response->data->get() != NULL);
EXPECT_TRUE(cJSON_Equal(data->get(), maybe_point_read_response->data->get()));
} else {
ADD_FAILURE() << "got wrong result back";
}
}
}
TEST(RDBProtocol, GetSet) {
run_in_thread_pool_with_namespace_interface(&run_get_set_test);
}
} /* namespace unittest */
<|endoftext|>
|
<commit_before><commit_msg>Removed unused cpp file<commit_after><|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm 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 <realm/util/to_string.hpp>
#include <atomic>
#include <dispatch/dispatch.h>
#include <objc/runtime.h>
#include <pthread.h>
namespace {
using namespace realm;
class RunLoopScheduler : public util::Scheduler {
public:
RunLoopScheduler(CFRunLoopRef run_loop = nullptr);
~RunLoopScheduler();
void notify() override;
void set_notify_callback(std::function<void()>) override;
bool is_on_thread() const noexcept override;
bool is_same_as(const Scheduler* other) const noexcept override;
bool can_deliver_notifications() const noexcept override;
private:
CFRunLoopRef m_runloop;
CFRunLoopSourceRef m_signal = nullptr;
};
RunLoopScheduler::RunLoopScheduler(CFRunLoopRef run_loop)
: m_runloop(run_loop ?: CFRunLoopGetCurrent())
{
CFRetain(m_runloop);
}
RunLoopScheduler::~RunLoopScheduler()
{
if (m_signal) {
CFRunLoopSourceInvalidate(m_signal);
CFRelease(m_signal);
}
CFRelease(m_runloop);
}
void RunLoopScheduler::set_notify_callback(std::function<void ()> callback)
{
if (m_signal) {
CFRunLoopSourceInvalidate(m_signal);
CFRelease(m_signal);
m_signal = nullptr;
}
struct RefCountedRunloopCallback {
std::function<void()> callback;
std::atomic<size_t> ref_count;
};
CFRunLoopSourceContext ctx{};
ctx.info = new RefCountedRunloopCallback{std::move(callback), {0}};
ctx.perform = [](void* info) {
static_cast<RefCountedRunloopCallback*>(info)->callback();
};
ctx.retain = [](const void* info) {
static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info))->ref_count.fetch_add(1, std::memory_order_relaxed);
return info;
};
ctx.release = [](const void* info) {
auto ptr = static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info));
if (ptr->ref_count.fetch_add(-1, std::memory_order_acq_rel) == 1) {
delete ptr;
}
};
m_signal = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &ctx);
CFRunLoopAddSource(m_runloop, m_signal, kCFRunLoopDefaultMode);
}
void RunLoopScheduler::notify()
{
if (!m_signal)
return;
CFRunLoopSourceSignal(m_signal);
// Signalling the source makes it run the next time the runloop gets
// to it, but doesn't make the runloop start if it's currently idle
// waiting for events
CFRunLoopWakeUp(m_runloop);
}
bool RunLoopScheduler::is_on_thread() const noexcept
{
return CFRunLoopGetCurrent() == m_runloop;
}
bool RunLoopScheduler::is_same_as(const Scheduler* other) const noexcept
{
auto o = dynamic_cast<const RunLoopScheduler*>(other);
return (o && (o->m_runloop == m_runloop));
}
bool RunLoopScheduler::can_deliver_notifications() const noexcept
{
// The main thread may not be in a run loop yet if we're called from
// something like `applicationDidFinishLaunching:`, but it presumably will
// be in the future
if (pthread_main_np())
return true;
// Current mode indicates why the current callout from the runloop was made,
// and is null if a runloop callout isn't currently being processed
if (auto mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())) {
CFRelease(mode);
return true;
}
return false;
}
class DispatchQueueScheduler : public util::Scheduler {
public:
DispatchQueueScheduler(dispatch_queue_t queue);
~DispatchQueueScheduler();
void notify() override;
void set_notify_callback(std::function<void()>) override;
bool is_on_thread() const noexcept override;
bool is_same_as(const Scheduler* other) const noexcept override;
bool can_deliver_notifications() const noexcept override { return true; }
private:
dispatch_queue_t m_queue = nullptr;
void (^m_callback)() = nullptr;
};
static const void* c_queue_key = &c_queue_key;
DispatchQueueScheduler::DispatchQueueScheduler(dispatch_queue_t queue)
: m_queue(queue)
{
static auto class_dispatch_queue_serial = objc_getClass("OS_dispatch_queue_serial");
static auto class_dispatch_queue_main = objc_getClass("OS_dispatch_queue_main");
auto cls = object_getClass(reinterpret_cast<id>(queue));
if (cls != class_dispatch_queue_serial && cls != class_dispatch_queue_main) {
auto msg = util::format("Invalid queue '%1' (%2): Realms can only be confined to serial queues or the main queue.",
dispatch_queue_get_label(queue) ?: "<nil>", class_getName(cls));
throw std::logic_error(msg);
}
dispatch_retain(m_queue);
if (dispatch_queue_get_specific(m_queue, c_queue_key) == nullptr) {
dispatch_queue_set_specific(m_queue, c_queue_key, queue, nullptr);
}
}
DispatchQueueScheduler::~DispatchQueueScheduler()
{
dispatch_release(m_queue);
if (m_callback)
Block_release(m_callback);
}
void DispatchQueueScheduler::notify()
{
dispatch_async(m_queue, m_callback);
}
void DispatchQueueScheduler::set_notify_callback(std::function<void ()> callback)
{
m_callback = Block_copy(^{
callback();
});
}
bool DispatchQueueScheduler::is_on_thread() const noexcept
{
return dispatch_get_specific(c_queue_key) == m_queue;
}
bool DispatchQueueScheduler::is_same_as(const Scheduler* other) const noexcept
{
auto o = dynamic_cast<const DispatchQueueScheduler*>(other);
return (o && (o->m_queue == m_queue));
}
} // anonymous namespace
namespace realm {
namespace util {
std::shared_ptr<Scheduler> Scheduler::make_default()
{
return std::make_shared<RunLoopScheduler>();
}
std::shared_ptr<Scheduler> Scheduler::make_runloop(CFRunLoopRef run_loop)
{
return std::make_shared<RunLoopScheduler>(run_loop ?: CFRunLoopGetCurrent());
}
std::shared_ptr<Scheduler> Scheduler::make_dispatch(void* queue)
{
return std::make_shared<DispatchQueueScheduler>(static_cast<dispatch_queue_t>(queue));
}
} // namespace util
} // namespace realm
<commit_msg>Skip validating dispatch queue types on older OSes<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm 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 <realm/util/to_string.hpp>
#include <atomic>
#include <dispatch/dispatch.h>
#include <objc/runtime.h>
#include <pthread.h>
namespace {
using namespace realm;
class RunLoopScheduler : public util::Scheduler {
public:
RunLoopScheduler(CFRunLoopRef run_loop = nullptr);
~RunLoopScheduler();
void notify() override;
void set_notify_callback(std::function<void()>) override;
bool is_on_thread() const noexcept override;
bool is_same_as(const Scheduler* other) const noexcept override;
bool can_deliver_notifications() const noexcept override;
private:
CFRunLoopRef m_runloop;
CFRunLoopSourceRef m_signal = nullptr;
};
RunLoopScheduler::RunLoopScheduler(CFRunLoopRef run_loop)
: m_runloop(run_loop ?: CFRunLoopGetCurrent())
{
CFRetain(m_runloop);
}
RunLoopScheduler::~RunLoopScheduler()
{
if (m_signal) {
CFRunLoopSourceInvalidate(m_signal);
CFRelease(m_signal);
}
CFRelease(m_runloop);
}
void RunLoopScheduler::set_notify_callback(std::function<void ()> callback)
{
if (m_signal) {
CFRunLoopSourceInvalidate(m_signal);
CFRelease(m_signal);
m_signal = nullptr;
}
struct RefCountedRunloopCallback {
std::function<void()> callback;
std::atomic<size_t> ref_count;
};
CFRunLoopSourceContext ctx{};
ctx.info = new RefCountedRunloopCallback{std::move(callback), {0}};
ctx.perform = [](void* info) {
static_cast<RefCountedRunloopCallback*>(info)->callback();
};
ctx.retain = [](const void* info) {
static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info))->ref_count.fetch_add(1, std::memory_order_relaxed);
return info;
};
ctx.release = [](const void* info) {
auto ptr = static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info));
if (ptr->ref_count.fetch_add(-1, std::memory_order_acq_rel) == 1) {
delete ptr;
}
};
m_signal = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &ctx);
CFRunLoopAddSource(m_runloop, m_signal, kCFRunLoopDefaultMode);
}
void RunLoopScheduler::notify()
{
if (!m_signal)
return;
CFRunLoopSourceSignal(m_signal);
// Signalling the source makes it run the next time the runloop gets
// to it, but doesn't make the runloop start if it's currently idle
// waiting for events
CFRunLoopWakeUp(m_runloop);
}
bool RunLoopScheduler::is_on_thread() const noexcept
{
return CFRunLoopGetCurrent() == m_runloop;
}
bool RunLoopScheduler::is_same_as(const Scheduler* other) const noexcept
{
auto o = dynamic_cast<const RunLoopScheduler*>(other);
return (o && (o->m_runloop == m_runloop));
}
bool RunLoopScheduler::can_deliver_notifications() const noexcept
{
// The main thread may not be in a run loop yet if we're called from
// something like `applicationDidFinishLaunching:`, but it presumably will
// be in the future
if (pthread_main_np())
return true;
// Current mode indicates why the current callout from the runloop was made,
// and is null if a runloop callout isn't currently being processed
if (auto mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())) {
CFRelease(mode);
return true;
}
return false;
}
class DispatchQueueScheduler : public util::Scheduler {
public:
DispatchQueueScheduler(dispatch_queue_t queue);
~DispatchQueueScheduler();
void notify() override;
void set_notify_callback(std::function<void()>) override;
bool is_on_thread() const noexcept override;
bool is_same_as(const Scheduler* other) const noexcept override;
bool can_deliver_notifications() const noexcept override { return true; }
private:
dispatch_queue_t m_queue = nullptr;
void (^m_callback)() = nullptr;
};
static const void* c_queue_key = &c_queue_key;
DispatchQueueScheduler::DispatchQueueScheduler(dispatch_queue_t queue)
: m_queue(queue)
{
if (__builtin_available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0, *)) {
static auto class_dispatch_queue_serial = objc_getClass("OS_dispatch_queue_serial");
static auto class_dispatch_queue_main = objc_getClass("OS_dispatch_queue_main");
auto cls = object_getClass(reinterpret_cast<id>(queue));
if (cls != class_dispatch_queue_serial && cls != class_dispatch_queue_main) {
auto msg = util::format("Invalid queue '%1' (%2): Realms can only be confined to serial queues or the main queue.",
dispatch_queue_get_label(queue) ?: "<nil>", class_getName(cls));
throw std::logic_error(msg);
}
}
dispatch_retain(m_queue);
if (dispatch_queue_get_specific(m_queue, c_queue_key) == nullptr) {
dispatch_queue_set_specific(m_queue, c_queue_key, queue, nullptr);
}
}
DispatchQueueScheduler::~DispatchQueueScheduler()
{
dispatch_release(m_queue);
if (m_callback)
Block_release(m_callback);
}
void DispatchQueueScheduler::notify()
{
dispatch_async(m_queue, m_callback);
}
void DispatchQueueScheduler::set_notify_callback(std::function<void ()> callback)
{
m_callback = Block_copy(^{
callback();
});
}
bool DispatchQueueScheduler::is_on_thread() const noexcept
{
return dispatch_get_specific(c_queue_key) == m_queue;
}
bool DispatchQueueScheduler::is_same_as(const Scheduler* other) const noexcept
{
auto o = dynamic_cast<const DispatchQueueScheduler*>(other);
return (o && (o->m_queue == m_queue));
}
} // anonymous namespace
namespace realm {
namespace util {
std::shared_ptr<Scheduler> Scheduler::make_default()
{
return std::make_shared<RunLoopScheduler>();
}
std::shared_ptr<Scheduler> Scheduler::make_runloop(CFRunLoopRef run_loop)
{
return std::make_shared<RunLoopScheduler>(run_loop ?: CFRunLoopGetCurrent());
}
std::shared_ptr<Scheduler> Scheduler::make_dispatch(void* queue)
{
return std::make_shared<DispatchQueueScheduler>(static_cast<dispatch_queue_t>(queue));
}
} // namespace util
} // namespace realm
<|endoftext|>
|
<commit_before><commit_msg>Pipe cmd-z back to browser.<commit_after><|endoftext|>
|
<commit_before>#include "../bitmap.h"
#include "../trans-bitmap.h"
#include "scroll-list.h"
#include "../font.h"
#include <math.h>
#include "../debug.h"
namespace Gui{
static const double FONT_SPACER = 1.3;
static const int GradientMax = 50;
double SCROLL_STEP = 20;
double SCROLL_MOTION = 2;
const int SCROLL_WAIT = 4;
static int selectedGradientStart(){
static int color = Graphics::makeColor(19, 167, 168);
return color;
}
static int selectedGradientEnd(){
static int color = Graphics::makeColor(27, 237, 239);
return color;
}
ScrollItem::ScrollItem(){
}
ScrollItem::~ScrollItem(){
}
ScrollList::ScrollList():
currentIndex(0),
fontSpacingX(0),
fontSpacingY(0),
currentPosition(0),
scrollWait(0),
selectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),
useGradient(false),
useHighlight(false),
allowWrap(true),
scroll(0){}
ScrollList::ScrollList(const ScrollList & copy):
currentIndex(copy.currentIndex),
fontSpacingX(copy.fontSpacingX),
fontSpacingY(copy.fontSpacingY),
currentPosition(copy.currentPosition),
scrollWait(copy.scrollWait),
selectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),
useGradient(copy.useGradient),
useHighlight(copy.useHighlight),
allowWrap(true),
scroll(0){}
ScrollList::~ScrollList(){}
ScrollList & ScrollList::operator=(const ScrollList & copy){
return *this;
}
void ScrollList::act(){
if (scrollWait == 0){
if (scroll > SCROLL_MOTION){
scroll -= SCROLL_MOTION;
} else if (scroll < -SCROLL_MOTION){
scroll += SCROLL_MOTION;
} else {
scroll = 0;
currentPosition = currentIndex;
}
} else {
scrollWait -= 1;
}
/*
if (scrollWait > 0){
scrollWait -= 1;
} else {
currentPosition = currentIndex;
}
*/
}
/* this is the smooth scroll stuff from context-box */
void ScrollList::doDraw(int x, int y, int middle_x, int min_y, int max_y, const Font & font, int current, int selected, const Graphics::Bitmap & area, int direction){
int fadeAlpha = 255;
while (y < max_y && y > min_y){
int pick = current;
while (pick < 0){
pick += text.size();
}
pick = pick % text.size();
Util::ReferenceCount<ScrollItem> option = text[pick];
const int startx = middle_x - option->size(font) / 2;
/* draw current selection, make it glow */
if (current == selected){
Graphics::Bitmap::transBlender(0, 0, 0, fadeAlpha);
Graphics::TranslucentBitmap translucent(area);
const int color = useGradient ? selectedGradient.current() : selectedGradientStart();
option->draw(x + startx, y, color, translucent, font);
#if 0
if (option->isAdjustable()){
const int triangleSize = 14;
int cx = startx - 15;
int cy = (int)(y + (font.getHeight()/FONT_SPACER) / 2 + 2);
/* do the triangles need to be translucent? */
translucent.equilateralTriangle(cx, cy, 180, triangleSize, option->getLeftColor());
cx = (x + startx + font.textLength(option->getName().c_str()))+15;
translucent.equilateralTriangle(cx, cy, 0, triangleSize, option->getRightColor());
}
#endif
} else {
/* draw some other item, and fade it */
int count = (int) fabs((double) current - (double) selected);
/* TODO: maybe scale by the number of total items instead of using 35 */
int textAlpha = fadeAlpha - (count * 35);
if (textAlpha < 0){
textAlpha = 0;
}
Graphics::Bitmap::transBlender(0, 0, 0, textAlpha);
const int color = Graphics::makeColor(255,255,255);
option->draw(x + startx, y, color, area.translucent(), font);
// font.printf(x + startx, y, color, area.translucent(), option->getName(), 0);
}
if (text.size() == 1){
return;
}
current += direction;
y += direction * font.getHeight() / FONT_SPACER;
}
}
void ScrollList::render(const Graphics::Bitmap & where, const Font & font){
SCROLL_STEP = font.getHeight() / 2;
SCROLL_MOTION = SCROLL_STEP / 8;
// Global::debug(0) << "Scroll is " << scroll << std::endl;
int y = where.getHeight() / 2 + scroll - font.getHeight() / 2;
int min_y = 0 - font.getHeight() / FONT_SPACER;
int max_y = where.getHeight();
doDraw(0, y, where.getWidth() / 2, min_y, max_y, font, currentIndex, currentIndex, where, 1);
/* draw above the current selection */
doDraw(0, y - font.getHeight() / FONT_SPACER, where.getWidth() / 2, min_y, max_y, font, currentIndex - 1, currentIndex, where, -1);
/*
int y = 0;
int x = 5;
int current = currentIndex;
while (y < where.getHeight()){
Util::ReferenceCount<ScrollItem> & item = this->text[current];
if (current == currentIndex){
Graphics::Bitmap::transBlender(0, 0, 0, 255);
} else {
Graphics::Bitmap::transBlender(0, 0, 0, 128);
}
item->draw(x, y, where.translucent(), font);
y += font.getHeight();
current = (current + 1 + this->text.size()) % this->text.size();
}
*/
}
void ScrollList::addItem(const Util::ReferenceCount<ScrollItem> & text){
this->text.push_back(text);
}
void ScrollList::addItems(const std::vector<Util::ReferenceCount<ScrollItem> > & texts){
this->text.insert(text.end(), texts.begin(), texts.end());
}
void ScrollList::setPosition(const Gui::Coordinate & location){
this->position = location;
}
bool ScrollList::next(){
currentIndex++;
scroll = SCROLL_STEP;
if (scrollWait == 0){
scrollWait = SCROLL_WAIT;
}
if (currentIndex >= text.size()){
if (allowWrap){
currentIndex = 0;
return true;
} else {
currentIndex = text.size()-1;
return false;
}
}
return true;
}
bool ScrollList::previous(){
scroll = -SCROLL_STEP;
if (scrollWait == 0){
scrollWait = SCROLL_WAIT;
}
if (currentIndex > 0){
currentIndex--;
} else if (currentIndex == 0){
if (allowWrap){
currentIndex = text.size()-1;
return true;
} else {
return false;
}
}
return true;
}
bool ScrollList::setCurrentIndex(unsigned int index){
if (index >= text.size()){
return false;
}
currentIndex = index;
return true;
}
}
<commit_msg>[gui] smoother scrolling<commit_after>#include "../bitmap.h"
#include "../trans-bitmap.h"
#include "scroll-list.h"
#include "../font.h"
#include <math.h>
#include "../debug.h"
namespace Gui{
static const double FONT_SPACER = 1.3;
static const int GradientMax = 50;
double SCROLL_STEP = 20;
const double SCROLL_MOTION = 1.2;
const int SCROLL_WAIT = 4;
static int selectedGradientStart(){
static int color = Graphics::makeColor(19, 167, 168);
return color;
}
static int selectedGradientEnd(){
static int color = Graphics::makeColor(27, 237, 239);
return color;
}
ScrollItem::ScrollItem(){
}
ScrollItem::~ScrollItem(){
}
ScrollList::ScrollList():
currentIndex(0),
fontSpacingX(0),
fontSpacingY(0),
currentPosition(0),
scrollWait(0),
selectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),
useGradient(false),
useHighlight(false),
allowWrap(true),
scroll(0){}
ScrollList::ScrollList(const ScrollList & copy):
currentIndex(copy.currentIndex),
fontSpacingX(copy.fontSpacingX),
fontSpacingY(copy.fontSpacingY),
currentPosition(copy.currentPosition),
scrollWait(copy.scrollWait),
selectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),
useGradient(copy.useGradient),
useHighlight(copy.useHighlight),
allowWrap(true),
scroll(0){}
ScrollList::~ScrollList(){}
ScrollList & ScrollList::operator=(const ScrollList & copy){
return *this;
}
void ScrollList::act(){
if (scrollWait == 0){
if (scroll > SCROLL_MOTION){
// scroll -= SCROLL_MOTION;
scroll /= SCROLL_MOTION;
} else if (scroll < -SCROLL_MOTION){
// scroll += SCROLL_MOTION;
scroll /= SCROLL_MOTION;
} else {
scroll = 0;
currentPosition = currentIndex;
}
} else {
scrollWait -= 1;
}
/*
if (scrollWait > 0){
scrollWait -= 1;
} else {
currentPosition = currentIndex;
}
*/
}
/* this is the smooth scroll stuff from context-box */
void ScrollList::doDraw(int x, int y, int middle_x, int min_y, int max_y, const Font & font, int current, int selected, const Graphics::Bitmap & area, int direction){
int fadeAlpha = 255;
while (y < max_y && y > min_y){
int pick = current;
while (pick < 0){
pick += text.size();
}
pick = pick % text.size();
Util::ReferenceCount<ScrollItem> option = text[pick];
const int startx = middle_x - option->size(font) / 2;
/* draw current selection, make it glow */
if (current == selected){
Graphics::Bitmap::transBlender(0, 0, 0, fadeAlpha);
Graphics::TranslucentBitmap translucent(area);
const int color = useGradient ? selectedGradient.current() : selectedGradientStart();
option->draw(x + startx, y, color, translucent, font);
#if 0
if (option->isAdjustable()){
const int triangleSize = 14;
int cx = startx - 15;
int cy = (int)(y + (font.getHeight()/FONT_SPACER) / 2 + 2);
/* do the triangles need to be translucent? */
translucent.equilateralTriangle(cx, cy, 180, triangleSize, option->getLeftColor());
cx = (x + startx + font.textLength(option->getName().c_str()))+15;
translucent.equilateralTriangle(cx, cy, 0, triangleSize, option->getRightColor());
}
#endif
} else {
/* draw some other item, and fade it */
int count = (int) fabs((double) current - (double) selected);
/* TODO: maybe scale by the number of total items instead of using 35 */
int textAlpha = fadeAlpha - (count * 35);
if (textAlpha < 0){
textAlpha = 0;
}
Graphics::Bitmap::transBlender(0, 0, 0, textAlpha);
const int color = Graphics::makeColor(255,255,255);
option->draw(x + startx, y, color, area.translucent(), font);
// font.printf(x + startx, y, color, area.translucent(), option->getName(), 0);
}
if (text.size() == 1){
return;
}
current += direction;
y += direction * font.getHeight() / FONT_SPACER;
}
}
void ScrollList::render(const Graphics::Bitmap & where, const Font & font){
SCROLL_STEP = font.getHeight() / 2;
// SCROLL_MOTION = SCROLL_STEP / 8;
// Global::debug(0) << "Scroll is " << scroll << std::endl;
int y = where.getHeight() / 2 + scroll - font.getHeight() / 2;
int min_y = 0 - font.getHeight() / FONT_SPACER;
int max_y = where.getHeight();
doDraw(0, y, where.getWidth() / 2, min_y, max_y, font, currentIndex, currentIndex, where, 1);
/* draw above the current selection */
doDraw(0, y - font.getHeight() / FONT_SPACER, where.getWidth() / 2, min_y, max_y, font, currentIndex - 1, currentIndex, where, -1);
/*
int y = 0;
int x = 5;
int current = currentIndex;
while (y < where.getHeight()){
Util::ReferenceCount<ScrollItem> & item = this->text[current];
if (current == currentIndex){
Graphics::Bitmap::transBlender(0, 0, 0, 255);
} else {
Graphics::Bitmap::transBlender(0, 0, 0, 128);
}
item->draw(x, y, where.translucent(), font);
y += font.getHeight();
current = (current + 1 + this->text.size()) % this->text.size();
}
*/
}
void ScrollList::addItem(const Util::ReferenceCount<ScrollItem> & text){
this->text.push_back(text);
}
void ScrollList::addItems(const std::vector<Util::ReferenceCount<ScrollItem> > & texts){
this->text.insert(text.end(), texts.begin(), texts.end());
}
void ScrollList::setPosition(const Gui::Coordinate & location){
this->position = location;
}
bool ScrollList::next(){
currentIndex++;
scroll = SCROLL_STEP;
if (scrollWait == 0){
scrollWait = SCROLL_WAIT;
}
if (currentIndex >= text.size()){
if (allowWrap){
currentIndex = 0;
return true;
} else {
currentIndex = text.size()-1;
return false;
}
}
return true;
}
bool ScrollList::previous(){
scroll = -SCROLL_STEP;
if (scrollWait == 0){
scrollWait = SCROLL_WAIT;
}
if (currentIndex > 0){
currentIndex--;
} else if (currentIndex == 0){
if (allowWrap){
currentIndex = text.size()-1;
return true;
} else {
return false;
}
}
return true;
}
bool ScrollList::setCurrentIndex(unsigned int index){
if (index >= text.size()){
return false;
}
currentIndex = index;
return true;
}
}
<|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:
*
* * 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 Google Inc. 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.
*/
#include "config.h"
#include "LocalizedStrings.h"
#include "IntSize.h"
#include "NotImplemented.h"
#include "PlatformString.h"
#include "StringBuilder.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebLocalizedString.h"
#include "WebString.h"
using WebKit::WebLocalizedString;
namespace WebCore {
static String query(WebLocalizedString::Name name)
{
return WebKit::webKitClient()->queryLocalizedString(name);
}
static String query(WebLocalizedString::Name name, int numericValue)
{
return WebKit::webKitClient()->queryLocalizedString(name, numericValue);
}
String searchableIndexIntroduction()
{
return query(WebLocalizedString::SearchableIndexIntroduction);
}
String submitButtonDefaultLabel()
{
return query(WebLocalizedString::SubmitButtonDefaultLabel);
}
String inputElementAltText()
{
return query(WebLocalizedString::InputElementAltText);
}
String resetButtonDefaultLabel()
{
return query(WebLocalizedString::ResetButtonDefaultLabel);
}
String fileButtonChooseFileLabel()
{
return query(WebLocalizedString::FileButtonChooseFileLabel);
}
String fileButtonNoFileSelectedLabel()
{
return query(WebLocalizedString::FileButtonNoFileSelectedLabel);
}
String searchMenuNoRecentSearchesText()
{
return query(WebLocalizedString::SearchMenuNoRecentSearchesText);
}
String searchMenuRecentSearchesText()
{
return query(WebLocalizedString::SearchMenuRecentSearchesText);
}
String searchMenuClearRecentSearchesText()
{
return query(WebLocalizedString::SearchMenuClearRecentSearchesText);
}
String AXWebAreaText()
{
return query(WebLocalizedString::AXWebAreaText);
}
String AXLinkText()
{
return query(WebLocalizedString::AXLinkText);
}
String AXListMarkerText()
{
return query(WebLocalizedString::AXListMarkerText);
}
String AXImageMapText()
{
return query(WebLocalizedString::AXImageMapText);
}
String AXHeadingText()
{
return query(WebLocalizedString::AXHeadingText);
}
String AXDefinitionListTermText()
{
notImplemented();
return String("term");
}
String AXDefinitionListDefinitionText()
{
notImplemented();
return String("definition");
}
String AXButtonActionVerb()
{
return query(WebLocalizedString::AXButtonActionVerb);
}
String AXRadioButtonActionVerb()
{
return query(WebLocalizedString::AXRadioButtonActionVerb);
}
String AXTextFieldActionVerb()
{
return query(WebLocalizedString::AXTextFieldActionVerb);
}
String AXCheckedCheckBoxActionVerb()
{
return query(WebLocalizedString::AXCheckedCheckBoxActionVerb);
}
String AXUncheckedCheckBoxActionVerb()
{
return query(WebLocalizedString::AXUncheckedCheckBoxActionVerb);
}
String AXLinkActionVerb()
{
return query(WebLocalizedString::AXLinkActionVerb);
}
String multipleFileUploadText(unsigned numberOfFiles)
{
return query(WebLocalizedString::MultipleFileUploadText, numberOfFiles);
}
// Used in FTPDirectoryDocument.cpp
String unknownFileSizeText()
{
return String();
}
// The following two functions are not declared in LocalizedStrings.h.
// They are used by the menu for the HTML keygen tag.
String keygenMenuHighGradeKeySize()
{
return query(WebLocalizedString::KeygenMenuHighGradeKeySize);
}
String keygenMenuMediumGradeKeySize()
{
return query(WebLocalizedString::KeygenMenuMediumGradeKeySize);
}
// Used in ImageDocument.cpp as the title for pages when that page is an image.
String imageTitle(const String& filename, const IntSize& size)
{
// Note that we cannot use String::format because it works for ASCII only.
StringBuilder result;
result.append(filename);
result.append(" (");
result.append(String::number(size.width()));
result.append(static_cast<UChar>(0xD7)); // U+00D7 (multiplication sign)
result.append(String::number(size.height()));
result.append(")");
return result.toString();
}
// We don't use these strings, so they return an empty String. We can't just
// make them asserts because webcore still calls them.
String contextMenuItemTagOpenLinkInNewWindow() { return String(); }
String contextMenuItemTagDownloadLinkToDisk() { return String(); }
String contextMenuItemTagCopyLinkToClipboard() { return String(); }
String contextMenuItemTagOpenImageInNewWindow() { return String(); }
String contextMenuItemTagDownloadImageToDisk() { return String(); }
String contextMenuItemTagCopyImageToClipboard() { return String(); }
String contextMenuItemTagOpenFrameInNewWindow() { return String(); }
String contextMenuItemTagCopy() { return String(); }
String contextMenuItemTagGoBack() { return String(); }
String contextMenuItemTagGoForward() { return String(); }
String contextMenuItemTagStop() { return String(); }
String contextMenuItemTagReload() { return String(); }
String contextMenuItemTagCut() { return String(); }
String contextMenuItemTagPaste() { return String(); }
String contextMenuItemTagNoGuessesFound() { return String(); }
String contextMenuItemTagIgnoreSpelling() { return String(); }
String contextMenuItemTagLearnSpelling() { return String(); }
String contextMenuItemTagSearchWeb() { return String(); }
String contextMenuItemTagLookUpInDictionary() { return String(); }
String contextMenuItemTagOpenLink() { return String(); }
String contextMenuItemTagIgnoreGrammar() { return String(); }
String contextMenuItemTagSpellingMenu() { return String(); }
String contextMenuItemTagCheckSpelling() { return String(); }
String contextMenuItemTagCheckSpellingWhileTyping() { return String(); }
String contextMenuItemTagCheckGrammarWithSpelling() { return String(); }
String contextMenuItemTagFontMenu() { return String(); }
String contextMenuItemTagBold() { return String(); }
String contextMenuItemTagItalic() { return String(); }
String contextMenuItemTagUnderline() { return String(); }
String contextMenuItemTagOutline() { return String(); }
String contextMenuItemTagWritingDirectionMenu() { return String(); }
String contextMenuItemTagTextDirectionMenu() { return String(); }
String contextMenuItemTagDefaultDirection() { return String(); }
String contextMenuItemTagLeftToRight() { return String(); }
String contextMenuItemTagRightToLeft() { return String(); }
String contextMenuItemTagInspectElement() { return String(); }
String contextMenuItemTagShowSpellingPanel(bool show) { return String(); }
String mediaElementLiveBroadcastStateText() { return String(); }
String mediaElementLoadingStateText() { return String(); }
} // namespace WebCore
<commit_msg>Add dummy implementation for newly added localized string in WebKit. This is to fix compiling errors in incoming WebKit merge.<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:
*
* * 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 Google Inc. 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.
*/
#include "config.h"
#include "LocalizedStrings.h"
#include "IntSize.h"
#include "NotImplemented.h"
#include "PlatformString.h"
#include "StringBuilder.h"
#include "WebKit.h"
#include "WebKitClient.h"
#include "WebLocalizedString.h"
#include "WebString.h"
using WebKit::WebLocalizedString;
namespace WebCore {
static String query(WebLocalizedString::Name name)
{
return WebKit::webKitClient()->queryLocalizedString(name);
}
static String query(WebLocalizedString::Name name, int numericValue)
{
return WebKit::webKitClient()->queryLocalizedString(name, numericValue);
}
String searchableIndexIntroduction()
{
return query(WebLocalizedString::SearchableIndexIntroduction);
}
String submitButtonDefaultLabel()
{
return query(WebLocalizedString::SubmitButtonDefaultLabel);
}
String inputElementAltText()
{
return query(WebLocalizedString::InputElementAltText);
}
String resetButtonDefaultLabel()
{
return query(WebLocalizedString::ResetButtonDefaultLabel);
}
String fileButtonChooseFileLabel()
{
return query(WebLocalizedString::FileButtonChooseFileLabel);
}
String fileButtonNoFileSelectedLabel()
{
return query(WebLocalizedString::FileButtonNoFileSelectedLabel);
}
String searchMenuNoRecentSearchesText()
{
return query(WebLocalizedString::SearchMenuNoRecentSearchesText);
}
String searchMenuRecentSearchesText()
{
return query(WebLocalizedString::SearchMenuRecentSearchesText);
}
String searchMenuClearRecentSearchesText()
{
return query(WebLocalizedString::SearchMenuClearRecentSearchesText);
}
String AXWebAreaText()
{
return query(WebLocalizedString::AXWebAreaText);
}
String AXLinkText()
{
return query(WebLocalizedString::AXLinkText);
}
String AXListMarkerText()
{
return query(WebLocalizedString::AXListMarkerText);
}
String AXImageMapText()
{
return query(WebLocalizedString::AXImageMapText);
}
String AXHeadingText()
{
return query(WebLocalizedString::AXHeadingText);
}
String AXDefinitionListTermText()
{
notImplemented();
return String("term");
}
String AXDefinitionListDefinitionText()
{
notImplemented();
return String("definition");
}
String AXButtonActionVerb()
{
return query(WebLocalizedString::AXButtonActionVerb);
}
String AXRadioButtonActionVerb()
{
return query(WebLocalizedString::AXRadioButtonActionVerb);
}
String AXTextFieldActionVerb()
{
return query(WebLocalizedString::AXTextFieldActionVerb);
}
String AXCheckedCheckBoxActionVerb()
{
return query(WebLocalizedString::AXCheckedCheckBoxActionVerb);
}
String AXUncheckedCheckBoxActionVerb()
{
return query(WebLocalizedString::AXUncheckedCheckBoxActionVerb);
}
String AXLinkActionVerb()
{
return query(WebLocalizedString::AXLinkActionVerb);
}
String multipleFileUploadText(unsigned numberOfFiles)
{
return query(WebLocalizedString::MultipleFileUploadText, numberOfFiles);
}
// Used in FTPDirectoryDocument.cpp
String unknownFileSizeText()
{
return String();
}
// The following two functions are not declared in LocalizedStrings.h.
// They are used by the menu for the HTML keygen tag.
String keygenMenuHighGradeKeySize()
{
return query(WebLocalizedString::KeygenMenuHighGradeKeySize);
}
String keygenMenuMediumGradeKeySize()
{
return query(WebLocalizedString::KeygenMenuMediumGradeKeySize);
}
// Used in ImageDocument.cpp as the title for pages when that page is an image.
String imageTitle(const String& filename, const IntSize& size)
{
// Note that we cannot use String::format because it works for ASCII only.
StringBuilder result;
result.append(filename);
result.append(" (");
result.append(String::number(size.width()));
result.append(static_cast<UChar>(0xD7)); // U+00D7 (multiplication sign)
result.append(String::number(size.height()));
result.append(")");
return result.toString();
}
// We don't use these strings, so they return an empty String. We can't just
// make them asserts because webcore still calls them.
String contextMenuItemTagOpenLinkInNewWindow() { return String(); }
String contextMenuItemTagDownloadLinkToDisk() { return String(); }
String contextMenuItemTagCopyLinkToClipboard() { return String(); }
String contextMenuItemTagOpenImageInNewWindow() { return String(); }
String contextMenuItemTagDownloadImageToDisk() { return String(); }
String contextMenuItemTagCopyImageToClipboard() { return String(); }
String contextMenuItemTagOpenFrameInNewWindow() { return String(); }
String contextMenuItemTagCopy() { return String(); }
String contextMenuItemTagGoBack() { return String(); }
String contextMenuItemTagGoForward() { return String(); }
String contextMenuItemTagStop() { return String(); }
String contextMenuItemTagReload() { return String(); }
String contextMenuItemTagCut() { return String(); }
String contextMenuItemTagPaste() { return String(); }
String contextMenuItemTagNoGuessesFound() { return String(); }
String contextMenuItemTagIgnoreSpelling() { return String(); }
String contextMenuItemTagLearnSpelling() { return String(); }
String contextMenuItemTagSearchWeb() { return String(); }
String contextMenuItemTagLookUpInDictionary() { return String(); }
String contextMenuItemTagOpenLink() { return String(); }
String contextMenuItemTagIgnoreGrammar() { return String(); }
String contextMenuItemTagSpellingMenu() { return String(); }
String contextMenuItemTagCheckSpelling() { return String(); }
String contextMenuItemTagCheckSpellingWhileTyping() { return String(); }
String contextMenuItemTagCheckGrammarWithSpelling() { return String(); }
String contextMenuItemTagFontMenu() { return String(); }
String contextMenuItemTagBold() { return String(); }
String contextMenuItemTagItalic() { return String(); }
String contextMenuItemTagUnderline() { return String(); }
String contextMenuItemTagOutline() { return String(); }
String contextMenuItemTagWritingDirectionMenu() { return String(); }
String contextMenuItemTagTextDirectionMenu() { return String(); }
String contextMenuItemTagDefaultDirection() { return String(); }
String contextMenuItemTagLeftToRight() { return String(); }
String contextMenuItemTagRightToLeft() { return String(); }
String contextMenuItemTagInspectElement() { return String(); }
String contextMenuItemTagShowSpellingPanel(bool show) { return String(); }
String mediaElementLiveBroadcastStateText() { return String(); }
String mediaElementLoadingStateText() { return String(); }
String localizedMediaControlElementString(const String& /*name*/)
{
// FIXME: to be fixed.
return String();
}
String localizedMediaControlElementHelpText(const String& /*name*/)
{
// FIXME: to be fixed.
return String();
}
String localizedMediaTimeDescription(float /*time*/)
{
// FIXME: to be fixed.
return String();
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "webkit/tools/test_shell/test_shell_test.h"
namespace {
class BookmarkletTest : public TestShellTest {
public:
virtual void SetUp() {
TestShellTest::SetUp();
test_shell_->LoadURL(L"data:text/html,start page");
test_shell_->WaitTestFinished();
}
};
}
TEST_F(BookmarkletTest, Redirect) {
test_shell_->LoadURL(L"javascript:location.href='data:text/plain,SUCCESS'");
test_shell_->WaitTestFinished();
std::wstring text = test_shell_->GetDocumentText();
EXPECT_EQ(L"SUCCESS", text);
}
TEST_F(BookmarkletTest, NonEmptyResult) {
test_shell_->LoadURL(L"javascript:false");
MessageLoop::current()->RunAllPending();
std::wstring text = test_shell_->GetDocumentText();
EXPECT_EQ(L"false", text);
test_shell_->LoadURL(L"javascript:'hello world'");
MessageLoop::current()->RunAllPending();
text = test_shell_->GetDocumentText();
EXPECT_EQ(L"hello world", text);
}
TEST_F(BookmarkletTest, DocumentWrite) {
test_shell_->LoadURL(
L"javascript:document.open();"
L"document.write('hello world');"
L"document.close()");
MessageLoop::current()->RunAllPending();
std::wstring text = test_shell_->GetDocumentText();
EXPECT_EQ(L"hello world", text);
}
<commit_msg>Disable this bookmarklet test since it covers functionality that JSC doesn't support.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "webkit/tools/test_shell/test_shell_test.h"
namespace {
class BookmarkletTest : public TestShellTest {
public:
virtual void SetUp() {
TestShellTest::SetUp();
test_shell_->LoadURL(L"data:text/html,start page");
test_shell_->WaitTestFinished();
}
};
}
TEST_F(BookmarkletTest, Redirect) {
test_shell_->LoadURL(L"javascript:location.href='data:text/plain,SUCCESS'");
test_shell_->WaitTestFinished();
std::wstring text = test_shell_->GetDocumentText();
EXPECT_EQ(L"SUCCESS", text);
}
TEST_F(BookmarkletTest, NonEmptyResult) {
std::wstring text;
// TODO(darin): This test fails in a JSC build. WebCore+JSC does not really
// need to support this usage until WebCore supports javascript: URLs that
// generate content (https://bugs.webkit.org/show_bug.cgi?id=14959). It is
// important to note that Safari does not support bookmarklets, and this is
// really an edge case. Our behavior with V8 is consistent with FF and IE.
#if 0
test_shell_->LoadURL(L"javascript:false");
MessageLoop::current()->RunAllPending();
text = test_shell_->GetDocumentText();
EXPECT_EQ(L"false", text);
#endif
test_shell_->LoadURL(L"javascript:'hello world'");
MessageLoop::current()->RunAllPending();
text = test_shell_->GetDocumentText();
EXPECT_EQ(L"hello world", text);
}
TEST_F(BookmarkletTest, DocumentWrite) {
test_shell_->LoadURL(
L"javascript:document.open();"
L"document.write('hello world');"
L"document.close()");
MessageLoop::current()->RunAllPending();
std::wstring text = test_shell_->GetDocumentText();
EXPECT_EQ(L"hello world", text);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Jules Cléro
*
* 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.
*
*/
extern "C"
{
/** LibLineFollowing */
#include "SystemDrone.h"
}
#include <libDroneMovement/Drone.hpp>
#include <libDroneVideo/FrameGrabber.hpp>
#include <libDroneVideo/LineDetector.hpp>
#include <chrono>
#include <thread>
int main(void)
{
using namespace ghost::libDroneMovement;
using namespace ghost::libDroneVideo;
Drone drone("127.0.0.1");
FrameGrabber frameGrabber = FrameGrabber();
// Auto Pilot initialization
inC_SystemDrone inputAutoPilot;
outC_SystemDrone outputAutoPilot;
SystemDrone_init(&outputAutoPilot);
drone.takeOff();
// Drop Frames
frameGrabber.getNextVerticalFrame(),
std::this_thread::sleep_for(std::chrono::milliseconds(500));
double lineAngle = 0.0;
bool needImageUpdate = true;
for (size_t i = 0; i < 1000; i++) {
if (i % 10 == 0) {
needImageUpdate = true;
}
if (needImageUpdate) {
// Frame Analysis
std::cout << "Update Image: " << std::endl;
LineDetector<FrameGrabber::DroneVerticalFrame> lineDetector(
frameGrabber.getNextVerticalFrame(),
320,
240);
lineAngle = lineDetector.getLineAngle();
if (std::isnan(lineAngle)) {
// we don't see the line, let's assume we are good for now
lineAngle = 0.0;
}
inputAutoPilot.LineAngle = lineAngle;
inputAutoPilot.RightWay = true;
inputAutoPilot.GoLeft = false;
inputAutoPilot.GoRight = false;
inputAutoPilot.ImageUpdate = needImageUpdate;
needImageUpdate = false;
} else {
inputAutoPilot.ImageUpdate = needImageUpdate;
}
float currentAngle = drone.getPsiAngle() / 1000.0;
inputAutoPilot.currentAngle = currentAngle;
std::cout << "Angle Ligne: " << lineAngle << std::endl;
std::cout << "Angle Drone: " << currentAngle << std::endl;
std::cout << "Yaw speed Drone: " << outputAutoPilot.Yaw << std::endl;
SystemDrone(&inputAutoPilot, &outputAutoPilot);
drone.movement(
outputAutoPilot.Roll,
outputAutoPilot.Pitch,
outputAutoPilot.Gaz,
outputAutoPilot.Yaw);
std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
drone.land();
return 0;
}
<commit_msg>[Core] Add support of the emergency mode of LibLineFollowing library<commit_after>/*
* Copyright 2014 Jules Cléro
*
* 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.
*
*/
extern "C"
{
/** LibLineFollowing */
#include "SystemDrone.h"
}
#include <libDroneMovement/Drone.hpp>
#include <libDroneVideo/FrameGrabber.hpp>
#include <libDroneVideo/LineDetector.hpp>
#include <chrono>
#include <thread>
int main(void)
{
using namespace ghost::libDroneMovement;
using namespace ghost::libDroneVideo;
Drone drone("127.0.0.1");
FrameGrabber frameGrabber = FrameGrabber();
// Auto Pilot initialization
inC_SystemDrone inputAutoPilot;
outC_SystemDrone outputAutoPilot;
SystemDrone_init(&outputAutoPilot);
drone.takeOff();
// Drop Frames
frameGrabber.getNextVerticalFrame(),
std::this_thread::sleep_for(std::chrono::milliseconds(500));
double lineAngle = 0.0;
bool needToGoLeft = false;
bool needToGoRight = false;
bool needImageUpdate = true;
bool lineDetected = true;
int count = 0;
for (size_t i = 0; i < 1000; i++) {
if (i % 10 == 0) {
needImageUpdate = true;
}
if (needImageUpdate) {
// Frame Analysis
std::cout << "Update Image: " << std::endl;
LineDetector<FrameGrabber::DroneVerticalFrame> lineDetector(
frameGrabber.getNextVerticalFrame(),
320,
240);
lineDetected = true;
lineAngle = lineDetector.getLineAngle();
needToGoRight = lineDetector.needToGoRight();
needToGoLeft = lineDetector.needToGoLeft();
if (std::isnan(lineAngle)) {
// we don't see the line, let's assume we are good for now
lineAngle = 0.0;
count++;
} else {
lineDetected = true;
count = 0;
}
if (count >= 5) {
lineDetected = false;
}
inputAutoPilot.LineAngle = lineAngle;
inputAutoPilot.RightWay = true;
inputAutoPilot.GoLeft = needToGoLeft;
inputAutoPilot.GoRight = needToGoRight;
inputAutoPilot.ImageUpdate = needImageUpdate;
inputAutoPilot.LineDetected = lineDetected;
needImageUpdate = false;
} else {
inputAutoPilot.ImageUpdate = needImageUpdate;
}
float currentAngle = drone.getPsiAngle() / 1000.0;
inputAutoPilot.currentAngle = currentAngle;
std::cout << "Angle Ligne: " << lineAngle << std::endl;
std::cout << "Angle Drone: " << currentAngle << std::endl;
std::cout << "Yaw speed Drone: " << outputAutoPilot.Yaw << std::endl;
SystemDrone(&inputAutoPilot, &outputAutoPilot);
drone.movement(
outputAutoPilot.Roll,
outputAutoPilot.Pitch,
outputAutoPilot.Gaz,
outputAutoPilot.Yaw);
std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
drone.land();
return 0;
}
<|endoftext|>
|
<commit_before>#include "BufferUtilsPvp.hpp"
#include "utils/conversions.h"
namespace PV {
namespace BufferUtils {
WeightHeader buildWeightHeader(
bool shared,
int preLayerNx,
int preLayerNy,
int preLayerNf,
int preLayerNxExt,
int preLayerNyExt,
int numArbors,
double timestamp,
int nxp,
int nyp,
int nfp,
bool compress,
float minVal,
float maxVal) {
WeightHeader weightHeader;
ActivityHeader &baseHeader = weightHeader.baseHeader;
baseHeader.headerSize = (int)sizeof(weightHeader);
baseHeader.numParams = baseHeader.headerSize / 4;
pvAssert(baseHeader.numParams * 4 == baseHeader.headerSize);
baseHeader.fileType = shared ? PVP_KERNEL_FILE_TYPE : PVP_WGT_FILE_TYPE;
baseHeader.nx = preLayerNx;
baseHeader.ny = preLayerNy;
baseHeader.nf = preLayerNf;
baseHeader.numRecords = numArbors;
baseHeader.recordSize = 0;
int numPatches = preLayerNxExt * preLayerNyExt * preLayerNf;
int numPatchItems = nxp * nyp * nfp;
baseHeader.recordSize = numPatches * weightPatchSize(numPatchItems, compress);
if (compress) {
baseHeader.dataSize = (int)sizeof(unsigned char);
baseHeader.dataType = returnDataType<unsigned char>();
}
else {
baseHeader.dataSize = (int)sizeof(float);
baseHeader.dataType = returnDataType<float>();
}
baseHeader.nxProcs = 1;
baseHeader.nyProcs = 1;
baseHeader.nxExtended = preLayerNxExt;
baseHeader.nyExtended = preLayerNyExt;
baseHeader.kx0 = 0;
baseHeader.ky0 = 0;
baseHeader.nBatch = 1;
baseHeader.nBands = numArbors;
baseHeader.timestamp = timestamp;
weightHeader.nxp = nxp;
weightHeader.nyp = nyp;
weightHeader.nfp = nfp;
weightHeader.minVal = minVal;
weightHeader.maxVal = maxVal;
weightHeader.numPatches = numPatches;
return weightHeader;
}
WeightHeader buildSharedWeightHeader(
int nxp,
int nyp,
int nfp,
int numArbors,
int numPatchesX,
int numPatchesY,
int numPatchesF,
double timestamp,
bool compress,
float minVal,
float maxVal) {
WeightHeader weightHeader = buildWeightHeader(
true /* shared weights*/,
numPatchesX,
numPatchesY,
numPatchesF,
numPatchesX,
numPatchesY,
numArbors,
timestamp,
nxp,
nyp,
nfp,
compress,
minVal,
maxVal);
return weightHeader;
}
WeightHeader buildNonsharedWeightHeader(
int nxp,
int nyp,
int nfp,
int numArbors,
bool extended,
double timestamp,
PVLayerLoc const *preLayerLoc,
PVLayerLoc const *postLayerLoc,
int numColumnProcesses,
int numRowProcesses,
float minVal,
float maxVal,
bool compress) {
int numPatchesX, numPatchesY, numPatchesF, numPatchesXExt, numPatchesYExt;
calcNumberOfPatches(
preLayerLoc,
postLayerLoc,
numColumnProcesses,
numRowProcesses,
extended,
nxp,
nyp,
numPatchesX,
numPatchesY,
numPatchesF,
numPatchesXExt,
numPatchesYExt);
WeightHeader weightHeader = buildWeightHeader(
false /*non-shared weights*/,
numPatchesX,
numPatchesY,
numPatchesF,
numPatchesXExt,
numPatchesYExt,
numArbors,
timestamp,
nxp,
nyp,
nfp,
compress,
minVal,
maxVal);
return weightHeader;
}
std::size_t weightPatchSize(int numWeightsInPatch, bool compressed) {
if (compressed) {
return weightPatchSize<unsigned char>(numWeightsInPatch);
}
else {
return weightPatchSize<float>(numWeightsInPatch);
}
}
void calcNumberOfPatches(
PVLayerLoc const *preLayerLoc,
PVLayerLoc const *postLayerLoc,
int numColumnProcesses,
int numRowProcesses,
bool extended,
int nxp,
int nyp,
int &numPatchesX,
int &numPatchesY,
int &numPatchesF,
int &numPatchesXExt,
int &numPatchesYExt) {
int nxPreRestricted = preLayerLoc->nx * numColumnProcesses;
int nyPreRestricted = preLayerLoc->ny * numRowProcesses;
numPatchesX = preLayerLoc->nx * numColumnProcesses;
numPatchesY = preLayerLoc->ny * numRowProcesses;
numPatchesXExt = numPatchesX;
numPatchesYExt = numPatchesY;
if (extended) {
int marginX = requiredConvolveMargin(preLayerLoc->nx, postLayerLoc->nx, nxp);
numPatchesXExt += marginX + marginX;
int marginY = requiredConvolveMargin(preLayerLoc->ny, postLayerLoc->ny, nyp);
numPatchesYExt += marginY + marginY;
}
numPatchesF = preLayerLoc->nf;
}
} // end namespace BufferUtils
} // end namespace PV
<commit_msg>Fixes recordsize from imperfect merge<commit_after>#include "BufferUtilsPvp.hpp"
#include "utils/conversions.h"
namespace PV {
namespace BufferUtils {
WeightHeader buildWeightHeader(
bool shared,
int preLayerNx,
int preLayerNy,
int preLayerNf,
int preLayerNxExt,
int preLayerNyExt,
int numArbors,
double timestamp,
int nxp,
int nyp,
int nfp,
bool compress,
float minVal,
float maxVal) {
WeightHeader weightHeader;
ActivityHeader &baseHeader = weightHeader.baseHeader;
baseHeader.headerSize = (int)sizeof(weightHeader);
baseHeader.numParams = baseHeader.headerSize / 4;
pvAssert(baseHeader.numParams * 4 == baseHeader.headerSize);
baseHeader.fileType = shared ? PVP_KERNEL_FILE_TYPE : PVP_WGT_FILE_TYPE;
baseHeader.nx = preLayerNx;
baseHeader.ny = preLayerNy;
baseHeader.nf = preLayerNf;
baseHeader.numRecords = numArbors;
baseHeader.recordSize = 0;
int numPatches = preLayerNxExt * preLayerNyExt * preLayerNf;
int numPatchItems = nxp * nyp * nfp;
if (compress) {
baseHeader.dataSize = (int)sizeof(unsigned char);
baseHeader.dataType = returnDataType<unsigned char>();
}
else {
baseHeader.dataSize = (int)sizeof(float);
baseHeader.dataType = returnDataType<float>();
}
baseHeader.nxProcs = 1;
baseHeader.nyProcs = 1;
baseHeader.nxExtended = preLayerNxExt;
baseHeader.nyExtended = preLayerNyExt;
baseHeader.kx0 = 0;
baseHeader.ky0 = 0;
baseHeader.nBatch = 1;
baseHeader.nBands = numArbors;
baseHeader.timestamp = timestamp;
weightHeader.nxp = nxp;
weightHeader.nyp = nyp;
weightHeader.nfp = nfp;
weightHeader.minVal = minVal;
weightHeader.maxVal = maxVal;
weightHeader.numPatches = numPatches;
return weightHeader;
}
WeightHeader buildSharedWeightHeader(
int nxp,
int nyp,
int nfp,
int numArbors,
int numPatchesX,
int numPatchesY,
int numPatchesF,
double timestamp,
bool compress,
float minVal,
float maxVal) {
WeightHeader weightHeader = buildWeightHeader(
true /* shared weights*/,
numPatchesX,
numPatchesY,
numPatchesF,
numPatchesX,
numPatchesY,
numArbors,
timestamp,
nxp,
nyp,
nfp,
compress,
minVal,
maxVal);
return weightHeader;
}
WeightHeader buildNonsharedWeightHeader(
int nxp,
int nyp,
int nfp,
int numArbors,
bool extended,
double timestamp,
PVLayerLoc const *preLayerLoc,
PVLayerLoc const *postLayerLoc,
int numColumnProcesses,
int numRowProcesses,
float minVal,
float maxVal,
bool compress) {
int numPatchesX, numPatchesY, numPatchesF, numPatchesXExt, numPatchesYExt;
calcNumberOfPatches(
preLayerLoc,
postLayerLoc,
numColumnProcesses,
numRowProcesses,
extended,
nxp,
nyp,
numPatchesX,
numPatchesY,
numPatchesF,
numPatchesXExt,
numPatchesYExt);
WeightHeader weightHeader = buildWeightHeader(
false /*non-shared weights*/,
numPatchesX,
numPatchesY,
numPatchesF,
numPatchesXExt,
numPatchesYExt,
numArbors,
timestamp,
nxp,
nyp,
nfp,
compress,
minVal,
maxVal);
return weightHeader;
}
std::size_t weightPatchSize(int numWeightsInPatch, bool compressed) {
if (compressed) {
return weightPatchSize<unsigned char>(numWeightsInPatch);
}
else {
return weightPatchSize<float>(numWeightsInPatch);
}
}
void calcNumberOfPatches(
PVLayerLoc const *preLayerLoc,
PVLayerLoc const *postLayerLoc,
int numColumnProcesses,
int numRowProcesses,
bool extended,
int nxp,
int nyp,
int &numPatchesX,
int &numPatchesY,
int &numPatchesF,
int &numPatchesXExt,
int &numPatchesYExt) {
int nxPreRestricted = preLayerLoc->nx * numColumnProcesses;
int nyPreRestricted = preLayerLoc->ny * numRowProcesses;
numPatchesX = preLayerLoc->nx * numColumnProcesses;
numPatchesY = preLayerLoc->ny * numRowProcesses;
numPatchesXExt = numPatchesX;
numPatchesYExt = numPatchesY;
if (extended) {
int marginX = requiredConvolveMargin(preLayerLoc->nx, postLayerLoc->nx, nxp);
numPatchesXExt += marginX + marginX;
int marginY = requiredConvolveMargin(preLayerLoc->ny, postLayerLoc->ny, nyp);
numPatchesYExt += marginY + marginY;
}
numPatchesF = preLayerLoc->nf;
}
} // end namespace BufferUtils
} // end namespace PV
<|endoftext|>
|
<commit_before>#include "../Include/CTransitionVisitor.h"
#include "../Include/CSceneNode.h"
#include "../Include/CSequenceNode.h"
#include "../Include/CKernel.h"
#include "../../Modules/Util/Include/CStats.h"
#include "cocos2d.h"
using namespace cocos2d;
namespace LM
{
CTransitionVisitor::CTransitionVisitor(CKernel* a_pKernel, bool a_bTransitionNext) :
m_bTransitionNext(a_bTransitionNext),
m_pKernel(a_pKernel)
{
}
Result CTransitionVisitor::ProcessNodeTopDown(CNode* a_pNode)
{
// pSequence is the father node of all the scenes.
// transition will be done on the between the current scene in the node
// (CSequenceNode::m_iCurrentNode) and the next node
CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(a_pNode);
CSceneNode* pScene = nullptr;
if (pSequence)
{
pScene = dynamic_cast<CSceneNode*>(pSequence->GetCurrentNode());
}
if (pScene)
{
GotoScene(pSequence);
}
return RESULT_PRUNE;
}
void CTransitionVisitor::GotoScene(CSequenceNode* a_pSequence)
{
if (m_pKernel->m_pCurrentScene->m_bDashboardTrigger && m_bTransitionNext)
{
// init dashboard
InitScene(m_pKernel->m_pDashboard);
return;
}
bool bSceneExists = false;
if (m_bTransitionNext)
{
// if TransitioNext offset of 1 scene
bSceneExists = a_pSequence->OffsetCurrentNode(1);
}
else
{
// else return to previous scene
bSceneExists = a_pSequence->OffsetCurrentNode(-1);
}
if (!bSceneExists)
{
return;
}
CSceneNode* pNewSceneNode = dynamic_cast<CSceneNode*>(a_pSequence->GetCurrentNode());
if (!m_pKernel->PlayerHasScene(pNewSceneNode->GetSceneID()))
{ // if the player does not have this scene in his list, skip it and go to the next one
GotoScene(a_pSequence);
return;
}
else if (pNewSceneNode)
{
InitScene(pNewSceneNode);
}
}
void CTransitionVisitor::InitScene(CSceneNode* a_pSceneNode)
{
Scene* pNewScene = a_pSceneNode->CreateScene();
a_pSceneNode->init();
if (m_bTransitionNext)
{
Director::getInstance()->replaceScene(TransitionSlideInR::create(0.5f, pNewScene));
}
else
{
Director::getInstance()->replaceScene(TransitionSlideInL::create(0.5f, pNewScene));
}
//CSceneNode* pOldScene = m_pKernel->m_pCurrentScene;
m_pKernel->m_pCurrentScene = a_pSceneNode;
//pOldScene->UnInit();
M_STATS->StartStats();
}
} // namespace LM
<commit_msg>[FIX] dashboard crash on message, but introducing black screens on transition<commit_after>#include "../Include/CTransitionVisitor.h"
#include "../Include/CSceneNode.h"
#include "../Include/CSequenceNode.h"
#include "../Include/CKernel.h"
#include "../../Modules/Util/Include/CStats.h"
#include "cocos2d.h"
using namespace cocos2d;
namespace LM
{
CTransitionVisitor::CTransitionVisitor(CKernel* a_pKernel, bool a_bTransitionNext) :
m_bTransitionNext(a_bTransitionNext),
m_pKernel(a_pKernel)
{
}
Result CTransitionVisitor::ProcessNodeTopDown(CNode* a_pNode)
{
// pSequence is the father node of all the scenes.
// transition will be done on the between the current scene in the node
// (CSequenceNode::m_iCurrentNode) and the next node
CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(a_pNode);
CSceneNode* pScene = nullptr;
if (pSequence)
{
pScene = dynamic_cast<CSceneNode*>(pSequence->GetCurrentNode());
}
if (pScene)
{
GotoScene(pSequence);
}
return RESULT_PRUNE;
}
void CTransitionVisitor::GotoScene(CSequenceNode* a_pSequence)
{
if (m_pKernel->m_pCurrentScene->m_bDashboardTrigger && m_bTransitionNext)
{
// init dashboard
InitScene(m_pKernel->m_pDashboard);
return;
}
bool bSceneExists = false;
if (m_bTransitionNext)
{
// if TransitioNext offset of 1 scene
bSceneExists = a_pSequence->OffsetCurrentNode(1);
}
else
{
// else return to previous scene
bSceneExists = a_pSequence->OffsetCurrentNode(-1);
}
if (!bSceneExists)
{
return;
}
CSceneNode* pNewSceneNode = dynamic_cast<CSceneNode*>(a_pSequence->GetCurrentNode());
if (!m_pKernel->PlayerHasScene(pNewSceneNode->GetSceneID()))
{ // if the player does not have this scene in his list, skip it and go to the next one
GotoScene(a_pSequence);
return;
}
else if (pNewSceneNode)
{
InitScene(pNewSceneNode);
}
}
void CTransitionVisitor::InitScene(CSceneNode* a_pSceneNode)
{
Scene* pNewScene = a_pSceneNode->CreateScene();
a_pSceneNode->init();
if (m_bTransitionNext)
{
Director::getInstance()->replaceScene(TransitionSlideInR::create(0.5f, pNewScene));
}
else
{
Director::getInstance()->replaceScene(TransitionSlideInL::create(0.5f, pNewScene));
}
CSceneNode* pOldScene = m_pKernel->m_pCurrentScene;
m_pKernel->m_pCurrentScene = a_pSceneNode;
pOldScene->UnInit();
M_STATS->StartStats();
}
} // namespace LM
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPictureUtils.h"
#include "SkCanvas.h"
#include "SkData.h"
#include "SkDevice.h"
#include "SkPixelRef.h"
#include "SkShader.h"
class PixelRefSet {
public:
PixelRefSet(SkTDArray<SkPixelRef*>* array) : fArray(array) {}
// This does a linear search on existing pixelrefs, so if this list gets big
// we should use a more complex sorted/hashy thing.
//
void add(SkPixelRef* pr) {
uint32_t genID = pr->getGenerationID();
if (fGenID.find(genID) < 0) {
*fArray->append() = pr;
*fGenID.append() = genID;
// SkDebugf("--- adding [%d] %x %d\n", fArray->count() - 1, pr, genID);
} else {
// SkDebugf("--- already have %x %d\n", pr, genID);
}
}
private:
SkTDArray<SkPixelRef*>* fArray;
SkTDArray<uint32_t> fGenID;
};
static void not_supported() {
SkASSERT(!"this method should never be called");
}
static void nothing_to_do() {}
/**
* This device will route all bitmaps (primitives and in shaders) to its PRSet.
* It should never actually draw anything, so there need not be any pixels
* behind its device-bitmap.
*/
class GatherPixelRefDevice : public SkDevice {
private:
PixelRefSet* fPRSet;
void addBitmap(const SkBitmap& bm) {
fPRSet->add(bm.pixelRef());
}
void addBitmapFromPaint(const SkPaint& paint) {
SkShader* shader = paint.getShader();
if (shader) {
SkBitmap bm;
// Check whether the shader is a gradient in order to short-circuit
// call to asABitmap to prevent generation of bitmaps from
// gradient shaders, which implement asABitmap.
if (SkShader::kNone_GradientType == shader->asAGradient(NULL) &&
shader->asABitmap(&bm, NULL, NULL)) {
fPRSet->add(bm.pixelRef());
}
}
}
public:
GatherPixelRefDevice(const SkBitmap& bm, PixelRefSet* prset) : SkDevice(bm) {
fPRSet = prset;
}
virtual void clear(SkColor color) SK_OVERRIDE {
nothing_to_do();
}
virtual void writePixels(const SkBitmap& bitmap, int x, int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
not_supported();
}
virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count,
const SkPoint[], const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawRect(const SkDraw&, const SkRect&,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawOval(const SkDraw&, const SkRect&,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawPath(const SkDraw&, const SkPath& path,
const SkPaint& paint, const SkMatrix* prePathMatrix,
bool pathIsMutable) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap,
const SkIRect* srcRectOrNull,
const SkMatrix&, const SkPaint&) SK_OVERRIDE {
this->addBitmap(bitmap);
}
virtual void drawBitmapRect(const SkDraw&, const SkBitmap& bitmap,
const SkRect* srcOrNull, const SkRect& dst,
const SkPaint&) SK_OVERRIDE {
this->addBitmap(bitmap);
}
virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,
int x, int y, const SkPaint& paint) SK_OVERRIDE {
this->addBitmap(bitmap);
}
virtual void drawText(const SkDraw&, const void* text, size_t len,
SkScalar x, SkScalar y,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawPosText(const SkDraw&, const void* text, size_t len,
const SkScalar pos[], SkScalar constY,
int, const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,
const SkPath& path, const SkMatrix* matrix,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,
const SkPoint verts[], const SkPoint texs[],
const SkColor colors[], SkXfermode* xmode,
const uint16_t indices[], int indexCount,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y,
const SkPaint&) SK_OVERRIDE {
nothing_to_do();
}
protected:
virtual bool onReadPixels(const SkBitmap& bitmap,
int x, int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
not_supported();
return false;
}
};
class NoSaveLayerCanvas : public SkCanvas {
public:
NoSaveLayerCanvas(SkDevice* device) : INHERITED(device) {}
// turn saveLayer() into save() for speed, should not affect correctness.
virtual int saveLayer(const SkRect* bounds, const SkPaint* paint,
SaveFlags flags) SK_OVERRIDE {
// Like SkPictureRecord, we don't want to create layers, but we do need
// to respect the save and (possibly) its rect-clip.
int count = this->INHERITED::save(flags);
if (bounds) {
this->INHERITED::clipRectBounds(bounds, flags, NULL);
}
return count;
}
// disable aa for speed
virtual bool clipRect(const SkRect& rect, SkRegion::Op op,
bool doAA) SK_OVERRIDE {
return this->INHERITED::clipRect(rect, op, false);
}
// for speed, just respect the bounds, and disable AA. May give us a few
// false positives and negatives.
virtual bool clipPath(const SkPath& path, SkRegion::Op op,
bool doAA) SK_OVERRIDE {
return this->INHERITED::clipRect(path.getBounds(), op, false);
}
private:
typedef SkCanvas INHERITED;
};
SkData* SkPictureUtils::GatherPixelRefs(SkPicture* pict, const SkRect& area) {
if (NULL == pict) {
return NULL;
}
// this test also handles if either area or pict's width/height are empty
if (!SkRect::Intersects(area,
SkRect::MakeWH(SkIntToScalar(pict->width()),
SkIntToScalar(pict->height())))) {
return NULL;
}
SkTDArray<SkPixelRef*> array;
PixelRefSet prset(&array);
SkBitmap emptyBitmap;
emptyBitmap.setConfig(SkBitmap::kARGB_8888_Config, pict->width(), pict->height());
// note: we do not set any pixels (shouldn't need to)
GatherPixelRefDevice device(emptyBitmap, &prset);
NoSaveLayerCanvas canvas(&device);
canvas.clipRect(area, SkRegion::kIntersect_Op, false);
canvas.drawPicture(*pict);
SkData* data = NULL;
int count = array.count();
if (count > 0) {
data = SkData::NewFromMalloc(array.detach(), count * sizeof(SkPixelRef*));
}
return data;
}
<commit_msg>Accelerate handling of clipRRect in calls to SkPictureUtils::GatherPixelRefs<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPictureUtils.h"
#include "SkCanvas.h"
#include "SkData.h"
#include "SkDevice.h"
#include "SkPixelRef.h"
#include "SkShader.h"
#include "SkRRect.h"
class PixelRefSet {
public:
PixelRefSet(SkTDArray<SkPixelRef*>* array) : fArray(array) {}
// This does a linear search on existing pixelrefs, so if this list gets big
// we should use a more complex sorted/hashy thing.
//
void add(SkPixelRef* pr) {
uint32_t genID = pr->getGenerationID();
if (fGenID.find(genID) < 0) {
*fArray->append() = pr;
*fGenID.append() = genID;
// SkDebugf("--- adding [%d] %x %d\n", fArray->count() - 1, pr, genID);
} else {
// SkDebugf("--- already have %x %d\n", pr, genID);
}
}
private:
SkTDArray<SkPixelRef*>* fArray;
SkTDArray<uint32_t> fGenID;
};
static void not_supported() {
SkASSERT(!"this method should never be called");
}
static void nothing_to_do() {}
/**
* This device will route all bitmaps (primitives and in shaders) to its PRSet.
* It should never actually draw anything, so there need not be any pixels
* behind its device-bitmap.
*/
class GatherPixelRefDevice : public SkDevice {
private:
PixelRefSet* fPRSet;
void addBitmap(const SkBitmap& bm) {
fPRSet->add(bm.pixelRef());
}
void addBitmapFromPaint(const SkPaint& paint) {
SkShader* shader = paint.getShader();
if (shader) {
SkBitmap bm;
// Check whether the shader is a gradient in order to short-circuit
// call to asABitmap to prevent generation of bitmaps from
// gradient shaders, which implement asABitmap.
if (SkShader::kNone_GradientType == shader->asAGradient(NULL) &&
shader->asABitmap(&bm, NULL, NULL)) {
fPRSet->add(bm.pixelRef());
}
}
}
public:
GatherPixelRefDevice(const SkBitmap& bm, PixelRefSet* prset) : SkDevice(bm) {
fPRSet = prset;
}
virtual void clear(SkColor color) SK_OVERRIDE {
nothing_to_do();
}
virtual void writePixels(const SkBitmap& bitmap, int x, int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
not_supported();
}
virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count,
const SkPoint[], const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawRect(const SkDraw&, const SkRect&,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawOval(const SkDraw&, const SkRect&,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawPath(const SkDraw&, const SkPath& path,
const SkPaint& paint, const SkMatrix* prePathMatrix,
bool pathIsMutable) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap,
const SkIRect* srcRectOrNull,
const SkMatrix&, const SkPaint&) SK_OVERRIDE {
this->addBitmap(bitmap);
}
virtual void drawBitmapRect(const SkDraw&, const SkBitmap& bitmap,
const SkRect* srcOrNull, const SkRect& dst,
const SkPaint&) SK_OVERRIDE {
this->addBitmap(bitmap);
}
virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,
int x, int y, const SkPaint& paint) SK_OVERRIDE {
this->addBitmap(bitmap);
}
virtual void drawText(const SkDraw&, const void* text, size_t len,
SkScalar x, SkScalar y,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawPosText(const SkDraw&, const void* text, size_t len,
const SkScalar pos[], SkScalar constY,
int, const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,
const SkPath& path, const SkMatrix* matrix,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,
const SkPoint verts[], const SkPoint texs[],
const SkColor colors[], SkXfermode* xmode,
const uint16_t indices[], int indexCount,
const SkPaint& paint) SK_OVERRIDE {
this->addBitmapFromPaint(paint);
}
virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y,
const SkPaint&) SK_OVERRIDE {
nothing_to_do();
}
protected:
virtual bool onReadPixels(const SkBitmap& bitmap,
int x, int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
not_supported();
return false;
}
};
class NoSaveLayerCanvas : public SkCanvas {
public:
NoSaveLayerCanvas(SkDevice* device) : INHERITED(device) {}
// turn saveLayer() into save() for speed, should not affect correctness.
virtual int saveLayer(const SkRect* bounds, const SkPaint* paint,
SaveFlags flags) SK_OVERRIDE {
// Like SkPictureRecord, we don't want to create layers, but we do need
// to respect the save and (possibly) its rect-clip.
int count = this->INHERITED::save(flags);
if (bounds) {
this->INHERITED::clipRectBounds(bounds, flags, NULL);
}
return count;
}
// disable aa for speed
virtual bool clipRect(const SkRect& rect, SkRegion::Op op,
bool doAA) SK_OVERRIDE {
return this->INHERITED::clipRect(rect, op, false);
}
// for speed, just respect the bounds, and disable AA. May give us a few
// false positives and negatives.
virtual bool clipPath(const SkPath& path, SkRegion::Op op,
bool doAA) SK_OVERRIDE {
return this->INHERITED::clipRect(path.getBounds(), op, false);
}
virtual bool clipRRect(const SkRRect& rrect, SkRegion::Op op,
bool doAA) SK_OVERRIDE {
return this->INHERITED::clipRect(rrect.getBounds(), op, false);
}
private:
typedef SkCanvas INHERITED;
};
SkData* SkPictureUtils::GatherPixelRefs(SkPicture* pict, const SkRect& area) {
if (NULL == pict) {
return NULL;
}
// this test also handles if either area or pict's width/height are empty
if (!SkRect::Intersects(area,
SkRect::MakeWH(SkIntToScalar(pict->width()),
SkIntToScalar(pict->height())))) {
return NULL;
}
SkTDArray<SkPixelRef*> array;
PixelRefSet prset(&array);
SkBitmap emptyBitmap;
emptyBitmap.setConfig(SkBitmap::kARGB_8888_Config, pict->width(), pict->height());
// note: we do not set any pixels (shouldn't need to)
GatherPixelRefDevice device(emptyBitmap, &prset);
NoSaveLayerCanvas canvas(&device);
canvas.clipRect(area, SkRegion::kIntersect_Op, false);
canvas.drawPicture(*pict);
SkData* data = NULL;
int count = array.count();
if (count > 0) {
data = SkData::NewFromMalloc(array.detach(), count * sizeof(SkPixelRef*));
}
return data;
}
<|endoftext|>
|
<commit_before>#include "Variant.h"
#include "split.h"
#include <string>
#include <list>
#include <iostream>
using namespace std;
using namespace vcf;
void annotateWithBlankGenotypes(Variant& var, string& annotationTag) {
var.addFormatField(annotationTag);
map<string, map<string, vector<string> > >::iterator s = var.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
sample[annotationTag].clear(); // means "no genotype" genotype
sample[annotationTag].push_back("./."); // means "no genotype" genotype
}
}
void annotateWithGenotypes(Variant& varA, Variant& varB, string& annotationTag) {
varA.addFormatField(annotationTag);
map<string, map<string, vector<string> > >::iterator s = varA.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = varA.samples.end();
map<string, int> varAAlleleInts;
int i = 1;
for (vector<string>::iterator a = varA.alt.begin(); a != varA.alt.end(); ++a, ++i) {
varAAlleleInts[*a] = i;
}
map<int, int> varBconvertToVarA; // maps alleles in the second file to allele numbers for the first
varBconvertToVarA[0] = 0; // reference == reference!
i = 1;
for (vector<string>::iterator a = varB.alt.begin(); a != varB.alt.end(); ++a, ++i) {
map<string, int>::iterator ita = varAAlleleInts.find(*a);
if (ita != varAAlleleInts.end()) {
varBconvertToVarA[i] = ita->second;
}
}
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
const string& name = s->first;
map<string, map<string, vector<string> > >::iterator o = varB.samples.find(name);
sample[annotationTag].clear();
if (o == varB.samples.end()) {
sample[annotationTag].push_back("./."); // means "no genotype"
} else {
map<string, vector<string> >& other = o->second;
string& otherGenotype = other["GT"].front();
// XXX this must compare the genotypes in the two files
map<int, int> gtB = decomposeGenotype(otherGenotype);
map<int, int> gtnew;
for (map<int, int>::iterator g = gtB.begin(); g != gtB.end(); ++g) {
map<int, int>::iterator f = varBconvertToVarA.find(g->first);
if (f != varBconvertToVarA.end()) {
gtnew[f->second] += g->second;
} else {
gtnew[-1] += g->second;
}
}
sample[annotationTag].push_back(genotypeToString(gtnew));
}
}
}
int main(int argc, char** argv) {
if (argc != 4) {
cerr << "usage: " << argv[0] << " <annotation-tag> <vcf file> <vcf file>" << endl
<< "annotates genotypes in the first file with genotypes in the second" << endl
<< "adding the genotype as another flag to each sample filed in the first file." << endl
<< "annotation-tag is the name of the sample flag which is added to store the annotation." << endl
<< "also adds a 'has_variant' flag for sites where the second file has a variant." << endl;
return 1;
}
string annotag = argv[1];
string filenameA = argv[2];
string filenameB = argv[3];
if (filenameA == filenameB) {
cerr << "it won't help to annotate samples with their own genotypes!" << endl;
return 1;
}
VariantCallFile variantFileA;
if (filenameA == "-") {
variantFileA.open(std::cin);
} else {
variantFileA.open(filenameA);
}
VariantCallFile variantFileB;
if (filenameB == "-") {
variantFileB.open(std::cin);
} else {
variantFileB.open(filenameB);
}
if (!variantFileA.is_open() || !variantFileB.is_open()) {
return 1;
}
Variant varA(variantFileA);
Variant varB(variantFileB);
// while the first file doesn't match the second positionally,
// step forward, annotating each genotype record with an empty genotype
// when the two match, iterate through the genotypes from the first file
// and get the genotypes reported in the second file
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
string line = "##INFO=<ID=" + annotag + ".has_variant,Number=0,Type=Flag,Description=\"True if "
+ annotag + " has a called alternate among samples under comparison.\">";
variantFileA.addHeaderLine(line);
line = "##FORMAT=<ID=" + annotag + ",Number=1,Type=String,Description=\"Genotype from "
+ annotag + ".\">";
variantFileA.addHeaderLine(line);
cout << variantFileA.header << endl;
int counter = 0;
do {
counter ++;
// this is broken. to do it right, it'll be necessary to get reference ids from the fasta reference used to make the alignments...
// if B is NOT done, and is less than A, read new B.
if (!variantFileB.done()
&& (varB.sequenceName != varA.sequenceName
|| (varB.sequenceName == varA.sequenceName && varB.position < varA.position)
|| variantFileA.done())
) {
variantFileB.getNextVariant(varB);
}
// if A is not done- and A is less than B, read A.
// should also read if variant B is done.
if (!variantFileA.done()
&& (varA.sequenceName != varB.sequenceName
|| (varA.sequenceName == varB.sequenceName && varA.position < varB.position)
|| variantFileB.done())
) {
cout << varA << endl;
variantFileA.getNextVariant(varA);
}
vector<Variant> varsA;
vector<Variant> varsB;
bool hasMultipleAlts = false;
long int thisPosition = 0;
string thisSequenceName;
if (varA.position == varB.position
&& varA.sequenceName == varB.sequenceName) {
thisPosition = varA.position;
thisSequenceName = varA.sequenceName;
}
while (!variantFileA.done()
&& !variantFileB.done()
&& thisPosition == varA.position
&& thisSequenceName == varA.sequenceName
&& varA.sequenceName == varB.sequenceName
&& varA.position == varB.position) {
// accumulate all the alts at the current position
varsA.push_back(varA);
varsB.push_back(varB);
if (varA.alt.size() > 1 || varB.alt.size() > 1)
hasMultipleAlts = true;
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
}
// multiple lines per position
if (!hasMultipleAlts && (varsA.size() > 1 || varsB.size() > 1)) {
map<pair<string, string>, Variant> varsAParsed;
map<pair<string, string>, Variant> varsBParsed;
for (vector<Variant>::iterator v = varsA.begin(); v != varsA.end(); ++v) {
varsAParsed[make_pair(v->ref, v->alt.front())] = *v;
}
for (vector<Variant>::iterator v = varsB.begin(); v != varsB.end(); ++v) {
varsBParsed[make_pair(v->ref, v->alt.front())] = *v;
}
for (map<pair<string, string>, Variant>::iterator vs = varsAParsed.begin(); vs != varsAParsed.end(); ++vs) {
Variant& varA = vs->second;
if (varsBParsed.find(make_pair(varA.ref, varA.alt.front())) != varsBParsed.end()) {
Variant& varB = varsBParsed[make_pair(varA.ref, varA.alt.front())]; // TODO cleanup
annotateWithGenotypes(varA, varB, annotag);
varA.infoFlags[annotag + ".has_variant"] = true;
} else {
annotateWithBlankGenotypes(varA, annotag);
}
cout << varA << endl;
}
} else if (!varsA.empty() && !varsB.empty()) { // one line per multi-allelic
Variant& varA = varsA.front();
Variant& varB = varsB.front();
annotateWithGenotypes(varA, varB, annotag);
// XXX TODO, and also allow for records with multiple alts
// XXX assume that if the other file has a corresponding record, some kind of variation was detected at the same site
varA.infoFlags[annotag + ".has_variant"] = true;
cout << varA << endl;
}
} while (!variantFileA.done() || !variantFileB.done());
cerr << "check: " << counter << "\n";
return 0;
}
<commit_msg>Removed testing prints to serr<commit_after>#include "Variant.h"
#include "split.h"
#include <string>
#include <list>
#include <iostream>
using namespace std;
using namespace vcf;
void annotateWithBlankGenotypes(Variant& var, string& annotationTag) {
var.addFormatField(annotationTag);
map<string, map<string, vector<string> > >::iterator s = var.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
sample[annotationTag].clear(); // means "no genotype" genotype
sample[annotationTag].push_back("./."); // means "no genotype" genotype
}
}
void annotateWithGenotypes(Variant& varA, Variant& varB, string& annotationTag) {
varA.addFormatField(annotationTag);
map<string, map<string, vector<string> > >::iterator s = varA.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = varA.samples.end();
map<string, int> varAAlleleInts;
int i = 1;
for (vector<string>::iterator a = varA.alt.begin(); a != varA.alt.end(); ++a, ++i) {
varAAlleleInts[*a] = i;
}
map<int, int> varBconvertToVarA; // maps alleles in the second file to allele numbers for the first
varBconvertToVarA[0] = 0; // reference == reference!
i = 1;
for (vector<string>::iterator a = varB.alt.begin(); a != varB.alt.end(); ++a, ++i) {
map<string, int>::iterator ita = varAAlleleInts.find(*a);
if (ita != varAAlleleInts.end()) {
varBconvertToVarA[i] = ita->second;
}
}
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
const string& name = s->first;
map<string, map<string, vector<string> > >::iterator o = varB.samples.find(name);
sample[annotationTag].clear();
if (o == varB.samples.end()) {
sample[annotationTag].push_back("./."); // means "no genotype"
} else {
map<string, vector<string> >& other = o->second;
string& otherGenotype = other["GT"].front();
// XXX this must compare the genotypes in the two files
map<int, int> gtB = decomposeGenotype(otherGenotype);
map<int, int> gtnew;
for (map<int, int>::iterator g = gtB.begin(); g != gtB.end(); ++g) {
map<int, int>::iterator f = varBconvertToVarA.find(g->first);
if (f != varBconvertToVarA.end()) {
gtnew[f->second] += g->second;
} else {
gtnew[-1] += g->second;
}
}
sample[annotationTag].push_back(genotypeToString(gtnew));
}
}
}
int main(int argc, char** argv) {
if (argc != 4) {
cerr << "usage: " << argv[0] << " <annotation-tag> <vcf file> <vcf file>" << endl
<< "annotates genotypes in the first file with genotypes in the second" << endl
<< "adding the genotype as another flag to each sample filed in the first file." << endl
<< "annotation-tag is the name of the sample flag which is added to store the annotation." << endl
<< "also adds a 'has_variant' flag for sites where the second file has a variant." << endl;
return 1;
}
string annotag = argv[1];
string filenameA = argv[2];
string filenameB = argv[3];
if (filenameA == filenameB) {
cerr << "it won't help to annotate samples with their own genotypes!" << endl;
return 1;
}
VariantCallFile variantFileA;
if (filenameA == "-") {
variantFileA.open(std::cin);
} else {
variantFileA.open(filenameA);
}
VariantCallFile variantFileB;
if (filenameB == "-") {
variantFileB.open(std::cin);
} else {
variantFileB.open(filenameB);
}
if (!variantFileA.is_open() || !variantFileB.is_open()) {
return 1;
}
Variant varA(variantFileA);
Variant varB(variantFileB);
// while the first file doesn't match the second positionally,
// step forward, annotating each genotype record with an empty genotype
// when the two match, iterate through the genotypes from the first file
// and get the genotypes reported in the second file
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
string line = "##INFO=<ID=" + annotag + ".has_variant,Number=0,Type=Flag,Description=\"True if "
+ annotag + " has a called alternate among samples under comparison.\">";
variantFileA.addHeaderLine(line);
line = "##FORMAT=<ID=" + annotag + ",Number=1,Type=String,Description=\"Genotype from "
+ annotag + ".\">";
variantFileA.addHeaderLine(line);
cout << variantFileA.header << endl;
do {
// this is broken. to do it right, it'll be necessary to get reference ids from the fasta reference used to make the alignments...
// if B is NOT done, and is less than A, read new B.
if (!variantFileB.done()
&& (varB.sequenceName != varA.sequenceName
|| (varB.sequenceName == varA.sequenceName && varB.position < varA.position)
|| variantFileA.done())
) {
variantFileB.getNextVariant(varB);
}
// if A is not done- and A is less than B, read A.
// should also read if variant B is done.
if (!variantFileA.done()
&& (varA.sequenceName != varB.sequenceName
|| (varA.sequenceName == varB.sequenceName && varA.position < varB.position)
|| variantFileB.done())
) {
cout << varA << endl;
variantFileA.getNextVariant(varA);
}
vector<Variant> varsA;
vector<Variant> varsB;
bool hasMultipleAlts = false;
long int thisPosition = 0;
string thisSequenceName;
if (varA.position == varB.position
&& varA.sequenceName == varB.sequenceName) {
thisPosition = varA.position;
thisSequenceName = varA.sequenceName;
}
while (!variantFileA.done()
&& !variantFileB.done()
&& thisPosition == varA.position
&& thisSequenceName == varA.sequenceName
&& varA.sequenceName == varB.sequenceName
&& varA.position == varB.position) {
// accumulate all the alts at the current position
varsA.push_back(varA);
varsB.push_back(varB);
if (varA.alt.size() > 1 || varB.alt.size() > 1)
hasMultipleAlts = true;
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
}
// multiple lines per position
if (!hasMultipleAlts && (varsA.size() > 1 || varsB.size() > 1)) {
map<pair<string, string>, Variant> varsAParsed;
map<pair<string, string>, Variant> varsBParsed;
for (vector<Variant>::iterator v = varsA.begin(); v != varsA.end(); ++v) {
varsAParsed[make_pair(v->ref, v->alt.front())] = *v;
}
for (vector<Variant>::iterator v = varsB.begin(); v != varsB.end(); ++v) {
varsBParsed[make_pair(v->ref, v->alt.front())] = *v;
}
for (map<pair<string, string>, Variant>::iterator vs = varsAParsed.begin(); vs != varsAParsed.end(); ++vs) {
Variant& varA = vs->second;
if (varsBParsed.find(make_pair(varA.ref, varA.alt.front())) != varsBParsed.end()) {
Variant& varB = varsBParsed[make_pair(varA.ref, varA.alt.front())]; // TODO cleanup
annotateWithGenotypes(varA, varB, annotag);
varA.infoFlags[annotag + ".has_variant"] = true;
} else {
annotateWithBlankGenotypes(varA, annotag);
}
cout << varA << endl;
}
} else if (!varsA.empty() && !varsB.empty()) { // one line per multi-allelic
Variant& varA = varsA.front();
Variant& varB = varsB.front();
annotateWithGenotypes(varA, varB, annotag);
// XXX TODO, and also allow for records with multiple alts
// XXX assume that if the other file has a corresponding record, some kind of variation was detected at the same site
varA.infoFlags[annotag + ".has_variant"] = true;
cout << varA << endl;
}
} while (!variantFileA.done() || !variantFileB.done());
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "istream_deflate.hxx"
#include "UnusedPtr.hxx"
#include "New.hxx"
#include "FacadeIstream.hxx"
#include "pool/pool.hxx"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include "event/DeferEvent.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/DestructObserver.hxx"
#include "util/WritableBuffer.hxx"
#include <zlib.h>
#include <stdexcept>
#include <assert.h>
class ZlibError : public std::runtime_error {
int code;
public:
explicit ZlibError(int _code, const char *_msg)
:std::runtime_error(_msg), code(_code) {}
int GetCode() const noexcept {
return code;
}
};
class DeflateIstream final : public FacadeIstream, DestructAnchor {
const bool gzip;
bool z_initialized = false, z_stream_end = false;
z_stream z;
bool had_input, had_output;
bool reading;
SliceFifoBuffer buffer;
/**
* This callback is used to request more data from the input if an
* OnData() call did not produce any output. This tries to
* prevent stalling the stream.
*/
DeferEvent defer;
public:
DeflateIstream(struct pool &_pool, UnusedIstreamPtr _input,
EventLoop &event_loop, bool _gzip)
:FacadeIstream(_pool, std::move(_input)),
gzip(_gzip),
reading(false),
defer(event_loop, BIND_THIS_METHOD(OnDeferred))
{
}
~DeflateIstream() {
defer.Cancel();
}
bool InitZlib() noexcept;
void DeinitZlib() noexcept {
if (z_initialized)
deflateEnd(&z);
}
void Abort(std::exception_ptr ep) noexcept {
DeinitZlib();
if (HasInput())
ClearAndCloseInput();
DestroyError(ep);
}
void Abort(int code, const char *msg) noexcept {
Abort(std::make_exception_ptr(ZlibError(code, msg)));
}
/**
* Submit data from the buffer to our istream handler.
*
* @return the number of bytes which were handled, or 0 if the
* stream was closed
*/
size_t TryWrite() noexcept;
/**
* Starts to write to the buffer.
*
* @return a pointer to the writable buffer, or nullptr if there is no
* room (our istream handler blocks) or if the stream was closed
*/
WritableBuffer<void> BufferWrite() noexcept {
buffer.AllocateIfNull(fb_pool_get());
auto w = buffer.Write();
if (w.empty() && TryWrite() > 0)
w = buffer.Write();
return w.ToVoid();
}
void TryFlush() noexcept;
/**
* Read from our input until we have submitted some bytes to our
* istream handler.
*/
void ForceRead() noexcept;
void TryFinish() noexcept;
/* virtual methods from class Istream */
void _Read() noexcept override {
if (!buffer.empty())
TryWrite();
else if (HasInput())
ForceRead();
else
TryFinish();
}
void _Close() noexcept override {
DeinitZlib();
if (HasInput())
input.Close();
Destroy();
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) noexcept override;
void OnEof() noexcept override;
void OnError(std::exception_ptr ep) noexcept override;
private:
int GetWindowBits() const noexcept {
return MAX_WBITS + gzip * 16;
}
void OnDeferred() noexcept {
assert(HasInput());
ForceRead();
}
};
static voidpf
z_alloc(voidpf opaque, uInt items, uInt size) noexcept
{
struct pool *pool = (struct pool *)opaque;
return p_malloc(pool, items * size);
}
static void
z_free(voidpf opaque, voidpf address) noexcept
{
(void)opaque;
(void)address;
}
bool
DeflateIstream::InitZlib() noexcept
{
if (z_initialized)
return true;
z.zalloc = z_alloc;
z.zfree = z_free;
z.opaque = &GetPool();
int err = deflateInit2(&z, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, GetWindowBits(), 8,
Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
Abort(err, "deflateInit2() failed");
return false;
}
z_initialized = true;
return true;
}
size_t
DeflateIstream::TryWrite() noexcept
{
auto r = buffer.Read();
assert(!r.empty());
size_t nbytes = InvokeData(r.data, r.size);
if (nbytes == 0)
return 0;
buffer.Consume(nbytes);
buffer.FreeIfEmpty();
if (nbytes == r.size && !HasInput() && z_stream_end) {
DeinitZlib();
DestroyEof();
return 0;
}
return nbytes;
}
inline void
DeflateIstream::TryFlush() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_SYNC_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate(Z_SYNC_FLUSH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (!buffer.empty())
TryWrite();
}
inline void
DeflateIstream::ForceRead() noexcept
{
assert(!reading);
const DestructObserver destructed(*this);
bool had_input2 = false;
had_output = false;
while (1) {
had_input = false;
reading = true;
input.Read();
if (destructed)
return;
reading = false;
if (!HasInput() || had_output)
return;
if (!had_input)
break;
had_input2 = true;
}
if (had_input2)
TryFlush();
}
void
DeflateIstream::TryFinish() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_FINISH);
if (err == Z_STREAM_END)
z_stream_end = true;
else if (err != Z_OK) {
Abort(err, "deflate(Z_FINISH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (z_stream_end && buffer.empty()) {
DeinitZlib();
DestroyEof();
} else
TryWrite();
}
/*
* istream handler
*
*/
size_t
DeflateIstream::OnData(const void *data, size_t length) noexcept
{
assert(HasInput());
auto w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
return 0;
if (!InitZlib())
return 0;
had_input = true;
if (!reading)
had_output = false;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = (Bytef *)const_cast<void *>(data);
z.avail_in = (uInt)length;
do {
auto err = deflate(&z, Z_NO_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate() failed");
return 0;
}
size_t nbytes = w.size - (size_t)z.avail_out;
if (nbytes > 0) {
had_output = true;
buffer.Append(nbytes);
const DestructObserver destructed(*this);
TryWrite();
if (destructed)
return 0;
} else
break;
w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
break;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
} while (z.avail_in > 0);
if (!reading && !had_output)
/* we received data from our input, but we did not produce any
output (and we're not looping inside ForceRead()) - to
avoid stalling the stream, trigger the DeferEvent */
defer.Schedule();
return length - (size_t)z.avail_in;
}
void
DeflateIstream::OnEof() noexcept
{
ClearInput();
defer.Cancel();
if (!InitZlib())
return;
TryFinish();
}
void
DeflateIstream::OnError(std::exception_ptr ep) noexcept
{
ClearInput();
DeinitZlib();
DestroyError(ep);
}
/*
* constructor
*
*/
UnusedIstreamPtr
istream_deflate_new(struct pool &pool, UnusedIstreamPtr input,
EventLoop &event_loop, bool gzip) noexcept
{
return NewIstreamPtr<DeflateIstream>(pool, std::move(input),
event_loop, gzip);
}
<commit_msg>istream/deflate: deinitialize zlib in destructor<commit_after>/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "istream_deflate.hxx"
#include "UnusedPtr.hxx"
#include "New.hxx"
#include "FacadeIstream.hxx"
#include "pool/pool.hxx"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include "event/DeferEvent.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/DestructObserver.hxx"
#include "util/WritableBuffer.hxx"
#include <zlib.h>
#include <stdexcept>
#include <assert.h>
class ZlibError : public std::runtime_error {
int code;
public:
explicit ZlibError(int _code, const char *_msg)
:std::runtime_error(_msg), code(_code) {}
int GetCode() const noexcept {
return code;
}
};
class DeflateIstream final : public FacadeIstream, DestructAnchor {
const bool gzip;
bool z_initialized = false, z_stream_end = false;
z_stream z;
bool had_input, had_output;
bool reading;
SliceFifoBuffer buffer;
/**
* This callback is used to request more data from the input if an
* OnData() call did not produce any output. This tries to
* prevent stalling the stream.
*/
DeferEvent defer;
public:
DeflateIstream(struct pool &_pool, UnusedIstreamPtr _input,
EventLoop &event_loop, bool _gzip)
:FacadeIstream(_pool, std::move(_input)),
gzip(_gzip),
reading(false),
defer(event_loop, BIND_THIS_METHOD(OnDeferred))
{
}
~DeflateIstream() {
defer.Cancel();
if (z_initialized)
deflateEnd(&z);
}
bool InitZlib() noexcept;
void Abort(std::exception_ptr ep) noexcept {
if (HasInput())
ClearAndCloseInput();
DestroyError(ep);
}
void Abort(int code, const char *msg) noexcept {
Abort(std::make_exception_ptr(ZlibError(code, msg)));
}
/**
* Submit data from the buffer to our istream handler.
*
* @return the number of bytes which were handled, or 0 if the
* stream was closed
*/
size_t TryWrite() noexcept;
/**
* Starts to write to the buffer.
*
* @return a pointer to the writable buffer, or nullptr if there is no
* room (our istream handler blocks) or if the stream was closed
*/
WritableBuffer<void> BufferWrite() noexcept {
buffer.AllocateIfNull(fb_pool_get());
auto w = buffer.Write();
if (w.empty() && TryWrite() > 0)
w = buffer.Write();
return w.ToVoid();
}
void TryFlush() noexcept;
/**
* Read from our input until we have submitted some bytes to our
* istream handler.
*/
void ForceRead() noexcept;
void TryFinish() noexcept;
/* virtual methods from class Istream */
void _Read() noexcept override {
if (!buffer.empty())
TryWrite();
else if (HasInput())
ForceRead();
else
TryFinish();
}
void _Close() noexcept override {
if (HasInput())
input.Close();
Destroy();
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) noexcept override;
void OnEof() noexcept override;
void OnError(std::exception_ptr ep) noexcept override;
private:
int GetWindowBits() const noexcept {
return MAX_WBITS + gzip * 16;
}
void OnDeferred() noexcept {
assert(HasInput());
ForceRead();
}
};
static voidpf
z_alloc(voidpf opaque, uInt items, uInt size) noexcept
{
struct pool *pool = (struct pool *)opaque;
return p_malloc(pool, items * size);
}
static void
z_free(voidpf opaque, voidpf address) noexcept
{
(void)opaque;
(void)address;
}
bool
DeflateIstream::InitZlib() noexcept
{
if (z_initialized)
return true;
z.zalloc = z_alloc;
z.zfree = z_free;
z.opaque = &GetPool();
int err = deflateInit2(&z, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, GetWindowBits(), 8,
Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
Abort(err, "deflateInit2() failed");
return false;
}
z_initialized = true;
return true;
}
size_t
DeflateIstream::TryWrite() noexcept
{
auto r = buffer.Read();
assert(!r.empty());
size_t nbytes = InvokeData(r.data, r.size);
if (nbytes == 0)
return 0;
buffer.Consume(nbytes);
buffer.FreeIfEmpty();
if (nbytes == r.size && !HasInput() && z_stream_end) {
DestroyEof();
return 0;
}
return nbytes;
}
inline void
DeflateIstream::TryFlush() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_SYNC_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate(Z_SYNC_FLUSH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (!buffer.empty())
TryWrite();
}
inline void
DeflateIstream::ForceRead() noexcept
{
assert(!reading);
const DestructObserver destructed(*this);
bool had_input2 = false;
had_output = false;
while (1) {
had_input = false;
reading = true;
input.Read();
if (destructed)
return;
reading = false;
if (!HasInput() || had_output)
return;
if (!had_input)
break;
had_input2 = true;
}
if (had_input2)
TryFlush();
}
void
DeflateIstream::TryFinish() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_FINISH);
if (err == Z_STREAM_END)
z_stream_end = true;
else if (err != Z_OK) {
Abort(err, "deflate(Z_FINISH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (z_stream_end && buffer.empty()) {
DestroyEof();
} else
TryWrite();
}
/*
* istream handler
*
*/
size_t
DeflateIstream::OnData(const void *data, size_t length) noexcept
{
assert(HasInput());
auto w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
return 0;
if (!InitZlib())
return 0;
had_input = true;
if (!reading)
had_output = false;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = (Bytef *)const_cast<void *>(data);
z.avail_in = (uInt)length;
do {
auto err = deflate(&z, Z_NO_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate() failed");
return 0;
}
size_t nbytes = w.size - (size_t)z.avail_out;
if (nbytes > 0) {
had_output = true;
buffer.Append(nbytes);
const DestructObserver destructed(*this);
TryWrite();
if (destructed)
return 0;
} else
break;
w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
break;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
} while (z.avail_in > 0);
if (!reading && !had_output)
/* we received data from our input, but we did not produce any
output (and we're not looping inside ForceRead()) - to
avoid stalling the stream, trigger the DeferEvent */
defer.Schedule();
return length - (size_t)z.avail_in;
}
void
DeflateIstream::OnEof() noexcept
{
ClearInput();
defer.Cancel();
if (!InitZlib())
return;
TryFinish();
}
void
DeflateIstream::OnError(std::exception_ptr ep) noexcept
{
ClearInput();
DestroyError(ep);
}
/*
* constructor
*
*/
UnusedIstreamPtr
istream_deflate_new(struct pool &pool, UnusedIstreamPtr input,
EventLoop &event_loop, bool gzip) noexcept
{
return NewIstreamPtr<DeflateIstream>(pool, std::move(input),
event_loop, gzip);
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "sysapi.h"
#include "sysapi_externs.h"
#include "condor_sockaddr.h"
static bool net_devices_cached = false;
static std::vector<NetworkDeviceInfo> net_devices_cache;
#if WIN32
#include <Ws2ipdef.h>
bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)
{
int i,num_interfaces=0,max_interfaces=20;
LPINTERFACE_INFO interfaces=NULL;
DWORD bytes_out=0;
SOCKET sock;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if( sock == INVALID_SOCKET ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d)\n",
WSAGetLastError());
return false;
}
while( true ) {
interfaces = new INTERFACE_INFO[max_interfaces];
int rc = WSAIoctl(
sock,
SIO_GET_INTERFACE_LIST,
NULL,
0,
interfaces,
sizeof(INTERFACE_INFO)*max_interfaces,
&bytes_out,
NULL,
NULL);
if( rc == 0 ) { // success
num_interfaces = bytes_out/sizeof(INTERFACE_INFO);
break;
}
delete [] interfaces;
int error = WSAGetLastError();
if( error == WSAEFAULT ) { // not enough space in buffer
max_interfaces *= 2;
continue;
}
dprintf(D_ALWAYS,"SIO_GET_INTERFACE_LIST failed: %d\n",error);
closesocket(sock);
return false;
}
for(i=0;i<num_interfaces;i++) {
char const *ip = NULL;
if( interfaces[i].iiAddress.Address.sa_family == AF_INET ) {
ip = inet_ntoa(((struct sockaddr_in *)&interfaces[i].iiAddress)->sin_addr);
}
if( ip ) {
NetworkDeviceInfo inf("",ip);
devices.push_back(inf);
}
}
delete [] interfaces;
closesocket(sock);
return true;
}
#elif HAVE_GETIFADDRS
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)
{
struct ifaddrs *ifap_list=NULL;
if( getifaddrs(&ifap_list) == -1 ) {
dprintf(D_ALWAYS,"getifaddrs failed: errno=%d: %s\n",errno,strerror(errno));
return false;
}
struct ifaddrs *ifap=ifap_list;
char ip_buf[INET6_ADDRSTRLEN];
for(ifap=ifap_list;
ifap;
ifap=ifap->ifa_next)
{
const char* ip = NULL;
char const *name = ifap->ifa_name;
if( ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_INET ) {
condor_sockaddr addr(ifap->ifa_addr);
ip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);
}
if( ip ) {
NetworkDeviceInfo inf(name,ip);
devices.push_back(inf);
}
}
freeifaddrs(ifap_list);
return true;
}
#elif defined(SIOCGIFCONF)
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if( sock == -1 ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d) %s\n",
errno,strerror(errno));
return false;
}
struct ifconf ifc,prev;
memset(&ifc, 0, sizeof(ifc));
const int max_interfaces = 10000;
int num_interfaces;
for(num_interfaces=100;num_interfaces<max_interfaces;num_interfaces+=100) {
prev.ifc_len = ifc.ifc_len;
ifc.ifc_len = num_interfaces*sizeof(struct ifreq);
ifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len);
if( ifc.ifc_req == NULL ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: out of memory\n");
return false;
}
// EINVAL (on some platforms) indicates that the buffer
// is not large enough
if( ioctl(sock, SIOCGIFCONF, &ifc) < 0 && errno != EINVAL ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: ioctlsocket() failed after allocating buffer: (errno %d) %s\n",
errno,strerror(errno));
free( ifc.ifc_req );
return false;
}
if( ifc.ifc_len == prev.ifc_len ) {
// Getting the same length in successive calls to
// SIOCGIFCONF is the only reliable way to know that
// the buffer was big enough, because some
// implementations silently return truncated results
// if the buffer isn't big enough.
break;
}
free( ifc.ifc_req );
ifc.ifc_req = NULL;
}
if( num_interfaces > max_interfaces ) {
// something must be going wrong
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: unexpectedly large SIOCGIFCONF buffer: %d (errno=%d)\n",num_interfaces,errno);
return false;
}
num_interfaces = ifc.ifc_len/sizeof(struct ifreq);
char ip_buf[INET6_ADDRSTRLEN];
int i;
for(i=0; i<num_interfaces; i++) {
struct ifreq *ifr = &ifc.ifc_req[i];
char const *name = ifr->ifr_name;
const char* ip = NULL;
if( ifr->ifr_addr.sa_family == AF_INET ||ifr->ifr_addr.sa_family == AF_INET6 ) {
condor_sockaddr addr(&ifr->ifr_addr);
ip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);
}
if( ip ) {
NetworkDeviceInfo inf(name,ip);
devices.push_back(inf);
}
}
free( ifc.ifc_req );
return true;
}
#else
#error sysapi_get_network_device_info() must be implemented for this platform
#endif
bool sysapi_get_network_device_info(std::vector<NetworkDeviceInfo> &devices)
{
if( net_devices_cached ) {
devices = net_devices_cache;
return true;
}
bool rc = sysapi_get_network_device_info_raw(devices);
if( rc ) {
net_devices_cached = true;
net_devices_cache = devices;
}
return rc;
}
void sysapi_clear_network_device_info_cache() {
net_devices_cached = false;
}
<commit_msg>sysapi_get_network_device_nifo_raw is now allowed to return IPv6 devices. Not user facing.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "sysapi.h"
#include "sysapi_externs.h"
#include "condor_sockaddr.h"
static bool net_devices_cached = false;
static std::vector<NetworkDeviceInfo> net_devices_cache;
#if WIN32
#include <Ws2ipdef.h>
bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)
{
int i,num_interfaces=0,max_interfaces=20;
LPINTERFACE_INFO interfaces=NULL;
DWORD bytes_out=0;
SOCKET sock;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if( sock == INVALID_SOCKET ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d)\n",
WSAGetLastError());
return false;
}
while( true ) {
interfaces = new INTERFACE_INFO[max_interfaces];
int rc = WSAIoctl(
sock,
SIO_GET_INTERFACE_LIST,
NULL,
0,
interfaces,
sizeof(INTERFACE_INFO)*max_interfaces,
&bytes_out,
NULL,
NULL);
if( rc == 0 ) { // success
num_interfaces = bytes_out/sizeof(INTERFACE_INFO);
break;
}
delete [] interfaces;
int error = WSAGetLastError();
if( error == WSAEFAULT ) { // not enough space in buffer
max_interfaces *= 2;
continue;
}
dprintf(D_ALWAYS,"SIO_GET_INTERFACE_LIST failed: %d\n",error);
closesocket(sock);
return false;
}
for(i=0;i<num_interfaces;i++) {
char const *ip = NULL;
if( interfaces[i].iiAddress.Address.sa_family == AF_INET ) {
ip = inet_ntoa(((struct sockaddr_in *)&interfaces[i].iiAddress)->sin_addr);
}
if( ip ) {
NetworkDeviceInfo inf("",ip);
devices.push_back(inf);
}
}
delete [] interfaces;
closesocket(sock);
return true;
}
#elif HAVE_GETIFADDRS
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)
{
struct ifaddrs *ifap_list=NULL;
if( getifaddrs(&ifap_list) == -1 ) {
dprintf(D_ALWAYS,"getifaddrs failed: errno=%d: %s\n",errno,strerror(errno));
return false;
}
struct ifaddrs *ifap=ifap_list;
char ip_buf[INET6_ADDRSTRLEN];
for(ifap=ifap_list;
ifap;
ifap=ifap->ifa_next)
{
const char* ip = NULL;
char const *name = ifap->ifa_name;
if( ifap->ifa_addr &&
(ifap->ifa_addr->sa_family == AF_INET ||
ifap->ifa_addr->sa_family == AF_INET6)
) {
condor_sockaddr addr(ifap->ifa_addr);
ip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);
}
if( ip ) {
NetworkDeviceInfo inf(name,ip);
devices.push_back(inf);
}
}
freeifaddrs(ifap_list);
return true;
}
#elif defined(SIOCGIFCONF)
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
bool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if( sock == -1 ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: socket() failed: (errno %d) %s\n",
errno,strerror(errno));
return false;
}
struct ifconf ifc,prev;
memset(&ifc, 0, sizeof(ifc));
const int max_interfaces = 10000;
int num_interfaces;
for(num_interfaces=100;num_interfaces<max_interfaces;num_interfaces+=100) {
prev.ifc_len = ifc.ifc_len;
ifc.ifc_len = num_interfaces*sizeof(struct ifreq);
ifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len);
if( ifc.ifc_req == NULL ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: out of memory\n");
return false;
}
// EINVAL (on some platforms) indicates that the buffer
// is not large enough
if( ioctl(sock, SIOCGIFCONF, &ifc) < 0 && errno != EINVAL ) {
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: ioctlsocket() failed after allocating buffer: (errno %d) %s\n",
errno,strerror(errno));
free( ifc.ifc_req );
return false;
}
if( ifc.ifc_len == prev.ifc_len ) {
// Getting the same length in successive calls to
// SIOCGIFCONF is the only reliable way to know that
// the buffer was big enough, because some
// implementations silently return truncated results
// if the buffer isn't big enough.
break;
}
free( ifc.ifc_req );
ifc.ifc_req = NULL;
}
if( num_interfaces > max_interfaces ) {
// something must be going wrong
dprintf(D_ALWAYS,"sysapi_get_network_device_info_raw: unexpectedly large SIOCGIFCONF buffer: %d (errno=%d)\n",num_interfaces,errno);
return false;
}
num_interfaces = ifc.ifc_len/sizeof(struct ifreq);
char ip_buf[INET6_ADDRSTRLEN];
int i;
for(i=0; i<num_interfaces; i++) {
struct ifreq *ifr = &ifc.ifc_req[i];
char const *name = ifr->ifr_name;
const char* ip = NULL;
if( ifr->ifr_addr.sa_family == AF_INET ||ifr->ifr_addr.sa_family == AF_INET6 ) {
condor_sockaddr addr(&ifr->ifr_addr);
ip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);
}
if( ip ) {
NetworkDeviceInfo inf(name,ip);
devices.push_back(inf);
}
}
free( ifc.ifc_req );
return true;
}
#else
#error sysapi_get_network_device_info() must be implemented for this platform
#endif
bool sysapi_get_network_device_info(std::vector<NetworkDeviceInfo> &devices)
{
if( net_devices_cached ) {
devices = net_devices_cache;
return true;
}
bool rc = sysapi_get_network_device_info_raw(devices);
if( rc ) {
net_devices_cached = true;
net_devices_cache = devices;
}
return rc;
}
void sysapi_clear_network_device_info_cache() {
net_devices_cached = false;
}
<|endoftext|>
|
<commit_before>// Copyright 2018 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/vulkan/transfer_image.h"
#include <cstring>
#include <limits>
#include <vector>
#include "src/vulkan/command_buffer.h"
#include "src/vulkan/device.h"
namespace amber {
namespace vulkan {
namespace {
const VkImageCreateInfo kDefaultImageInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* sType */
nullptr, /* pNext */
0, /* flags */
VK_IMAGE_TYPE_2D, /* imageType */
VK_FORMAT_R8G8B8A8_UNORM, /* format */
{250, 250, 1}, /* extent */
1, /* mipLevels */
1, /* arrayLayers */
VK_SAMPLE_COUNT_1_BIT, /* samples */
VK_IMAGE_TILING_OPTIMAL, /* tiling */
0, /* usage */
VK_SHARING_MODE_EXCLUSIVE, /* sharingMode */
0, /* queueFamilyIndexCount */
nullptr, /* pQueueFamilyIndices */
VK_IMAGE_LAYOUT_UNDEFINED, /* initialLayout */
};
VkSampleCountFlagBits GetVkSampleCount(uint32_t samples) {
switch (samples) {
case 1u:
return VK_SAMPLE_COUNT_1_BIT;
case 2u:
return VK_SAMPLE_COUNT_2_BIT;
case 4u:
return VK_SAMPLE_COUNT_4_BIT;
case 8u:
return VK_SAMPLE_COUNT_8_BIT;
case 16u:
return VK_SAMPLE_COUNT_16_BIT;
case 32u:
return VK_SAMPLE_COUNT_32_BIT;
case 64u:
return VK_SAMPLE_COUNT_64_BIT;
}
return VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM;
}
} // namespace
TransferImage::TransferImage(Device* device,
const Format& format,
VkImageAspectFlags aspect,
VkImageType image_type,
uint32_t x,
uint32_t y,
uint32_t z,
uint32_t mip_levels,
uint32_t base_mip_level,
uint32_t used_mip_levels,
uint32_t samples)
: Resource(device, x * y * z * format.SizeInBytes()),
image_info_(kDefaultImageInfo),
aspect_(aspect),
mip_levels_(mip_levels),
base_mip_level_(base_mip_level),
used_mip_levels_(used_mip_levels),
samples_(samples) {
image_info_.format = device_->GetVkFormat(format);
image_info_.imageType = image_type;
image_info_.extent = {x, y, z};
image_info_.mipLevels = mip_levels;
image_info_.samples = GetVkSampleCount(samples);
}
TransferImage::~TransferImage() {
if (view_ != VK_NULL_HANDLE) {
device_->GetPtrs()->vkDestroyImageView(device_->GetVkDevice(), view_,
nullptr);
}
if (image_ != VK_NULL_HANDLE)
device_->GetPtrs()->vkDestroyImage(device_->GetVkDevice(), image_, nullptr);
if (memory_ != VK_NULL_HANDLE)
device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(), memory_, nullptr);
if (host_accessible_memory_ != VK_NULL_HANDLE) {
UnMapMemory(host_accessible_memory_);
device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(),
host_accessible_memory_, nullptr);
}
if (host_accessible_buffer_ != VK_NULL_HANDLE) {
device_->GetPtrs()->vkDestroyBuffer(device_->GetVkDevice(),
host_accessible_buffer_, nullptr);
}
}
Result TransferImage::Initialize(VkImageUsageFlags usage) {
if (image_ != VK_NULL_HANDLE)
return Result("Vulkan::TransferImage was already initialized");
image_info_.usage = usage;
if (device_->GetPtrs()->vkCreateImage(device_->GetVkDevice(), &image_info_,
nullptr, &image_) != VK_SUCCESS) {
return Result("Vulkan::Calling vkCreateImage Fail");
}
uint32_t memory_type_index = 0;
Result r = AllocateAndBindMemoryToVkImage(image_, &memory_,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
false, &memory_type_index);
if (!r.IsSuccess())
return r;
if (aspect_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) &&
!(usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
// Combined depth/stencil image used as a descriptor. Only one aspect can be
// used for the image view.
r = CreateVkImageView(VK_IMAGE_ASPECT_DEPTH_BIT);
} else {
r = CreateVkImageView(aspect_);
}
if (!r.IsSuccess())
return r;
// For images, we always make a secondary buffer. When the tiling of an image
// is optimal, read/write data from CPU does not show correct values. We need
// a secondary buffer to convert the GPU-optimal data to CPU-readable data
// and vice versa.
r = CreateVkBuffer(
&host_accessible_buffer_,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
if (!r.IsSuccess())
return r;
memory_type_index = 0;
r = AllocateAndBindMemoryToVkBuffer(host_accessible_buffer_,
&host_accessible_memory_,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
true, &memory_type_index);
if (!r.IsSuccess())
return r;
return MapMemory(host_accessible_memory_);
}
VkImageViewType TransferImage::GetImageViewType() const {
// TODO(alan-baker): handle other view types.
// 1D-array, 2D-array, Cube, Cube-array.
switch (image_info_.imageType) {
case VK_IMAGE_TYPE_1D:
return VK_IMAGE_VIEW_TYPE_1D;
case VK_IMAGE_TYPE_2D:
return VK_IMAGE_VIEW_TYPE_2D;
case VK_IMAGE_TYPE_3D:
return VK_IMAGE_VIEW_TYPE_3D;
default:
break;
}
// Default to 2D image view.
return VK_IMAGE_VIEW_TYPE_2D;
}
Result TransferImage::CreateVkImageView(VkImageAspectFlags aspect) {
VkImageViewCreateInfo image_view_info = VkImageViewCreateInfo();
image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_info.image = image_;
image_view_info.viewType = GetImageViewType();
image_view_info.format = image_info_.format;
image_view_info.components = {
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A,
};
image_view_info.subresourceRange = {
aspect, /* aspectMask */
base_mip_level_, /* baseMipLevel */
used_mip_levels_, /* levelCount */
0, /* baseArrayLayer */
1, /* layerCount */
};
if (device_->GetPtrs()->vkCreateImageView(device_->GetVkDevice(),
&image_view_info, nullptr,
&view_) != VK_SUCCESS) {
return Result("Vulkan::Calling vkCreateImageView Fail");
}
return {};
}
VkBufferImageCopy TransferImage::CreateBufferImageCopy(
VkImageAspectFlags aspect,
uint32_t mip_level) {
VkBufferImageCopy copy_region = VkBufferImageCopy();
if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT) {
// Store stencil data at the end of the buffer after depth data.
copy_region.bufferOffset =
GetSizeInBytes() - image_info_.extent.width * image_info_.extent.height;
} else {
copy_region.bufferOffset = 0;
}
// Row length of 0 results in tight packing of rows, so the row stride
// is the number of texels times the texel stride.
copy_region.bufferRowLength = 0;
copy_region.bufferImageHeight = 0;
copy_region.imageSubresource = {
aspect, /* aspectMask */
mip_level, /* mipLevel */
0, /* baseArrayLayer */
1, /* layerCount */
};
copy_region.imageOffset = {0, 0, 0};
copy_region.imageExtent = {image_info_.extent.width >> mip_level,
image_info_.extent.height >> mip_level,
image_info_.extent.depth};
return copy_region;
}
void TransferImage::CopyToHost(CommandBuffer* command_buffer) {
const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_ASPECT_DEPTH_BIT,
VK_IMAGE_ASPECT_STENCIL_BIT};
// Copy operations don't support multisample images.
if (samples_ > 1)
return;
std::vector<VkBufferImageCopy> copy_regions;
uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS
? mip_levels_
: base_mip_level_ + used_mip_levels_;
for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {
for (auto aspect : aspects) {
if (aspect_ & aspect) {
copy_regions.push_back(CreateBufferImageCopy(aspect, i));
}
}
}
device_->GetPtrs()->vkCmdCopyImageToBuffer(
command_buffer->GetVkCommandBuffer(), image_,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, host_accessible_buffer_,
static_cast<uint32_t>(copy_regions.size()), copy_regions.data());
MemoryBarrier(command_buffer);
}
void TransferImage::CopyToDevice(CommandBuffer* command_buffer) {
// Copy operations don't support multisample images.
if (samples_ > 1)
return;
const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_ASPECT_DEPTH_BIT,
VK_IMAGE_ASPECT_STENCIL_BIT};
std::vector<VkBufferImageCopy> copy_regions;
uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS
? mip_levels_
: base_mip_level_ + used_mip_levels_;
for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {
for (auto aspect : aspects) {
if (aspect_ & aspect) {
copy_regions.push_back(CreateBufferImageCopy(aspect, i));
}
}
}
device_->GetPtrs()->vkCmdCopyBufferToImage(
command_buffer->GetVkCommandBuffer(), host_accessible_buffer_, image_,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
static_cast<uint32_t>(copy_regions.size()), copy_regions.data());
MemoryBarrier(command_buffer);
}
void TransferImage::ImageBarrier(CommandBuffer* command_buffer,
VkImageLayout to_layout,
VkPipelineStageFlags to_stage) {
if (to_layout == layout_ && to_stage == stage_)
return;
VkImageMemoryBarrier barrier = VkImageMemoryBarrier();
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = layout_;
barrier.newLayout = to_layout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image_;
barrier.subresourceRange = {
aspect_, /* aspectMask */
0, /* baseMipLevel */
VK_REMAINING_MIP_LEVELS, /* levelCount */
0, /* baseArrayLayer */
1, /* layerCount */
};
switch (layout_) {
case VK_IMAGE_LAYOUT_PREINITIALIZED:
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
default:
barrier.srcAccessMask = 0;
break;
}
switch (to_layout) {
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
default:
barrier.dstAccessMask = 0;
break;
}
device_->GetPtrs()->vkCmdPipelineBarrier(command_buffer->GetVkCommandBuffer(),
stage_, to_stage, 0, 0, NULL, 0,
NULL, 1, &barrier);
layout_ = to_layout;
stage_ = to_stage;
}
Result TransferImage::AllocateAndBindMemoryToVkImage(
VkImage image,
VkDeviceMemory* memory,
VkMemoryPropertyFlags flags,
bool force_flags,
uint32_t* memory_type_index) {
if (memory_type_index == nullptr) {
return Result(
"Vulkan: TransferImage::AllocateAndBindMemoryToVkImage "
"memory_type_index is "
"nullptr");
}
*memory_type_index = 0;
if (image == VK_NULL_HANDLE)
return Result("Vulkan::Given VkImage is VK_NULL_HANDLE");
if (memory == nullptr)
return Result("Vulkan::Given VkDeviceMemory pointer is nullptr");
VkMemoryRequirements requirement;
device_->GetPtrs()->vkGetImageMemoryRequirements(device_->GetVkDevice(),
image, &requirement);
*memory_type_index =
ChooseMemory(requirement.memoryTypeBits, flags, force_flags);
if (*memory_type_index == std::numeric_limits<uint32_t>::max())
return Result("Vulkan::Find Proper Memory Fail");
Result r = AllocateMemory(memory, requirement.size, *memory_type_index);
if (!r.IsSuccess())
return r;
if (device_->GetPtrs()->vkBindImageMemory(device_->GetVkDevice(), image,
*memory, 0) != VK_SUCCESS) {
return Result("Vulkan::Calling vkBindImageMemory Fail");
}
return {};
}
} // namespace vulkan
} // namespace amber
<commit_msg>Fix Vulkan synchronization validation errors (#926)<commit_after>// Copyright 2018 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/vulkan/transfer_image.h"
#include <cstring>
#include <limits>
#include <vector>
#include "src/vulkan/command_buffer.h"
#include "src/vulkan/device.h"
namespace amber {
namespace vulkan {
namespace {
const VkImageCreateInfo kDefaultImageInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* sType */
nullptr, /* pNext */
0, /* flags */
VK_IMAGE_TYPE_2D, /* imageType */
VK_FORMAT_R8G8B8A8_UNORM, /* format */
{250, 250, 1}, /* extent */
1, /* mipLevels */
1, /* arrayLayers */
VK_SAMPLE_COUNT_1_BIT, /* samples */
VK_IMAGE_TILING_OPTIMAL, /* tiling */
0, /* usage */
VK_SHARING_MODE_EXCLUSIVE, /* sharingMode */
0, /* queueFamilyIndexCount */
nullptr, /* pQueueFamilyIndices */
VK_IMAGE_LAYOUT_UNDEFINED, /* initialLayout */
};
VkSampleCountFlagBits GetVkSampleCount(uint32_t samples) {
switch (samples) {
case 1u:
return VK_SAMPLE_COUNT_1_BIT;
case 2u:
return VK_SAMPLE_COUNT_2_BIT;
case 4u:
return VK_SAMPLE_COUNT_4_BIT;
case 8u:
return VK_SAMPLE_COUNT_8_BIT;
case 16u:
return VK_SAMPLE_COUNT_16_BIT;
case 32u:
return VK_SAMPLE_COUNT_32_BIT;
case 64u:
return VK_SAMPLE_COUNT_64_BIT;
}
return VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM;
}
} // namespace
TransferImage::TransferImage(Device* device,
const Format& format,
VkImageAspectFlags aspect,
VkImageType image_type,
uint32_t x,
uint32_t y,
uint32_t z,
uint32_t mip_levels,
uint32_t base_mip_level,
uint32_t used_mip_levels,
uint32_t samples)
: Resource(device, x * y * z * format.SizeInBytes()),
image_info_(kDefaultImageInfo),
aspect_(aspect),
mip_levels_(mip_levels),
base_mip_level_(base_mip_level),
used_mip_levels_(used_mip_levels),
samples_(samples) {
image_info_.format = device_->GetVkFormat(format);
image_info_.imageType = image_type;
image_info_.extent = {x, y, z};
image_info_.mipLevels = mip_levels;
image_info_.samples = GetVkSampleCount(samples);
}
TransferImage::~TransferImage() {
if (view_ != VK_NULL_HANDLE) {
device_->GetPtrs()->vkDestroyImageView(device_->GetVkDevice(), view_,
nullptr);
}
if (image_ != VK_NULL_HANDLE)
device_->GetPtrs()->vkDestroyImage(device_->GetVkDevice(), image_, nullptr);
if (memory_ != VK_NULL_HANDLE)
device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(), memory_, nullptr);
if (host_accessible_memory_ != VK_NULL_HANDLE) {
UnMapMemory(host_accessible_memory_);
device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(),
host_accessible_memory_, nullptr);
}
if (host_accessible_buffer_ != VK_NULL_HANDLE) {
device_->GetPtrs()->vkDestroyBuffer(device_->GetVkDevice(),
host_accessible_buffer_, nullptr);
}
}
Result TransferImage::Initialize(VkImageUsageFlags usage) {
if (image_ != VK_NULL_HANDLE)
return Result("Vulkan::TransferImage was already initialized");
image_info_.usage = usage;
if (device_->GetPtrs()->vkCreateImage(device_->GetVkDevice(), &image_info_,
nullptr, &image_) != VK_SUCCESS) {
return Result("Vulkan::Calling vkCreateImage Fail");
}
uint32_t memory_type_index = 0;
Result r = AllocateAndBindMemoryToVkImage(image_, &memory_,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
false, &memory_type_index);
if (!r.IsSuccess())
return r;
if (aspect_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) &&
!(usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
// Combined depth/stencil image used as a descriptor. Only one aspect can be
// used for the image view.
r = CreateVkImageView(VK_IMAGE_ASPECT_DEPTH_BIT);
} else {
r = CreateVkImageView(aspect_);
}
if (!r.IsSuccess())
return r;
// For images, we always make a secondary buffer. When the tiling of an image
// is optimal, read/write data from CPU does not show correct values. We need
// a secondary buffer to convert the GPU-optimal data to CPU-readable data
// and vice versa.
r = CreateVkBuffer(
&host_accessible_buffer_,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
if (!r.IsSuccess())
return r;
memory_type_index = 0;
r = AllocateAndBindMemoryToVkBuffer(host_accessible_buffer_,
&host_accessible_memory_,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
true, &memory_type_index);
if (!r.IsSuccess())
return r;
return MapMemory(host_accessible_memory_);
}
VkImageViewType TransferImage::GetImageViewType() const {
// TODO(alan-baker): handle other view types.
// 1D-array, 2D-array, Cube, Cube-array.
switch (image_info_.imageType) {
case VK_IMAGE_TYPE_1D:
return VK_IMAGE_VIEW_TYPE_1D;
case VK_IMAGE_TYPE_2D:
return VK_IMAGE_VIEW_TYPE_2D;
case VK_IMAGE_TYPE_3D:
return VK_IMAGE_VIEW_TYPE_3D;
default:
break;
}
// Default to 2D image view.
return VK_IMAGE_VIEW_TYPE_2D;
}
Result TransferImage::CreateVkImageView(VkImageAspectFlags aspect) {
VkImageViewCreateInfo image_view_info = VkImageViewCreateInfo();
image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_info.image = image_;
image_view_info.viewType = GetImageViewType();
image_view_info.format = image_info_.format;
image_view_info.components = {
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A,
};
image_view_info.subresourceRange = {
aspect, /* aspectMask */
base_mip_level_, /* baseMipLevel */
used_mip_levels_, /* levelCount */
0, /* baseArrayLayer */
1, /* layerCount */
};
if (device_->GetPtrs()->vkCreateImageView(device_->GetVkDevice(),
&image_view_info, nullptr,
&view_) != VK_SUCCESS) {
return Result("Vulkan::Calling vkCreateImageView Fail");
}
return {};
}
VkBufferImageCopy TransferImage::CreateBufferImageCopy(
VkImageAspectFlags aspect,
uint32_t mip_level) {
VkBufferImageCopy copy_region = VkBufferImageCopy();
if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT) {
// Store stencil data at the end of the buffer after depth data.
copy_region.bufferOffset =
GetSizeInBytes() - image_info_.extent.width * image_info_.extent.height;
} else {
copy_region.bufferOffset = 0;
}
// Row length of 0 results in tight packing of rows, so the row stride
// is the number of texels times the texel stride.
copy_region.bufferRowLength = 0;
copy_region.bufferImageHeight = 0;
copy_region.imageSubresource = {
aspect, /* aspectMask */
mip_level, /* mipLevel */
0, /* baseArrayLayer */
1, /* layerCount */
};
copy_region.imageOffset = {0, 0, 0};
copy_region.imageExtent = {image_info_.extent.width >> mip_level,
image_info_.extent.height >> mip_level,
image_info_.extent.depth};
return copy_region;
}
void TransferImage::CopyToHost(CommandBuffer* command_buffer) {
const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_ASPECT_DEPTH_BIT,
VK_IMAGE_ASPECT_STENCIL_BIT};
// Copy operations don't support multisample images.
if (samples_ > 1)
return;
std::vector<VkBufferImageCopy> copy_regions;
uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS
? mip_levels_
: base_mip_level_ + used_mip_levels_;
for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {
for (auto aspect : aspects) {
if (aspect_ & aspect) {
copy_regions.push_back(CreateBufferImageCopy(aspect, i));
}
}
}
device_->GetPtrs()->vkCmdCopyImageToBuffer(
command_buffer->GetVkCommandBuffer(), image_,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, host_accessible_buffer_,
static_cast<uint32_t>(copy_regions.size()), copy_regions.data());
MemoryBarrier(command_buffer);
}
void TransferImage::CopyToDevice(CommandBuffer* command_buffer) {
// Copy operations don't support multisample images.
if (samples_ > 1)
return;
const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,
VK_IMAGE_ASPECT_DEPTH_BIT,
VK_IMAGE_ASPECT_STENCIL_BIT};
std::vector<VkBufferImageCopy> copy_regions;
uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS
? mip_levels_
: base_mip_level_ + used_mip_levels_;
for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {
for (auto aspect : aspects) {
if (aspect_ & aspect) {
copy_regions.push_back(CreateBufferImageCopy(aspect, i));
}
}
}
device_->GetPtrs()->vkCmdCopyBufferToImage(
command_buffer->GetVkCommandBuffer(), host_accessible_buffer_, image_,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
static_cast<uint32_t>(copy_regions.size()), copy_regions.data());
MemoryBarrier(command_buffer);
}
void TransferImage::ImageBarrier(CommandBuffer* command_buffer,
VkImageLayout to_layout,
VkPipelineStageFlags to_stage) {
if (to_layout == layout_ && to_stage == stage_)
return;
VkImageMemoryBarrier barrier = VkImageMemoryBarrier();
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = layout_;
barrier.newLayout = to_layout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image_;
barrier.subresourceRange = {
aspect_, /* aspectMask */
0, /* baseMipLevel */
VK_REMAINING_MIP_LEVELS, /* levelCount */
0, /* baseArrayLayer */
1, /* layerCount */
};
switch (layout_) {
case VK_IMAGE_LAYOUT_PREINITIALIZED:
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
default:
barrier.srcAccessMask = 0;
break;
}
switch (to_layout) {
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
default:
barrier.dstAccessMask = 0;
break;
}
device_->GetPtrs()->vkCmdPipelineBarrier(command_buffer->GetVkCommandBuffer(),
stage_, to_stage, 0, 0, NULL, 0,
NULL, 1, &barrier);
layout_ = to_layout;
stage_ = to_stage;
}
Result TransferImage::AllocateAndBindMemoryToVkImage(
VkImage image,
VkDeviceMemory* memory,
VkMemoryPropertyFlags flags,
bool force_flags,
uint32_t* memory_type_index) {
if (memory_type_index == nullptr) {
return Result(
"Vulkan: TransferImage::AllocateAndBindMemoryToVkImage "
"memory_type_index is "
"nullptr");
}
*memory_type_index = 0;
if (image == VK_NULL_HANDLE)
return Result("Vulkan::Given VkImage is VK_NULL_HANDLE");
if (memory == nullptr)
return Result("Vulkan::Given VkDeviceMemory pointer is nullptr");
VkMemoryRequirements requirement;
device_->GetPtrs()->vkGetImageMemoryRequirements(device_->GetVkDevice(),
image, &requirement);
*memory_type_index =
ChooseMemory(requirement.memoryTypeBits, flags, force_flags);
if (*memory_type_index == std::numeric_limits<uint32_t>::max())
return Result("Vulkan::Find Proper Memory Fail");
Result r = AllocateMemory(memory, requirement.size, *memory_type_index);
if (!r.IsSuccess())
return r;
if (device_->GetPtrs()->vkBindImageMemory(device_->GetVkDevice(), image,
*memory, 0) != VK_SUCCESS) {
return Result("Vulkan::Calling vkBindImageMemory Fail");
}
return {};
}
} // namespace vulkan
} // namespace amber
<|endoftext|>
|
<commit_before>//
// yas_audio_rendering_connection.cpp
//
#include "yas_audio_rendering_connection.h"
#include "yas_audio_rendering_node.h"
using namespace yas;
audio::rendering_connection::rendering_connection(uint32_t const src_bus_idx, rendering_node const *const src_node,
audio::format const format)
: source_bus_idx(src_bus_idx), source_node(src_node), format(std::move(format)) {
}
bool audio::rendering_connection::render(audio::pcm_buffer *const buffer, audio::time const &time) const {
if (buffer->format() != this->format) {
return false;
}
this->source_node->render_handler()({.buffer = buffer,
.bus_idx = this->source_bus_idx,
.time = time,
.source_connections = this->source_node->source_connections()});
return true;
}
<commit_msg>fix connection<commit_after>//
// yas_audio_rendering_connection.cpp
//
#include "yas_audio_rendering_connection.h"
#include "yas_audio_rendering_node.h"
using namespace yas;
audio::rendering_connection::rendering_connection(uint32_t const src_bus_idx, rendering_node const *const src_node,
audio::format const format)
: source_bus_idx(src_bus_idx), source_node(src_node), format(std::move(format)) {
}
bool audio::rendering_connection::render(audio::pcm_buffer *const buffer, audio::time const &time) const {
if (buffer->format() != this->format) {
return false;
}
if (!this->source_node) {
return false;
}
this->source_node->render_handler()({.buffer = buffer,
.bus_idx = this->source_bus_idx,
.time = time,
.source_connections = this->source_node->source_connections()});
return true;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Standard file manager
//==============================================================================
#include "corecliutils.h"
#include "filemanager.h"
#include "standardfilemanager.h"
#include "standardsupportplugin.h"
//==============================================================================
namespace OpenCOR {
namespace StandardSupport {
//==============================================================================
StandardFileManager::StandardFileManager() :
mFiles(Files())
{
// Create some connections to keep track of some events related to our
// 'global' file manager
Core::FileManager *fileManagerInstance = Core::FileManager::instance();
connect(fileManagerInstance, SIGNAL(fileManaged(const QString &)),
this, SLOT(manageFile(const QString &)));
connect(fileManagerInstance, SIGNAL(fileUnmanaged(const QString &)),
this, SLOT(unmanageFile(const QString &)));
connect(fileManagerInstance, SIGNAL(fileReloaded(const QString &)),
this, SLOT(reloadFile(const QString &)));
connect(fileManagerInstance, SIGNAL(fileRenamed(const QString &, const QString &)),
this, SLOT(renameFile(const QString &, const QString &)));
}
//==============================================================================
StandardFileManager::~StandardFileManager()
{
// Remove all the managed files
foreach (QObject *file, mFiles)
delete file;
}
//==============================================================================
bool StandardFileManager::isFile(const QString &pFileName)
{
// If the given file is already managed, then we consider that it's of the
// right type (e.g. CellML file), even though it may not be of the right
// type anymore after having been edited and saved, but in this case it's
// good to keep considering the file as of the right type, so that the user
// can continue editing it without any problem, for example
QString nativeFileName = Core::nativeCanonicalFileName(pFileName);
if (file(nativeFileName))
return true;
// The given file is not managed, so do the following:
// - Check whether it is a text file and consider it of the right type if,
// after having been trimmed, it is empty, or check whether it can be
// loaded
// - Check whether it is a binary file and consider it of the right type if
// it can be loaded
// - Consider the file of the right type if it is new
if (Core::isTextFile(nativeFileName)) {
QByteArray fileContents;
if (Core::readFileContentsFromFile(nativeFileName, fileContents)) {
if (fileContents.trimmed().isEmpty())
return true;
return canLoadFile(nativeFileName);
} else {
return false;
}
} else if (canLoadFile(nativeFileName)) {
return true;
} else {
return Core::FileManager::instance()->isNew(nativeFileName);
}
}
//==============================================================================
QObject * StandardFileManager::file(const QString &pFileName)
{
// Return the File object, if any, associated with the given file
return mFiles.value(Core::nativeCanonicalFileName(pFileName));
}
//==============================================================================
void StandardFileManager::manageFile(const QString &pFileName)
{
QString nativeFileName = Core::nativeCanonicalFileName(pFileName);
if (!file(nativeFileName) && isFile(nativeFileName)) {
// We are dealing with a file, which is not already managed, so we can
// add it to our list of managed files
mFiles.insert(nativeFileName, newFile(nativeFileName));
}
}
//==============================================================================
void StandardFileManager::unmanageFile(const QString &pFileName)
{
QObject *crtFile = file(pFileName);
if (crtFile) {
// We are dealing with a file, so we can remove it from our list of
// managed files after having deleted it
delete crtFile;
mFiles.remove(Core::nativeCanonicalFileName(pFileName));
}
}
//==============================================================================
void StandardFileManager::reloadFile(const QString &pFileName)
{
// The file is to be reloaded, so reload it
// Note: to reload a file here ensures that our different standard-based
// views won't each do it, thus saving time and ensuring that a
// standard-based view doesn't forget to do it...
QObject *crtFile = file(pFileName);
if (crtFile) {
// The file is managed, but should it still be (i.e. can it still be
// considered as being a file)?
if (isFile(pFileName))
static_cast<StandardFile *>(crtFile)->reload();
else
unmanageFile(pFileName);
} else {
// The file is not managed, which means that previously it wasn't
// considered as being a file, but things may be different now, so try
// to remanage it and load it, if possible
manageFile(pFileName);
crtFile = file(pFileName);
if (crtFile)
static_cast<StandardFile *>(crtFile)->load();
}
}
//==============================================================================
void StandardFileManager::renameFile(const QString &pOldFileName,
const QString &pNewFileName)
{
// The file has been renamed, so we need to update our files mapping, if
// needed
QObject *crtFile = file(pOldFileName);
if (!crtFile)
return;
mFiles.insert(pNewFileName, crtFile);
mFiles.remove(pOldFileName);
// We also need to ensure that our file object has its file name updated
static_cast<StandardFile *>(crtFile)->setFileName(pNewFileName);
}
//==============================================================================
} // namespace StandardSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Standard file manager: revised StandardFileManager::isFile() so that it doesn't consider new files being necessarily of the right type (useful when duplicating a file) [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Standard file manager
//==============================================================================
#include "corecliutils.h"
#include "filemanager.h"
#include "standardfilemanager.h"
#include "standardsupportplugin.h"
//==============================================================================
namespace OpenCOR {
namespace StandardSupport {
//==============================================================================
StandardFileManager::StandardFileManager() :
mFiles(Files())
{
// Create some connections to keep track of some events related to our
// 'global' file manager
Core::FileManager *fileManagerInstance = Core::FileManager::instance();
connect(fileManagerInstance, SIGNAL(fileManaged(const QString &)),
this, SLOT(manageFile(const QString &)));
connect(fileManagerInstance, SIGNAL(fileUnmanaged(const QString &)),
this, SLOT(unmanageFile(const QString &)));
connect(fileManagerInstance, SIGNAL(fileReloaded(const QString &)),
this, SLOT(reloadFile(const QString &)));
connect(fileManagerInstance, SIGNAL(fileRenamed(const QString &, const QString &)),
this, SLOT(renameFile(const QString &, const QString &)));
}
//==============================================================================
StandardFileManager::~StandardFileManager()
{
// Remove all the managed files
foreach (QObject *file, mFiles)
delete file;
}
//==============================================================================
bool StandardFileManager::isFile(const QString &pFileName)
{
// If the given file is already managed, then we consider that it's of the
// right type (e.g. CellML file), even though it may not be of the right
// type anymore after having been edited and saved, but in this case it's
// good to keep considering the file as of the right type, so that the user
// can continue editing it without any problem, for example
QString nativeFileName = Core::nativeCanonicalFileName(pFileName);
if (file(nativeFileName))
return true;
// The given file is not managed, so consider it of the right type if it is
// an empty file (after having been trimmed) or it can be loaded
QByteArray fileContents;
if (Core::readFileContentsFromFile(nativeFileName, fileContents)) {
if (fileContents.trimmed().isEmpty())
return true;
return canLoadFile(nativeFileName);
} else {
return false;
}
}
//==============================================================================
QObject * StandardFileManager::file(const QString &pFileName)
{
// Return the File object, if any, associated with the given file
return mFiles.value(Core::nativeCanonicalFileName(pFileName));
}
//==============================================================================
void StandardFileManager::manageFile(const QString &pFileName)
{
QString nativeFileName = Core::nativeCanonicalFileName(pFileName);
if (!file(nativeFileName) && isFile(nativeFileName)) {
// We are dealing with a file, which is not already managed, so we can
// add it to our list of managed files
mFiles.insert(nativeFileName, newFile(nativeFileName));
}
}
//==============================================================================
void StandardFileManager::unmanageFile(const QString &pFileName)
{
QObject *crtFile = file(pFileName);
if (crtFile) {
// We are dealing with a file, so we can remove it from our list of
// managed files after having deleted it
delete crtFile;
mFiles.remove(Core::nativeCanonicalFileName(pFileName));
}
}
//==============================================================================
void StandardFileManager::reloadFile(const QString &pFileName)
{
// The file is to be reloaded, so reload it
// Note: to reload a file here ensures that our different standard-based
// views won't each do it, thus saving time and ensuring that a
// standard-based view doesn't forget to do it...
QObject *crtFile = file(pFileName);
if (crtFile) {
// The file is managed, but should it still be (i.e. can it still be
// considered as being a file)?
if (isFile(pFileName))
static_cast<StandardFile *>(crtFile)->reload();
else
unmanageFile(pFileName);
} else {
// The file is not managed, which means that previously it wasn't
// considered as being a file, but things may be different now, so try
// to remanage it and load it, if possible
manageFile(pFileName);
crtFile = file(pFileName);
if (crtFile)
static_cast<StandardFile *>(crtFile)->load();
}
}
//==============================================================================
void StandardFileManager::renameFile(const QString &pOldFileName,
const QString &pNewFileName)
{
// The file has been renamed, so we need to update our files mapping, if
// needed
QObject *crtFile = file(pOldFileName);
if (!crtFile)
return;
mFiles.insert(pNewFileName, crtFile);
mFiles.remove(pOldFileName);
// We also need to ensure that our file object has its file name updated
static_cast<StandardFile *>(crtFile)->setFileName(pNewFileName);
}
//==============================================================================
} // namespace StandardSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: expftext.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:34:19 $
*
* 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 _SC_EXPFTEXT_HXX
#define _SC_EXPFTEXT_HXX
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
class SC_DLLPUBLIC ScExpandedFixedText: public FixedText
{
protected:
void RequestHelp( const HelpEvent& rHEvt );
public:
ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);
ScExpandedFixedText( Window* pWindow, const ResId& rResId);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.346); FILE MERGED 2005/09/05 15:05:20 rt 1.2.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: expftext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:24:30 $
*
* 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_EXPFTEXT_HXX
#define _SC_EXPFTEXT_HXX
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
class SC_DLLPUBLIC ScExpandedFixedText: public FixedText
{
protected:
void RequestHelp( const HelpEvent& rHEvt );
public:
ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);
ScExpandedFixedText( Window* pWindow, const ResId& rResId);
};
#endif
<|endoftext|>
|
<commit_before>#ifndef _FDSB_NID_
#define _FDSB_NID_
namespace fdsb
{
/**
* Node Identifier Plain Old Data type.
*/
struct Nid
{
enum struct Type : unsigned char
{
special,
integer,
real,
character,
allocated,
};
enum struct Special : unsigned long long
{
null,
bool_true,
bool_false,
};
Type t;
union
{
unsigned long long v;
double vd;
};
/** Generate a new unique node id. */
static Nid unique();
};
constexpr Nid operator"" _nid(unsigned long long v)
{
return {Nid::Type::integer, { .v = v }};
}
constexpr Nid operator"" _nid(long double v)
{
return {Nid::Type::real, { .vd = v }};
}
constexpr Nid operator"" _nid(char v)
{
return {Nid::Type::character, { .v = v }};
}
constexpr Nid null_nid = {Nid::Type::special,Nid::Special::null};
constexpr Nid true_nid = {Nid::Type::special,Nid::Special::bool_true};
constexpr Nid false_nid = {Nid::Type::special,Nid::Special::bool_false};
};
#endif
<commit_msg>Minor rename, attempting to fix compiler crash<commit_after>#ifndef _FDSB_NID_
#define _FDSB_NID_
namespace fdsb
{
/**
* Node Identifier Plain Old Data type.
*/
struct Nid
{
enum struct Type : unsigned char
{
special,
integer,
real,
character,
allocated,
};
enum struct Special : unsigned long long
{
null,
bool_true,
bool_false,
};
Type t;
union
{
unsigned long long i;
double d;
};
/** Generate a new unique node id. */
static Nid unique();
};
constexpr Nid operator"" _nid(unsigned long long v)
{
return Nid{Nid::Type::integer, { .i = v }};
}
constexpr Nid operator"" _nid(long double v)
{
return Nid{Nid::Type::real, { .d = v }};
}
constexpr Nid operator"" _nid(char v)
{
return Nid{Nid::Type::character, { .i = v }};
}
constexpr Nid null_nid = {Nid::Type::special,Nid::Special::null};
constexpr Nid true_nid = {Nid::Type::special,Nid::Special::bool_true};
constexpr Nid false_nid = {Nid::Type::special,Nid::Special::bool_false};
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: shtabdlg.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: dr $ $Date: 2002-10-02 14:59:25 $
*
* 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 SC_SHTABDLG_HXX
#define SC_SHTABDLG_HXX
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef SVTOOLS_TOOLTIPLBOX_HXX
#include <svtools/tooltiplbox.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
//------------------------------------------------------------------------
class ScShowTabDlg : public ModalDialog
{
private:
::svtools::ToolTipMultiListBox aLb;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
FixedText aFtLbTitle;
DECL_LINK( DblClkHdl, void * );
public:
ScShowTabDlg( Window* pParent );
~ScShowTabDlg();
/** Sets dialog title, fixed text for listbox and help IDs. */
void SetDescription(
const String& rTitle, const String& rFixedText,
ULONG nDlgHelpId, ULONG nLbHelpId );
/** Inserts a string into the ListBox. */
void Insert( const String& rString, BOOL bSelected );
USHORT GetSelectEntryCount() const;
String GetSelectEntry(USHORT nPos) const;
USHORT GetSelectEntryPos(USHORT nPos) const;
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.898); FILE MERGED 2005/09/05 15:05:48 rt 1.3.898.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shtabdlg.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:50:01 $
*
* 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_SHTABDLG_HXX
#define SC_SHTABDLG_HXX
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef SVTOOLS_TOOLTIPLBOX_HXX
#include <svtools/tooltiplbox.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
//------------------------------------------------------------------------
class ScShowTabDlg : public ModalDialog
{
private:
::svtools::ToolTipMultiListBox aLb;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
FixedText aFtLbTitle;
DECL_LINK( DblClkHdl, void * );
public:
ScShowTabDlg( Window* pParent );
~ScShowTabDlg();
/** Sets dialog title, fixed text for listbox and help IDs. */
void SetDescription(
const String& rTitle, const String& rFixedText,
ULONG nDlgHelpId, ULONG nLbHelpId );
/** Inserts a string into the ListBox. */
void Insert( const String& rString, BOOL bSelected );
USHORT GetSelectEntryCount() const;
String GetSelectEntry(USHORT nPos) const;
USHORT GetSelectEntryPos(USHORT nPos) const;
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: undobase.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: nn $ $Date: 2002-10-09 10:58:13 $
*
* 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 SC_UNDOBASE_HXX
#define SC_UNDOBASE_HXX
#ifndef _UNDO_HXX //autogen
#include <svtools/undo.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
class ScDocument;
class ScDocShell;
class SdrUndoAction;
class ScRefUndoData;
//----------------------------------------------------------------------------
class ScSimpleUndo: public SfxUndoAction
{
public:
TYPEINFO();
ScSimpleUndo( ScDocShell* pDocSh );
virtual ~ScSimpleUndo();
virtual BOOL Merge( SfxUndoAction *pNextAction );
protected:
ScDocShell* pDocShell;
SfxUndoAction* pDetectiveUndo;
void BeginUndo();
void EndUndo();
void BeginRedo();
void EndRedo();
static void ShowTable( USHORT nTab );
static void ShowTable( const ScRange& rRange );
};
//----------------------------------------------------------------------------
enum ScBlockUndoMode { SC_UNDO_SIMPLE, SC_UNDO_MANUALHEIGHT, SC_UNDO_AUTOHEIGHT };
class ScBlockUndo: public ScSimpleUndo
{
public:
TYPEINFO();
ScBlockUndo( ScDocShell* pDocSh, const ScRange& rRange,
ScBlockUndoMode eBlockMode );
virtual ~ScBlockUndo();
protected:
ScRange aBlockRange;
SdrUndoAction* pDrawUndo;
ScBlockUndoMode eMode;
void BeginUndo();
void EndUndo();
// void BeginRedo();
void EndRedo();
BOOL AdjustHeight();
void ShowBlock();
};
//----------------------------------------------------------------------------
enum ScMoveUndoMode { SC_UNDO_REFFIRST, SC_UNDO_REFLAST };
class ScMoveUndo: public ScSimpleUndo // mit Referenzen
{
public:
TYPEINFO();
ScMoveUndo( ScDocShell* pDocSh,
ScDocument* pRefDoc, ScRefUndoData* pRefData,
ScMoveUndoMode eRefMode );
virtual ~ScMoveUndo();
protected:
SdrUndoAction* pDrawUndo;
ScDocument* pRefUndoDoc;
ScRefUndoData* pRefUndoData;
ScMoveUndoMode eMode;
void BeginUndo();
void EndUndo();
// void BeginRedo();
// void EndRedo();
private:
void UndoRef();
};
//----------------------------------------------------------------------------
class ScUndoWrapper: public SfxUndoAction // for manual merging of actions
{
SfxUndoAction* pWrappedUndo;
public:
TYPEINFO();
ScUndoWrapper( SfxUndoAction* pUndo );
virtual ~ScUndoWrapper();
SfxUndoAction* GetWrappedUndo() { return pWrappedUndo; }
void ForgetWrappedUndo();
virtual BOOL IsLinked();
virtual void SetLinked( BOOL bIsLinked );
virtual void Undo();
virtual void Redo();
virtual void Repeat(SfxRepeatTarget& rTarget);
virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;
virtual BOOL Merge( SfxUndoAction *pNextAction );
virtual String GetComment() const;
virtual String GetRepeatComment(SfxRepeatTarget&) const;
virtual USHORT GetId() const;
};
#endif
<commit_msg>INTEGRATION: CWS rowlimit (1.2.302); FILE MERGED 2004/01/13 20:04:46 er 1.2.302.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003/11/28 19:48:03 er 1.2.302.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/*************************************************************************
*
* $RCSfile: undobase.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:43:57 $
*
* 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 SC_UNDOBASE_HXX
#define SC_UNDOBASE_HXX
#ifndef _UNDO_HXX //autogen
#include <svtools/undo.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
class ScDocument;
class ScDocShell;
class SdrUndoAction;
class ScRefUndoData;
//----------------------------------------------------------------------------
class ScSimpleUndo: public SfxUndoAction
{
public:
TYPEINFO();
ScSimpleUndo( ScDocShell* pDocSh );
virtual ~ScSimpleUndo();
virtual BOOL Merge( SfxUndoAction *pNextAction );
protected:
ScDocShell* pDocShell;
SfxUndoAction* pDetectiveUndo;
void BeginUndo();
void EndUndo();
void BeginRedo();
void EndRedo();
static void ShowTable( SCTAB nTab );
static void ShowTable( const ScRange& rRange );
};
//----------------------------------------------------------------------------
enum ScBlockUndoMode { SC_UNDO_SIMPLE, SC_UNDO_MANUALHEIGHT, SC_UNDO_AUTOHEIGHT };
class ScBlockUndo: public ScSimpleUndo
{
public:
TYPEINFO();
ScBlockUndo( ScDocShell* pDocSh, const ScRange& rRange,
ScBlockUndoMode eBlockMode );
virtual ~ScBlockUndo();
protected:
ScRange aBlockRange;
SdrUndoAction* pDrawUndo;
ScBlockUndoMode eMode;
void BeginUndo();
void EndUndo();
// void BeginRedo();
void EndRedo();
BOOL AdjustHeight();
void ShowBlock();
};
//----------------------------------------------------------------------------
enum ScMoveUndoMode { SC_UNDO_REFFIRST, SC_UNDO_REFLAST };
class ScMoveUndo: public ScSimpleUndo // mit Referenzen
{
public:
TYPEINFO();
ScMoveUndo( ScDocShell* pDocSh,
ScDocument* pRefDoc, ScRefUndoData* pRefData,
ScMoveUndoMode eRefMode );
virtual ~ScMoveUndo();
protected:
SdrUndoAction* pDrawUndo;
ScDocument* pRefUndoDoc;
ScRefUndoData* pRefUndoData;
ScMoveUndoMode eMode;
void BeginUndo();
void EndUndo();
// void BeginRedo();
// void EndRedo();
private:
void UndoRef();
};
//----------------------------------------------------------------------------
class ScUndoWrapper: public SfxUndoAction // for manual merging of actions
{
SfxUndoAction* pWrappedUndo;
public:
TYPEINFO();
ScUndoWrapper( SfxUndoAction* pUndo );
virtual ~ScUndoWrapper();
SfxUndoAction* GetWrappedUndo() { return pWrappedUndo; }
void ForgetWrappedUndo();
virtual BOOL IsLinked();
virtual void SetLinked( BOOL bIsLinked );
virtual void Undo();
virtual void Redo();
virtual void Repeat(SfxRepeatTarget& rTarget);
virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;
virtual BOOL Merge( SfxUndoAction *pNextAction );
virtual String GetComment() const;
virtual String GetRepeatComment(SfxRepeatTarget&) const;
virtual USHORT GetId() const;
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/source/event_win.h"
#include "Mmsystem.h"
namespace webrtc {
EventWindows::EventWindows()
: event_(::CreateEvent(NULL, // security attributes
FALSE, // manual reset
FALSE, // initial state
NULL)), // name of event
timerID_(NULL) {
}
EventWindows::~EventWindows() {
CloseHandle(event_);
}
bool EventWindows::Set() {
// Note: setting an event that is already set has no effect.
return SetEvent(event_) == 1 ? true : false;
}
bool EventWindows::Reset() {
return ResetEvent(event_) == 1 ? true : false;
}
EventTypeWrapper EventWindows::Wait(unsigned long max_time) {
unsigned long res = WaitForSingleObject(event_, max_time);
switch (res) {
case WAIT_OBJECT_0:
return kEventSignaled;
case WAIT_TIMEOUT:
return kEventTimeout;
default:
return kEventError;
}
}
bool EventWindows::StartTimer(bool periodic, unsigned long time) {
if (timerID_ != NULL) {
timeKillEvent(timerID_);
timerID_ = NULL;
}
if (periodic) {
timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
TIME_PERIODIC | TIME_CALLBACK_EVENT_PULSE);
} else {
timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
}
if (timerID_ == NULL) {
return false;
}
return true;
}
bool EventWindows::StopTimer() {
timeKillEvent(timerID_);
timerID_ = NULL;
return true;
}
} // namespace webrtc
<commit_msg>Stop timer in ~EventWindows().<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/source/event_win.h"
#include "Mmsystem.h"
namespace webrtc {
EventWindows::EventWindows()
: event_(::CreateEvent(NULL, // security attributes
FALSE, // manual reset
FALSE, // initial state
NULL)), // name of event
timerID_(NULL) {
}
EventWindows::~EventWindows() {
StopTimer();
CloseHandle(event_);
}
bool EventWindows::Set() {
// Note: setting an event that is already set has no effect.
return SetEvent(event_) == 1;
}
bool EventWindows::Reset() {
return ResetEvent(event_) == 1;
}
EventTypeWrapper EventWindows::Wait(unsigned long max_time) {
unsigned long res = WaitForSingleObject(event_, max_time);
switch (res) {
case WAIT_OBJECT_0:
return kEventSignaled;
case WAIT_TIMEOUT:
return kEventTimeout;
default:
return kEventError;
}
}
bool EventWindows::StartTimer(bool periodic, unsigned long time) {
if (timerID_ != NULL) {
timeKillEvent(timerID_);
timerID_ = NULL;
}
if (periodic) {
timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
TIME_PERIODIC | TIME_CALLBACK_EVENT_PULSE);
} else {
timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
}
return timerID_ != NULL;
}
bool EventWindows::StopTimer() {
if (timerID_ != NULL) {
timeKillEvent(timerID_);
timerID_ = NULL;
}
return true;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
#include "CursorResourceLinux.h"
#include "core/Engine.h"
#include "core/linux/WindowLinux.h"
#include "utils/Log.h"
namespace ouzel
{
namespace input
{
CursorResourceLinux::~CursorResourceLinux()
{
if (sharedEngine)
{
WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
Display* display = windowLinux->getDisplay();
if (cursor != None) XFreeCursor(display, cursor);
}
}
bool CursorResourceLinux::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
if (sharedEngine)
{
WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
Display* display = windowLinux->getDisplay();
if (cursor != None)
{
XFreeCursor(display, cursor);
cursor = None;
}
if (data.empty())
{
switch (systemCursor)
{
case SystemCursor::DEFAULT:
cursor = XcursorLibraryLoadCursor(display, "arrow");
break;
case SystemCursor::ARROW:
cursor = XcursorLibraryLoadCursor(display, "arrow");
break;
case SystemCursor::HAND:
cursor = XcursorLibraryLoadCursor(display, "hand1");
break;
case SystemCursor::HORIZONTAL_RESIZE:
cursor = XcursorLibraryLoadCursor(display, "sb_h_double_arrow");
break;
case SystemCursor::VERTICAL_RESIZE:
cursor = XcursorLibraryLoadCursor(display, "sb_v_double_arrow");
break;
case SystemCursor::CROSS:
cursor = XcursorLibraryLoadCursor(display, "crosshair");
break;
case SystemCursor::I_BEAM:
cursor = XcursorLibraryLoadCursor(display, "xterm");
break;
}
}
else
{
int width = static_cast<int>(size.v[0]);
int height = static_cast<int>(size.v[1]);
XcursorImage* cursorImage = XcursorImageCreate(width, height);
if (!cursorImage)
{
Log(Log::Level::ERR) << "Failed to create cursor image";
return false;
}
cursorImage->xhot = static_cast<int>(hotSpot.v[0]);
cursorImage->yhot = height - static_cast<int>(hotSpot.v[1]) - 1;
cursorImage->delay = 0;
unsigned char* target = reinterpret_cast<unsigned char*>(cursorImage->pixels);
for (int i = 0; i < width * height; ++i)
{
target[i * 4 + 0] = data[i * 4 + 3];
target[i * 4 + 1] = data[i * 4 + 0];
target[i * 4 + 2] = data[i * 4 + 1];
target[i * 4 + 3] = data[i * 4 + 2];
}
cursor = XcursorImageLoadCursor(display, cursorImage);
XcursorImageDestroy(cursorImage);
}
}
dirty = false;
}
return true;
}
} // namespace input
} // namespace ouzel
<commit_msg>Reverse pixel byte order<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
#include "CursorResourceLinux.h"
#include "core/Engine.h"
#include "core/linux/WindowLinux.h"
#include "utils/Log.h"
namespace ouzel
{
namespace input
{
CursorResourceLinux::~CursorResourceLinux()
{
if (sharedEngine)
{
WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
Display* display = windowLinux->getDisplay();
if (cursor != None) XFreeCursor(display, cursor);
}
}
bool CursorResourceLinux::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
if (sharedEngine)
{
WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
Display* display = windowLinux->getDisplay();
if (cursor != None)
{
XFreeCursor(display, cursor);
cursor = None;
}
if (data.empty())
{
switch (systemCursor)
{
case SystemCursor::DEFAULT:
cursor = XcursorLibraryLoadCursor(display, "arrow");
break;
case SystemCursor::ARROW:
cursor = XcursorLibraryLoadCursor(display, "arrow");
break;
case SystemCursor::HAND:
cursor = XcursorLibraryLoadCursor(display, "hand1");
break;
case SystemCursor::HORIZONTAL_RESIZE:
cursor = XcursorLibraryLoadCursor(display, "sb_h_double_arrow");
break;
case SystemCursor::VERTICAL_RESIZE:
cursor = XcursorLibraryLoadCursor(display, "sb_v_double_arrow");
break;
case SystemCursor::CROSS:
cursor = XcursorLibraryLoadCursor(display, "crosshair");
break;
case SystemCursor::I_BEAM:
cursor = XcursorLibraryLoadCursor(display, "xterm");
break;
}
}
else
{
int width = static_cast<int>(size.v[0]);
int height = static_cast<int>(size.v[1]);
XcursorImage* cursorImage = XcursorImageCreate(width, height);
if (!cursorImage)
{
Log(Log::Level::ERR) << "Failed to create cursor image";
return false;
}
cursorImage->xhot = static_cast<int>(hotSpot.v[0]);
cursorImage->yhot = height - static_cast<int>(hotSpot.v[1]) - 1;
cursorImage->delay = 0;
unsigned char* target = reinterpret_cast<unsigned char*>(cursorImage->pixels);
for (int i = 0; i < width * height; ++i)
{
target[i * 4 + 0] = data[i * 4 + 2];
target[i * 4 + 1] = data[i * 4 + 1];
target[i * 4 + 2] = data[i * 4 + 0];
target[i * 4 + 3] = data[i * 4 + 3];
}
cursor = XcursorImageLoadCursor(display, cursorImage);
XcursorImageDestroy(cursorImage);
}
}
dirty = false;
}
return true;
}
} // namespace input
} // namespace ouzel
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the matroska parser
// library, which allows clients to handle a matroska format file.
#include "mkvreader.hpp"
#include "mkvparser.hpp"
static const wchar_t* utf8towcs(const char* str)
{
if (str == NULL)
return NULL;
//TODO: this probably requires that the locale be
//configured somehow:
const size_t size = mbstowcs(NULL, str, 0);
if (size == 0)
return NULL;
wchar_t* const val = new wchar_t[size+1];
mbstowcs(val, str, size);
val[size] = L'\0';
return val;
}
int main(int argc, char* argv[])
{
if (argc == 1)
{
printf("\t\t\tMkv Parser Sample Application\n");
printf("\t\t\tUsage: \n");
printf("\t\t\t ./sample [input file] \n");
printf("\t\t\t ./sample sample.mkv \n");
return -1;
}
using namespace mkvparser;
MkvReader reader;
if (reader.Open(argv[1]))
{
printf("\n Filename is invalid or error while opening.\n");
return -1;
}
int maj, min, build, rev;
GetVersion(maj, min, build, rev);
printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);
long long pos = 0;
EBMLHeader ebmlHeader;
ebmlHeader.Parse(&reader, pos);
printf("\t\t\t EBML Header\n");
printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
printf("\t\tPos\t\t\t: %lld\n", pos);
mkvparser::Segment* pSegment;
long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);
if (ret)
{
printf("\n Segment::CreateInstance() failed.");
return -1;
}
ret = pSegment->Load();
if (ret < 0)
{
printf("\n Segment::Load() failed.");
return -1;
}
const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();
const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
const long long duration_ns = pSegmentInfo->GetDuration();
const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
const wchar_t* const pTitle = utf8towcs(pTitle_);
const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);
const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);
printf("\n");
printf("\t\t\t Segment Info\n");
printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
printf("\t\tDuration\t\t: %lld\n", duration_ns);
const double duration_sec = double(duration_ns) / 1000000000;
printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);
if (pTitle == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else
{
printf("\t\tTrack Name\t\t: %ls\n", pTitle);
delete [] pTitle;
}
if (pMuxingApp == NULL)
printf("\t\tMuxing App\t\t: NULL\n");
else
{
printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
delete [] pMuxingApp;
}
if (pWritingApp == NULL)
printf("\t\tWriting App\t\t: NULL\n");
else
{
printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
delete [] pWritingApp;
}
// pos of segment payload
printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);
// size of segment payload
printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);
mkvparser::Tracks* const pTracks = pSegment->GetTracks();
unsigned long i = 0;
const unsigned long j = pTracks->GetTracksCount();
enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };
printf("\n\t\t\t Track Info\n");
while (i != j)
{
const Track* const pTrack = pTracks->GetTrackByIndex(i++);
if (pTrack == NULL)
continue;
const long long trackType = pTrack->GetType();
const long long trackNumber = pTrack->GetNumber();
const unsigned long long trackUid = pTrack->GetUid();
const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());
printf("\t\tTrack Type\t\t: %lld\n", trackType);
printf("\t\tTrack Number\t\t: %lld\n", trackNumber);
printf("\t\tTrack Uid\t\t: %lld\n", trackUid);
if (pTrackName == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else
{
printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
delete [] pTrackName;
}
const char* const pCodecId = pTrack->GetCodecId();
if (pCodecId == NULL)
printf("\t\tCodec Id\t\t: NULL\n");
else
printf("\t\tCodec Id\t\t: %s\n", pCodecId);
const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
const wchar_t* const pCodecName = utf8towcs(pCodecName_);
if (pCodecName == NULL)
printf("\t\tCodec Name\t\t: NULL\n");
else
{
printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
delete [] pCodecName;
}
if (trackType == VIDEO_TRACK)
{
const VideoTrack* const pVideoTrack =
static_cast<const VideoTrack*>(pTrack);
const long long width = pVideoTrack->GetWidth();
printf("\t\tVideo Width\t\t: %lld\n", width);
const long long height = pVideoTrack->GetHeight();
printf("\t\tVideo Height\t\t: %lld\n", height);
const double rate = pVideoTrack->GetFrameRate();
printf("\t\tVideo Rate\t\t: %f\n",rate);
}
if (trackType == AUDIO_TRACK)
{
const AudioTrack* const pAudioTrack =
static_cast<const AudioTrack*>(pTrack);
const long long channels = pAudioTrack->GetChannels();
printf("\t\tAudio Channels\t\t: %lld\n", channels);
const long long bitDepth = pAudioTrack->GetBitDepth();
printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);
const double sampleRate = pAudioTrack->GetSamplingRate();
printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
}
}
printf("\n\n\t\t\t Cluster Info\n");
const unsigned long clusterCount = pSegment->GetCount();
printf("\t\tCluster Count\t: %ld\n\n", clusterCount);
if (clusterCount == 0)
{
printf("\t\tSegment has no clusters.\n");
delete pSegment;
return -1;
}
const mkvparser::Cluster* pCluster = pSegment->GetFirst();
while ((pCluster != NULL) && !pCluster->EOS())
{
const long long timeCode = pCluster->GetTimeCode();
printf("\t\tCluster Time Code\t: %lld\n", timeCode);
const long long time_ns = pCluster->GetTime();
printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);
const BlockEntry* pBlockEntry = pCluster->GetFirst();
while ((pBlockEntry != NULL) && !pBlockEntry->EOS())
{
const Block* const pBlock = pBlockEntry->GetBlock();
const long long trackNum = pBlock->GetTrackNumber();
const unsigned long tn = static_cast<unsigned long>(trackNum);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
const long long trackType = pTrack->GetType();
const int frameCount = pBlock->GetFrameCount();
const long long time_ns = pBlock->GetTime(pCluster);
printf("\t\t\tBlock\t\t:%s,%s,%15lld\n",
(trackType == VIDEO_TRACK) ? "V" : "A",
pBlock->IsKey() ? "I" : "P",
time_ns);
for (int i = 0; i < frameCount; ++i)
{
const Block::Frame& theFrame = pBlock->GetFrame(i);
const long size = theFrame.len;
const long long offset = theFrame.pos;
printf("\t\t\t %15ld,%15llx\n", size, offset);
}
pBlockEntry = pCluster->GetNext(pBlockEntry);
}
pCluster = pSegment->GetNext(pCluster);
}
delete pSegment;
return 0;
}
<commit_msg>fixed build error in sample<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the matroska parser
// library, which allows clients to handle a matroska format file.
#include "mkvreader.hpp"
#include "mkvparser.hpp"
static const wchar_t* utf8towcs(const char* str)
{
if (str == NULL)
return NULL;
//TODO: this probably requires that the locale be
//configured somehow:
const size_t size = mbstowcs(NULL, str, 0);
if (size == 0)
return NULL;
wchar_t* const val = new wchar_t[size+1];
mbstowcs(val, str, size);
val[size] = L'\0';
return val;
}
int main(int argc, char* argv[])
{
if (argc == 1)
{
printf("\t\t\tMkv Parser Sample Application\n");
printf("\t\t\tUsage: \n");
printf("\t\t\t ./sample [input file] \n");
printf("\t\t\t ./sample sample.mkv \n");
return -1;
}
using namespace mkvparser;
MkvReader reader;
if (reader.Open(argv[1]))
{
printf("\n Filename is invalid or error while opening.\n");
return -1;
}
int maj, min, build, rev;
GetVersion(maj, min, build, rev);
printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);
long long pos = 0;
EBMLHeader ebmlHeader;
ebmlHeader.Parse(&reader, pos);
printf("\t\t\t EBML Header\n");
printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
printf("\t\tPos\t\t\t: %lld\n", pos);
mkvparser::Segment* pSegment;
long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);
if (ret)
{
printf("\n Segment::CreateInstance() failed.");
return -1;
}
ret = pSegment->Load();
if (ret < 0)
{
printf("\n Segment::Load() failed.");
return -1;
}
const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();
const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
const long long duration_ns = pSegmentInfo->GetDuration();
const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
const wchar_t* const pTitle = utf8towcs(pTitle_);
const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);
const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);
printf("\n");
printf("\t\t\t Segment Info\n");
printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
printf("\t\tDuration\t\t: %lld\n", duration_ns);
const double duration_sec = double(duration_ns) / 1000000000;
printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);
if (pTitle == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else
{
printf("\t\tTrack Name\t\t: %ls\n", pTitle);
delete [] pTitle;
}
if (pMuxingApp == NULL)
printf("\t\tMuxing App\t\t: NULL\n");
else
{
printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
delete [] pMuxingApp;
}
if (pWritingApp == NULL)
printf("\t\tWriting App\t\t: NULL\n");
else
{
printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
delete [] pWritingApp;
}
// pos of segment payload
printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);
// size of segment payload
printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);
const mkvparser::Tracks* pTracks = pSegment->GetTracks();
unsigned long i = 0;
const unsigned long j = pTracks->GetTracksCount();
enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };
printf("\n\t\t\t Track Info\n");
while (i != j)
{
const Track* const pTrack = pTracks->GetTrackByIndex(i++);
if (pTrack == NULL)
continue;
const long long trackType = pTrack->GetType();
const long long trackNumber = pTrack->GetNumber();
const unsigned long long trackUid = pTrack->GetUid();
const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());
printf("\t\tTrack Type\t\t: %lld\n", trackType);
printf("\t\tTrack Number\t\t: %lld\n", trackNumber);
printf("\t\tTrack Uid\t\t: %lld\n", trackUid);
if (pTrackName == NULL)
printf("\t\tTrack Name\t\t: NULL\n");
else
{
printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
delete [] pTrackName;
}
const char* const pCodecId = pTrack->GetCodecId();
if (pCodecId == NULL)
printf("\t\tCodec Id\t\t: NULL\n");
else
printf("\t\tCodec Id\t\t: %s\n", pCodecId);
const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
const wchar_t* const pCodecName = utf8towcs(pCodecName_);
if (pCodecName == NULL)
printf("\t\tCodec Name\t\t: NULL\n");
else
{
printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
delete [] pCodecName;
}
if (trackType == VIDEO_TRACK)
{
const VideoTrack* const pVideoTrack =
static_cast<const VideoTrack*>(pTrack);
const long long width = pVideoTrack->GetWidth();
printf("\t\tVideo Width\t\t: %lld\n", width);
const long long height = pVideoTrack->GetHeight();
printf("\t\tVideo Height\t\t: %lld\n", height);
const double rate = pVideoTrack->GetFrameRate();
printf("\t\tVideo Rate\t\t: %f\n",rate);
}
if (trackType == AUDIO_TRACK)
{
const AudioTrack* const pAudioTrack =
static_cast<const AudioTrack*>(pTrack);
const long long channels = pAudioTrack->GetChannels();
printf("\t\tAudio Channels\t\t: %lld\n", channels);
const long long bitDepth = pAudioTrack->GetBitDepth();
printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);
const double sampleRate = pAudioTrack->GetSamplingRate();
printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
}
}
printf("\n\n\t\t\t Cluster Info\n");
const unsigned long clusterCount = pSegment->GetCount();
printf("\t\tCluster Count\t: %ld\n\n", clusterCount);
if (clusterCount == 0)
{
printf("\t\tSegment has no clusters.\n");
delete pSegment;
return -1;
}
const mkvparser::Cluster* pCluster = pSegment->GetFirst();
while ((pCluster != NULL) && !pCluster->EOS())
{
const long long timeCode = pCluster->GetTimeCode();
printf("\t\tCluster Time Code\t: %lld\n", timeCode);
const long long time_ns = pCluster->GetTime();
printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);
const BlockEntry* pBlockEntry = pCluster->GetFirst();
while ((pBlockEntry != NULL) && !pBlockEntry->EOS())
{
const Block* const pBlock = pBlockEntry->GetBlock();
const long long trackNum = pBlock->GetTrackNumber();
const unsigned long tn = static_cast<unsigned long>(trackNum);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
const long long trackType = pTrack->GetType();
const int frameCount = pBlock->GetFrameCount();
const long long time_ns = pBlock->GetTime(pCluster);
printf("\t\t\tBlock\t\t:%s,%s,%15lld\n",
(trackType == VIDEO_TRACK) ? "V" : "A",
pBlock->IsKey() ? "I" : "P",
time_ns);
for (int i = 0; i < frameCount; ++i)
{
const Block::Frame& theFrame = pBlock->GetFrame(i);
const long size = theFrame.len;
const long long offset = theFrame.pos;
printf("\t\t\t %15ld,%15llx\n", size, offset);
}
pBlockEntry = pCluster->GetNext(pBlockEntry);
}
pCluster = pSegment->GetNext(pCluster);
}
delete pSegment;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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 "webkit/glue/plugins/pepper_audio.h"
#include "base/logging.h"
#include "third_party/ppapi/c/dev/ppb_audio_dev.h"
#include "third_party/ppapi/c/dev/ppb_audio_trusted_dev.h"
namespace pepper {
namespace {
// PPB_AudioConfig -------------------------------------------------------------
uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count);
PP_Resource CreateStereo16bit(PP_Module module_id,
PP_AudioSampleRate_Dev sample_rate,
uint32_t sample_frame_count) {
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
// TODO(brettw): Currently we don't actually check what the hardware
// supports, so just allow sample rates of the "guaranteed working" ones.
if (sample_rate != PP_AUDIOSAMPLERATE_44100 &&
sample_rate != PP_AUDIOSAMPLERATE_48000)
return 0;
// TODO(brettw): Currently we don't actually query to get a value from the
// hardware, so just validate the range.
if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count)
return 0;
scoped_refptr<AudioConfig> config(new AudioConfig(module,
sample_rate,
sample_frame_count));
return config->GetReference();
}
uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) {
// TODO(brettw) Currently we don't actually query to get a value from the
// hardware, so we always return the input for in-range values.
if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT)
return PP_AUDIOMINSAMPLEFRAMECOUNT;
if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT)
return PP_AUDIOMAXSAMPLEFRAMECOUNT;
return requested_sample_frame_count;
}
bool IsAudioConfig(PP_Resource resource) {
scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource);
return config;
}
PP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) {
scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE;
}
uint32_t GetSampleFrameCount(PP_Resource config_id) {
scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
return config ? config->sample_frame_count() : 0;
}
const PPB_AudioConfig_Dev ppb_audioconfig = {
&CreateStereo16bit,
&RecommendSampleFrameCount,
&IsAudioConfig,
&GetSampleRate,
&GetSampleFrameCount
};
// PPB_Audio -------------------------------------------------------------------
PP_Resource Create(PP_Instance instance_id, PP_Resource config_id,
PPB_Audio_Callback callback, void* user_data) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return 0;
// TODO(neb): Require callback to be present for untrusted plugins.
scoped_refptr<Audio> audio(new Audio(instance->module()));
if (!audio->Init(instance->delegate(), config_id, callback, user_data))
return 0;
return audio->GetReference();
}
bool IsAudio(PP_Resource resource) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource);
return audio;
}
PP_Resource GetCurrentConfiguration(PP_Resource audio_id) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
return audio ? audio->GetCurrentConfiguration() : 0;
}
bool StartPlayback(PP_Resource audio_id) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
return audio ? audio->StartPlayback() : false;
}
bool StopPlayback(PP_Resource audio_id) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
return audio ? audio->StopPlayback() : false;
}
const PPB_Audio_Dev ppb_audio = {
&Create,
&IsAudio,
&GetCurrentConfiguration,
&StartPlayback,
&StopPlayback,
};
// PPB_AudioTrusted ------------------------------------------------------------
PP_Resource GetBuffer(PP_Resource audio_id) {
// TODO(neb): Implement me!
return 0;
}
int GetOSDescriptor(PP_Resource audio_id) {
// TODO(neb): Implement me!
return -1;
}
const PPB_AudioTrusted_Dev ppb_audiotrusted = {
&GetBuffer,
&GetOSDescriptor
};
} // namespace
// AudioConfig -----------------------------------------------------------------
AudioConfig::AudioConfig(PluginModule* module,
PP_AudioSampleRate_Dev sample_rate,
uint32_t sample_frame_count)
: Resource(module),
sample_rate_(sample_rate),
sample_frame_count_(sample_frame_count) {
}
const PPB_AudioConfig_Dev* AudioConfig::GetInterface() {
return &ppb_audioconfig;
}
size_t AudioConfig::BufferSize() {
// TODO(audio): as more options become available, we'll need to
// have additional code here to correctly calculate the size in
// bytes of an audio buffer. For now, only support two channel
// int16_t sample buffers.
const int kChannels = 2;
const int kSizeOfSample = sizeof(int16_t);
return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels);
}
AudioConfig* AudioConfig::AsAudioConfig() {
return this;
}
// Audio -----------------------------------------------------------------------
Audio::Audio(PluginModule* module)
: Resource(module),
playing_(false),
socket_(NULL),
shared_memory_(NULL),
shared_memory_size_(0),
callback_(NULL),
user_data_(NULL) {
}
Audio::~Audio() {
// Calling ShutDown() makes sure StreamCreated cannot be called anymore.
audio_->ShutDown();
// Closing the socket causes the thread to exit - wait for it.
socket_->Close();
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
// Shared memory destructor will unmap the memory automatically.
}
const PPB_Audio_Dev* Audio::GetInterface() {
return &ppb_audio;
}
const PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() {
return &ppb_audiotrusted;
}
Audio* Audio::AsAudio() {
return this;
}
bool Audio::Init(PluginDelegate* plugin_delegate, PP_Resource config_id,
PPB_Audio_Callback callback, void* user_data) {
CHECK(!audio_.get());
config_ = Resource::GetAs<AudioConfig>(config_id);
if (!config_)
return false;
callback_ = callback;
user_data_ = user_data;
// When the stream is created, we'll get called back in StreamCreated().
audio_.reset(plugin_delegate->CreateAudio(config_->sample_rate(),
config_->sample_frame_count(),
this));
return audio_.get() != NULL;
}
bool Audio::StartPlayback() {
if (playing_)
return true;
CHECK(!audio_thread_.get());
if (callback_ && socket_.get()) {
audio_thread_.reset(new base::DelegateSimpleThread(this,
"plugin_audio_thread"));
audio_thread_->Start();
}
playing_ = true;
return audio_->StartPlayback();
}
bool Audio::StopPlayback() {
if (!playing_)
return true;
if (!audio_->StopPlayback())
return false;
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
playing_ = false;
return true;
}
void Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle,
size_t shared_memory_size,
base::SyncSocket::Handle socket_handle) {
socket_.reset(new base::SyncSocket(socket_handle));
shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
shared_memory_size_ = shared_memory_size;
if (callback_) {
shared_memory_->Map(shared_memory_size_);
// In common case StartPlayback() was called before StreamCreated().
if (playing_) {
audio_thread_.reset(new base::DelegateSimpleThread(this,
"plugin_audio_thread"));
audio_thread_->Start();
}
}
}
void Audio::Run() {
int pending_data;
void* buffer = shared_memory_->memory();
size_t buffer_size_in_bytes = config_->BufferSize();
while (sizeof(pending_data) ==
socket_->Receive(&pending_data, sizeof(pending_data)) &&
pending_data >= 0) {
// Exit the thread on pause.
if (pending_data < 0)
return;
callback_(buffer, buffer_size_in_bytes, user_data_);
}
}
} // namespace pepper
<commit_msg>Fix the build warnings about bool conversion.<commit_after>// Copyright (c) 2010 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 "webkit/glue/plugins/pepper_audio.h"
#include "base/logging.h"
#include "third_party/ppapi/c/dev/ppb_audio_dev.h"
#include "third_party/ppapi/c/dev/ppb_audio_trusted_dev.h"
namespace pepper {
namespace {
// PPB_AudioConfig -------------------------------------------------------------
uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count);
PP_Resource CreateStereo16bit(PP_Module module_id,
PP_AudioSampleRate_Dev sample_rate,
uint32_t sample_frame_count) {
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
// TODO(brettw): Currently we don't actually check what the hardware
// supports, so just allow sample rates of the "guaranteed working" ones.
if (sample_rate != PP_AUDIOSAMPLERATE_44100 &&
sample_rate != PP_AUDIOSAMPLERATE_48000)
return 0;
// TODO(brettw): Currently we don't actually query to get a value from the
// hardware, so just validate the range.
if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count)
return 0;
scoped_refptr<AudioConfig> config(new AudioConfig(module,
sample_rate,
sample_frame_count));
return config->GetReference();
}
uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) {
// TODO(brettw) Currently we don't actually query to get a value from the
// hardware, so we always return the input for in-range values.
if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT)
return PP_AUDIOMINSAMPLEFRAMECOUNT;
if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT)
return PP_AUDIOMAXSAMPLEFRAMECOUNT;
return requested_sample_frame_count;
}
bool IsAudioConfig(PP_Resource resource) {
scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource);
return !!config;
}
PP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) {
scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE;
}
uint32_t GetSampleFrameCount(PP_Resource config_id) {
scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
return config ? config->sample_frame_count() : 0;
}
const PPB_AudioConfig_Dev ppb_audioconfig = {
&CreateStereo16bit,
&RecommendSampleFrameCount,
&IsAudioConfig,
&GetSampleRate,
&GetSampleFrameCount
};
// PPB_Audio -------------------------------------------------------------------
PP_Resource Create(PP_Instance instance_id, PP_Resource config_id,
PPB_Audio_Callback callback, void* user_data) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return 0;
// TODO(neb): Require callback to be present for untrusted plugins.
scoped_refptr<Audio> audio(new Audio(instance->module()));
if (!audio->Init(instance->delegate(), config_id, callback, user_data))
return 0;
return audio->GetReference();
}
bool IsAudio(PP_Resource resource) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource);
return !!audio;
}
PP_Resource GetCurrentConfiguration(PP_Resource audio_id) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
return audio ? audio->GetCurrentConfiguration() : 0;
}
bool StartPlayback(PP_Resource audio_id) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
return audio ? audio->StartPlayback() : false;
}
bool StopPlayback(PP_Resource audio_id) {
scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
return audio ? audio->StopPlayback() : false;
}
const PPB_Audio_Dev ppb_audio = {
&Create,
&IsAudio,
&GetCurrentConfiguration,
&StartPlayback,
&StopPlayback,
};
// PPB_AudioTrusted ------------------------------------------------------------
PP_Resource GetBuffer(PP_Resource audio_id) {
// TODO(neb): Implement me!
return 0;
}
int GetOSDescriptor(PP_Resource audio_id) {
// TODO(neb): Implement me!
return -1;
}
const PPB_AudioTrusted_Dev ppb_audiotrusted = {
&GetBuffer,
&GetOSDescriptor
};
} // namespace
// AudioConfig -----------------------------------------------------------------
AudioConfig::AudioConfig(PluginModule* module,
PP_AudioSampleRate_Dev sample_rate,
uint32_t sample_frame_count)
: Resource(module),
sample_rate_(sample_rate),
sample_frame_count_(sample_frame_count) {
}
const PPB_AudioConfig_Dev* AudioConfig::GetInterface() {
return &ppb_audioconfig;
}
size_t AudioConfig::BufferSize() {
// TODO(audio): as more options become available, we'll need to
// have additional code here to correctly calculate the size in
// bytes of an audio buffer. For now, only support two channel
// int16_t sample buffers.
const int kChannels = 2;
const int kSizeOfSample = sizeof(int16_t);
return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels);
}
AudioConfig* AudioConfig::AsAudioConfig() {
return this;
}
// Audio -----------------------------------------------------------------------
Audio::Audio(PluginModule* module)
: Resource(module),
playing_(false),
socket_(NULL),
shared_memory_(NULL),
shared_memory_size_(0),
callback_(NULL),
user_data_(NULL) {
}
Audio::~Audio() {
// Calling ShutDown() makes sure StreamCreated cannot be called anymore.
audio_->ShutDown();
// Closing the socket causes the thread to exit - wait for it.
socket_->Close();
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
// Shared memory destructor will unmap the memory automatically.
}
const PPB_Audio_Dev* Audio::GetInterface() {
return &ppb_audio;
}
const PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() {
return &ppb_audiotrusted;
}
Audio* Audio::AsAudio() {
return this;
}
bool Audio::Init(PluginDelegate* plugin_delegate, PP_Resource config_id,
PPB_Audio_Callback callback, void* user_data) {
CHECK(!audio_.get());
config_ = Resource::GetAs<AudioConfig>(config_id);
if (!config_)
return false;
callback_ = callback;
user_data_ = user_data;
// When the stream is created, we'll get called back in StreamCreated().
audio_.reset(plugin_delegate->CreateAudio(config_->sample_rate(),
config_->sample_frame_count(),
this));
return audio_.get() != NULL;
}
bool Audio::StartPlayback() {
if (playing_)
return true;
CHECK(!audio_thread_.get());
if (callback_ && socket_.get()) {
audio_thread_.reset(new base::DelegateSimpleThread(this,
"plugin_audio_thread"));
audio_thread_->Start();
}
playing_ = true;
return audio_->StartPlayback();
}
bool Audio::StopPlayback() {
if (!playing_)
return true;
if (!audio_->StopPlayback())
return false;
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
playing_ = false;
return true;
}
void Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle,
size_t shared_memory_size,
base::SyncSocket::Handle socket_handle) {
socket_.reset(new base::SyncSocket(socket_handle));
shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
shared_memory_size_ = shared_memory_size;
if (callback_) {
shared_memory_->Map(shared_memory_size_);
// In common case StartPlayback() was called before StreamCreated().
if (playing_) {
audio_thread_.reset(new base::DelegateSimpleThread(this,
"plugin_audio_thread"));
audio_thread_->Start();
}
}
}
void Audio::Run() {
int pending_data;
void* buffer = shared_memory_->memory();
size_t buffer_size_in_bytes = config_->BufferSize();
while (sizeof(pending_data) ==
socket_->Receive(&pending_data, sizeof(pending_data)) &&
pending_data >= 0) {
// Exit the thread on pause.
if (pending_data < 0)
return;
callback_(buffer, buffer_size_in_bytes, user_data_);
}
}
} // namespace pepper
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
std::cout << "Welcome to NYX !" << std::endl;
return 0;
}
<commit_msg>:construction: chore(test) add test for nyx script<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fstream>
#include <iostream>
#include <sstream>
#include "lexer.hh"
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
std::cout << "Welcome to NYX !" << std::endl;
if (argc < 2) {
std::cerr << "USAGE: " << argv[0] << " {FILE_NAME}" << std::endl;
return -1;
}
std::ifstream fp(argv[1]);
if (!fp.is_open()) {
std::cerr << "open file \"" << argv[1] << "\" failed" << std::endl;
return -1;
}
std::stringstream ss;
ss << fp.rdbuf();
std::string source_bytes(ss.str());
nyx::Lexer lex(source_bytes);
while (true) {
auto tok = lex.next_token();
std::cout << tok << std::endl;
if (tok.get_kind() == nyx::TokenKind::TK_EOF)
break;
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "dirtab.h"
#include <fstream>
#include <sstream>
#include "util.h"
using namespace catalog;
Dirtab::Dirtab() : valid_(true) {}
Dirtab::Dirtab(const std::string &dirtab_path) {
if (! FileExists(dirtab_path)) {
LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'",
dirtab_path.c_str());
valid_ = false;
return;
}
std::ifstream dirtab(dirtab_path.c_str());
if (!dirtab) {
LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s'",
dirtab_path.c_str());
valid_ = false;
return;
}
valid_ = Parse(dirtab);
dirtab.close();
}
bool Dirtab::Parse(const std::string &dirtab) {
std::istringstream iss(dirtab);
const bool parse_success = Parse(iss);
valid_ = parse_success;
return parse_success;
}
bool Dirtab::Parse(std::istream &dirtab) {
std::string line;
bool all_valid = true;
while (std::getline(dirtab, line)) {
if (! ParseLine(line)) {
all_valid = false;
}
}
return all_valid && CheckRuleValidity();
}
bool Dirtab::ParseLine(const std::string &line) {
std::string::const_iterator itr = line.begin();
const std::string::const_iterator iend = line.end();
bool negation = false;
// parse preamble
SkipWhitespace(itr, iend);
if (*itr == Dirtab::kCommentMarker) {
return true;
} else if (*itr == Dirtab::kNegationMarker) {
negation = true;
++itr;
SkipWhitespace(itr, iend);
}
// extract and parse pathspec
std::string pathspec_str(itr, iend);
if (pathspec_str.empty()) {
return true;
}
Pathspec pathspec(pathspec_str);
if (!pathspec.IsValid()) {
return false;
}
// create a new dirtab rule
const Rule rule(pathspec, negation);
AddRule(rule);
return true;
}
void Dirtab::AddRule(const Rule &rule) {
if (rule.is_negation) {
negative_rules_.push_back(rule);
} else {
positive_rules_.push_back(rule);
}
}
bool Dirtab::CheckRuleValidity() const {
// check if there are contradicting positive and negative rules
Rules::const_iterator p = positive_rules_.begin();
const Rules::const_iterator pend = positive_rules_.end();
for (; p != pend; ++p) {
assert (! p->is_negation);
Rules::const_iterator n = negative_rules_.begin();
const Rules::const_iterator nend = negative_rules_.end();
for (; n != nend; ++n) {
assert (n->is_negation);
if (p->pathspec == n->pathspec) {
return false;
}
}
}
return true;
}
bool Dirtab::IsMatching(const std::string &path) const {
// check if path has a positive match
bool has_positive_match = false;
Rules::const_iterator p = positive_rules_.begin();
const Rules::const_iterator pend = positive_rules_.end();
for (; p != pend; ++p) {
assert (! p->is_negation);
if (p->pathspec.IsMatching(path)) {
has_positive_match = true;
break;
}
}
// no positive match, no match in general!
if (! has_positive_match) {
return false;
}
// check for negative matches (meaning no match in general)
Rules::const_iterator n = negative_rules_.begin();
const Rules::const_iterator nend = negative_rules_.end();
for (; n != nend; ++n) {
assert (n->is_negation);
if (n->pathspec.IsMatching(path)) {
return false;
}
}
// all good, path is matching dirtab
return true;
}
<commit_msg>positive rules in dirtab must be absolute<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "dirtab.h"
#include <fstream>
#include <sstream>
#include "util.h"
using namespace catalog;
Dirtab::Dirtab() : valid_(true) {}
Dirtab::Dirtab(const std::string &dirtab_path) {
if (! FileExists(dirtab_path)) {
LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'",
dirtab_path.c_str());
valid_ = false;
return;
}
std::ifstream dirtab(dirtab_path.c_str());
if (!dirtab) {
LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s'",
dirtab_path.c_str());
valid_ = false;
return;
}
valid_ = Parse(dirtab);
dirtab.close();
}
bool Dirtab::Parse(const std::string &dirtab) {
std::istringstream iss(dirtab);
const bool parse_success = Parse(iss);
valid_ = parse_success;
return parse_success;
}
bool Dirtab::Parse(std::istream &dirtab) {
std::string line;
bool all_valid = true;
while (std::getline(dirtab, line)) {
if (! ParseLine(line)) {
all_valid = false;
}
}
return all_valid && CheckRuleValidity();
}
bool Dirtab::ParseLine(const std::string &line) {
std::string::const_iterator itr = line.begin();
const std::string::const_iterator iend = line.end();
bool negation = false;
// parse preamble
SkipWhitespace(itr, iend);
if (*itr == Dirtab::kCommentMarker) {
return true;
} else if (*itr == Dirtab::kNegationMarker) {
negation = true;
++itr;
SkipWhitespace(itr, iend);
}
// extract and parse pathspec
std::string pathspec_str(itr, iend);
if (pathspec_str.empty()) {
return true;
}
Pathspec pathspec(pathspec_str);
if ( !pathspec.IsValid() ||
(!negation && !pathspec.IsAbsolute())) {
return false;
}
// create a new dirtab rule
const Rule rule(pathspec, negation);
AddRule(rule);
return true;
}
void Dirtab::AddRule(const Rule &rule) {
if (rule.is_negation) {
negative_rules_.push_back(rule);
} else {
positive_rules_.push_back(rule);
}
}
bool Dirtab::CheckRuleValidity() const {
// check if there are contradicting positive and negative rules
Rules::const_iterator p = positive_rules_.begin();
const Rules::const_iterator pend = positive_rules_.end();
for (; p != pend; ++p) {
assert (! p->is_negation);
Rules::const_iterator n = negative_rules_.begin();
const Rules::const_iterator nend = negative_rules_.end();
for (; n != nend; ++n) {
assert (n->is_negation);
if (p->pathspec == n->pathspec) {
return false;
}
}
}
return true;
}
bool Dirtab::IsMatching(const std::string &path) const {
// check if path has a positive match
bool has_positive_match = false;
Rules::const_iterator p = positive_rules_.begin();
const Rules::const_iterator pend = positive_rules_.end();
for (; p != pend; ++p) {
assert (! p->is_negation);
if (p->pathspec.IsMatching(path)) {
has_positive_match = true;
break;
}
}
// no positive match, no match in general!
if (! has_positive_match) {
return false;
}
// check for negative matches (meaning no match in general)
Rules::const_iterator n = negative_rules_.begin();
const Rules::const_iterator nend = negative_rules_.end();
for (; n != nend; ++n) {
assert (n->is_negation);
if (n->pathspec.IsMatching(path)) {
return false;
}
}
// all good, path is matching dirtab
return true;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TimerTaskHeap.h"
using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::util;
////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::TimerTaskHeap() {
}
////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::~TimerTaskHeap() {
}
////////////////////////////////////////////////////////////////////////////////
Pointer<TimerTask> TimerTaskHeap::peek() {
if( heap.empty() ) {
return Pointer<TimerTask>();
}
return heap[0];
}
////////////////////////////////////////////////////////////////////////////////
bool TimerTaskHeap::isEmpty() const {
return heap.empty();
}
////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::size() const {
return this->heap.size();
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {
heap.push_back( task );
upHeap();
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::remove( std::size_t pos ) {
// possible to delete any position of the heap
if( pos < heap.size() ) {
heap[pos] = heap.back();
heap.pop_back();
downHeap( pos );
}
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::upHeap() {
std::size_t current = heap.size() - 1;
std::size_t parent = ( current - 1 ) / 2;
while( heap[current]->when < heap[parent]->when) {
// swap the two
Pointer<TimerTask> tmp = heap[current];
heap[current] = heap[parent];
heap[parent] = tmp;
// update parent and current positions.
current = parent;
parent = ( current - 1 ) / 2;
}
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::downHeap( std::size_t pos ) {
std::size_t current = pos;
std::size_t child = 2 * current + 1;
while( child < heap.size() && !heap.empty() ) {
// compare the children if they exist
if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {
child++;
}
// compare selected child with parent
if( heap[current]->when < heap[child]->when ) {
break;
}
// swap the two
Pointer<TimerTask> tmp = heap[current];
heap[current] = heap[child];
heap[child] = tmp;
// update child and current positions
current = child;
child = 2 * current + 1;
}
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::reset() {
heap.clear();
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::adjustMinimum() {
downHeap( 0 );
}
////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::deleteIfCancelled() {
std::size_t result = 0;
for( std::size_t i = 0; i < heap.size(); ++i ) {
if( heap[i]->cancelled ) {
result++;
remove( i );
// re-try this point
i--;
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {
for( std::size_t i = 0; i < heap.size(); ++i ) {
if( heap[i] == task ) {
return i;
}
}
return -1;
}
<commit_msg>64bit OS fix<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TimerTaskHeap.h"
using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::util;
////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::TimerTaskHeap() {
}
////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::~TimerTaskHeap() {
}
////////////////////////////////////////////////////////////////////////////////
Pointer<TimerTask> TimerTaskHeap::peek() {
if( heap.empty() ) {
return Pointer<TimerTask>();
}
return heap[0];
}
////////////////////////////////////////////////////////////////////////////////
bool TimerTaskHeap::isEmpty() const {
return heap.empty();
}
////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::size() const {
return this->heap.size();
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {
heap.push_back( task );
upHeap();
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::remove( std::size_t pos ) {
// possible to delete any position of the heap
if( pos < heap.size() ) {
heap[pos] = heap.back();
heap.pop_back();
downHeap( pos );
}
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::upHeap() {
if( heap.size() <= 1 ) {
return; // Can't get any higher than the top.
}
std::size_t current = heap.size() - 1;
std::size_t parent = ( current - 1 ) / 2;
while( heap[current]->when < heap[parent]->when) {
// swap the two
Pointer<TimerTask> tmp = heap[current];
heap[current] = heap[parent];
heap[parent] = tmp;
// update parent and current positions.
current = parent;
parent = ( current - 1 ) / 2;
}
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::downHeap( std::size_t pos ) {
std::size_t current = pos;
std::size_t child = 2 * current + 1;
while( child < heap.size() && !heap.empty() ) {
// compare the children if they exist
if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {
child++;
}
// compare selected child with parent
if( heap[current]->when < heap[child]->when ) {
break;
}
// swap the two
Pointer<TimerTask> tmp = heap[current];
heap[current] = heap[child];
heap[child] = tmp;
// update child and current positions
current = child;
child = 2 * current + 1;
}
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::reset() {
heap.clear();
}
////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::adjustMinimum() {
downHeap( 0 );
}
////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::deleteIfCancelled() {
std::size_t result = 0;
for( std::size_t i = 0; i < heap.size(); ++i ) {
if( heap[i]->cancelled ) {
result++;
remove( i );
// re-try this point
i--;
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {
for( std::size_t i = 0; i < heap.size(); ++i ) {
if( heap[i] == task ) {
return i;
}
}
return -1;
}
<|endoftext|>
|
<commit_before>#include "commands.h"
#include "sim/except.h"
#include <iostream>
using namespace std;
void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
out << endl << e.what() << endl;
auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
if (se != NULL)
{
// SimulationExceptions hold more information, print it
for (auto& p : se->GetDetails())
out << p << endl;
auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
if (te == NULL && se->GetPC() != 0)
{
// We avoid printing the backtrace when receiving an exception
// for normal program termination.
assert(sys != NULL);
sys->Disassemble(se->GetPC());
}
}
}
<commit_msg>Enable using PrintException even when no MGSystem is present.<commit_after>#include "commands.h"
#include "sim/except.h"
#include <iostream>
using namespace std;
void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
out << endl << e.what() << endl;
auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
if (se != NULL)
{
// SimulationExceptions hold more information, print it
for (auto& p : se->GetDetails())
out << p << endl;
auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
if (te == NULL && se->GetPC() != 0)
{
// We avoid printing the backtrace when receiving an exception
// for normal program termination.
if (sys != NULL)
// Only disassemble if there is a system to do so.
sys->Disassemble(se->GetPC());
}
}
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "uv.h"
#include "Core.h"
#ifdef WIN32
#include "webrtc/base/win32socketinit.h"
#endif
using namespace WebRTC;
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;
rtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;
uv_check_t _msg;
static void ProcessMessages(uv_check_t* handle) {
rtc::Thread::Current()->ProcessMessages(0);
}
void Core::Init() {
#ifdef WIN32
rtc::EnsureWinsockInit();
#endif
uv_check_init(uv_default_loop(), &_msg);
uv_check_start(&_msg, ProcessMessages);
uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));
rtc::InitializeSSL();
_factory = webrtc::CreatePeerConnectionFactory();
_manager.reset(cricket::DeviceManagerFactory::Create());
if (!_manager->Init()) {
_manager.release();
}
}
void Core::Dispose() {
uv_check_stop(&_msg);
_factory.release();
_manager.release();
}
webrtc::PeerConnectionFactoryInterface* Core::GetFactory() {
return _factory.get();
}
cricket::DeviceManagerInterface* Core::GetManager() {
return _manager.get();
}<commit_msg>Terminate Manager<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "uv.h"
#include "Core.h"
#ifdef WIN32
#include "webrtc/base/win32socketinit.h"
#endif
using namespace WebRTC;
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;
rtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;
uv_check_t _msg;
static void ProcessMessages(uv_check_t* handle) {
rtc::Thread::Current()->ProcessMessages(0);
}
void Core::Init() {
#ifdef WIN32
rtc::EnsureWinsockInit();
#endif
uv_check_init(uv_default_loop(), &_msg);
uv_check_start(&_msg, ProcessMessages);
uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));
rtc::InitializeSSL();
_factory = webrtc::CreatePeerConnectionFactory();
_manager.reset(cricket::DeviceManagerFactory::Create());
if (!_manager->Init()) {
_manager.release();
}
}
void Core::Dispose() {
uv_check_stop(&_msg);
_factory.release();
if (_manager.get()) {
_manager->Terminate();
}
_manager.release();
}
webrtc::PeerConnectionFactoryInterface* Core::GetFactory() {
return _factory.get();
}
cricket::DeviceManagerInterface* Core::GetManager() {
return _manager.get();
}<|endoftext|>
|
<commit_before>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// TriMesh code by Erwin de Vries.
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_util.h"
#define TRIMESH_INTERNAL
#include "collision_trimesh_internal.h"
int dCollideRTL(dxGeom* g1, dxGeom* RayGeom, int Flags, dContactGeom* Contacts, int Stride){
dxTriMesh* TriMesh = (dxTriMesh*)g1;
const dVector3& TLPosition = *(const dVector3*)dGeomGetPosition(TriMesh);
const dMatrix3& TLRotation = *(const dMatrix3*)dGeomGetRotation(TriMesh);
RayCollider& Collider = TriMesh->_RayCollider;
dReal Length = dGeomRayGetLength(RayGeom);
int FirstContact, BackfaceCull;
dGeomRayGetParams(RayGeom, &FirstContact, &BackfaceCull);
int ClosestHit = dGeomRayGetClosestHit(RayGeom);
Collider.SetFirstContact(FirstContact != 0);
Collider.SetClosestHit(ClosestHit != 0);
Collider.SetCulling(BackfaceCull != 0);
Collider.SetMaxDist(Length);
dVector3 Origin, Direction;
dGeomRayGet(RayGeom, Origin, Direction);
/* Make Ray */
Ray WorldRay;
WorldRay.mOrig.x = Origin[0];
WorldRay.mOrig.y = Origin[1];
WorldRay.mOrig.z = Origin[2];
WorldRay.mDir.x = Direction[0];
WorldRay.mDir.y = Direction[1];
WorldRay.mDir.z = Direction[2];
/* Intersect */
Matrix4x4 amatrix;
Collider.Collide(WorldRay, TriMesh->Data->BVTree, &MakeMatrix(TLPosition, TLRotation, amatrix));
/* Retrieve data */
int TriCount = TriMesh->Faces.GetNbFaces();
if (TriCount != 0){
const CollisionFace* Faces = TriMesh->Faces.GetFaces();
int OutTriCount = 0;
for (int i = 0; i < TriCount; i++){
if (OutTriCount == (Flags & 0xffff)){
break;
}
if (TriMesh->RayCallback == null || TriMesh->RayCallback(TriMesh, RayGeom, Faces[i].mFaceID, Faces[i].mU, Faces[i].mV)){
const int& TriIndex = Faces[i].mFaceID;
if (!Callback(TriMesh, RayGeom, TriIndex)) continue;
dContactGeom* Contact = SAFECONTACT(Flags, Contacts, OutTriCount, Stride);
dVector3 dv[3];
FetchTriangle(TriMesh, TriIndex, TLPosition, TLRotation, dv);
float T = Faces[i].mDistance;
Contact->pos[0] = Origin[0] + (Direction[0] * T);
Contact->pos[1] = Origin[1] + (Direction[1] * T);
Contact->pos[2] = Origin[2] + (Direction[2] * T);
Contact->pos[3] = REAL(0.0);
dVector3 vu;
vu[0] = dv[1][0] - dv[0][0];
vu[1] = dv[1][1] - dv[0][1];
vu[2] = dv[1][2] - dv[0][2];
vu[3] = REAL(0.0);
dVector3 vv;
vv[0] = dv[2][0] - dv[0][0];
vv[1] = dv[2][1] - dv[0][1];
vv[2] = dv[2][2] - dv[0][2];
vv[3] = REAL(0.0);
dCROSS(Contact->normal, =, vv, vu); // Reversed
dNormalize3(Contact->normal);
Contact->depth = T;
Contact->g1 = TriMesh;
Contact->g2 = RayGeom;
OutTriCount++;
}
}
return OutTriCount;
}
else return 0;
}
<commit_msg>ray-triangle collider correctness fix from Joe Ante <joe@uti.is><commit_after>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// TriMesh code by Erwin de Vries.
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_util.h"
#define TRIMESH_INTERNAL
#include "collision_trimesh_internal.h"
int dCollideRTL(dxGeom* g1, dxGeom* RayGeom, int Flags, dContactGeom* Contacts, int Stride){
dxTriMesh* TriMesh = (dxTriMesh*)g1;
const dVector3& TLPosition = *(const dVector3*)dGeomGetPosition(TriMesh);
const dMatrix3& TLRotation = *(const dMatrix3*)dGeomGetRotation(TriMesh);
RayCollider& Collider = TriMesh->_RayCollider;
dReal Length = dGeomRayGetLength(RayGeom);
int FirstContact, BackfaceCull;
dGeomRayGetParams(RayGeom, &FirstContact, &BackfaceCull);
int ClosestHit = dGeomRayGetClosestHit(RayGeom);
Collider.SetFirstContact(FirstContact != 0);
Collider.SetClosestHit(ClosestHit != 0);
Collider.SetCulling(BackfaceCull != 0);
Collider.SetMaxDist(Length);
dVector3 Origin, Direction;
dGeomRayGet(RayGeom, Origin, Direction);
/* Make Ray */
Ray WorldRay;
WorldRay.mOrig.x = Origin[0];
WorldRay.mOrig.y = Origin[1];
WorldRay.mOrig.z = Origin[2];
WorldRay.mDir.x = Direction[0];
WorldRay.mDir.y = Direction[1];
WorldRay.mDir.z = Direction[2];
/* Intersect */
Matrix4x4 amatrix;
int TriCount = 0;
if (Collider.Collide(WorldRay, TriMesh->Data->BVTree, &MakeMatrix(TLPosition, TLRotation, amatrix))) {
TriCount = TriMesh->Faces.GetNbFaces();
}
if (TriCount == 0) {
return 0;
}
const CollisionFace* Faces = TriMesh->Faces.GetFaces();
int OutTriCount = 0;
for (int i = 0; i < TriCount; i++) {
if (OutTriCount == (Flags & 0xffff)) {
break;
}
if (TriMesh->RayCallback == null ||
TriMesh->RayCallback(TriMesh, RayGeom, Faces[i].mFaceID,
Faces[i].mU, Faces[i].mV)) {
const int& TriIndex = Faces[i].mFaceID;
if (!Callback(TriMesh, RayGeom, TriIndex)) {
continue;
}
dContactGeom* Contact = SAFECONTACT(Flags, Contacts, OutTriCount, Stride);
dVector3 dv[3];
FetchTriangle(TriMesh, TriIndex, TLPosition, TLRotation, dv);
float T = Faces[i].mDistance;
Contact->pos[0] = Origin[0] + (Direction[0] * T);
Contact->pos[1] = Origin[1] + (Direction[1] * T);
Contact->pos[2] = Origin[2] + (Direction[2] * T);
Contact->pos[3] = REAL(0.0);
dVector3 vu;
vu[0] = dv[1][0] - dv[0][0];
vu[1] = dv[1][1] - dv[0][1];
vu[2] = dv[1][2] - dv[0][2];
vu[3] = REAL(0.0);
dVector3 vv;
vv[0] = dv[2][0] - dv[0][0];
vv[1] = dv[2][1] - dv[0][1];
vv[2] = dv[2][2] - dv[0][2];
vv[3] = REAL(0.0);
dCROSS(Contact->normal, =, vv, vu); // Reversed
dNormalize3(Contact->normal);
Contact->depth = T;
Contact->g1 = TriMesh;
Contact->g2 = RayGeom;
OutTriCount++;
}
}
return OutTriCount;
}
<|endoftext|>
|
<commit_before>/* =======================================================================
Copyright (c) 2011, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaFVM - The Vienna Finite Volume Method Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
(add your name here)
license: To be discussed, see file LICENSE in the ViennaFVM base directory
======================================================================= */
// include necessary system headers
#include <iostream>
#define VIENNAFVM_DEBUG
// ViennaFVM includes:
#include "viennafvm/forwards.h"
//#include "viennafvm/poisson_assembler.hpp"
#include "viennafvm/linear_assembler.hpp"
#include "viennafvm/io/vtk_writer.hpp"
#include "viennafvm/ncell_quantity.hpp"
#include "viennafvm/linear_solve.hpp"
#include "viennafvm/pde_solver.hpp"
// ViennaGrid includes:
#include "viennagrid/domain/domain.hpp"
#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/io/netgen_reader.hpp"
#include "viennagrid/io/vtk_writer.hpp"
#include "viennagrid/algorithm/voronoi.hpp"
// ViennaData includes:
#include "viennadata/api.hpp"
// ViennaMath includes:
#include "viennamath/expression.hpp"
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/operation_sparse.hpp>
struct permittivity_key
{
// Operator< is required for compatibility with std::map
bool operator<(permittivity_key const & /*other*/) const { return false; }
};
int main()
{
typedef double numeric_type;
typedef viennagrid::tetrahedral_3d_domain DomainType;
typedef viennagrid::result_of::segmentation<DomainType>::type SegmentationType;
typedef viennagrid::result_of::cell_tag<DomainType>::type CellTag;
typedef viennagrid::result_of::element<DomainType, CellTag>::type CellType;
typedef viennamath::function_symbol FunctionSymbol;
typedef viennamath::equation Equation;
typedef viennadata::storage<> StorageType;
typedef viennagrid::result_of::element_range<DomainType, CellTag>::type CellContainer;
typedef viennagrid::result_of::iterator<CellContainer>::type CellIterator;
typedef viennagrid::result_of::vertex_range<CellType>::type VertexOnCellContainer;
typedef viennagrid::result_of::iterator<VertexOnCellContainer>::type VertexOnCellIterator;
typedef viennamath::function_symbol FunctionSymbol;
typedef viennamath::equation Equation;
typedef viennafvm::boundary_key BoundaryKey;
//
// Create a domain from file
//
DomainType domain;
SegmentationType segmentation(domain);
StorageType storage/**/;
try
{
viennagrid::io::netgen_reader my_netgen_reader;
my_netgen_reader(domain, segmentation, "../examples/data/cube3072.mesh");
}
catch (...)
{
std::cerr << "File-Reader failed. Aborting program..." << std::endl;
return EXIT_FAILURE;
}
// Specify Poisson equation:
viennafvm::ncell_quantity<CellType, viennamath::expr::interface_type> permittivity; permittivity.wrap_constant( storage, permittivity_key() );
FunctionSymbol u(0, viennamath::unknown_tag<>()); //an unknown function used for PDE specification
Equation poisson_eq = viennamath::make_equation( viennamath::div(permittivity * viennamath::grad(u)), -1); // \Delta u = -1
//
// Setting boundary information on domain (this should come from device specification)
//
//setting some boundary flags:
viennagrid::result_of::default_point_accessor<DomainType>::type point_accessor = viennagrid::default_point_accessor(domain);
viennadata::result_of::accessor<StorageType, permittivity_key, double, CellType>::type permittivity_accessor =
viennadata::accessor<permittivity_key, double, CellType>(storage, permittivity_key());
viennadata::result_of::accessor<StorageType, BoundaryKey, bool, CellType>::type boundary_accessor =
viennadata::accessor<BoundaryKey, bool, CellType>(storage, BoundaryKey( u.id() ));
CellContainer cells = viennagrid::elements(domain);
for (CellIterator cit = cells.begin();
cit != cells.end();
++cit)
{
bool cell_on_boundary = false;
// write dummy permittivity to cells:
permittivity_accessor(*cit) = 1.0;
VertexOnCellContainer vertices = viennagrid::elements(*cit);
for (VertexOnCellIterator vit = vertices.begin();
vit != vertices.end();
++vit)
{
//boundary for first equation: Homogeneous Dirichlet everywhere
if (point_accessor(*vit)[0] == 0.0 || point_accessor(*vit)[0] == 1.0
|| point_accessor(*vit)[2] == 0.0 || point_accessor(*vit)[2] == 1.0 )
{
cell_on_boundary = true;
break;
}
}
boundary_accessor(*cit) = cell_on_boundary;
}
//
// Create PDE solver instance
//
viennafvm::pde_solver<> pde_solver;
//
// Pass system to solver:
//
pde_solver(viennafvm::make_linear_pde_system(poisson_eq, u), // PDE with associated unknown
domain,
storage);
//
// Writing solution back to domain (discussion about proper way of returning a solution required...)
//
viennafvm::io::write_solution_to_VTK_file(pde_solver.result(), "poisson_3d", domain, segmentation, storage, 0);
std::cout << "*****************************************" << std::endl;
std::cout << "* Poisson solver finished successfully! *" << std::endl;
std::cout << "*****************************************" << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>Removed unnecessary comment, removed duplicate typedef<commit_after>/* =======================================================================
Copyright (c) 2011, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaFVM - The Vienna Finite Volume Method Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
(add your name here)
license: To be discussed, see file LICENSE in the ViennaFVM base directory
======================================================================= */
// include necessary system headers
#include <iostream>
#define VIENNAFVM_DEBUG
// ViennaFVM includes:
#include "viennafvm/forwards.h"
//#include "viennafvm/poisson_assembler.hpp"
#include "viennafvm/linear_assembler.hpp"
#include "viennafvm/io/vtk_writer.hpp"
#include "viennafvm/ncell_quantity.hpp"
#include "viennafvm/linear_solve.hpp"
#include "viennafvm/pde_solver.hpp"
// ViennaGrid includes:
#include "viennagrid/domain/domain.hpp"
#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/io/netgen_reader.hpp"
#include "viennagrid/io/vtk_writer.hpp"
#include "viennagrid/algorithm/voronoi.hpp"
// ViennaData includes:
#include "viennadata/api.hpp"
// ViennaMath includes:
#include "viennamath/expression.hpp"
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/operation_sparse.hpp>
struct permittivity_key
{
// Operator< is required for compatibility with std::map
bool operator<(permittivity_key const & /*other*/) const { return false; }
};
int main()
{
typedef double numeric_type;
typedef viennagrid::tetrahedral_3d_domain DomainType;
typedef viennagrid::result_of::segmentation<DomainType>::type SegmentationType;
typedef viennagrid::result_of::cell_tag<DomainType>::type CellTag;
typedef viennagrid::result_of::element<DomainType, CellTag>::type CellType;
typedef viennadata::storage<> StorageType;
typedef viennagrid::result_of::element_range<DomainType, CellTag>::type CellContainer;
typedef viennagrid::result_of::iterator<CellContainer>::type CellIterator;
typedef viennagrid::result_of::vertex_range<CellType>::type VertexOnCellContainer;
typedef viennagrid::result_of::iterator<VertexOnCellContainer>::type VertexOnCellIterator;
typedef viennamath::function_symbol FunctionSymbol;
typedef viennamath::equation Equation;
typedef viennafvm::boundary_key BoundaryKey;
//
// Create a domain from file
//
DomainType domain;
SegmentationType segmentation(domain);
StorageType storage;
try
{
viennagrid::io::netgen_reader my_netgen_reader;
my_netgen_reader(domain, segmentation, "../examples/data/cube3072.mesh");
}
catch (...)
{
std::cerr << "File-Reader failed. Aborting program..." << std::endl;
return EXIT_FAILURE;
}
// Specify Poisson equation:
viennafvm::ncell_quantity<CellType, viennamath::expr::interface_type> permittivity; permittivity.wrap_constant( storage, permittivity_key() );
FunctionSymbol u(0, viennamath::unknown_tag<>()); //an unknown function used for PDE specification
Equation poisson_eq = viennamath::make_equation( viennamath::div(permittivity * viennamath::grad(u)), -1); // \Delta u = -1
//
// Setting boundary information on domain (this should come from device specification)
//
//setting some boundary flags:
viennagrid::result_of::default_point_accessor<DomainType>::type point_accessor = viennagrid::default_point_accessor(domain);
viennadata::result_of::accessor<StorageType, permittivity_key, double, CellType>::type permittivity_accessor =
viennadata::accessor<permittivity_key, double, CellType>(storage, permittivity_key());
viennadata::result_of::accessor<StorageType, BoundaryKey, bool, CellType>::type boundary_accessor =
viennadata::accessor<BoundaryKey, bool, CellType>(storage, BoundaryKey( u.id() ));
CellContainer cells = viennagrid::elements(domain);
for (CellIterator cit = cells.begin();
cit != cells.end();
++cit)
{
bool cell_on_boundary = false;
// write dummy permittivity to cells:
permittivity_accessor(*cit) = 1.0;
VertexOnCellContainer vertices = viennagrid::elements(*cit);
for (VertexOnCellIterator vit = vertices.begin();
vit != vertices.end();
++vit)
{
//boundary for first equation: Homogeneous Dirichlet everywhere
if (point_accessor(*vit)[0] == 0.0 || point_accessor(*vit)[0] == 1.0
|| point_accessor(*vit)[2] == 0.0 || point_accessor(*vit)[2] == 1.0 )
{
cell_on_boundary = true;
break;
}
}
boundary_accessor(*cit) = cell_on_boundary;
}
//
// Create PDE solver instance
//
viennafvm::pde_solver<> pde_solver;
//
// Pass system to solver:
//
pde_solver(viennafvm::make_linear_pde_system(poisson_eq, u), // PDE with associated unknown
domain,
storage);
//
// Writing solution back to domain (discussion about proper way of returning a solution required...)
//
viennafvm::io::write_solution_to_VTK_file(pde_solver.result(), "poisson_3d", domain, segmentation, storage, 0);
std::cout << "*****************************************" << std::endl;
std::cout << "* Poisson solver finished successfully! *" << std::endl;
std::cout << "*****************************************" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/** @file tutorialAdaptiveCDR.cpp
@brief Tutorial on how to use G+Smo to solve a convection-diffusion-reaction problem.
This file is part of the G+Smo library.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Author(s): S. Kleiss
*/
//! [Include namespace]
# include <gismo.h>
# include <gsAssembler/gsAdaptiveRefUtils.h>
using namespace std;
using namespace gismo;
//! [Include namespace]
int main(int argc, char *argv[])
{
//! [Parse command line]
bool plot = false;
gsCmdLine cmd("Example for solving a convection-diffusion problem.");
cmd.addSwitch("plot", "Create a ParaView visualization file with the solution", plot);
const bool ok = cmd.getValues(argc,argv);
if (!ok) { gsWarn << "Error during parsing the command line!\n"; return 0;}
//! [Parse command line]
// --------------- specify exact solution and right-hand-side ---------------
//! [Function data]
// Define exact solution (will be used for specifying Dirichlet boundary conditions
//gsFunctionExpr<> g("if( y<-x/2-1/2, 1, 0 )", 2);
gsFunctionExpr<> g("if( y>=0, if( x <=-1, 1, 0 ), 0 )", 2);
// Define source function
gsFunctionExpr<> rhs("0",2);
// diffusion coefficient:
gsFunctionExpr<> coeff_diff("0.000001","0","0","0.000001",2);
// convection coefficient:
gsFunctionExpr<> coeff_conv("3/sqrt(13)","-2/sqrt(13)",2);
// reaction coefficient:
gsFunctionExpr<> coeff_reac("0",2);
//! [Function data]
// Print out source function and solution
gsInfo<<"Source function " << rhs << "\n";
gsInfo<<"Dirichlet boundary conditions " << g << "\n\n";
// --------------- read geometry from file ---------------
// Read geometry from file (full path needed, or
// GISMO_DATA_DIR macro which leads to the "filedata" directory
//! [GetGeometryData]
// Read xml and create gsMultiPatch
string fileSrc( GISMO_DATA_DIR "/planar/lshape2d_3patches_thb.xml" );
gsMultiPatch<real_t> patches;
gsReadFile<real_t>( fileSrc, patches);
//! [GetGeometryData]
gsInfo << "The domain is a "<< patches <<"\n";
//! [computeTopology]
// Get all interfaces and boundaries:
patches.computeTopology();
//! [computeTopology]
// --------------- add bonudary conditions ---------------
//! [Boundary conditions]
gsBoundaryConditions<> bcInfo;
// For simplicity, set Dirichlet boundary conditions
// given by exact solution g on all boundaries:
for ( gsMultiPatch<>::const_biterator
bit = patches.bBegin(); bit != patches.bEnd(); ++bit)
{
bcInfo.addCondition( *bit, condition_type::dirichlet, &g );
}
//! [Boundary conditions]
// --------------- define Pde ---------------
//! [definePde]
gsConvDiffRePde<real_t> cdrPde(patches, bcInfo, & coeff_diff,& coeff_conv, & coeff_reac, & rhs);
//! [definePde]
// --------------- set up basis ---------------
//! [GetBasisFromTHB]
// Copy basis from the geometry
gsMultiBasis<> bases( patches );
//! [GetBasisFromTHB]
//! [initialRefinements]
// Number of initial uniform refinement steps:
int numInitUniformRefine = 2;
for (int i = 0; i < numInitUniformRefine; ++i)
bases.uniformRefine();
//! [initialRefinements]
// --------------- set up adaptive refinement loop ---------------
//! [adaptRefSettings]
// Number of refinement loops to be done
int numRefinementLoops = 4;
// Specify cell-marking strategy...
MarkingStrategy adaptRefCrit = PUCA;
// MarkingStrategy adaptRefCrit = GARU;
// MarkingStrategy adaptRefCrit = errorFraction;
// ... and parameter.
const real_t adaptRefParam = 0.7;
//! [adaptRefSettings]
//! [constructAssembler]
// Construct assembler
gsCDRAssembler<real_t> cdrAss( cdrPde, bases);
// Set stabilization flag to 1 = SUPG
cdrAss.options().setInt("Stabilization", 1);
// Compute Dirichlet values by L2-projection
// Caution: Interpolation does not work for locally refined (T)HB-splines!
cdrAss.options().setInt("DirichletValues",dirichlet::l2Projection);
//! [constructAssembler]
// --------------- adaptive refinement loop ---------------
//! [beginRefLoop]
for( int refLoop = 0; refLoop <= numRefinementLoops; refLoop++)
{
//! [beginRefLoop]
gsInfo << "====== Loop " << refLoop << " of "
<<numRefinementLoops<< " ======" << "\n";
// --------------- solving ---------------
//! [solverPart]
// Generate system matrix and load vector
cdrAss.assemble();
// Solve the system
gsMatrix<real_t> solVector = Eigen::BiCGSTAB< gsSparseMatrix<real_t>, Eigen::IncompleteLUT<real_t> >( cdrAss.matrix() ).solve( cdrAss.rhs() );
// Construct the solution as a scalar field
gsField<> solField;
solField = cdrAss.constructSolution(solVector);
//! [solverPart]
// --------------- error estimation/computation ---------------
//! [errorComputation]
// Compute the H1-seminorm of the computed solution
// ( which is, at least, equivalent to the energy norm in this example )
// using the known exact solution.
gsSeminormH1<real_t> norm( solField );
norm.compute(true); // "true" indicates that element-wise norms shall be stored
// Get the element-wise norms.
const std::vector<real_t> & eltErrs = norm.elementNorms();
//! [errorComputation]
// --------------- adaptive refinement ---------------
//! [adaptRefinementPart]
// Mark elements for refinement, based on the computed local errors and
// the refinement-criterion and -parameter.
std::vector<bool> elMarked( eltErrs.size() );
gsMarkElementsForRef( eltErrs, adaptRefCrit, adaptRefParam, elMarked);
gsInfo <<"Marked "<< std::count(elMarked.begin(), elMarked.end(), true) <<" elements.\n";
// Refine the marked elements with a 1-ring of cells around marked elements
gsRefineMarkedElements( cdrAss.multiBasis(), elMarked, 1 );
//! [adaptRefinementPart]
//! [repairInterfaces]
// Call repair interfaces to make sure that the new meshes
// match along patch interfaces.
cdrAss.multiBasis().repairInterfaces( patches.interfaces() );
//! [repairInterfaces]
//! [refreshAssembler]
cdrAss.refresh();
//! [refreshAssembler]
//! [Export to Paraview]
// Export the final solution
if( plot && refLoop == numRefinementLoops )
{
// Write the computed solution to paraview files
gsWriteParaview<>( solField, "adaptRef", 1000, true);
}
//! [Export to Paraview]
}
//! [Plot in Paraview]
if( plot )
{
// Run paraview
return system("paraview adaptRef.pvd &");
}
//! [Plot in Paraview]
else
{
gsInfo<<"Quitting.. No output created, re-run with --plot to get a ParaView "
"file containing Plotting image data.\n";
return 0;
}
}// end main
<commit_msg>minor<commit_after>/** @file tutorialAdaptiveCDR.cpp
@brief Tutorial on how to use G+Smo to solve a convection-diffusion-reaction problem.
This file is part of the G+Smo library.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Author(s): S. Kleiss
*/
//! [Include namespace]
# include <gismo.h>
# include <gsAssembler/gsAdaptiveRefUtils.h>
using namespace std;
using namespace gismo;
//! [Include namespace]
int main(int argc, char *argv[])
{
//! [Parse command line]
bool plot = false;
gsCmdLine cmd("Example for solving a convection-diffusion problem.");
cmd.addSwitch("plot", "Create a ParaView visualization file with the solution", plot);
const bool ok = cmd.getValues(argc,argv);
if (!ok) { gsWarn << "Error during parsing the command line!\n"; return 0;}
//! [Parse command line]
// --------------- specify exact solution and right-hand-side ---------------
//! [Function data]
// Define exact solution (will be used for specifying Dirichlet boundary conditions
//gsFunctionExpr<> g("if( y<-x/2-1/2, 1, 0 )", 2);
gsFunctionExpr<> g("if( y>=0, if( x <=-1, 1, 0 ), 0 )", 2);
// Define source function
gsFunctionExpr<> rhs("0",2);
// diffusion coefficient:
gsFunctionExpr<> coeff_diff("0.000001","0","0","0.000001",2);
// convection coefficient:
gsFunctionExpr<> coeff_conv("3/sqrt(13)","-2/sqrt(13)",2);
// reaction coefficient:
gsFunctionExpr<> coeff_reac("0",2);
//! [Function data]
// Print out source function and solution
gsInfo<<"Source function " << rhs << "\n";
gsInfo<<"Dirichlet boundary conditions " << g << "\n\n";
// --------------- read geometry from file ---------------
// Read geometry from file (full path needed, or
// GISMO_DATA_DIR macro which leads to the "filedata" directory
//! [GetGeometryData]
// Read xml and create gsMultiPatch
string fileSrc( GISMO_DATA_DIR "/planar/lshape2d_3patches_thb.xml" );
gsMultiPatch<real_t> patches;
gsReadFile<real_t>( fileSrc, patches);
//! [GetGeometryData]
gsInfo << "The domain is a "<< patches <<"\n";
//! [computeTopology]
// Get all interfaces and boundaries:
patches.computeTopology();
//! [computeTopology]
// --------------- add bonudary conditions ---------------
//! [Boundary conditions]
gsBoundaryConditions<> bcInfo;
// For simplicity, set Dirichlet boundary conditions
// given by exact solution g on all boundaries:
for ( gsMultiPatch<>::const_biterator
bit = patches.bBegin(); bit != patches.bEnd(); ++bit)
{
bcInfo.addCondition( *bit, condition_type::dirichlet, &g );
}
//! [Boundary conditions]
// --------------- define Pde ---------------
//! [definePde]
gsConvDiffRePde<real_t> cdrPde(patches, bcInfo, & coeff_diff,& coeff_conv, & coeff_reac, & rhs);
//! [definePde]
// --------------- set up basis ---------------
//! [GetBasisFromTHB]
// Copy basis from the geometry
gsMultiBasis<> bases( patches );
//! [GetBasisFromTHB]
//! [initialRefinements]
// Number of initial uniform refinement steps:
int numInitUniformRefine = 2;
for (int i = 0; i < numInitUniformRefine; ++i)
bases.uniformRefine();
//! [initialRefinements]
// --------------- set up adaptive refinement loop ---------------
//! [adaptRefSettings]
// Number of refinement loops to be done
int numRefinementLoops = 4;
// Specify cell-marking strategy...
MarkingStrategy adaptRefCrit = PUCA;
// MarkingStrategy adaptRefCrit = GARU;
// MarkingStrategy adaptRefCrit = errorFraction;
// ... and parameter.
const real_t adaptRefParam = 0.7;
//! [adaptRefSettings]
//! [constructAssembler]
// Construct assembler
gsCDRAssembler<real_t> cdrAss( cdrPde, bases);
// Set stabilization flag to 1 = SUPG
cdrAss.options().setInt("Stabilization", 1);
// Compute Dirichlet values by L2-projection
// Caution: Interpolation does not work for locally refined (T)HB-splines!
cdrAss.options().setInt("DirichletValues",dirichlet::l2Projection);
//! [constructAssembler]
// --------------- adaptive refinement loop ---------------
//! [beginRefLoop]
for( int refLoop = 0; refLoop <= numRefinementLoops; refLoop++)
{
//! [beginRefLoop]
gsInfo << "====== Loop " << refLoop << " of "
<<numRefinementLoops<< " ======" << "\n";
// --------------- solving ---------------
//! [solverPart]
// Generate system matrix and load vector
cdrAss.assemble();
// Solve the system
gsMatrix<real_t> solVector =
gsSparseSolver<>::BiCGSTABILUT( cdrAss.matrix() ).solve( cdrAss.rhs() );
// Construct the solution as a scalar field
gsField<> solField;
solField = cdrAss.constructSolution(solVector);
//! [solverPart]
// --------------- error estimation/computation ---------------
//! [errorComputation]
// Compute the H1-seminorm of the computed solution
// ( which is, at least, equivalent to the energy norm in this example )
// using the known exact solution.
gsSeminormH1<real_t> norm( solField );
norm.compute(true); // "true" indicates that element-wise norms shall be stored
// Get the element-wise norms.
const std::vector<real_t> & eltErrs = norm.elementNorms();
//! [errorComputation]
// --------------- adaptive refinement ---------------
//! [adaptRefinementPart]
// Mark elements for refinement, based on the computed local errors and
// the refinement-criterion and -parameter.
std::vector<bool> elMarked( eltErrs.size() );
gsMarkElementsForRef( eltErrs, adaptRefCrit, adaptRefParam, elMarked);
gsInfo <<"Marked "<< std::count(elMarked.begin(), elMarked.end(), true) <<" elements.\n";
// Refine the marked elements with a 1-ring of cells around marked elements
gsRefineMarkedElements( cdrAss.multiBasis(), elMarked, 1 );
//! [adaptRefinementPart]
//! [repairInterfaces]
// Call repair interfaces to make sure that the new meshes
// match along patch interfaces.
cdrAss.multiBasis().repairInterfaces( patches.interfaces() );
//! [repairInterfaces]
//! [refreshAssembler]
cdrAss.refresh();
//! [refreshAssembler]
//! [Export to Paraview]
// Export the final solution
if( plot && refLoop == numRefinementLoops )
{
// Write the computed solution to paraview files
gsWriteParaview<>( solField, "adaptRef", 1000, true);
}
//! [Export to Paraview]
}
//! [Plot in Paraview]
if( plot )
{
// Run paraview
return system("paraview adaptRef.pvd &");
}
//! [Plot in Paraview]
else
{
gsInfo<<"Quitting.. No output created, re-run with --plot to get a ParaView "
"file containing Plotting image data.\n";
return 0;
}
}// end main
<|endoftext|>
|
<commit_before>/* <x0/HttpListener.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpListener.h>
#include <x0/http/HttpConnection.h>
#include <x0/http/HttpServer.h>
#include <x0/SocketDriver.h>
#include <x0/sysconfig.h>
#if defined(WITH_SSL)
# include <x0/SslDriver.h>
#endif
#include <arpa/inet.h> // inet_pton()
#include <netinet/tcp.h> // TCP_QUICKACK, TCP_DEFER_ACCEPT
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
namespace x0 {
HttpListener::HttpListener(HttpServer& srv) :
watcher_(srv.loop()),
fd_(-1),
server_(srv),
address_(),
port_(-1),
backlog_(SOMAXCONN),
errors_(0),
socketDriver_(new SocketDriver(srv.loop()))
{
watcher_.set<HttpListener, &HttpListener::callback>(this);
}
HttpListener::~HttpListener()
{
stop();
}
void HttpListener::stop()
{
if (fd_ == -1)
return;
watcher_.stop();
::close(fd_);
fd_ = -1;
setSocketDriver(NULL);
}
inline void HttpListener::setsockopt(int socket, int layer, int option, int value)
{
if (::setsockopt(socket, layer, option, &value, sizeof(value)) < 0)
{
log(Severity::error, "Error setting socket option (fd=%d, layer=%d, opt=%d, val=%d): %s",
socket, layer, option, value, strerror(errno));
}
}
void HttpListener::setSocketDriver(SocketDriver *sd)
{
if (socketDriver_)
delete socketDriver_;
socketDriver_ = sd;
}
std::error_code HttpListener::prepare()
{
#if defined(WITH_SSL)
if (isSecure())
log(Severity::info, "Start listening on [%s]:%d [secure]", address_.c_str(), port_);
else
log(Severity::info, "Start listening on [%s]:%d", address_.c_str(), port_);
#else
log(Severity::info, "Start listening on [%s]:%d", address_.c_str(), port_);
#endif
fd_ = ::socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (fd_ < 0) return std::make_error_code(static_cast<std::errc>(errno));
fcntl(fd_, F_SETFL, FD_CLOEXEC);
if (fcntl(fd_, F_SETFL, O_NONBLOCK) < 0)
{
//log(Severity::error, "could not set server socket into non-blocking mode: %s\n", strerror(errno));
return std::make_error_code(static_cast<std::errc>(errno));
}
sockaddr_in6 sin;
bzero(&sin, sizeof(sin));
sin.sin6_family = AF_INET6;
sin.sin6_port = htons(port_);
if (inet_pton(sin.sin6_family, address_.c_str(), sin.sin6_addr.s6_addr) < 0)
log(Severity::error, "Could not resolve IP address (%s): %s", address_.c_str(), strerror(errno));
#if defined(SO_REUSEADDR)
//! \todo SO_REUSEADDR: could be configurable
setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, 1);
#endif
#if defined(TCP_QUICKACK)
//! \todo TCP_QUICKACK: could be configurable
setsockopt(fd_, SOL_TCP, TCP_QUICKACK, 1);
#endif
#if defined(TCP_DEFER_ACCEPT)
setsockopt(fd_, SOL_TCP, TCP_DEFER_ACCEPT, 1);
#endif
// acceptor_.set_option(asio::ip::tcp::acceptor::linger(false, 0));
// acceptor_.set_option(asio::ip::tcp::acceptor::keep_alive(true));
if (::bind(fd_, (sockaddr *)&sin, sizeof(sin)) < 0) {
log(Severity::error, "Cannot bind to IP-address (%s): %s", address_.c_str(), strerror(errno));
return std::make_error_code(static_cast<std::errc>(errno));
}
if (::listen(fd_, backlog_) < 0) {
log(Severity::error, "Cannot listen to IP-address (%s): %s", address_.c_str(), strerror(errno));
return std::make_error_code(static_cast<std::errc>(errno));
}
return std::error_code();
}
std::error_code HttpListener::start()
{
std::error_code ec;
if (fd_ == -1)
{
ec = prepare();
if (ec)
return ec;
}
watcher_.start(fd_, ev::READ);
return ec;
}
void HttpListener::callback(ev::io& watcher, int revents)
{
// TODO accept() as much until it would block.
if (HttpConnection *c = new HttpConnection(*this))
{
if (c->isClosed())
delete c;
else
// TODO: introduce a PREPARE mode, that would defer the code fragment below - required for SSL handshaking, which takes place *before* processing the HTTP request
c->start();
}
}
std::string HttpListener::address() const
{
return address_;
}
void HttpListener::address(const std::string& value)
{
address_ = value;
}
int HttpListener::port() const
{
return port_;
}
void HttpListener::port(int value)
{
port_ = value;
}
int HttpListener::backlog() const
{
return backlog_;
}
void HttpListener::backlog(int value)
{
backlog_ = value;
}
} // namespace x0
<commit_msg>code cleanup<commit_after>/* <x0/HttpListener.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpListener.h>
#include <x0/http/HttpConnection.h>
#include <x0/http/HttpServer.h>
#include <x0/SocketDriver.h>
#include <x0/sysconfig.h>
#include <arpa/inet.h> // inet_pton()
#include <netinet/tcp.h> // TCP_QUICKACK, TCP_DEFER_ACCEPT
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
namespace x0 {
HttpListener::HttpListener(HttpServer& srv) :
watcher_(srv.loop()),
fd_(-1),
server_(srv),
address_(),
port_(-1),
backlog_(SOMAXCONN),
errors_(0),
socketDriver_(new SocketDriver(srv.loop()))
{
watcher_.set<HttpListener, &HttpListener::callback>(this);
}
HttpListener::~HttpListener()
{
stop();
}
void HttpListener::stop()
{
if (fd_ == -1)
return;
watcher_.stop();
::close(fd_);
fd_ = -1;
setSocketDriver(NULL);
}
inline void HttpListener::setsockopt(int socket, int layer, int option, int value)
{
if (::setsockopt(socket, layer, option, &value, sizeof(value)) < 0)
{
log(Severity::error, "Error setting socket option (fd=%d, layer=%d, opt=%d, val=%d): %s",
socket, layer, option, value, strerror(errno));
}
}
void HttpListener::setSocketDriver(SocketDriver *sd)
{
if (socketDriver_)
delete socketDriver_;
socketDriver_ = sd;
}
std::error_code HttpListener::prepare()
{
#if defined(WITH_SSL)
if (isSecure())
log(Severity::info, "Start listening on [%s]:%d [secure]", address_.c_str(), port_);
else
log(Severity::info, "Start listening on [%s]:%d", address_.c_str(), port_);
#else
log(Severity::info, "Start listening on [%s]:%d", address_.c_str(), port_);
#endif
fd_ = ::socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (fd_ < 0) return std::make_error_code(static_cast<std::errc>(errno));
fcntl(fd_, F_SETFL, FD_CLOEXEC);
if (fcntl(fd_, F_SETFL, O_NONBLOCK) < 0)
{
//log(Severity::error, "could not set server socket into non-blocking mode: %s\n", strerror(errno));
return std::make_error_code(static_cast<std::errc>(errno));
}
sockaddr_in6 sin;
bzero(&sin, sizeof(sin));
sin.sin6_family = AF_INET6;
sin.sin6_port = htons(port_);
if (inet_pton(sin.sin6_family, address_.c_str(), sin.sin6_addr.s6_addr) < 0)
log(Severity::error, "Could not resolve IP address (%s): %s", address_.c_str(), strerror(errno));
#if defined(SO_REUSEADDR)
//! \todo SO_REUSEADDR: could be configurable
setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, 1);
#endif
#if defined(TCP_QUICKACK)
//! \todo TCP_QUICKACK: could be configurable
setsockopt(fd_, SOL_TCP, TCP_QUICKACK, 1);
#endif
#if defined(TCP_DEFER_ACCEPT)
setsockopt(fd_, SOL_TCP, TCP_DEFER_ACCEPT, 1);
#endif
// acceptor_.set_option(asio::ip::tcp::acceptor::linger(false, 0));
// acceptor_.set_option(asio::ip::tcp::acceptor::keep_alive(true));
if (::bind(fd_, (sockaddr *)&sin, sizeof(sin)) < 0) {
log(Severity::error, "Cannot bind to IP-address (%s): %s", address_.c_str(), strerror(errno));
return std::make_error_code(static_cast<std::errc>(errno));
}
if (::listen(fd_, backlog_) < 0) {
log(Severity::error, "Cannot listen to IP-address (%s): %s", address_.c_str(), strerror(errno));
return std::make_error_code(static_cast<std::errc>(errno));
}
return std::error_code();
}
std::error_code HttpListener::start()
{
std::error_code ec;
if (fd_ == -1)
{
ec = prepare();
if (ec)
return ec;
}
watcher_.start(fd_, ev::READ);
return ec;
}
void HttpListener::callback(ev::io& watcher, int revents)
{
// TODO accept() as much until it would block.
if (HttpConnection *c = new HttpConnection(*this))
{
if (c->isClosed())
delete c;
else
// TODO: introduce a PREPARE mode, that would defer the code fragment below - required for SSL handshaking, which takes place *before* processing the HTTP request
c->start();
}
}
std::string HttpListener::address() const
{
return address_;
}
void HttpListener::address(const std::string& value)
{
address_ = value;
}
int HttpListener::port() const
{
return port_;
}
void HttpListener::port(int value)
{
port_ = value;
}
int HttpListener::backlog() const
{
return backlog_;
}
void HttpListener::backlog(int value)
{
backlog_ = value;
}
} // namespace x0
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 Module
* -------------------------------------------------
*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Negative Precise Tests
*//*--------------------------------------------------------------------*/
#include "es31fNegativePreciseTests.hpp"
#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"
namespace deqp
{
namespace gles31
{
namespace Functional
{
namespace NegativeTestShared
{
namespace
{
enum TestPrecise
{
TEST_PRECISE_AS_VARIABLE_NAME = 0,
TEST_PRECISE_AS_FUNCTION_NAME,
TEST_PRECISE_AS_ARGUMENT_NAME,
TEST_PRECISE_AS_MACRO_NAME,
TEST_PRECISE_MACRO_AND_VARIABLE,
TEST_PRECISE_MACRO_AND_FUNCTION,
TEST_PRECISE_MACRO_AND_ARGUMENT,
TEST_PRECISE_LAST
};
static const glu::ShaderType s_shaderTypes[] =
{
glu::SHADERTYPE_VERTEX,
glu::SHADERTYPE_FRAGMENT,
glu::SHADERTYPE_GEOMETRY,
glu::SHADERTYPE_COMPUTE,
glu::SHADERTYPE_TESSELLATION_CONTROL,
glu::SHADERTYPE_TESSELLATION_EVALUATION
};
std::string generateShaderSource (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
const bool isES32 = contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2));
const glu::GLSLVersion version = isES32 ? glu::GLSL_VERSION_320_ES : glu::GLSL_VERSION_310_ES;
std::ostringstream source;
source << glu::getGLSLVersionDeclaration(version) << "\n"
<< (isES32 ? "" : "#extension GL_EXT_gpu_shader5 : enable\n");
switch (test)
{
case TEST_PRECISE_AS_MACRO_NAME: source << "#define precise 0\n"; break;
case TEST_PRECISE_MACRO_AND_VARIABLE:
case TEST_PRECISE_MACRO_AND_FUNCTION:
case TEST_PRECISE_MACRO_AND_ARGUMENT: source << "#define precise aName\n"; break;
default:
break;
}
switch (shaderType)
{
case glu::SHADERTYPE_GEOMETRY:
source << (isES32 ? "" : "#extension GL_EXT_geometry_shader : enable\n")
<< "layout(max_vertices = 5) out;\n";
break;
case glu::SHADERTYPE_TESSELLATION_CONTROL:
source << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
<< "layout(vertices = 3) out;\n";
break;
case glu::SHADERTYPE_TESSELLATION_EVALUATION:
source << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
<< "layout(triangles, equal_spacing, cw) in;\n";
break;
default:
break;
}
switch (test)
{
case TEST_PRECISE_AS_FUNCTION_NAME:
case TEST_PRECISE_MACRO_AND_FUNCTION:
source << "\n"
<< "void precise()\n"
<< "{\n"
<< "}\n";
break;
case TEST_PRECISE_AS_ARGUMENT_NAME:
case TEST_PRECISE_MACRO_AND_ARGUMENT:
source << "\n"
<< "void example(int precise)\n"
<< "{\n"
<< "}\n";
break;
default:
break;
}
source << "void main()\n"
<< "{\n";
switch (test)
{
case TEST_PRECISE_AS_VARIABLE_NAME:
case TEST_PRECISE_MACRO_AND_VARIABLE: source << " int precise = 1;\n"; break;
case TEST_PRECISE_AS_MACRO_NAME: source << " int number = precise;\n"; break;
default:
break;
}
source << "}\n";
return source.str();
}
void generateAndVerifyShader (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
glu::Shader shader (ctx.getRenderContext(), shaderType);
std::string shaderSource = generateShaderSource(ctx, shaderType, test);
const char* const source = shaderSource.c_str();
const int length = (int) shaderSource.size();
shader.setSources(1, &source, &length);
shader.compile();
ctx.getLog() << shader;
if (shader.getCompileStatus())
ctx.fail("Shader was not expected to compile.");
}
void precise_as_variable_name (NegativeTestContext& ctx)
{
TCU_CHECK_AND_THROW(NotSupportedError,
ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");
ctx.beginSection("Test that precise cannot be used as a variable name.");
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_VARIABLE_NAME);
ctx.endSection();
}
void precise_as_function_name (NegativeTestContext& ctx)
{
TCU_CHECK_AND_THROW(NotSupportedError,
ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");
ctx.beginSection("Test that precise cannot be used as a function name.");
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_FUNCTION_NAME);
ctx.endSection();
}
void precise_as_function_argument (NegativeTestContext& ctx)
{
TCU_CHECK_AND_THROW(NotSupportedError,
ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");
ctx.beginSection("Test that precise cannot be used as a argument name.");
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_ARGUMENT_NAME);
ctx.endSection();
}
} // anonymous
std::vector<FunctionContainer> getNegativePreciseTestFunctions (void)
{
const FunctionContainer funcs[] =
{
{precise_as_variable_name, "precise_as_variable_name", "Test precise keyword as variable name." },
{precise_as_function_name, "precise_as_function_name", "Test precise keyword as function name." },
{precise_as_function_argument, "precise_as_function_argument", "Test precise keyword as argument name." },
};
return std::vector<FunctionContainer>(DE_ARRAY_BEGIN(funcs), DE_ARRAY_END(funcs));
}
} // NegativeTestShared
} // Functional
} // gles31
} // deqp
<commit_msg>Check for shader type support in negative precise tests am: 4a3a2d79a0<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 Module
* -------------------------------------------------
*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Negative Precise Tests
*//*--------------------------------------------------------------------*/
#include "es31fNegativePreciseTests.hpp"
#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"
namespace deqp
{
namespace gles31
{
namespace Functional
{
namespace NegativeTestShared
{
namespace
{
enum TestPrecise
{
TEST_PRECISE_AS_VARIABLE_NAME = 0,
TEST_PRECISE_AS_FUNCTION_NAME,
TEST_PRECISE_AS_ARGUMENT_NAME,
TEST_PRECISE_AS_MACRO_NAME,
TEST_PRECISE_MACRO_AND_VARIABLE,
TEST_PRECISE_MACRO_AND_FUNCTION,
TEST_PRECISE_MACRO_AND_ARGUMENT,
TEST_PRECISE_LAST
};
static const glu::ShaderType s_shaderTypes[] =
{
glu::SHADERTYPE_VERTEX,
glu::SHADERTYPE_FRAGMENT,
glu::SHADERTYPE_GEOMETRY,
glu::SHADERTYPE_COMPUTE,
glu::SHADERTYPE_TESSELLATION_CONTROL,
glu::SHADERTYPE_TESSELLATION_EVALUATION
};
std::string generateShaderSource (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
const bool isES32 = contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2));
const glu::GLSLVersion version = isES32 ? glu::GLSL_VERSION_320_ES : glu::GLSL_VERSION_310_ES;
std::ostringstream source;
source << glu::getGLSLVersionDeclaration(version) << "\n"
<< (isES32 ? "" : "#extension GL_EXT_gpu_shader5 : enable\n");
switch (test)
{
case TEST_PRECISE_AS_MACRO_NAME: source << "#define precise 0\n"; break;
case TEST_PRECISE_MACRO_AND_VARIABLE:
case TEST_PRECISE_MACRO_AND_FUNCTION:
case TEST_PRECISE_MACRO_AND_ARGUMENT: source << "#define precise aName\n"; break;
default:
break;
}
switch (shaderType)
{
case glu::SHADERTYPE_GEOMETRY:
source << (isES32 ? "" : "#extension GL_EXT_geometry_shader : enable\n")
<< "layout(max_vertices = 5) out;\n";
break;
case glu::SHADERTYPE_TESSELLATION_CONTROL:
source << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
<< "layout(vertices = 3) out;\n";
break;
case glu::SHADERTYPE_TESSELLATION_EVALUATION:
source << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
<< "layout(triangles, equal_spacing, cw) in;\n";
break;
default:
break;
}
switch (test)
{
case TEST_PRECISE_AS_FUNCTION_NAME:
case TEST_PRECISE_MACRO_AND_FUNCTION:
source << "\n"
<< "void precise()\n"
<< "{\n"
<< "}\n";
break;
case TEST_PRECISE_AS_ARGUMENT_NAME:
case TEST_PRECISE_MACRO_AND_ARGUMENT:
source << "\n"
<< "void example(int precise)\n"
<< "{\n"
<< "}\n";
break;
default:
break;
}
source << "void main()\n"
<< "{\n";
switch (test)
{
case TEST_PRECISE_AS_VARIABLE_NAME:
case TEST_PRECISE_MACRO_AND_VARIABLE: source << " int precise = 1;\n"; break;
case TEST_PRECISE_AS_MACRO_NAME: source << " int number = precise;\n"; break;
default:
break;
}
source << "}\n";
return source.str();
}
void generateAndVerifyShader (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
glu::Shader shader (ctx.getRenderContext(), shaderType);
std::string shaderSource = generateShaderSource(ctx, shaderType, test);
const char* const source = shaderSource.c_str();
const int length = (int) shaderSource.size();
shader.setSources(1, &source, &length);
shader.compile();
ctx.getLog() << shader;
if (shader.getCompileStatus())
ctx.fail("Shader was not expected to compile.");
}
void precise_as_variable_name (NegativeTestContext& ctx)
{
TCU_CHECK_AND_THROW(NotSupportedError,
ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");
ctx.beginSection("Test that precise cannot be used as a variable name.");
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
{
if (ctx.isShaderSupported(s_shaderTypes[ndx]))
generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_VARIABLE_NAME);
}
ctx.endSection();
}
void precise_as_function_name (NegativeTestContext& ctx)
{
TCU_CHECK_AND_THROW(NotSupportedError,
ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");
ctx.beginSection("Test that precise cannot be used as a function name.");
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
{
if (ctx.isShaderSupported(s_shaderTypes[ndx]))
generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_FUNCTION_NAME);
}
ctx.endSection();
}
void precise_as_function_argument (NegativeTestContext& ctx)
{
TCU_CHECK_AND_THROW(NotSupportedError,
ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");
ctx.beginSection("Test that precise cannot be used as a argument name.");
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
{
if (ctx.isShaderSupported(s_shaderTypes[ndx]))
generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_ARGUMENT_NAME);
}
ctx.endSection();
}
} // anonymous
std::vector<FunctionContainer> getNegativePreciseTestFunctions (void)
{
const FunctionContainer funcs[] =
{
{precise_as_variable_name, "precise_as_variable_name", "Test precise keyword as variable name." },
{precise_as_function_name, "precise_as_function_name", "Test precise keyword as function name." },
{precise_as_function_argument, "precise_as_function_argument", "Test precise keyword as argument name." },
};
return std::vector<FunctionContainer>(DE_ARRAY_BEGIN(funcs), DE_ARRAY_END(funcs));
}
} // NegativeTestShared
} // Functional
} // gles31
} // deqp
<|endoftext|>
|
<commit_before>#include "execHelperOptions.h"
#include <iostream>
#include <string>
#include <assert.h>
#include "log/log.h"
#include "yaml/yaml.h"
#include "config/settingsNode.h"
#include "executorInterface.h"
#include "pattern.h"
#include "patternsHandler.h"
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::shared_ptr;
using std::make_shared;
using boost::program_options::variables_map;
using execHelper::core::CommandCollection;
using execHelper::config::SettingsNode;
using execHelper::yaml::Yaml;
using execHelper::yaml::YamlFile;
namespace execHelper { namespace core {
ExecHelperOptions::ExecHelperOptions() noexcept :
m_verbose(false),
m_singleThreaded(false),
m_executor(0)
{
;
}
ExecHelperOptions::ExecHelperOptions(const ExecHelperOptions& other) noexcept :
m_verbose(other.m_verbose),
m_singleThreaded(other.m_singleThreaded),
m_settings(other.m_settings),
m_executor(other.m_executor)
{
;
}
bool ExecHelperOptions::operator==(const ExecHelperOptions& other) const noexcept {
return (
m_verbose == other.m_verbose &&
m_singleThreaded == other.m_singleThreaded &&
m_settings == other.m_settings &&
m_patternsHandler == other.m_patternsHandler &&
m_executor == other.m_executor
);
}
bool ExecHelperOptions::operator!=(const ExecHelperOptions& other) const noexcept {
return !(*this == other);
}
bool ExecHelperOptions::getVerbosity() const noexcept {
return m_verbose;
}
bool ExecHelperOptions::getDryRun() const noexcept {
return m_dryRun;
}
bool ExecHelperOptions::getSingleThreaded() const noexcept {
return m_singleThreaded;
}
const CommandCollection& ExecHelperOptions::getCommands() const noexcept {
return m_commands;
}
string ExecHelperOptions::getSettingsFile(int argc, const char* const * argv) const noexcept {
variables_map optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv, true);
if(optionsMap.count("settings-file")) {
return optionsMap["settings-file"].as<string>();
}
return ".exec-helper";
}
bool ExecHelperOptions::parse(int argc, const char* const * argv) {
m_optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv);
if(m_optionsMap.count("verbose")) {
m_verbose = true;
}
if(m_optionsMap.count("single-threaded")) {
m_singleThreaded = true;
}
if(m_optionsMap.count("command")) {
m_commands.clear();
m_commands = m_optionsMap["command"].as<CommandCollection>();
}
return true;
}
bool ExecHelperOptions::parseSettingsFile(const std::string& file) noexcept {
YamlFile yamlFile;
yamlFile.file = file;
Yaml yaml(yamlFile);
if(! yaml.getTree({}, m_settings)) {
LOG("Could not get settings tree");
return false;
}
static const string patternsKey("patterns");
if(m_settings.contains(patternsKey)) {
for(const auto& pattern : m_settings[patternsKey].m_values) {
PatternKey key = pattern.m_key;
PatternValues defaultValues;
for(const auto& defaultValue : pattern["default-values"].toStringCollection()) {
defaultValues.push_back(defaultValue);
}
static const string shortOptionKey("short-option");
string shortOptionString;
if(pattern.contains(shortOptionKey)) {
shortOptionString = pattern[shortOptionKey].m_values.back().m_key;
}
char shortOption = '\0';
if(shortOptionString.size() > 0) {
shortOption = shortOptionString.at(0);
}
static const string longOptionKey("long-option");
string longOption;
if(pattern.contains(longOptionKey)) {
longOption = pattern[longOptionKey].m_values.back().m_key;
}
m_patternsHandler.addPattern(Pattern(key, defaultValues, shortOption, longOption));
string option = longOption + "," + shortOptionString;
string explanation = string("Values for pattern '") + key + "'";
m_optionsDescriptions.addOption<PatternValues>(option, explanation, true);
}
}
return true;
}
bool ExecHelperOptions::containsHelp() const noexcept {
return (m_optionsMap.count("help") > 0U);
}
const config::SettingsNode& ExecHelperOptions::getSettings() const noexcept {
return m_settings;
}
const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) noexcept {
if(m_settings.contains(key)) {
return m_settings[key];
}
return m_settings;
}
const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) const noexcept {
if(m_settings.contains(key)) {
return m_settings[key];
}
return m_settings;
}
void ExecHelperOptions::setExecutor(ExecutorInterface* const executor) noexcept {
m_executor = executor;
}
ExecutorInterface* ExecHelperOptions::getExecutor() const noexcept {
assert(m_executor != 0);
return m_executor;
}
void ExecHelperOptions::printHelp() const noexcept {
user_feedback(m_optionsDescriptions.getOptionDescriptions());
}
bool ExecHelperOptions::contains(const std::string& longOptions) const noexcept {
return m_optionsMap.count(longOptions) > 0;
}
vector<string> ExecHelperOptions::getLongOption(const std::string& longOptions) const noexcept {
return m_optionsMap[longOptions].as<vector<string>>();
}
const PatternsHandler& ExecHelperOptions::getPatternsHandler() const noexcept {
return m_patternsHandler;
}
PatternValues ExecHelperOptions::getValues(const Pattern& pattern) const noexcept {
string longOption = pattern.getLongOption();
if(contains(longOption)) {
return getLongOption(longOption);
}
return pattern.getDefaultValues();
}
PatternPermutator ExecHelperOptions::makePatternPermutator(const PatternKeys& patterns) const noexcept {
std::map<core::PatternKey, core::PatternValues> patternValuesMatrix;
for(const auto& patternKey : patterns) {
core::Pattern pattern = m_patternsHandler.getPattern(patternKey);
PatternValues commandlineValues = getValues(pattern);
patternValuesMatrix.emplace(pattern.getKey(), commandlineValues);
}
return core::PatternPermutator(patternValuesMatrix);
}
} }
<commit_msg>Fixed issue where everything got dry-runned all the time<commit_after>#include "execHelperOptions.h"
#include <iostream>
#include <string>
#include <assert.h>
#include "log/log.h"
#include "yaml/yaml.h"
#include "config/settingsNode.h"
#include "executorInterface.h"
#include "pattern.h"
#include "patternsHandler.h"
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::shared_ptr;
using std::make_shared;
using boost::program_options::variables_map;
using execHelper::core::CommandCollection;
using execHelper::config::SettingsNode;
using execHelper::yaml::Yaml;
using execHelper::yaml::YamlFile;
namespace execHelper { namespace core {
ExecHelperOptions::ExecHelperOptions() noexcept :
m_verbose(false),
m_dryRun(false),
m_singleThreaded(false),
m_executor(0)
{
;
}
ExecHelperOptions::ExecHelperOptions(const ExecHelperOptions& other) noexcept :
m_verbose(other.m_verbose),
m_dryRun(other.m_dryRun),
m_singleThreaded(other.m_singleThreaded),
m_settings(other.m_settings),
m_executor(other.m_executor)
{
;
}
bool ExecHelperOptions::operator==(const ExecHelperOptions& other) const noexcept {
return (
m_verbose == other.m_verbose &&
m_dryRun == other.m_dryRun &&
m_singleThreaded == other.m_singleThreaded &&
m_settings == other.m_settings &&
m_patternsHandler == other.m_patternsHandler &&
m_executor == other.m_executor
);
}
bool ExecHelperOptions::operator!=(const ExecHelperOptions& other) const noexcept {
return !(*this == other);
}
bool ExecHelperOptions::getVerbosity() const noexcept {
return m_verbose;
}
bool ExecHelperOptions::getDryRun() const noexcept {
return m_dryRun;
}
bool ExecHelperOptions::getSingleThreaded() const noexcept {
return m_singleThreaded;
}
const CommandCollection& ExecHelperOptions::getCommands() const noexcept {
return m_commands;
}
string ExecHelperOptions::getSettingsFile(int argc, const char* const * argv) const noexcept {
variables_map optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv, true);
if(optionsMap.count("settings-file")) {
return optionsMap["settings-file"].as<string>();
}
return ".exec-helper";
}
bool ExecHelperOptions::parse(int argc, const char* const * argv) {
m_optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv);
if(m_optionsMap.count("verbose")) {
m_verbose = true;
}
if(m_optionsMap.count("dry-run")) {
m_dryRun = true;
}
if(m_optionsMap.count("single-threaded")) {
m_singleThreaded = true;
}
if(m_optionsMap.count("command")) {
m_commands.clear();
m_commands = m_optionsMap["command"].as<CommandCollection>();
}
return true;
}
bool ExecHelperOptions::parseSettingsFile(const std::string& file) noexcept {
YamlFile yamlFile;
yamlFile.file = file;
Yaml yaml(yamlFile);
if(! yaml.getTree({}, m_settings)) {
LOG("Could not get settings tree");
return false;
}
static const string patternsKey("patterns");
if(m_settings.contains(patternsKey)) {
for(const auto& pattern : m_settings[patternsKey].m_values) {
PatternKey key = pattern.m_key;
PatternValues defaultValues;
for(const auto& defaultValue : pattern["default-values"].toStringCollection()) {
defaultValues.push_back(defaultValue);
}
static const string shortOptionKey("short-option");
string shortOptionString;
if(pattern.contains(shortOptionKey)) {
shortOptionString = pattern[shortOptionKey].m_values.back().m_key;
}
char shortOption = '\0';
if(shortOptionString.size() > 0) {
shortOption = shortOptionString.at(0);
}
static const string longOptionKey("long-option");
string longOption;
if(pattern.contains(longOptionKey)) {
longOption = pattern[longOptionKey].m_values.back().m_key;
}
m_patternsHandler.addPattern(Pattern(key, defaultValues, shortOption, longOption));
string option = longOption + "," + shortOptionString;
string explanation = string("Values for pattern '") + key + "'";
m_optionsDescriptions.addOption<PatternValues>(option, explanation, true);
}
}
return true;
}
bool ExecHelperOptions::containsHelp() const noexcept {
return (m_optionsMap.count("help") > 0U);
}
const config::SettingsNode& ExecHelperOptions::getSettings() const noexcept {
return m_settings;
}
const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) noexcept {
if(m_settings.contains(key)) {
return m_settings[key];
}
return m_settings;
}
const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) const noexcept {
if(m_settings.contains(key)) {
return m_settings[key];
}
return m_settings;
}
void ExecHelperOptions::setExecutor(ExecutorInterface* const executor) noexcept {
m_executor = executor;
}
ExecutorInterface* ExecHelperOptions::getExecutor() const noexcept {
assert(m_executor != 0);
return m_executor;
}
void ExecHelperOptions::printHelp() const noexcept {
user_feedback(m_optionsDescriptions.getOptionDescriptions());
}
bool ExecHelperOptions::contains(const std::string& longOptions) const noexcept {
return m_optionsMap.count(longOptions) > 0;
}
vector<string> ExecHelperOptions::getLongOption(const std::string& longOptions) const noexcept {
return m_optionsMap[longOptions].as<vector<string>>();
}
const PatternsHandler& ExecHelperOptions::getPatternsHandler() const noexcept {
return m_patternsHandler;
}
PatternValues ExecHelperOptions::getValues(const Pattern& pattern) const noexcept {
string longOption = pattern.getLongOption();
if(contains(longOption)) {
return getLongOption(longOption);
}
return pattern.getDefaultValues();
}
PatternPermutator ExecHelperOptions::makePatternPermutator(const PatternKeys& patterns) const noexcept {
std::map<core::PatternKey, core::PatternValues> patternValuesMatrix;
for(const auto& patternKey : patterns) {
core::Pattern pattern = m_patternsHandler.getPattern(patternKey);
PatternValues commandlineValues = getValues(pattern);
patternValuesMatrix.emplace(pattern.getKey(), commandlineValues);
}
return core::PatternPermutator(patternValuesMatrix);
}
} }
<|endoftext|>
|
<commit_before><commit_msg>perception:io_util add range check<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Erik Hallnor
* Steve Reinhardt
* Andreas Hansson
*/
#include "cpu/testers/memtest/memtest.hh"
#include "base/random.hh"
#include "base/statistics.hh"
#include "base/trace.hh"
#include "debug/MemTest.hh"
#include "sim/sim_exit.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
using namespace std;
unsigned int TESTER_ALLOCATOR = 0;
bool
MemTest::CpuPort::recvTimingResp(PacketPtr pkt)
{
memtest.completeRequest(pkt);
return true;
}
void
MemTest::CpuPort::recvReqRetry()
{
memtest.recvRetry();
}
bool
MemTest::sendPkt(PacketPtr pkt) {
if (atomic) {
port.sendAtomic(pkt);
completeRequest(pkt);
} else {
if (!port.sendTimingReq(pkt)) {
retryPkt = pkt;
return false;
}
}
return true;
}
MemTest::MemTest(const Params *p)
: ClockedObject(p),
tickEvent([this]{ tick(); }, name()),
noRequestEvent([this]{ noRequest(); }, name()),
noResponseEvent([this]{ noResponse(); }, name()),
port("port", *this),
retryPkt(nullptr),
size(p->size),
interval(p->interval),
percentReads(p->percent_reads),
percentFunctional(p->percent_functional),
percentUncacheable(p->percent_uncacheable),
masterId(p->system->getMasterId(this)),
blockSize(p->system->cacheLineSize()),
blockAddrMask(blockSize - 1),
progressInterval(p->progress_interval),
progressCheck(p->progress_check),
nextProgressMessage(p->progress_interval),
maxLoads(p->max_loads),
atomic(p->system->isAtomicMode()),
suppressFuncWarnings(p->suppress_func_warnings)
{
id = TESTER_ALLOCATOR++;
fatal_if(id >= blockSize, "Too many testers, only %d allowed\n",
blockSize - 1);
baseAddr1 = 0x100000;
baseAddr2 = 0x400000;
uncacheAddr = 0x800000;
// set up counters
numReads = 0;
numWrites = 0;
// kick things into action
schedule(tickEvent, curTick());
schedule(noRequestEvent, clockEdge(progressCheck));
schedule(noResponseEvent, clockEdge(progressCheck));
}
Port &
MemTest::getPort(const std::string &if_name, PortID idx)
{
if (if_name == "port")
return port;
else
return ClockedObject::getPort(if_name, idx);
}
void
MemTest::completeRequest(PacketPtr pkt, bool functional)
{
const RequestPtr &req = pkt->req;
assert(req->getSize() == 1);
// this address is no longer outstanding
auto remove_addr = outstandingAddrs.find(req->getPaddr());
assert(remove_addr != outstandingAddrs.end());
outstandingAddrs.erase(remove_addr);
DPRINTF(MemTest, "Completing %s at address %x (blk %x) %s\n",
pkt->isWrite() ? "write" : "read",
req->getPaddr(), blockAlign(req->getPaddr()),
pkt->isError() ? "error" : "success");
const uint8_t *pkt_data = pkt->getConstPtr<uint8_t>();
if (pkt->isError()) {
if (!functional || !suppressFuncWarnings) {
warn("%s access failed at %#x\n",
pkt->isWrite() ? "Write" : "Read", req->getPaddr());
}
} else {
if (pkt->isRead()) {
uint8_t ref_data = referenceData[req->getPaddr()];
if (pkt_data[0] != ref_data) {
panic("%s: read of %x (blk %x) @ cycle %d "
"returns %x, expected %x\n", name(),
req->getPaddr(), blockAlign(req->getPaddr()), curTick(),
pkt_data[0], ref_data);
}
numReads++;
numReadsStat++;
if (numReads == (uint64_t)nextProgressMessage) {
ccprintf(cerr, "%s: completed %d read, %d write accesses @%d\n",
name(), numReads, numWrites, curTick());
nextProgressMessage += progressInterval;
}
if (maxLoads != 0 && numReads >= maxLoads)
exitSimLoop("maximum number of loads reached");
} else {
assert(pkt->isWrite());
// update the reference data
referenceData[req->getPaddr()] = pkt_data[0];
numWrites++;
numWritesStat++;
}
}
// the packet will delete the data
delete pkt;
// finally shift the response timeout forward
reschedule(noResponseEvent, clockEdge(progressCheck), true);
}
void
MemTest::regStats()
{
ClockedObject::regStats();
using namespace Stats;
numReadsStat
.name(name() + ".num_reads")
.desc("number of read accesses completed")
;
numWritesStat
.name(name() + ".num_writes")
.desc("number of write accesses completed")
;
}
void
MemTest::tick()
{
// we should never tick if we are waiting for a retry
assert(!retryPkt);
// create a new request
unsigned cmd = random_mt.random(0, 100);
uint8_t data = random_mt.random<uint8_t>();
bool uncacheable = random_mt.random(0, 100) < percentUncacheable;
unsigned base = random_mt.random(0, 1);
Request::Flags flags;
Addr paddr;
// generate a unique address
do {
unsigned offset = random_mt.random<unsigned>(0, size - 1);
// use the tester id as offset within the block for false sharing
offset = blockAlign(offset);
offset += id;
if (uncacheable) {
flags.set(Request::UNCACHEABLE);
paddr = uncacheAddr + offset;
} else {
paddr = ((base) ? baseAddr1 : baseAddr2) + offset;
}
} while (outstandingAddrs.find(paddr) != outstandingAddrs.end());
bool do_functional = (random_mt.random(0, 100) < percentFunctional) &&
!uncacheable;
RequestPtr req = std::make_shared<Request>(paddr, 1, flags, masterId);
req->setContext(id);
outstandingAddrs.insert(paddr);
// sanity check
panic_if(outstandingAddrs.size() > 100,
"Tester %s has more than 100 outstanding requests\n", name());
PacketPtr pkt = nullptr;
uint8_t *pkt_data = new uint8_t[1];
if (cmd < percentReads) {
// start by ensuring there is a reference value if we have not
// seen this address before
uint8_t M5_VAR_USED ref_data = 0;
auto ref = referenceData.find(req->getPaddr());
if (ref == referenceData.end()) {
referenceData[req->getPaddr()] = 0;
} else {
ref_data = ref->second;
}
DPRINTF(MemTest,
"Initiating %sread at addr %x (blk %x) expecting %x\n",
do_functional ? "functional " : "", req->getPaddr(),
blockAlign(req->getPaddr()), ref_data);
pkt = new Packet(req, MemCmd::ReadReq);
pkt->dataDynamic(pkt_data);
} else {
DPRINTF(MemTest, "Initiating %swrite at addr %x (blk %x) value %x\n",
do_functional ? "functional " : "", req->getPaddr(),
blockAlign(req->getPaddr()), data);
pkt = new Packet(req, MemCmd::WriteReq);
pkt->dataDynamic(pkt_data);
pkt_data[0] = data;
}
// there is no point in ticking if we are waiting for a retry
bool keep_ticking = true;
if (do_functional) {
pkt->setSuppressFuncError();
port.sendFunctional(pkt);
completeRequest(pkt, true);
} else {
keep_ticking = sendPkt(pkt);
}
if (keep_ticking) {
// schedule the next tick
schedule(tickEvent, clockEdge(interval));
// finally shift the timeout for sending of requests forwards
// as we have successfully sent a packet
reschedule(noRequestEvent, clockEdge(progressCheck), true);
} else {
DPRINTF(MemTest, "Waiting for retry\n");
}
}
void
MemTest::noRequest()
{
panic("%s did not send a request for %d cycles", name(), progressCheck);
}
void
MemTest::noResponse()
{
panic("%s did not see a response for %d cycles", name(), progressCheck);
}
void
MemTest::recvRetry()
{
assert(retryPkt);
if (port.sendTimingReq(retryPkt)) {
DPRINTF(MemTest, "Proceeding after successful retry\n");
retryPkt = nullptr;
// kick things into action again
schedule(tickEvent, clockEdge(interval));
}
}
MemTest *
MemTestParams::create()
{
return new MemTest(this);
}
<commit_msg>cpu: Fix rescheduling of progress check events<commit_after>/*
* Copyright (c) 2015, 2019 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Erik Hallnor
* Steve Reinhardt
* Andreas Hansson
*/
#include "cpu/testers/memtest/memtest.hh"
#include "base/random.hh"
#include "base/statistics.hh"
#include "base/trace.hh"
#include "debug/MemTest.hh"
#include "sim/sim_exit.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
using namespace std;
unsigned int TESTER_ALLOCATOR = 0;
bool
MemTest::CpuPort::recvTimingResp(PacketPtr pkt)
{
memtest.completeRequest(pkt);
return true;
}
void
MemTest::CpuPort::recvReqRetry()
{
memtest.recvRetry();
}
bool
MemTest::sendPkt(PacketPtr pkt) {
if (atomic) {
port.sendAtomic(pkt);
completeRequest(pkt);
} else {
if (!port.sendTimingReq(pkt)) {
retryPkt = pkt;
return false;
}
}
return true;
}
MemTest::MemTest(const Params *p)
: ClockedObject(p),
tickEvent([this]{ tick(); }, name()),
noRequestEvent([this]{ noRequest(); }, name()),
noResponseEvent([this]{ noResponse(); }, name()),
port("port", *this),
retryPkt(nullptr),
size(p->size),
interval(p->interval),
percentReads(p->percent_reads),
percentFunctional(p->percent_functional),
percentUncacheable(p->percent_uncacheable),
masterId(p->system->getMasterId(this)),
blockSize(p->system->cacheLineSize()),
blockAddrMask(blockSize - 1),
progressInterval(p->progress_interval),
progressCheck(p->progress_check),
nextProgressMessage(p->progress_interval),
maxLoads(p->max_loads),
atomic(p->system->isAtomicMode()),
suppressFuncWarnings(p->suppress_func_warnings)
{
id = TESTER_ALLOCATOR++;
fatal_if(id >= blockSize, "Too many testers, only %d allowed\n",
blockSize - 1);
baseAddr1 = 0x100000;
baseAddr2 = 0x400000;
uncacheAddr = 0x800000;
// set up counters
numReads = 0;
numWrites = 0;
// kick things into action
schedule(tickEvent, curTick());
schedule(noRequestEvent, clockEdge(progressCheck));
}
Port &
MemTest::getPort(const std::string &if_name, PortID idx)
{
if (if_name == "port")
return port;
else
return ClockedObject::getPort(if_name, idx);
}
void
MemTest::completeRequest(PacketPtr pkt, bool functional)
{
const RequestPtr &req = pkt->req;
assert(req->getSize() == 1);
// this address is no longer outstanding
auto remove_addr = outstandingAddrs.find(req->getPaddr());
assert(remove_addr != outstandingAddrs.end());
outstandingAddrs.erase(remove_addr);
DPRINTF(MemTest, "Completing %s at address %x (blk %x) %s\n",
pkt->isWrite() ? "write" : "read",
req->getPaddr(), blockAlign(req->getPaddr()),
pkt->isError() ? "error" : "success");
const uint8_t *pkt_data = pkt->getConstPtr<uint8_t>();
if (pkt->isError()) {
if (!functional || !suppressFuncWarnings) {
warn("%s access failed at %#x\n",
pkt->isWrite() ? "Write" : "Read", req->getPaddr());
}
} else {
if (pkt->isRead()) {
uint8_t ref_data = referenceData[req->getPaddr()];
if (pkt_data[0] != ref_data) {
panic("%s: read of %x (blk %x) @ cycle %d "
"returns %x, expected %x\n", name(),
req->getPaddr(), blockAlign(req->getPaddr()), curTick(),
pkt_data[0], ref_data);
}
numReads++;
numReadsStat++;
if (numReads == (uint64_t)nextProgressMessage) {
ccprintf(cerr, "%s: completed %d read, %d write accesses @%d\n",
name(), numReads, numWrites, curTick());
nextProgressMessage += progressInterval;
}
if (maxLoads != 0 && numReads >= maxLoads)
exitSimLoop("maximum number of loads reached");
} else {
assert(pkt->isWrite());
// update the reference data
referenceData[req->getPaddr()] = pkt_data[0];
numWrites++;
numWritesStat++;
}
}
// the packet will delete the data
delete pkt;
// finally shift the response timeout forward if we are still
// expecting responses; deschedule it otherwise
if (outstandingAddrs.size() != 0)
reschedule(noResponseEvent, clockEdge(progressCheck));
else if (noResponseEvent.scheduled())
deschedule(noResponseEvent);
}
void
MemTest::regStats()
{
ClockedObject::regStats();
using namespace Stats;
numReadsStat
.name(name() + ".num_reads")
.desc("number of read accesses completed")
;
numWritesStat
.name(name() + ".num_writes")
.desc("number of write accesses completed")
;
}
void
MemTest::tick()
{
// we should never tick if we are waiting for a retry
assert(!retryPkt);
// create a new request
unsigned cmd = random_mt.random(0, 100);
uint8_t data = random_mt.random<uint8_t>();
bool uncacheable = random_mt.random(0, 100) < percentUncacheable;
unsigned base = random_mt.random(0, 1);
Request::Flags flags;
Addr paddr;
// generate a unique address
do {
unsigned offset = random_mt.random<unsigned>(0, size - 1);
// use the tester id as offset within the block for false sharing
offset = blockAlign(offset);
offset += id;
if (uncacheable) {
flags.set(Request::UNCACHEABLE);
paddr = uncacheAddr + offset;
} else {
paddr = ((base) ? baseAddr1 : baseAddr2) + offset;
}
} while (outstandingAddrs.find(paddr) != outstandingAddrs.end());
bool do_functional = (random_mt.random(0, 100) < percentFunctional) &&
!uncacheable;
RequestPtr req = std::make_shared<Request>(paddr, 1, flags, masterId);
req->setContext(id);
outstandingAddrs.insert(paddr);
// sanity check
panic_if(outstandingAddrs.size() > 100,
"Tester %s has more than 100 outstanding requests\n", name());
PacketPtr pkt = nullptr;
uint8_t *pkt_data = new uint8_t[1];
if (cmd < percentReads) {
// start by ensuring there is a reference value if we have not
// seen this address before
uint8_t M5_VAR_USED ref_data = 0;
auto ref = referenceData.find(req->getPaddr());
if (ref == referenceData.end()) {
referenceData[req->getPaddr()] = 0;
} else {
ref_data = ref->second;
}
DPRINTF(MemTest,
"Initiating %sread at addr %x (blk %x) expecting %x\n",
do_functional ? "functional " : "", req->getPaddr(),
blockAlign(req->getPaddr()), ref_data);
pkt = new Packet(req, MemCmd::ReadReq);
pkt->dataDynamic(pkt_data);
} else {
DPRINTF(MemTest, "Initiating %swrite at addr %x (blk %x) value %x\n",
do_functional ? "functional " : "", req->getPaddr(),
blockAlign(req->getPaddr()), data);
pkt = new Packet(req, MemCmd::WriteReq);
pkt->dataDynamic(pkt_data);
pkt_data[0] = data;
}
// there is no point in ticking if we are waiting for a retry
bool keep_ticking = true;
if (do_functional) {
pkt->setSuppressFuncError();
port.sendFunctional(pkt);
completeRequest(pkt, true);
} else {
keep_ticking = sendPkt(pkt);
}
if (keep_ticking) {
// schedule the next tick
schedule(tickEvent, clockEdge(interval));
// finally shift the timeout for sending of requests forwards
// as we have successfully sent a packet
reschedule(noRequestEvent, clockEdge(progressCheck), true);
} else {
DPRINTF(MemTest, "Waiting for retry\n");
}
// Schedule noResponseEvent now if we are expecting a response
if (!noResponseEvent.scheduled() && (outstandingAddrs.size() != 0))
schedule(noResponseEvent, clockEdge(progressCheck));
}
void
MemTest::noRequest()
{
panic("%s did not send a request for %d cycles", name(), progressCheck);
}
void
MemTest::noResponse()
{
panic("%s did not see a response for %d cycles", name(), progressCheck);
}
void
MemTest::recvRetry()
{
assert(retryPkt);
if (port.sendTimingReq(retryPkt)) {
DPRINTF(MemTest, "Proceeding after successful retry\n");
retryPkt = nullptr;
// kick things into action again
schedule(tickEvent, clockEdge(interval));
reschedule(noRequestEvent, clockEdge(progressCheck), true);
}
}
MemTest *
MemTestParams::create()
{
return new MemTest(this);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/onboard/radar_process_subnode.h"
#include <string>
#include <unordered_map>
#include <algorithm>
#include "Eigen/Core"
#include "eigen_conversions/eigen_msg.h"
#include "pcl_conversions/pcl_conversions.h"
#include "ros/include/ros/ros.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time_util.h"
#include "modules/common/time/timer.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/calibration_config_manager.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/obstacle/base/object.h"
#include "modules/perception/obstacle/radar/dummy/dummy_algorithms.h"
#include "modules/perception/onboard/subnode_helper.h"
#include "modules/perception/onboard/transform_input.h"
namespace apollo {
namespace perception {
using apollo::common::adapter::AdapterManager;
using pcl_util::Point;
using pcl_util::PointD;
using Eigen::Matrix4d;
using Eigen::Affine3d;
using std::string;
using std::unordered_map;
bool RadarProcessSubnode::InitInternal() {
if (inited_) {
return true;
}
RegistAllAlgorithm();
if (!InitFrameDependence()) {
AERROR << "failed to Init frame dependence.";
return false;
}
if (!InitAlgorithmPlugin()) {
AERROR << "failed to Init algorithm plugin.";
return false;
}
// parse reserve fileds
unordered_map<string, string> reserve_field_map;
if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
AERROR << "Failed to parse reserve filed: " << reserve_;
return false;
}
if (reserve_field_map.find("device_id") == reserve_field_map.end()) {
AERROR << "Failed to find field device_id, reserve: " << reserve_;
return false;
}
device_id_ = reserve_field_map["device_id"];
CHECK(AdapterManager::GetContiRadar()) << "Radar is not initialized.";
AdapterManager::AddContiRadarCallback(&RadarProcessSubnode::OnRadar, this);
CHECK(AdapterManager::GetLocalization()) << "Localiztion is not initialized.";
AdapterManager::AddLocalizationCallback(&RadarProcessSubnode::OnLocalization,
this);
localization_buffer_.set_capacity(FLAGS_localization_buffer_size);
std::string radar_extrinstic_path = FLAGS_radar_extrinsic_file;
AINFO << "radar extrinsic path: " << radar_extrinstic_path;
Eigen::Affine3d radar_extrinsic;
if (!LoadExtrinsic(radar_extrinstic_path, &radar_extrinsic)) {
AERROR << "Failed to load extrinsic.";
return false;
}
radar_extrinsic_ = radar_extrinsic.matrix();
AINFO << "get radar extrinsic succ. pose: \n" << radar_extrinsic_;
std::string short_camera_extrinsic_path = FLAGS_short_camera_extrinsic_file;
AINFO << "short camera extrinsic path: " << short_camera_extrinsic_path;
Eigen::Affine3d short_camera_extrinsic;
if (!LoadExtrinsic(short_camera_extrinsic_path, &short_camera_extrinsic)) {
AERROR << "Failed to load extrinsic.";
return false;
}
short_camera_extrinsic_ = short_camera_extrinsic.matrix();
AINFO << "get short camera extrinsic succ. pose: \n"
<< short_camera_extrinsic_;
inited_ = true;
return true;
}
void RadarProcessSubnode::OnRadar(const ContiRadar &radar_obs) {
PERF_FUNCTION("RadarProcess");
ContiRadar radar_obs_proto = radar_obs;
double timestamp = radar_obs_proto.header().timestamp_sec();
double unix_timestamp = timestamp;
const double cur_time = common::time::Clock::NowInSeconds();
const double start_latency = (cur_time - unix_timestamp) * 1e3;
AINFO << "FRAME_STATISTICS:Radar:Start:msg_time[" << GLOG_TIMESTAMP(timestamp)
<< "]:cur_time[" << GLOG_TIMESTAMP(cur_time) << "]:cur_latency["
<< start_latency << "]";
// 0. correct radar timestamp
timestamp -= 0.07;
auto *header = radar_obs_proto.mutable_header();
header->set_timestamp_sec(timestamp);
header->set_radar_timestamp(timestamp * 1e9);
conti_id_expansion_.UpdateTimestamp(timestamp);
conti_id_expansion_.ExpandIds(&radar_obs_proto);
if (fabs(timestamp - 0.0) < 10e-6) {
AERROR << "Error timestamp: " << GLOG_TIMESTAMP(timestamp);
return;
}
ADEBUG << "recv radar msg: [timestamp: " << GLOG_TIMESTAMP(timestamp)
<< " num_raw_obstacles: " << radar_obs_proto.contiobs_size() << "]";
// 1. get radar pose
std::shared_ptr<Matrix4d> velodyne2world_pose = std::make_shared<Matrix4d>();
ADEBUG << "use navigation mode " << FLAGS_use_navigation_mode;
if (!GetVelodyneTrans(timestamp, velodyne2world_pose.get()) &&
!FLAGS_use_navigation_mode) {
AERROR << "Failed to get trans at timestamp: " << GLOG_TIMESTAMP(timestamp);
error_code_ = common::PERCEPTION_ERROR_TF;
return;
}
std::shared_ptr<Matrix4d> radar2world_pose = std::make_shared<Matrix4d>();
std::shared_ptr<Matrix4d> radar2car_pose = std::make_shared<Matrix4d>();
if (!FLAGS_use_navigation_mode) {
*radar2world_pose =
*velodyne2world_pose * short_camera_extrinsic_ * radar_extrinsic_;
AINFO << "get radar trans pose succ. pose: \n" << *radar2world_pose;
} else {
CalibrationConfigManager *config_manager =
Singleton<CalibrationConfigManager>::get();
CameraCalibrationPtr calibrator = config_manager->get_camera_calibration();
Eigen::Matrix4d camera_to_car = calibrator->get_camera_extrinsics();
*radar2car_pose = radar_extrinsic_;
AINFO << "get radar trans pose succ. pose: \n" << *radar2car_pose;
}
std::vector<PolygonDType> map_polygons;
RadarDetectorOptions options;
// Current Localiztion, radar postion.
if (!FLAGS_use_navigation_mode) {
PointD position;
position.x = (*radar2world_pose)(0, 3);
position.y = (*radar2world_pose)(1, 3);
position.z = (*radar2world_pose)(2, 3);
// 2. Get map polygons.
HdmapStructPtr hdmap(new HdmapStruct);
if (FLAGS_enable_hdmap_input && hdmap_input_ &&
!hdmap_input_->GetROI(position, FLAGS_front_radar_forward_distance,
&hdmap)) {
AWARN << "Failed to get roi. timestamp: " << GLOG_TIMESTAMP(timestamp)
<< " position: [" << position.x << ", " << position.y << ", "
<< position.z << "]";
// NOTE: if call hdmap failed, using empty map_polygons.
}
if (roi_filter_ != nullptr) {
roi_filter_->MergeHdmapStructToPolygons(hdmap, &map_polygons);
}
}
// 3. get car car_linear_speed
if (!GetCarLinearSpeed(timestamp, &(options.car_linear_speed))) {
AERROR << "Failed to call get_car_linear_speed. [timestamp: "
<< GLOG_TIMESTAMP(timestamp);
return;
}
// 4. Call RadarDetector::detect.
PERF_BLOCK_START();
if (!FLAGS_use_navigation_mode) {
options.radar2world_pose = &(*radar2world_pose);
} else {
options.radar2world_pose = &(*radar2car_pose);
}
std::shared_ptr<SensorObjects> radar_objects(new SensorObjects);
radar_objects->timestamp = timestamp;
radar_objects->sensor_type = SensorType::RADAR;
radar_objects->sensor2world_pose = *radar2world_pose;
bool result = radar_detector_->Detect(radar_obs_proto, map_polygons, options,
&radar_objects->objects);
if (!result) {
radar_objects->error_code = common::PERCEPTION_ERROR_PROCESS;
PublishDataAndEvent(timestamp, radar_objects);
AERROR << "Failed to call RadarDetector. [timestamp: "
<< GLOG_TIMESTAMP(timestamp)
<< ", map_polygons_size: " << map_polygons.size()
<< ", num_raw_conti_obstacles: " << radar_obs_proto.contiobs_size()
<< "]";
return;
}
PERF_BLOCK_END("radar_detect");
PublishDataAndEvent(timestamp, radar_objects);
const double end_timestamp = common::time::Clock::NowInSeconds();
const double end_latency = (end_timestamp - unix_timestamp) * 1e3;
AINFO << "FRAME_STATISTICS:Radar:End:msg_time[" << GLOG_TIMESTAMP(timestamp)
<< "]:cur_time[" << GLOG_TIMESTAMP(end_timestamp) << "]:cur_latency["
<< end_latency << "]";
ADEBUG << "radar process succ, there are " << (radar_objects->objects).size()
<< " objects.";
return;
}
void RadarProcessSubnode::OnLocalization(
const apollo::localization::LocalizationEstimate &localization) {
double timestamp = localization.header().timestamp_sec();
AINFO << "localization timestamp:" << GLOG_TIMESTAMP(timestamp);
LocalizationPair localization_pair;
localization_pair.first = timestamp;
localization_pair.second = localization;
localization_buffer_.push_back(localization_pair);
}
bool RadarProcessSubnode::GetCarLinearSpeed(double timestamp,
Eigen::Vector3f *car_linear_speed) {
MutexLock lock(&mutex_);
if (car_linear_speed == nullptr) {
AERROR << "Param car_linear_speed nullptr error.";
return false;
}
if (localization_buffer_.empty()) {
AWARN << "Rosmsg buffer is empty.";
return false;
}
if (localization_buffer_.front().first - 0.1 > timestamp) {
AWARN << "Timestamp (" << GLOG_TIMESTAMP(timestamp)
<< ") is earlier than the oldest "
<< "timestamp (" << localization_buffer_.front().first << ").";
return false;
}
if (localization_buffer_.back().first + 0.1 < timestamp) {
AWARN << "Timestamp (" << GLOG_TIMESTAMP(timestamp)
<< ") is newer than the latest "
<< "timestamp (" << localization_buffer_.back().first << ").";
return false;
}
// loop to find nearest
double distance = 1e9;
int idx = localization_buffer_.size() - 1;
for (; idx >= 0; --idx) {
double temp_distance = fabs(timestamp - localization_buffer_[idx].first);
if (temp_distance >= distance) {
break;
}
distance = temp_distance;
}
idx = std::max(0, idx);
auto velocity =
localization_buffer_[idx].second.pose().linear_velocity();
(*car_linear_speed)[0] = velocity.x();
(*car_linear_speed)[1] = velocity.y();
(*car_linear_speed)[2] = velocity.z();
return true;
}
void RadarProcessSubnode::RegistAllAlgorithm() {
RegisterFactoryDummyRadarDetector();
RegisterFactoryModestRadarDetector();
}
bool RadarProcessSubnode::InitFrameDependence() {
/// init share data
CHECK(shared_data_manager_ != nullptr) << "shared_data_manager_ is nullptr";
// init preprocess_data
const string radar_data_name("RadarObjectData");
radar_data_ = dynamic_cast<RadarObjectData *>(
shared_data_manager_->GetSharedData(radar_data_name));
if (radar_data_ == nullptr) {
AERROR << "Failed to get shared data instance " << radar_data_name;
return false;
}
AINFO << "Init shared data successfully, data: " << radar_data_->name();
/// init hdmap
if (FLAGS_enable_hdmap_input) {
hdmap_input_ = HDMapInput::instance();
if (!hdmap_input_) {
AERROR << "Failed to get HDMapInput instance.";
return false;
}
if (!hdmap_input_->Init()) {
AERROR << "Failed to Init HDMapInput";
return false;
}
AINFO << "Get and Init hdmap_input succ.";
}
return true;
}
bool RadarProcessSubnode::InitAlgorithmPlugin() {
/// init roi filter
roi_filter_.reset(new HdmapROIFilter());
if (!roi_filter_->Init()) {
AERROR << "Failed to Init roi filter: " << roi_filter_->name();
return false;
}
AINFO << "Init algorithm plugin successfully, roi_filter_: "
<< roi_filter_->name();
/// init radar detector
radar_detector_.reset(BaseRadarDetectorRegisterer::GetInstanceByName(
FLAGS_onboard_radar_detector));
if (!radar_detector_) {
AERROR << "Failed to get instance: " << FLAGS_onboard_radar_detector;
return false;
}
if (!radar_detector_->Init()) {
AERROR << "Failed to Init radar detector: " << radar_detector_->name();
return false;
}
AINFO << "Init algorithm plugin successfully, radar detecor: "
<< radar_detector_->name();
return true;
}
void RadarProcessSubnode::PublishDataAndEvent(
double timestamp, const SharedDataPtr<SensorObjects> &data) {
// set shared data
std::string key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {
AERROR << "Failed to produce shared key. time: "
<< GLOG_TIMESTAMP(timestamp) << ", device_id: " << device_id_;
return;
}
radar_data_->Add(key, data);
// pub events
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id_;
event_manager_->Publish(event);
}
}
} // namespace perception
} // namespace apollo
<commit_msg>Perception: fixed compiling warning (#3669)<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/onboard/radar_process_subnode.h"
#include <algorithm>
#include <string>
#include <unordered_map>
#include "Eigen/Core"
#include "eigen_conversions/eigen_msg.h"
#include "pcl_conversions/pcl_conversions.h"
#include "ros/include/ros/ros.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time_util.h"
#include "modules/common/time/timer.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/calibration_config_manager.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/obstacle/base/object.h"
#include "modules/perception/obstacle/radar/dummy/dummy_algorithms.h"
#include "modules/perception/onboard/subnode_helper.h"
#include "modules/perception/onboard/transform_input.h"
namespace apollo {
namespace perception {
using Eigen::Affine3d;
using Eigen::Matrix4d;
using apollo::common::adapter::AdapterManager;
using pcl_util::Point;
using pcl_util::PointD;
using std::string;
using std::unordered_map;
bool RadarProcessSubnode::InitInternal() {
if (inited_) {
return true;
}
RegistAllAlgorithm();
if (!InitFrameDependence()) {
AERROR << "failed to Init frame dependence.";
return false;
}
if (!InitAlgorithmPlugin()) {
AERROR << "failed to Init algorithm plugin.";
return false;
}
// parse reserve fileds
unordered_map<string, string> reserve_field_map;
if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
AERROR << "Failed to parse reserve filed: " << reserve_;
return false;
}
if (reserve_field_map.find("device_id") == reserve_field_map.end()) {
AERROR << "Failed to find field device_id, reserve: " << reserve_;
return false;
}
device_id_ = reserve_field_map["device_id"];
CHECK(AdapterManager::GetContiRadar()) << "Radar is not initialized.";
AdapterManager::AddContiRadarCallback(&RadarProcessSubnode::OnRadar, this);
CHECK(AdapterManager::GetLocalization()) << "Localiztion is not initialized.";
AdapterManager::AddLocalizationCallback(&RadarProcessSubnode::OnLocalization,
this);
localization_buffer_.set_capacity(FLAGS_localization_buffer_size);
std::string radar_extrinstic_path = FLAGS_radar_extrinsic_file;
AINFO << "radar extrinsic path: " << radar_extrinstic_path;
Eigen::Affine3d radar_extrinsic;
if (!LoadExtrinsic(radar_extrinstic_path, &radar_extrinsic)) {
AERROR << "Failed to load extrinsic.";
return false;
}
radar_extrinsic_ = radar_extrinsic.matrix();
AINFO << "get radar extrinsic succ. pose: \n" << radar_extrinsic_;
std::string short_camera_extrinsic_path = FLAGS_short_camera_extrinsic_file;
AINFO << "short camera extrinsic path: " << short_camera_extrinsic_path;
Eigen::Affine3d short_camera_extrinsic;
if (!LoadExtrinsic(short_camera_extrinsic_path, &short_camera_extrinsic)) {
AERROR << "Failed to load extrinsic.";
return false;
}
short_camera_extrinsic_ = short_camera_extrinsic.matrix();
AINFO << "get short camera extrinsic succ. pose: \n"
<< short_camera_extrinsic_;
inited_ = true;
return true;
}
void RadarProcessSubnode::OnRadar(const ContiRadar &radar_obs) {
PERF_FUNCTION("RadarProcess");
ContiRadar radar_obs_proto = radar_obs;
double timestamp = radar_obs_proto.header().timestamp_sec();
double unix_timestamp = timestamp;
const double cur_time = common::time::Clock::NowInSeconds();
const double start_latency = (cur_time - unix_timestamp) * 1e3;
ADEBUG << "FRAME_STATISTICS: Radar:Start:msg_time["
<< GLOG_TIMESTAMP(timestamp) << "]:cur_time["
<< GLOG_TIMESTAMP(cur_time) << "]:cur_latency[" << start_latency
<< "]";
// 0. correct radar timestamp
timestamp -= 0.07;
auto *header = radar_obs_proto.mutable_header();
header->set_timestamp_sec(timestamp);
header->set_radar_timestamp(timestamp * 1e9);
conti_id_expansion_.UpdateTimestamp(timestamp);
conti_id_expansion_.ExpandIds(&radar_obs_proto);
if (fabs(timestamp - 0.0) < 10e-6) {
AERROR << "Error timestamp: " << GLOG_TIMESTAMP(timestamp);
return;
}
ADEBUG << "recv radar msg: [timestamp: " << GLOG_TIMESTAMP(timestamp)
<< " num_raw_obstacles: " << radar_obs_proto.contiobs_size() << "]";
// 1. get radar pose
std::shared_ptr<Matrix4d> velodyne2world_pose = std::make_shared<Matrix4d>();
ADEBUG << "use navigation mode " << FLAGS_use_navigation_mode;
if (!GetVelodyneTrans(timestamp, velodyne2world_pose.get()) &&
!FLAGS_use_navigation_mode) {
AERROR << "Failed to get trans at timestamp: " << GLOG_TIMESTAMP(timestamp);
error_code_ = common::PERCEPTION_ERROR_TF;
return;
}
std::shared_ptr<Matrix4d> radar2world_pose = std::make_shared<Matrix4d>();
std::shared_ptr<Matrix4d> radar2car_pose = std::make_shared<Matrix4d>();
if (!FLAGS_use_navigation_mode) {
*radar2world_pose =
*velodyne2world_pose * short_camera_extrinsic_ * radar_extrinsic_;
ADEBUG << "get radar trans pose succ. pose: \n" << *radar2world_pose;
} else {
CalibrationConfigManager *config_manager =
Singleton<CalibrationConfigManager>::get();
CameraCalibrationPtr calibrator = config_manager->get_camera_calibration();
// Eigen::Matrix4d camera_to_car = calibrator->get_camera_extrinsics();
*radar2car_pose = radar_extrinsic_;
ADEBUG << "get radar trans pose succ. pose: \n" << *radar2car_pose;
}
std::vector<PolygonDType> map_polygons;
RadarDetectorOptions options;
// Current Localiztion, radar postion.
if (!FLAGS_use_navigation_mode) {
PointD position;
position.x = (*radar2world_pose)(0, 3);
position.y = (*radar2world_pose)(1, 3);
position.z = (*radar2world_pose)(2, 3);
// 2. Get map polygons.
HdmapStructPtr hdmap(new HdmapStruct);
if (FLAGS_enable_hdmap_input && hdmap_input_ &&
!hdmap_input_->GetROI(position, FLAGS_front_radar_forward_distance,
&hdmap)) {
AWARN << "Failed to get roi. timestamp: " << GLOG_TIMESTAMP(timestamp)
<< " position: [" << position.x << ", " << position.y << ", "
<< position.z << "]";
// NOTE: if call hdmap failed, using empty map_polygons.
}
if (roi_filter_ != nullptr) {
roi_filter_->MergeHdmapStructToPolygons(hdmap, &map_polygons);
}
}
// 3. get car car_linear_speed
if (!GetCarLinearSpeed(timestamp, &(options.car_linear_speed))) {
AERROR << "Failed to call get_car_linear_speed. [timestamp: "
<< GLOG_TIMESTAMP(timestamp);
return;
}
// 4. Call RadarDetector::detect.
PERF_BLOCK_START();
if (!FLAGS_use_navigation_mode) {
options.radar2world_pose = &(*radar2world_pose);
} else {
options.radar2world_pose = &(*radar2car_pose);
}
std::shared_ptr<SensorObjects> radar_objects(new SensorObjects);
radar_objects->timestamp = timestamp;
radar_objects->sensor_type = SensorType::RADAR;
radar_objects->sensor2world_pose = *radar2world_pose;
bool result = radar_detector_->Detect(radar_obs_proto, map_polygons, options,
&radar_objects->objects);
if (!result) {
radar_objects->error_code = common::PERCEPTION_ERROR_PROCESS;
PublishDataAndEvent(timestamp, radar_objects);
AERROR << "Failed to call RadarDetector. [timestamp: "
<< GLOG_TIMESTAMP(timestamp)
<< ", map_polygons_size: " << map_polygons.size()
<< ", num_raw_conti_obstacles: " << radar_obs_proto.contiobs_size()
<< "]";
return;
}
PERF_BLOCK_END("radar_detect");
PublishDataAndEvent(timestamp, radar_objects);
const double end_timestamp = common::time::Clock::NowInSeconds();
const double end_latency = (end_timestamp - unix_timestamp) * 1e3;
ADEBUG << "FRAME_STATISTICS:Radar: End:msg_time[" << GLOG_TIMESTAMP(timestamp)
<< "]:cur_time[" << GLOG_TIMESTAMP(end_timestamp) << "]:cur_latency["
<< end_latency << "]";
ADEBUG << "radar process succ, there are " << (radar_objects->objects).size()
<< " objects.";
return;
}
void RadarProcessSubnode::OnLocalization(
const apollo::localization::LocalizationEstimate &localization) {
double timestamp = localization.header().timestamp_sec();
AINFO << "localization timestamp:" << GLOG_TIMESTAMP(timestamp);
LocalizationPair localization_pair;
localization_pair.first = timestamp;
localization_pair.second = localization;
localization_buffer_.push_back(localization_pair);
}
bool RadarProcessSubnode::GetCarLinearSpeed(double timestamp,
Eigen::Vector3f *car_linear_speed) {
MutexLock lock(&mutex_);
if (car_linear_speed == nullptr) {
AERROR << "Param car_linear_speed nullptr error.";
return false;
}
if (localization_buffer_.empty()) {
AWARN << "Rosmsg buffer is empty.";
return false;
}
if (localization_buffer_.front().first - 0.1 > timestamp) {
AWARN << "Timestamp (" << GLOG_TIMESTAMP(timestamp)
<< ") is earlier than the oldest "
<< "timestamp (" << localization_buffer_.front().first << ").";
return false;
}
if (localization_buffer_.back().first + 0.1 < timestamp) {
AWARN << "Timestamp (" << GLOG_TIMESTAMP(timestamp)
<< ") is newer than the latest "
<< "timestamp (" << localization_buffer_.back().first << ").";
return false;
}
// loop to find nearest
double distance = 1e9;
int idx = localization_buffer_.size() - 1;
for (; idx >= 0; --idx) {
double temp_distance = fabs(timestamp - localization_buffer_[idx].first);
if (temp_distance >= distance) {
break;
}
distance = temp_distance;
}
idx = std::max(0, idx);
auto velocity = localization_buffer_[idx].second.pose().linear_velocity();
(*car_linear_speed)[0] = velocity.x();
(*car_linear_speed)[1] = velocity.y();
(*car_linear_speed)[2] = velocity.z();
return true;
}
void RadarProcessSubnode::RegistAllAlgorithm() {
RegisterFactoryDummyRadarDetector();
RegisterFactoryModestRadarDetector();
}
bool RadarProcessSubnode::InitFrameDependence() {
/// init share data
CHECK(shared_data_manager_ != nullptr) << "shared_data_manager_ is nullptr";
// init preprocess_data
const string radar_data_name("RadarObjectData");
radar_data_ = dynamic_cast<RadarObjectData *>(
shared_data_manager_->GetSharedData(radar_data_name));
if (radar_data_ == nullptr) {
AERROR << "Failed to get shared data instance " << radar_data_name;
return false;
}
AINFO << "Init shared data successfully, data: " << radar_data_->name();
/// init hdmap
if (FLAGS_enable_hdmap_input) {
hdmap_input_ = HDMapInput::instance();
if (!hdmap_input_) {
AERROR << "Failed to get HDMapInput instance.";
return false;
}
if (!hdmap_input_->Init()) {
AERROR << "Failed to Init HDMapInput";
return false;
}
AINFO << "Get and Init hdmap_input succ.";
}
return true;
}
bool RadarProcessSubnode::InitAlgorithmPlugin() {
/// init roi filter
roi_filter_.reset(new HdmapROIFilter());
if (!roi_filter_->Init()) {
AERROR << "Failed to Init roi filter: " << roi_filter_->name();
return false;
}
AINFO << "Init algorithm plugin successfully, roi_filter_: "
<< roi_filter_->name();
/// init radar detector
radar_detector_.reset(BaseRadarDetectorRegisterer::GetInstanceByName(
FLAGS_onboard_radar_detector));
if (!radar_detector_) {
AERROR << "Failed to get instance: " << FLAGS_onboard_radar_detector;
return false;
}
if (!radar_detector_->Init()) {
AERROR << "Failed to Init radar detector: " << radar_detector_->name();
return false;
}
AINFO << "Init algorithm plugin successfully, radar detecor: "
<< radar_detector_->name();
return true;
}
void RadarProcessSubnode::PublishDataAndEvent(
double timestamp, const SharedDataPtr<SensorObjects> &data) {
// set shared data
std::string key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {
AERROR << "Failed to produce shared key. time: "
<< GLOG_TIMESTAMP(timestamp) << ", device_id: " << device_id_;
return;
}
radar_data_->Add(key, data);
// pub events
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id_;
event_manager_->Publish(event);
}
}
} // namespace perception
} // namespace apollo
<|endoftext|>
|
<commit_before>#include "spec_helper.h"
#include "helpers/load_language.h"
#include <unistd.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <fstream>
#include "tree_sitter/compiler.h"
using std::string;
using std::ofstream;
static std::string run_cmd(const char *cmd, const char *args[]) {
int child_pid = fork();
if (child_pid < 0)
return "fork failed";
if (child_pid == 0) {
close(0);
dup2(1, 0);
dup2(2, 1);
dup2(1, 2);
execvp(cmd, (char * const * )args);
return "";
}
int status;
do {
waitpid(child_pid, &status, 0);
} while (!WIFEXITED(status));
if (WEXITSTATUS(status) == 0)
return "";
else
return "command failed";
return "";
}
const TSLanguage *load_language(const string &name, const TSCompileResult &compile_result) {
if (compile_result.error_type != TSCompileErrorTypeNone) {
AssertThat(string(compile_result.error_message), IsEmpty());
return nullptr;
}
return load_language(name, compile_result.code);
}
const TSLanguage *load_language(const string &name, const string &code) {
string language_function_name = "ts_language_" + name;
static char source_file_template[256] = {};
snprintf(source_file_template, 256, "/tmp/tree-sitter-test-%sXXXXXXXXX", name.c_str());
const char *temp_directory = mkdtemp(source_file_template);
if (!temp_directory) {
AssertThat(string("Failed to create temp directory"), IsEmpty());
return nullptr;
}
string source_filename = string(temp_directory) + "/parser.c";
string obj_filename = string(source_filename) + ".o";
string lib_filename = string(source_filename) + ".so";
string header_dir = string(getenv("PWD")) + "/include";
ofstream source_file;
source_file.open(source_filename);
source_file << code;
source_file.close();
const char *compiler_name = getenv("CC");
if (!compiler_name) {
compiler_name = "gcc";
}
const char *compile_argv[] = {
compiler_name,
"-x", "c",
"-fPIC",
"-I", header_dir.c_str(),
"-c", source_filename.c_str(),
"-o", obj_filename.c_str(),
NULL
};
string compile_error = run_cmd("gcc", compile_argv);
if (!compile_error.empty()) {
AssertThat(string(compile_error), IsEmpty());
return nullptr;
}
const char *link_argv[] = {
compiler_name,
"-shared",
"-Wl", obj_filename.c_str(),
"-o", lib_filename.c_str(),
NULL
};
string link_error = run_cmd("gcc", link_argv);
if (!link_error.empty()) {
AssertThat(link_error, IsEmpty());
return nullptr;
}
void *parser_lib = dlopen(lib_filename.c_str(), RTLD_NOW);
if (!parser_lib) {
std::string message(dlerror());
AssertThat(message, IsEmpty());
return nullptr;
}
void *symbol_value = dlsym(parser_lib, language_function_name.c_str());
if (!symbol_value) {
std::string message(dlerror());
AssertThat(message, IsEmpty());
return nullptr;
}
typedef TSLanguage * (* LanguageFunction)();
LanguageFunction language_fn = reinterpret_cast<LanguageFunction>(symbol_value);
return language_fn();
}
<commit_msg>Compile test grammars w/ debug symbols<commit_after>#include "spec_helper.h"
#include "helpers/load_language.h"
#include <unistd.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <fstream>
#include "tree_sitter/compiler.h"
using std::string;
using std::ofstream;
static std::string run_cmd(const char *cmd, const char *args[]) {
int child_pid = fork();
if (child_pid < 0)
return "fork failed";
if (child_pid == 0) {
close(0);
dup2(1, 0);
dup2(2, 1);
dup2(1, 2);
execvp(cmd, (char * const * )args);
return "";
}
int status;
do {
waitpid(child_pid, &status, 0);
} while (!WIFEXITED(status));
if (WEXITSTATUS(status) == 0)
return "";
else
return "command failed";
return "";
}
const TSLanguage *load_language(const string &name, const TSCompileResult &compile_result) {
if (compile_result.error_type != TSCompileErrorTypeNone) {
AssertThat(string(compile_result.error_message), IsEmpty());
return nullptr;
}
return load_language(name, compile_result.code);
}
const TSLanguage *load_language(const string &name, const string &code) {
string language_function_name = "ts_language_" + name;
static char source_file_template[256] = {};
snprintf(source_file_template, 256, "/tmp/tree-sitter-test-%sXXXXXXXXX", name.c_str());
const char *temp_directory = mkdtemp(source_file_template);
if (!temp_directory) {
AssertThat(string("Failed to create temp directory"), IsEmpty());
return nullptr;
}
string source_filename = string(temp_directory) + "/parser.c";
string obj_filename = string(source_filename) + ".o";
string lib_filename = string(source_filename) + ".so";
string header_dir = string(getenv("PWD")) + "/include";
ofstream source_file;
source_file.open(source_filename);
source_file << code;
source_file.close();
const char *compiler_name = getenv("CC");
if (!compiler_name) {
compiler_name = "gcc";
}
const char *compile_argv[] = {
compiler_name,
"-x", "c",
"-fPIC",
"-g",
"-I", header_dir.c_str(),
"-c", source_filename.c_str(),
"-o", obj_filename.c_str(),
NULL
};
string compile_error = run_cmd("gcc", compile_argv);
if (!compile_error.empty()) {
AssertThat(string(compile_error), IsEmpty());
return nullptr;
}
const char *link_argv[] = {
compiler_name,
"-shared",
"-Wl", obj_filename.c_str(),
"-o", lib_filename.c_str(),
NULL
};
string link_error = run_cmd("gcc", link_argv);
if (!link_error.empty()) {
AssertThat(link_error, IsEmpty());
return nullptr;
}
void *parser_lib = dlopen(lib_filename.c_str(), RTLD_NOW);
if (!parser_lib) {
std::string message(dlerror());
AssertThat(message, IsEmpty());
return nullptr;
}
void *symbol_value = dlsym(parser_lib, language_function_name.c_str());
if (!symbol_value) {
std::string message(dlerror());
AssertThat(message, IsEmpty());
return nullptr;
}
typedef TSLanguage * (* LanguageFunction)();
LanguageFunction language_fn = reinterpret_cast<LanguageFunction>(symbol_value);
return language_fn();
}
<|endoftext|>
|
<commit_before>#include "bloomierHash.h"
BloomierHash::BloomierHash(const size_t pModulo, const size_t pNumberOfElements, const size_t pBitVectorSize, const size_t pHashSeed) {
mModulo = pModulo;
mNumberOfElements = pNumberOfElements;
mHash = new Hash();
mBitVectorSize = pBitVectorSize;
mHashSeed = pHashSeed;
};
BloomierHash::~BloomierHash() {
delete mHash;
};
bitVector* BloomierHash::getMask(const size_t pKey) {
bitVector* mask = new bitVector(mBitVectorSize);
size_t randValue = mHash->hash(pKey+1, mHashSeed, mModulo);
for (size_t i = 0; i < mBitVectorSize; ++i) {
(*mask)[i] = static_cast<unsigned char>((randValue >> (8*i)) & 0b00000000000000000000000011111111);
}
return mask;
};
void BloomierHash::getKNeighbors(const size_t pElement, const size_t pSeed, vsize_t* pNeighbors) {
size_t seedValue = pSeed;
if (seedValue == 0) {
seedValue = mHashSeed;
}
size_t seedChange = 1;
bitVector* bloomFilterValueSeen = new bitVector(ceil(mModulo/8.0));
for (size_t i = 0; i < pNeighbors->size(); ++i) {
size_t neighbor = mHash->hash(pElement+i, seedValue+seedChange, mModulo);
unsigned char index = floor(neighbor / 8.0);
unsigned char value = 1 << (neighbor % 8);
unsigned char valueSeen = (*bloomFilterValueSeen)[index] & value;
while (value == valueSeen) {
++seedChange;
neighbor = mHash->hash(pElement+1, (seedValue+seedChange), mModulo);
index = floor(neighbor / 8.0);
value = 1 << (neighbor % 8);
valueSeen = (*bloomFilterValueSeen)[index] & value;
}
(*bloomFilterValueSeen)[index] = (*bloomFilterValueSeen)[index] | value;
seedChange = 1;
(*pNeighbors)[i] = neighbor;
}
delete bloomFilterValueSeen;
};
size_t BloomierHash::getHashSeed() const {
return mHashSeed;
};
void BloomierHash::setHashSeed(size_t pHashSeed) {
mHashSeed = pHashSeed;
}<commit_msg>Changed return type for function getMask from bitVector* to bitVector<commit_after>#include "bloomierHash.h"
BloomierHash::BloomierHash(const size_t pModulo, const size_t pNumberOfElements, const size_t pBitVectorSize, const size_t pHashSeed) {
mModulo = pModulo;
mNumberOfElements = pNumberOfElements;
mHash = new Hash();
mBitVectorSize = pBitVectorSize;
mHashSeed = pHashSeed;
};
BloomierHash::~BloomierHash() {
delete mHash;
};
bitVector BloomierHash::getMask(const size_t pKey) {
// bitVector* mask = new bitVector(mBitVectorSize);
bitVector mask(mBitVectorSize);
size_t randValue = mHash->hash(pKey+1, mHashSeed, mModulo);
for (size_t i = 0; i < mBitVectorSize; ++i) {
mask[i] = static_cast<unsigned char>((randValue >> (8*i)) & 0b00000000000000000000000011111111);
}
return mask;
};
void BloomierHash::getKNeighbors(const size_t pElement, const size_t pSeed, vsize_t* pNeighbors) {
size_t seedValue = pSeed;
if (seedValue == 0) {
seedValue = mHashSeed;
}
size_t seedChange = 1;
bitVector* bloomFilterValueSeen = new bitVector(ceil(mModulo/8.0));
for (size_t i = 0; i < pNeighbors->size(); ++i) {
size_t neighbor = mHash->hash(pElement+i, seedValue+seedChange, mModulo);
unsigned char index = floor(neighbor / 8.0);
unsigned char value = 1 << (neighbor % 8);
unsigned char valueSeen = (*bloomFilterValueSeen)[index] & value;
while (value == valueSeen) {
++seedChange;
neighbor = mHash->hash(pElement+1, (seedValue+seedChange), mModulo);
index = floor(neighbor / 8.0);
value = 1 << (neighbor % 8);
valueSeen = (*bloomFilterValueSeen)[index] & value;
}
(*bloomFilterValueSeen)[index] = (*bloomFilterValueSeen)[index] | value;
seedChange = 1;
(*pNeighbors)[i] = neighbor;
}
delete bloomFilterValueSeen;
};
size_t BloomierHash::getHashSeed() const {
return mHashSeed;
};
void BloomierHash::setHashSeed(size_t pHashSeed) {
mHashSeed = pHashSeed;
}<|endoftext|>
|
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(CPPRX_RX_INCLUDES_HPP)
#define CPPRX_RX_INCLUDES_HPP
#pragma push_macro("min")
#pragma push_macro("max")
#undef min
#undef max
#include <exception>
#include <functional>
#include <memory>
#include <vector>
#include <algorithm>
#include <atomic>
#include <map>
#include <mutex>
#include <deque>
#include <thread>
#include <future>
#include <vector>
#include <list>
#include <queue>
#include <chrono>
#include <condition_variable>
// some configuration macros
#if defined(_MSC_VER)
#if _MSC_VER > 1600
#define RXCPP_USE_RVALUEREF 1
#define RXCPP_USE_VARIADIC_TEMPLATES 0
#endif
#if _CPPRTTI
#define RXCPP_USE_RTTI 1
#endif
#elif defined(__clang__)
#if __has_feature(cxx_rvalue_references)
#define RXCPP_USE_RVALUEREF 1
#endif
#if __has_feature(cxx_rtti)
#define RXCPP_USE_RTTI 1
#endif
#if __has_feature(cxx_variadic_templates)
#define RXCPP_USE_VARIADIC_TEMPLATES 1
#endif
#endif
#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)
#define RXCPP_USE_WINRT 0
#else
#define RXCPP_USE_WINRT 1
#endif
#if defined(RXCPP_FORCE_USE_VARIADIC_TEMPLATES)
#undef RXCPP_USE_VARIADIC_TEMPLATES
#define RXCPP_USE_VARIADIC_TEMPLATES RXCPP_FORCE_USE_VARIADIC_TEMPLATES
#endif
#if defined(RXCPP_FORCE_USE_RVALUEREF)
#undef RXCPP_USE_RVALUEREF
#define RXCPP_USE_RVALUEREF RXCPP_FORCE_USE_RVALUEREF
#endif
#if defined(RXCPP_FORCE_USE_RTTI)
#undef RXCPP_USE_RTTI
#define RXCPP_USE_RTTI RXCPP_FORCE_USE_RTTI
#endif
#if defined(RXCPP_FORCE_USE_WINRT)
#undef RXCPP_USE_WINRT
#define RXCPP_USE_WINRT RXCPP_FORCE_USE_WINRT
#endif
#include "rx-util.hpp"
#include "rx-base.hpp"
#include "rx-scheduler.hpp"
#include "rx-windows.hpp"
#include "rx-operators.hpp"
#include "rx-winrt.hpp"
#pragma pop_macro("min")
#pragma pop_macro("max")
#endif
<commit_msg>update _MSC_VER checks for VC2013<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(CPPRX_RX_INCLUDES_HPP)
#define CPPRX_RX_INCLUDES_HPP
#pragma push_macro("min")
#pragma push_macro("max")
#undef min
#undef max
#include <exception>
#include <functional>
#include <memory>
#include <vector>
#include <algorithm>
#include <atomic>
#include <map>
#include <mutex>
#include <deque>
#include <thread>
#include <future>
#include <vector>
#include <list>
#include <queue>
#include <chrono>
#include <condition_variable>
// some configuration macros
#if defined(_MSC_VER)
#if _MSC_VER > 1600
#define RXCPP_USE_RVALUEREF 1
#endif
#if _MSC_VER >= 1800
#define RXCPP_USE_VARIADIC_TEMPLATES 1
#endif
#if _CPPRTTI
#define RXCPP_USE_RTTI 1
#endif
#elif defined(__clang__)
#if __has_feature(cxx_rvalue_references)
#define RXCPP_USE_RVALUEREF 1
#endif
#if __has_feature(cxx_rtti)
#define RXCPP_USE_RTTI 1
#endif
#if __has_feature(cxx_variadic_templates)
#define RXCPP_USE_VARIADIC_TEMPLATES 1
#endif
#endif
#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)
#define RXCPP_USE_WINRT 0
#else
#define RXCPP_USE_WINRT 1
#endif
#if defined(RXCPP_FORCE_USE_VARIADIC_TEMPLATES)
#undef RXCPP_USE_VARIADIC_TEMPLATES
#define RXCPP_USE_VARIADIC_TEMPLATES RXCPP_FORCE_USE_VARIADIC_TEMPLATES
#endif
#if defined(RXCPP_FORCE_USE_RVALUEREF)
#undef RXCPP_USE_RVALUEREF
#define RXCPP_USE_RVALUEREF RXCPP_FORCE_USE_RVALUEREF
#endif
#if defined(RXCPP_FORCE_USE_RTTI)
#undef RXCPP_USE_RTTI
#define RXCPP_USE_RTTI RXCPP_FORCE_USE_RTTI
#endif
#if defined(RXCPP_FORCE_USE_WINRT)
#undef RXCPP_USE_WINRT
#define RXCPP_USE_WINRT RXCPP_FORCE_USE_WINRT
#endif
#include "rx-util.hpp"
#include "rx-base.hpp"
#include "rx-scheduler.hpp"
#include "rx-windows.hpp"
#include "rx-operators.hpp"
#include "rx-winrt.hpp"
#pragma pop_macro("min")
#pragma pop_macro("max")
#endif
<|endoftext|>
|
<commit_before>#include "runtime/debugger.h"
#include "runtime/helpers/spy_debugger.h"
#include "runtime/runtime_spec_helper.h"
extern "C" const TSLanguage * ts_language_json();
START_TEST
describe("Document", [&]() {
TSDocument *doc;
before_each([&]() {
doc = ts_document_make();
});
after_each([&]() {
ts_document_free(doc);
});
describe("set_input(TSInput)", [&]() {
describe("when the language is set", [&]() {
before_each([&]() {
ts_document_set_language(doc, ts_language_json());
});
it("parses the document", [&]() {
ts_document_set_input_string(doc, "{ \"key\": [1, 2] }");
AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(
"(DOCUMENT (object (string) (array (number) (number))))"));
});
});
describe("when the language is not set", [&]() {
it("does not try to parse the document", [&]() {
ts_document_set_input_string(doc, "{ \"key\": [1, 2] }");
AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));
});
});
});
describe("set_language(TSLanguage)", [&]() {
describe("when the input is not set", [&]() {
it("does not try to parse the document", [&]() {
ts_document_set_language(doc, ts_language_json());
AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));
});
});
describe("when the input is set", [&]() {
before_each([&]() {
ts_document_set_input_string(doc, "{ \"key\": [1, 2] }");
});
it("parses the document", [&]() {
ts_document_set_language(doc, ts_language_json());
AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(
"(DOCUMENT (object (string) (array (number) (number))))"));
});
});
});
describe("set_debugger(TSDebugger)", [&]() {
SpyDebugger *debugger;
before_each([&]() {
debugger = new SpyDebugger();
ts_document_set_language(doc, ts_language_json());
ts_document_set_debugger(doc, debugger->debugger());
});
it("calls the debugger with a message for each lex action", [&]() {
ts_document_set_input_string(doc, "[1, 2]");
AssertThat(debugger->messages, Contains("lookahead char:'1'"));
AssertThat(debugger->messages, Contains("advance state:1"));
AssertThat(debugger->messages, Contains("accept_token sym:number"));
});
it("calls the debugger with a message for each parse action", [&]() {
ts_document_set_input_string(doc, "[1, 2]");
AssertThat(debugger->messages, Contains("shift state:1"));
AssertThat(debugger->messages, Contains("reduce sym:value count:1"));
AssertThat(debugger->messages, Contains("accept"));
});
it("allows the debugger to be retrieved later", [&]() {
AssertThat(ts_document_get_debugger(doc).data, Equals(debugger));
});
describe("disabling debugging", [&]() {
before_each([&]() {
ts_document_set_debugger(doc, {});
});
it("does not call the debugger any more", [&]() {
ts_document_set_input_string(doc, "[1, 2]");
AssertThat(debugger->messages, IsEmpty());
});
it("releases the old debugger", [&]() {
AssertThat(debugger->release_call_count, Equals<size_t>(1));
});
});
});
});
END_TEST
<commit_msg>Fix build warnings in document spec<commit_after>#include "runtime/debugger.h"
#include "runtime/helpers/spy_debugger.h"
#include "runtime/runtime_spec_helper.h"
extern "C" const TSLanguage * ts_language_json();
START_TEST
describe("Document", [&]() {
TSDocument *doc;
before_each([&]() {
doc = ts_document_make();
});
after_each([&]() {
ts_document_free(doc);
});
describe("set_input(TSInput)", [&]() {
describe("when the language is set", [&]() {
before_each([&]() {
ts_document_set_language(doc, ts_language_json());
});
it("parses the document", [&]() {
ts_document_set_input_string(doc, "{ \"key\": [1, 2] }");
AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(
"(DOCUMENT (object (string) (array (number) (number))))"));
});
});
describe("when the language is not set", [&]() {
it("does not try to parse the document", [&]() {
ts_document_set_input_string(doc, "{ \"key\": [1, 2] }");
AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));
});
});
});
describe("set_language(TSLanguage)", [&]() {
describe("when the input is not set", [&]() {
it("does not try to parse the document", [&]() {
ts_document_set_language(doc, ts_language_json());
AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));
});
});
describe("when the input is set", [&]() {
before_each([&]() {
ts_document_set_input_string(doc, "{ \"key\": [1, 2] }");
});
it("parses the document", [&]() {
ts_document_set_language(doc, ts_language_json());
AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(
"(DOCUMENT (object (string) (array (number) (number))))"));
});
});
});
describe("set_debugger(TSDebugger)", [&]() {
SpyDebugger *debugger;
before_each([&]() {
debugger = new SpyDebugger();
ts_document_set_language(doc, ts_language_json());
ts_document_set_debugger(doc, debugger->debugger());
});
it("calls the debugger with a message for each lex action", [&]() {
ts_document_set_input_string(doc, "[1, 2]");
AssertThat(debugger->messages, Contains("lookahead char:'1'"));
AssertThat(debugger->messages, Contains("advance state:1"));
AssertThat(debugger->messages, Contains("accept_token sym:number"));
});
it("calls the debugger with a message for each parse action", [&]() {
ts_document_set_input_string(doc, "[1, 2]");
AssertThat(debugger->messages, Contains("shift state:1"));
AssertThat(debugger->messages, Contains("reduce sym:value count:1"));
AssertThat(debugger->messages, Contains("accept"));
});
it("allows the debugger to be retrieved later", [&]() {
AssertThat(ts_document_get_debugger(doc).data, Equals(debugger));
});
describe("disabling debugging", [&]() {
before_each([&]() {
ts_document_set_debugger(doc, ts_debugger_null());
});
it("does not call the debugger any more", [&]() {
ts_document_set_input_string(doc, "[1, 2]");
AssertThat(debugger->messages, IsEmpty());
});
it("releases the old debugger", [&]() {
AssertThat(debugger->release_call_count, Equals<size_t>(1));
});
});
});
});
END_TEST
<|endoftext|>
|
<commit_before>#include "TestCommon.hh"
using namespace SDLut::video;
class AssertEngine;
Logger testlog("TestPixelFormat");
Color bgc(128,128,128);
Color red(255,0,0);
Color green(0,255,0);
Color blue(0,0,255);
Color alpha(255,255,255,128);
class MyEngine : public TestEngine
{
Image * imgred,*imggreen,*imgblue,*imgalpha;
public:
MyEngine(Logger & log, AssertEngine & ae) : TestEngine(log,ae), imgred(0), imggreen(0),imgblue(0),imgalpha(0)
{
App::getInstance().getDisplay().getScreenBuffer().setBGColor(bgc);
}
virtual ~MyEngine()
{
delete imgred; delete imggreen; delete imgblue; delete imgalpha;
}
virtual bool init(int width, int height)
{
return resize(width,height);
}
virtual bool resize(int width, int height)
{
delete imgred; delete imggreen; delete imgblue; delete imgalpha;
imgred = new Image(width/4,height,32);
imgred->fill(red);
imggreen = new Image(width/4,height,32);
imggreen->fill(green);
imgblue = new Image(width/4,height,32);
imgblue->fill(blue);
imgalpha = new Image(width-imgred->getWidth()-imggreen->getWidth()-imgblue->getWidth(),height,32, true);
imgalpha->fill(alpha);
testlog << "Red Pixel : " << std::hex << imgred->getpixel(0,0) << std::endl;
testlog << "Green Pixel : " << std::hex << imggreen->getpixel(0,0)<< std::endl;
testlog << "Blue Pixel : " << std::hex << imgblue->getpixel(0,0)<< std::endl;
testlog << "Alpha Pixel : " << std::hex << imgalpha->getpixel(0,0)<< std::endl;
return true;
}
virtual bool render(ScreenBuffer & screen) const
{
Rect red_dst(0,0,imgred->getWidth(),imgred->getHeight());
screen.blit(*imgred,red_dst);
Rect green_dst(0 + imgred->getWidth(),0,imggreen->getWidth(),imggreen->getHeight());
screen.blit(*imggreen,green_dst);
Rect blue_dst(0 + imgred->getWidth() + imggreen->getWidth(), 0,imgblue->getWidth(),imgblue->getHeight());
screen.blit(*imgblue,blue_dst);
Rect alpha_dst(0 + imgred->getWidth() + imggreen->getWidth() + imgblue->getWidth(), 0, imgalpha->getWidth(),imgalpha->getHeight());
screen.blit(*imgalpha,alpha_dst);
return true;
}
};
class Test : public AssertEngine
{
Rect posred,posgreen,posblue,posalpha;
public:
//we only need one render to see which color are there
Test( Logger & log) : AssertEngine(log,1)
{
}
virtual ~Test()
{
}
virtual bool assertinit(int width, int height)
{
return assertresize(width,height);
}
virtual bool assertresize(int width, int height)
{
posred = Rect(0,0,width/4,height);
posgreen = Rect(0 + posred.getw(),0,width/4,height);
posblue = Rect(0 + posred.getw() + posgreen.getw(), 0,width/4,height);
posalpha = Rect(0 + posred.getw() + posgreen.getw() + posblue.getw(), 0,width-posred.getw()-posgreen.getw()-posblue.getw(),height);
return true;
}
virtual bool assertrender(ScreenBuffer & screen) const
{
bool res = true;
res = res && blend(red,bgc).isSimilarTo(screen.getpixel(posred.getx(),posred.gety()));
if (!res)
{
m_log << nl << "Red = " << blend(red,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posred.getx(),posred.gety());
setError(-1,"Red Pixel is wrong");
}
res = res && blend(green,bgc).isSimilarTo(screen.getpixel(posgreen.getx(),posgreen.gety()));
if (!res)
{
m_log << nl << "Green = " << blend(green,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posgreen.getx(),posgreen.gety());
setError(-1,"Green Pixel is wrong");
}
res = res && blend(blue,bgc).isSimilarTo( screen.getpixel(posblue.getx(),posblue.gety()));
if (!res)
{
m_log << nl << "Blue = " << blend(blue,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posblue.getx(),posblue.gety());
setError(-1,"Blue Pixel is wrong");
}
res = res && blend(alpha,bgc).isSimilarTo( screen.getpixel(posalpha.getx(),posalpha.gety()));
if (!res)
{
m_log << nl << "Alpha = " << blend(alpha,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posalpha.getx(),posalpha.gety());
setError(-1,"Alpha Pixel is wrong");
}
return res;
}
};
int main(int argc, char** argv)
{
ArgParser args(argc,argv);
//Starting with usual SDL window
App::getInstance().initVideo(false,true,false);
App::getInstance().setName ("SDLut::video test PixelFormat");
//Setting Display size and BPP
App::getInstance().getDisplay().setDisplay(300,240); // using autodetected bpp
App::getInstance().getDisplay().getScreenBuffer().setOpenGL(args.isOGL());
Test teng(testlog);
MyEngine engine(testlog,teng);
int exitstatus = -1;
if(App::getInstance().getDisplay().show())
{
exitstatus = App::getInstance().getDisplay().mainLoop();
}
return exitstatus;
}
<commit_msg> quick fix to match new test master classes<commit_after>#include "TestCommon.hh"
using namespace SDLut::video;
class AssertEngine;
Logger testlog("TestPixelFormat");
Color bgc(128,128,128);
Color red(255,0,0);
Color green(0,255,0);
Color blue(0,0,255);
Color alpha(255,255,255,128);
class MyEngine : public TestEngine
{
Image * imgred,*imggreen,*imgblue,*imgalpha;
public:
MyEngine(Logger & log, AssertEngine & ae) : TestEngine(log,ae), imgred(0), imggreen(0),imgblue(0),imgalpha(0)
{
App::getInstance().getDisplay().getScreenBuffer().setBGColor(bgc);
}
virtual ~MyEngine()
{
delete imgred; delete imggreen; delete imgblue; delete imgalpha;
}
virtual bool init(int width, int height)
{
return resize(width,height);
}
virtual bool resize(int width, int height)
{
delete imgred; delete imggreen; delete imgblue; delete imgalpha;
imgred = new Image(width/4,height,32);
imgred->fill(red);
imggreen = new Image(width/4,height,32);
imggreen->fill(green);
imgblue = new Image(width/4,height,32);
imgblue->fill(blue);
imgalpha = new Image(width-imgred->getWidth()-imggreen->getWidth()-imgblue->getWidth(),height,32, true);
imgalpha->fill(alpha);
testlog << "Red Pixel : " << std::hex << imgred->getpixel(0,0) << std::endl;
testlog << "Green Pixel : " << std::hex << imggreen->getpixel(0,0)<< std::endl;
testlog << "Blue Pixel : " << std::hex << imgblue->getpixel(0,0)<< std::endl;
testlog << "Alpha Pixel : " << std::hex << imgalpha->getpixel(0,0)<< std::endl;
return true;
}
virtual bool render(ScreenBuffer & screen) const
{
Rect red_dst(0,0,imgred->getWidth(),imgred->getHeight());
screen.blit(*imgred,red_dst);
Rect green_dst(0 + imgred->getWidth(),0,imggreen->getWidth(),imggreen->getHeight());
screen.blit(*imggreen,green_dst);
Rect blue_dst(0 + imgred->getWidth() + imggreen->getWidth(), 0,imgblue->getWidth(),imgblue->getHeight());
screen.blit(*imgblue,blue_dst);
Rect alpha_dst(0 + imgred->getWidth() + imggreen->getWidth() + imgblue->getWidth(), 0, imgalpha->getWidth(),imgalpha->getHeight());
screen.blit(*imgalpha,alpha_dst);
return true;
}
};
class Test : public AssertEngine
{
Rect posred,posgreen,posblue,posalpha;
public:
//we only need one render to see which color are there
Test( Logger & log, const ArgParser & args) : AssertEngine(log,args)
{
}
virtual ~Test()
{
}
virtual bool assertinit(int width, int height)
{
return assertresize(width,height);
}
virtual bool assertresize(int width, int height)
{
posred = Rect(0,0,width/4,height);
posgreen = Rect(0 + posred.getw(),0,width/4,height);
posblue = Rect(0 + posred.getw() + posgreen.getw(), 0,width/4,height);
posalpha = Rect(0 + posred.getw() + posgreen.getw() + posblue.getw(), 0,width-posred.getw()-posgreen.getw()-posblue.getw(),height);
return true;
}
virtual bool assertrender(ScreenBuffer & screen) const
{
bool res = true;
res = res && blend(red,bgc).isSimilarTo(screen.getpixel(posred.getx(),posred.gety()));
if (!res)
{
m_log << nl << "Red = " << blend(red,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posred.getx(),posred.gety());
setError(-1,"Red Pixel is wrong");
}
res = res && blend(green,bgc).isSimilarTo(screen.getpixel(posgreen.getx(),posgreen.gety()));
if (!res)
{
m_log << nl << "Green = " << blend(green,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posgreen.getx(),posgreen.gety());
setError(-1,"Green Pixel is wrong");
}
res = res && blend(blue,bgc).isSimilarTo( screen.getpixel(posblue.getx(),posblue.gety()));
if (!res)
{
m_log << nl << "Blue = " << blend(blue,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posblue.getx(),posblue.gety());
setError(-1,"Blue Pixel is wrong");
}
res = res && blend(alpha,bgc).isSimilarTo( screen.getpixel(posalpha.getx(),posalpha.gety()));
if (!res)
{
m_log << nl << "Alpha = " << blend(alpha,bgc);
m_log << nl << "Pixel = " << screen.getpixel(posalpha.getx(),posalpha.gety());
setError(-1,"Alpha Pixel is wrong");
}
return res;
}
};
int main(int argc, char** argv)
{
ArgParser args(argc,argv);
//Starting with usual SDL window
App::getInstance().initVideo(false,true,false);
App::getInstance().setName ("SDLut::video test PixelFormat");
//Setting Display size and BPP
App::getInstance().getDisplay().setDisplay(300,240); // using autodetected bpp
App::getInstance().getDisplay().getScreenBuffer().setOpenGL(args.isOGL());
Test teng(testlog,args);
MyEngine engine(testlog,teng);
int exitstatus = -1;
if(App::getInstance().getDisplay().show())
{
exitstatus = App::getInstance().getDisplay().mainLoop();
}
return exitstatus;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: dirctrl.cpp
// Purpose: Implementation of class wxExGenericDirCtrl
// Author: Anton van Wezenbeek
// Copyright: (c) 2013 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/textfile.h>
#include <wx/extension/filename.h>
#include <wx/extension/menu.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
#include <wx/extension/report/dirctrl.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/frame.h>
#if wxUSE_DIRDLG
BEGIN_EVENT_TABLE(wxExGenericDirCtrl, wxGenericDirCtrl)
EVT_MENU_RANGE(
ID_EDIT_VCS_LOWEST,
ID_EDIT_VCS_HIGHEST,
wxExGenericDirCtrl::OnCommand)
EVT_MENU_RANGE(ID_TREE_OPEN, ID_TREE_RUN_MAKE, wxExGenericDirCtrl::OnCommand)
EVT_MENU_RANGE(ID_TOOL_LOWEST, ID_TOOL_HIGHEST, wxExGenericDirCtrl::OnCommand)
EVT_TREE_ITEM_ACTIVATED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)
EVT_TREE_ITEM_MENU(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)
EVT_TREE_SEL_CHANGED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)
END_EVENT_TABLE()
wxExGenericDirCtrl::wxExGenericDirCtrl(
wxWindow *parent,
wxExFrameWithHistory* frame,
const wxWindowID id,
const wxPoint &pos,
const wxSize &size,
long style,
const wxString &filter,
int defaultFilter,
const wxString &name)
: wxGenericDirCtrl(
parent,
id,
wxDirDialogDefaultFolderStr,
pos,
size,
style,
filter,
defaultFilter,
name)
, m_Frame(frame)
{
}
void wxExGenericDirCtrl::ExpandAndSelectPath(const wxString& path)
{
ExpandPath(path);
SelectPath(path);
}
void wxExGenericDirCtrl::OnCommand(wxCommandEvent& event)
{
if (event.GetId() > ID_EDIT_VCS_LOWEST &&
event.GetId() < ID_EDIT_VCS_HIGHEST)
{
wxExVCSExecute(m_Frame,
event.GetId() - ID_EDIT_VCS_LOWEST - 1, wxExToVectorString(*this).Get());
}
else if (event.GetId() > ID_TOOL_LOWEST && event.GetId() < ID_TOOL_HIGHEST)
{
m_Frame->FindInFiles(wxExToVectorString(*this).Get(), event.GetId());
}
else switch (event.GetId())
{
case ID_TREE_COPY:
{
const std::vector<wxString> files(wxExToVectorString(*this).Get());
wxBusyCursor wait;
wxString clipboard;
for (const auto& it : files)
{
clipboard += it + wxTextFile::GetEOL();
}
wxExClipboardAdd(clipboard);
}
break;
case ID_TREE_OPEN:
wxExOpenFiles(m_Frame,
wxExToVectorString(*this).Get(), 0, wxDIR_FILES); // only files in this dir
break;
case ID_TREE_RUN_MAKE:
{
const std::vector<wxString> files(wxExToVectorString(*this).Get());
wxExMake(files[0]);
}
break;
default: wxFAIL;
}
}
void wxExGenericDirCtrl::OnTree(wxTreeEvent& event)
{
const std::vector< wxString > files(wxExToVectorString(*this).Get());
if (files.empty())
{
event.Skip();
return;
}
if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_MENU)
{
const wxExFileName filename(files[0]);
wxExMenu menu; // uses AppendVCS
if (filename.FileExists())
{
menu.Append(ID_TREE_OPEN, _("&Open"));
menu.AppendSeparator();
}
menu.Append(ID_TREE_COPY,
wxGetStockLabel(wxID_COPY), wxEmptyString, wxART_COPY);
if (wxExVCS::DirExists(filename))
{
menu.AppendSeparator();
menu.AppendVCS(filename);
}
if (filename.GetLexer().GetScintillaLexer() == "makefile")
{
menu.AppendSeparator();
menu.Append(ID_TREE_RUN_MAKE, "&Make");
}
menu.AppendSeparator();
menu.Append(ID_TOOL_REPORT_FIND,
wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_FIND)));
menu.Append(ID_TOOL_REPORT_REPLACE,
wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_REPLACE)));
PopupMenu(&menu);
}
else if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_ACTIVATED)
{
const wxFileName fn(files[0]);
if (!fn.FileExists() && fn.DirExists())
{
if (!GetTreeCtrl()->IsExpanded(event.GetItem()))
{
ExpandAndSelectPath(files[0]);
}
else
{
CollapsePath(files[0]);
}
}
else
{
wxExOpenFiles(m_Frame, files, 0, wxDIR_FILES); // only files in this dir
}
}
else if (event.GetEventType() == wxEVT_COMMAND_TREE_SEL_CHANGED)
{
wxExLogStatus(wxFileName(files[0]), STAT_FULLPATH);
}
else
{
wxFAIL;
}
}
#endif
<commit_msg>corrected filter<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: dirctrl.cpp
// Purpose: Implementation of class wxExGenericDirCtrl
// Author: Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/textfile.h>
#include <wx/extension/filename.h>
#include <wx/extension/menu.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
#include <wx/extension/report/dirctrl.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/frame.h>
#if wxUSE_DIRDLG
BEGIN_EVENT_TABLE(wxExGenericDirCtrl, wxGenericDirCtrl)
EVT_MENU_RANGE(
ID_EDIT_VCS_LOWEST,
ID_EDIT_VCS_HIGHEST,
wxExGenericDirCtrl::OnCommand)
EVT_MENU_RANGE(ID_TREE_OPEN, ID_TREE_RUN_MAKE, wxExGenericDirCtrl::OnCommand)
EVT_MENU_RANGE(ID_TOOL_LOWEST, ID_TOOL_HIGHEST, wxExGenericDirCtrl::OnCommand)
EVT_TREE_ITEM_ACTIVATED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)
EVT_TREE_ITEM_MENU(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)
EVT_TREE_SEL_CHANGED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)
END_EVENT_TABLE()
wxExGenericDirCtrl::wxExGenericDirCtrl(
wxWindow *parent,
wxExFrameWithHistory* frame,
const wxWindowID id,
const wxPoint &pos,
const wxSize &size,
long style,
const wxString &filter,
int defaultFilter,
const wxString &name)
: wxGenericDirCtrl(
parent,
id,
wxDirDialogDefaultFolderStr,
pos,
size,
style,
(filter.empty() ? "*": filter),
defaultFilter,
name)
, m_Frame(frame)
{
}
void wxExGenericDirCtrl::ExpandAndSelectPath(const wxString& path)
{
ExpandPath(path);
SelectPath(path);
}
void wxExGenericDirCtrl::OnCommand(wxCommandEvent& event)
{
if (event.GetId() > ID_EDIT_VCS_LOWEST &&
event.GetId() < ID_EDIT_VCS_HIGHEST)
{
wxExVCSExecute(m_Frame,
event.GetId() - ID_EDIT_VCS_LOWEST - 1, wxExToVectorString(*this).Get());
}
else if (event.GetId() > ID_TOOL_LOWEST && event.GetId() < ID_TOOL_HIGHEST)
{
m_Frame->FindInFiles(wxExToVectorString(*this).Get(), event.GetId());
}
else switch (event.GetId())
{
case ID_TREE_COPY:
{
const std::vector<wxString> files(wxExToVectorString(*this).Get());
wxBusyCursor wait;
wxString clipboard;
for (const auto& it : files)
{
clipboard += it + wxTextFile::GetEOL();
}
wxExClipboardAdd(clipboard);
}
break;
case ID_TREE_OPEN:
wxExOpenFiles(m_Frame,
wxExToVectorString(*this).Get(), 0, wxDIR_FILES); // only files in this dir
break;
case ID_TREE_RUN_MAKE:
{
const std::vector<wxString> files(wxExToVectorString(*this).Get());
wxExMake(files[0]);
}
break;
default: wxFAIL;
}
}
void wxExGenericDirCtrl::OnTree(wxTreeEvent& event)
{
const std::vector< wxString > files(wxExToVectorString(*this).Get());
if (files.empty())
{
event.Skip();
return;
}
if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_MENU)
{
const wxExFileName filename(files[0]);
wxExMenu menu; // uses AppendVCS
if (filename.FileExists())
{
menu.Append(ID_TREE_OPEN, _("&Open"));
menu.AppendSeparator();
}
menu.Append(ID_TREE_COPY,
wxGetStockLabel(wxID_COPY), wxEmptyString, wxART_COPY);
if (wxExVCS::DirExists(filename))
{
menu.AppendSeparator();
menu.AppendVCS(filename);
}
if (filename.GetLexer().GetScintillaLexer() == "makefile")
{
menu.AppendSeparator();
menu.Append(ID_TREE_RUN_MAKE, "&Make");
}
menu.AppendSeparator();
menu.Append(ID_TOOL_REPORT_FIND,
wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_FIND)));
menu.Append(ID_TOOL_REPORT_REPLACE,
wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_REPLACE)));
PopupMenu(&menu);
}
else if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_ACTIVATED)
{
const wxFileName fn(files[0]);
if (!fn.FileExists() && fn.DirExists())
{
if (!GetTreeCtrl()->IsExpanded(event.GetItem()))
{
ExpandAndSelectPath(files[0]);
}
else
{
CollapsePath(files[0]);
}
}
else
{
wxExOpenFiles(m_Frame, files, 0, wxDIR_FILES); // only files in this dir
}
}
else if (event.GetEventType() == wxEVT_COMMAND_TREE_SEL_CHANGED)
{
wxExLogStatus(wxFileName(files[0]), STAT_FULLPATH);
}
else
{
wxFAIL;
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2011-2016 Blender Foundation
*
* 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 "device_split_kernel.h"
#include "kernel_types.h"
#include "kernel_split_data.h"
#include "util_time.h"
CCL_NAMESPACE_BEGIN
static const double alpha = 0.1; /* alpha for rolling average */
DeviceSplitKernel::DeviceSplitKernel(Device *device) : device(device)
{
current_max_closure = -1;
first_tile = true;
avg_time_per_sample = 0.0;
}
DeviceSplitKernel::~DeviceSplitKernel()
{
device->mem_free(split_data);
device->mem_free(ray_state);
device->mem_free(use_queues_flag);
device->mem_free(queue_index);
device->mem_free(work_pool_wgs);
delete kernel_path_init;
delete kernel_scene_intersect;
delete kernel_lamp_emission;
delete kernel_queue_enqueue;
delete kernel_background_buffer_update;
delete kernel_shader_eval;
delete kernel_holdout_emission_blurring_pathtermination_ao;
delete kernel_direct_lighting;
delete kernel_shadow_blocked;
delete kernel_next_iteration_setup;
}
bool DeviceSplitKernel::load_kernels(const DeviceRequestedFeatures& requested_features)
{
#define LOAD_KERNEL(name) \
kernel_##name = get_split_kernel_function(#name, requested_features); \
if(!kernel_##name) { \
return false; \
}
LOAD_KERNEL(path_init);
LOAD_KERNEL(scene_intersect);
LOAD_KERNEL(lamp_emission);
LOAD_KERNEL(queue_enqueue);
LOAD_KERNEL(background_buffer_update);
LOAD_KERNEL(shader_eval);
LOAD_KERNEL(holdout_emission_blurring_pathtermination_ao);
LOAD_KERNEL(direct_lighting);
LOAD_KERNEL(shadow_blocked);
LOAD_KERNEL(next_iteration_setup);
#undef LOAD_KERNEL
current_max_closure = requested_features.max_closure;
return true;
}
size_t DeviceSplitKernel::max_elements_for_max_buffer_size(size_t max_buffer_size, size_t passes_size)
{
size_t size_per_element = split_data_buffer_size(1024, current_max_closure, passes_size) / 1024;
return max_buffer_size / size_per_element;
}
bool DeviceSplitKernel::path_trace(DeviceTask *task,
RenderTile& tile,
device_memory& kgbuffer,
device_memory& kernel_data)
{
if(device->have_error()) {
return false;
}
/* Get local size */
size_t local_size[2];
{
int2 lsize = split_kernel_local_size();
local_size[0] = lsize[0];
local_size[1] = lsize[1];
}
/* Calculate per_thread_output_buffer_size. */
size_t per_thread_output_buffer_size = task->passes_size;
/* Set gloabl size */
size_t global_size[2];
{
int2 gsize = split_kernel_global_size(task);
/* Make sure that set work size is a multiple of local
* work size dimensions.
*/
global_size[0] = round_up(gsize[0], local_size[0]);
global_size[1] = round_up(gsize[1], local_size[1]);
}
/* Number of elements in the global state buffer */
int num_global_elements = global_size[0] * global_size[1];
/* Allocate all required global memory once. */
if(first_tile) {
first_tile = false;
/* Calculate max groups */
/* Denotes the maximum work groups possible w.r.t. current requested tile size. */
unsigned int max_work_groups = num_global_elements / WORK_POOL_SIZE + 1;
/* Allocate work_pool_wgs memory. */
work_pool_wgs.resize(max_work_groups * sizeof(unsigned int));
device->mem_alloc("work_pool_wgs", work_pool_wgs, MEM_READ_WRITE);
queue_index.resize(NUM_QUEUES * sizeof(int));
device->mem_alloc("queue_index", queue_index, MEM_READ_WRITE);
use_queues_flag.resize(sizeof(char));
device->mem_alloc("use_queues_flag", use_queues_flag, MEM_READ_WRITE);
ray_state.resize(num_global_elements);
device->mem_alloc("ray_state", ray_state, MEM_READ_WRITE);
split_data.resize(split_data_buffer_size(num_global_elements,
current_max_closure,
per_thread_output_buffer_size));
device->mem_alloc("split_data", split_data, MEM_READ_WRITE);
}
#define ENQUEUE_SPLIT_KERNEL(name, global_size, local_size) \
if(device->have_error()) { \
return false; \
} \
if(!kernel_##name->enqueue(KernelDimensions(global_size, local_size), kgbuffer, kernel_data)) { \
return false; \
}
tile.sample = tile.start_sample;
/* for exponential increase between tile updates */
int time_multiplier = 1;
while(tile.sample < tile.start_sample + tile.num_samples) {
/* to keep track of how long it takes to run a number of samples */
double start_time = time_dt();
/* initial guess to start rolling average */
const int initial_num_samples = 1;
/* approx number of samples per second */
int samples_per_second = (avg_time_per_sample > 0.0) ?
int(double(time_multiplier) / avg_time_per_sample) + 1 : initial_num_samples;
RenderTile subtile = tile;
subtile.start_sample = tile.sample;
subtile.num_samples = min(samples_per_second, tile.start_sample + tile.num_samples - tile.sample);
if(device->have_error()) {
return false;
}
/* reset state memory here as global size for data_init
* kernel might not be large enough to do in kernel
*/
device->mem_zero(work_pool_wgs);
device->mem_zero(split_data);
if(!enqueue_split_kernel_data_init(KernelDimensions(global_size, local_size),
subtile,
num_global_elements,
kgbuffer,
kernel_data,
split_data,
ray_state,
queue_index,
use_queues_flag,
work_pool_wgs
))
{
return false;
}
ENQUEUE_SPLIT_KERNEL(path_init, global_size, local_size);
bool activeRaysAvailable = true;
while(activeRaysAvailable) {
/* Twice the global work size of other kernels for
* ckPathTraceKernel_shadow_blocked_direct_lighting. */
size_t global_size_shadow_blocked[2];
global_size_shadow_blocked[0] = global_size[0] * 2;
global_size_shadow_blocked[1] = global_size[1];
/* Do path-iteration in host [Enqueue Path-iteration kernels. */
for(int PathIter = 0; PathIter < 16; PathIter++) {
ENQUEUE_SPLIT_KERNEL(scene_intersect, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(lamp_emission, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(background_buffer_update, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(shader_eval, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(direct_lighting, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(shadow_blocked, global_size_shadow_blocked, local_size);
ENQUEUE_SPLIT_KERNEL(next_iteration_setup, global_size, local_size);
if(task->get_cancel()) {
return true;
}
}
/* Decide if we should exit path-iteration in host. */
device->mem_copy_from(ray_state, 0, global_size[0] * global_size[1] * sizeof(char), 1, 1);
activeRaysAvailable = false;
for(int rayStateIter = 0; rayStateIter < global_size[0] * global_size[1]; ++rayStateIter) {
if(int8_t(ray_state.get_data()[rayStateIter]) != RAY_INACTIVE) {
/* Not all rays are RAY_INACTIVE. */
activeRaysAvailable = true;
break;
}
}
if(task->get_cancel()) {
return true;
}
}
double time_per_sample = ((time_dt()-start_time) / subtile.num_samples);
if(avg_time_per_sample == 0.0) {
/* start rolling average */
avg_time_per_sample = time_per_sample;
}
else {
avg_time_per_sample = alpha*time_per_sample + (1.0-alpha)*avg_time_per_sample;
}
#undef ENQUEUE_SPLIT_KERNEL
tile.sample += subtile.num_samples;
task->update_progress(&tile, tile.w*tile.h*subtile.num_samples);
time_multiplier = min(time_multiplier << 1, 10);
if(task->get_cancel()) {
return true;
}
}
return true;
}
CCL_NAMESPACE_END
<commit_msg>Fix crash after failed kernel build<commit_after>/*
* Copyright 2011-2016 Blender Foundation
*
* 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 "device_split_kernel.h"
#include "kernel_types.h"
#include "kernel_split_data.h"
#include "util_time.h"
CCL_NAMESPACE_BEGIN
static const double alpha = 0.1; /* alpha for rolling average */
DeviceSplitKernel::DeviceSplitKernel(Device *device) : device(device)
{
current_max_closure = -1;
first_tile = true;
avg_time_per_sample = 0.0;
kernel_path_init = NULL;
kernel_scene_intersect = NULL;
kernel_lamp_emission = NULL;
kernel_queue_enqueue = NULL;
kernel_background_buffer_update = NULL;
kernel_shader_eval = NULL;
kernel_holdout_emission_blurring_pathtermination_ao = NULL;
kernel_direct_lighting = NULL;
kernel_shadow_blocked = NULL;
kernel_next_iteration_setup = NULL;
}
DeviceSplitKernel::~DeviceSplitKernel()
{
device->mem_free(split_data);
device->mem_free(ray_state);
device->mem_free(use_queues_flag);
device->mem_free(queue_index);
device->mem_free(work_pool_wgs);
delete kernel_path_init;
delete kernel_scene_intersect;
delete kernel_lamp_emission;
delete kernel_queue_enqueue;
delete kernel_background_buffer_update;
delete kernel_shader_eval;
delete kernel_holdout_emission_blurring_pathtermination_ao;
delete kernel_direct_lighting;
delete kernel_shadow_blocked;
delete kernel_next_iteration_setup;
}
bool DeviceSplitKernel::load_kernels(const DeviceRequestedFeatures& requested_features)
{
#define LOAD_KERNEL(name) \
kernel_##name = get_split_kernel_function(#name, requested_features); \
if(!kernel_##name) { \
return false; \
}
LOAD_KERNEL(path_init);
LOAD_KERNEL(scene_intersect);
LOAD_KERNEL(lamp_emission);
LOAD_KERNEL(queue_enqueue);
LOAD_KERNEL(background_buffer_update);
LOAD_KERNEL(shader_eval);
LOAD_KERNEL(holdout_emission_blurring_pathtermination_ao);
LOAD_KERNEL(direct_lighting);
LOAD_KERNEL(shadow_blocked);
LOAD_KERNEL(next_iteration_setup);
#undef LOAD_KERNEL
current_max_closure = requested_features.max_closure;
return true;
}
size_t DeviceSplitKernel::max_elements_for_max_buffer_size(size_t max_buffer_size, size_t passes_size)
{
size_t size_per_element = split_data_buffer_size(1024, current_max_closure, passes_size) / 1024;
return max_buffer_size / size_per_element;
}
bool DeviceSplitKernel::path_trace(DeviceTask *task,
RenderTile& tile,
device_memory& kgbuffer,
device_memory& kernel_data)
{
if(device->have_error()) {
return false;
}
/* Get local size */
size_t local_size[2];
{
int2 lsize = split_kernel_local_size();
local_size[0] = lsize[0];
local_size[1] = lsize[1];
}
/* Calculate per_thread_output_buffer_size. */
size_t per_thread_output_buffer_size = task->passes_size;
/* Set gloabl size */
size_t global_size[2];
{
int2 gsize = split_kernel_global_size(task);
/* Make sure that set work size is a multiple of local
* work size dimensions.
*/
global_size[0] = round_up(gsize[0], local_size[0]);
global_size[1] = round_up(gsize[1], local_size[1]);
}
/* Number of elements in the global state buffer */
int num_global_elements = global_size[0] * global_size[1];
/* Allocate all required global memory once. */
if(first_tile) {
first_tile = false;
/* Calculate max groups */
/* Denotes the maximum work groups possible w.r.t. current requested tile size. */
unsigned int max_work_groups = num_global_elements / WORK_POOL_SIZE + 1;
/* Allocate work_pool_wgs memory. */
work_pool_wgs.resize(max_work_groups * sizeof(unsigned int));
device->mem_alloc("work_pool_wgs", work_pool_wgs, MEM_READ_WRITE);
queue_index.resize(NUM_QUEUES * sizeof(int));
device->mem_alloc("queue_index", queue_index, MEM_READ_WRITE);
use_queues_flag.resize(sizeof(char));
device->mem_alloc("use_queues_flag", use_queues_flag, MEM_READ_WRITE);
ray_state.resize(num_global_elements);
device->mem_alloc("ray_state", ray_state, MEM_READ_WRITE);
split_data.resize(split_data_buffer_size(num_global_elements,
current_max_closure,
per_thread_output_buffer_size));
device->mem_alloc("split_data", split_data, MEM_READ_WRITE);
}
#define ENQUEUE_SPLIT_KERNEL(name, global_size, local_size) \
if(device->have_error()) { \
return false; \
} \
if(!kernel_##name->enqueue(KernelDimensions(global_size, local_size), kgbuffer, kernel_data)) { \
return false; \
}
tile.sample = tile.start_sample;
/* for exponential increase between tile updates */
int time_multiplier = 1;
while(tile.sample < tile.start_sample + tile.num_samples) {
/* to keep track of how long it takes to run a number of samples */
double start_time = time_dt();
/* initial guess to start rolling average */
const int initial_num_samples = 1;
/* approx number of samples per second */
int samples_per_second = (avg_time_per_sample > 0.0) ?
int(double(time_multiplier) / avg_time_per_sample) + 1 : initial_num_samples;
RenderTile subtile = tile;
subtile.start_sample = tile.sample;
subtile.num_samples = min(samples_per_second, tile.start_sample + tile.num_samples - tile.sample);
if(device->have_error()) {
return false;
}
/* reset state memory here as global size for data_init
* kernel might not be large enough to do in kernel
*/
device->mem_zero(work_pool_wgs);
device->mem_zero(split_data);
if(!enqueue_split_kernel_data_init(KernelDimensions(global_size, local_size),
subtile,
num_global_elements,
kgbuffer,
kernel_data,
split_data,
ray_state,
queue_index,
use_queues_flag,
work_pool_wgs
))
{
return false;
}
ENQUEUE_SPLIT_KERNEL(path_init, global_size, local_size);
bool activeRaysAvailable = true;
while(activeRaysAvailable) {
/* Twice the global work size of other kernels for
* ckPathTraceKernel_shadow_blocked_direct_lighting. */
size_t global_size_shadow_blocked[2];
global_size_shadow_blocked[0] = global_size[0] * 2;
global_size_shadow_blocked[1] = global_size[1];
/* Do path-iteration in host [Enqueue Path-iteration kernels. */
for(int PathIter = 0; PathIter < 16; PathIter++) {
ENQUEUE_SPLIT_KERNEL(scene_intersect, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(lamp_emission, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(background_buffer_update, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(shader_eval, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(direct_lighting, global_size, local_size);
ENQUEUE_SPLIT_KERNEL(shadow_blocked, global_size_shadow_blocked, local_size);
ENQUEUE_SPLIT_KERNEL(next_iteration_setup, global_size, local_size);
if(task->get_cancel()) {
return true;
}
}
/* Decide if we should exit path-iteration in host. */
device->mem_copy_from(ray_state, 0, global_size[0] * global_size[1] * sizeof(char), 1, 1);
activeRaysAvailable = false;
for(int rayStateIter = 0; rayStateIter < global_size[0] * global_size[1]; ++rayStateIter) {
if(int8_t(ray_state.get_data()[rayStateIter]) != RAY_INACTIVE) {
/* Not all rays are RAY_INACTIVE. */
activeRaysAvailable = true;
break;
}
}
if(task->get_cancel()) {
return true;
}
}
double time_per_sample = ((time_dt()-start_time) / subtile.num_samples);
if(avg_time_per_sample == 0.0) {
/* start rolling average */
avg_time_per_sample = time_per_sample;
}
else {
avg_time_per_sample = alpha*time_per_sample + (1.0-alpha)*avg_time_per_sample;
}
#undef ENQUEUE_SPLIT_KERNEL
tile.sample += subtile.num_samples;
task->update_progress(&tile, tile.w*tile.h*subtile.num_samples);
time_multiplier = min(time_multiplier << 1, 10);
if(task->get_cancel()) {
return true;
}
}
return true;
}
CCL_NAMESPACE_END
<|endoftext|>
|
<commit_before>/**
A portable OpenAL audio subsystem implementation
Based on https://github.com/corporateshark/Android-NDK-Game-Development-Cookbook/tree/master/Chapter5
**/
#include <atomic>
#include <thread>
#include "AudioSubsystem_OpenAL.h"
#include "OpenAL/LAL.h"
class clAudioSource_OpenAL: public iAudioSource
{
public:
};
class clAudioSubsystem_OpenAL: public iAudioSubsystem
{
public:
clAudioSubsystem_OpenAL();
virtual ~clAudioSubsystem_OpenAL();
virtual void Start() override;
virtual void Stop() override;
virtual std::shared_ptr<iAudioSource> CreateAudioSource() override;
virtual void SetListenerGain( float Gain ) override;
private:
void DebugPrintVersion();
private:
ALCdevice* m_Device;
ALCcontext* m_Context;
std::shared_ptr<std::thread> m_AudioThread;
std::atomic<bool> m_IsPendingExit;
std::atomic<bool> m_IsInitialized;
};
std::shared_ptr<iAudioSubsystem> CreateAudioSubsystem_OpenAL()
{
return std::make_shared<clAudioSubsystem_OpenAL>();
}
clAudioSubsystem_OpenAL::clAudioSubsystem_OpenAL()
: m_Device( nullptr )
, m_Context( nullptr )
, m_AudioThread()
, m_IsPendingExit( false )
, m_IsInitialized( false )
{
LoadAL();
}
clAudioSubsystem_OpenAL::~clAudioSubsystem_OpenAL()
{
UnloadAL();
}
void clAudioSubsystem_OpenAL::DebugPrintVersion()
{
printf( "OpenAL version : %s\n", alGetString( AL_VERSION ) );
printf( "OpenAL vendor : %s\n", alGetString( AL_VENDOR ) );
printf( "OpenAL renderer: %s\n", alGetString( AL_RENDERER ) );
printf( "OpenAL extensions:\n%s\n", alGetString( AL_EXTENSIONS ) );
}
void clAudioSubsystem_OpenAL::Start()
{
m_AudioThread = std::make_shared<std::thread>(
[this]()
{
m_Device = alcOpenDevice( nullptr );
m_Context = alcCreateContext( m_Device, nullptr );
alcMakeContextCurrent( m_Context );
DebugPrintVersion();
m_IsInitialized = true;
while ( !m_IsPendingExit )
{
}
alcDestroyContext( m_Context );
alcCloseDevice( m_Device );
m_IsInitialized = false;
}
);
}
void clAudioSubsystem_OpenAL::Stop()
{
m_IsPendingExit = true;
m_AudioThread->join();
}
std::shared_ptr<iAudioSource> clAudioSubsystem_OpenAL::CreateAudioSource()
{
return std::make_shared<clAudioSource_OpenAL>();
}
void clAudioSubsystem_OpenAL::SetListenerGain( float Gain )
{
}
<commit_msg>Implemented clAudioSubsystem_OpenAL::SetListenerGain()<commit_after>/**
A portable OpenAL audio subsystem implementation
Based on https://github.com/corporateshark/Android-NDK-Game-Development-Cookbook/tree/master/Chapter5
**/
#include <atomic>
#include <thread>
#include "AudioSubsystem_OpenAL.h"
#include "OpenAL/LAL.h"
class clAudioSource_OpenAL: public iAudioSource
{
public:
};
class clAudioSubsystem_OpenAL: public iAudioSubsystem
{
public:
clAudioSubsystem_OpenAL();
virtual ~clAudioSubsystem_OpenAL();
virtual void Start() override;
virtual void Stop() override;
virtual std::shared_ptr<iAudioSource> CreateAudioSource() override;
virtual void SetListenerGain( float Gain ) override;
private:
void DebugPrintVersion();
private:
ALCdevice* m_Device;
ALCcontext* m_Context;
std::shared_ptr<std::thread> m_AudioThread;
std::atomic<bool> m_IsPendingExit;
std::atomic<bool> m_IsInitialized;
};
std::shared_ptr<iAudioSubsystem> CreateAudioSubsystem_OpenAL()
{
return std::make_shared<clAudioSubsystem_OpenAL>();
}
clAudioSubsystem_OpenAL::clAudioSubsystem_OpenAL()
: m_Device( nullptr )
, m_Context( nullptr )
, m_AudioThread()
, m_IsPendingExit( false )
, m_IsInitialized( false )
{
LoadAL();
}
clAudioSubsystem_OpenAL::~clAudioSubsystem_OpenAL()
{
UnloadAL();
}
void clAudioSubsystem_OpenAL::DebugPrintVersion()
{
printf( "OpenAL version : %s\n", alGetString( AL_VERSION ) );
printf( "OpenAL vendor : %s\n", alGetString( AL_VENDOR ) );
printf( "OpenAL renderer: %s\n", alGetString( AL_RENDERER ) );
printf( "OpenAL extensions:\n%s\n", alGetString( AL_EXTENSIONS ) );
}
void clAudioSubsystem_OpenAL::Start()
{
m_AudioThread = std::make_shared<std::thread>(
[this]()
{
m_Device = alcOpenDevice( nullptr );
m_Context = alcCreateContext( m_Device, nullptr );
alcMakeContextCurrent( m_Context );
DebugPrintVersion();
m_IsInitialized = true;
while ( !m_IsPendingExit )
{
}
alcDestroyContext( m_Context );
alcCloseDevice( m_Device );
m_IsInitialized = false;
}
);
}
void clAudioSubsystem_OpenAL::Stop()
{
m_IsPendingExit = true;
m_AudioThread->join();
}
std::shared_ptr<iAudioSource> clAudioSubsystem_OpenAL::CreateAudioSource()
{
return std::make_shared<clAudioSource_OpenAL>();
}
void clAudioSubsystem_OpenAL::SetListenerGain( float Gain )
{
alListenerf( AL_GAIN, Gain );
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 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.
=========================================================================*/
#include "itkPhysicalImage.h"
#include "itkImageRegionIterator.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "vnl/vnl_math.h"
#include <iostream>
int main()
{
//------------------------------------------------------------
// Create two simple images
// Two Gaussians with one translated (7,3) pixels from another
//------------------------------------------------------------
//Allocate Images
typedef itk::PhysicalImage<unsigned char,2> ReferenceType;
typedef itk::PhysicalImage<unsigned char,2> TargetType;
enum { ImageDimension = ReferenceType::ImageDimension };
ReferenceType::SizeType size = {{100,100}};
ReferenceType::IndexType index = {{0,0}};
ReferenceType::RegionType region;
region.SetSize( size );
region.SetIndex( index );
ReferenceType::Pointer imgReference = ReferenceType::New();
imgReference->SetLargestPossibleRegion( region );
imgReference->SetBufferedRegion( region );
imgReference->SetRequestedRegion( region );
imgReference->Allocate();
TargetType::Pointer imgTarget = TargetType::New();
imgTarget->SetLargestPossibleRegion( region );
imgTarget->SetBufferedRegion( region );
imgTarget->SetRequestedRegion( region );
imgTarget->Allocate();
// Fill images with a 2D gaussian
typedef itk::ImageRegionIterator<ReferenceType>
ReferenceIteratorType;
typedef itk::ImageRegionIterator<TargetType>
TargetIteratorType;
itk::Point<double,2> center;
center[0] = (double)region.GetSize()[0]/2.0;
center[1] = (double)region.GetSize()[1]/2.0;
const double s = (double)region.GetSize()[0]/2.0;
itk::Point<double,2> p;
itk::Vector<double,2> d;
// Set the displacement
itk::Vector<double,2> displacement;
displacement[0] = 7;
displacement[1] = 3;
ReferenceIteratorType ri(imgReference,region);
TargetIteratorType ti(imgTarget,region);
ri.Begin();
while(!ri.IsAtEnd())
{
p[0] = ri.GetIndex()[0];
p[1] = ri.GetIndex()[1];
d = p-center;
d += displacement;
const double x = d[0];
const double y = d[1];
ri.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
++ri;
}
ti.Begin();
while(!ti.IsAtEnd())
{
p[0] = ti.GetIndex()[0];
p[1] = ti.GetIndex()[1];
d = p-center;
const double x = d[0];
const double y = d[1];
ti.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
++ti;
}
//-----------------------------------------------------------
// Set up a the registrator
//-----------------------------------------------------------
typedef itk::ImageToImageAffineMutualInformationGradientDescentRegistration<
ReferenceType,TargetType> RegistrationType;
RegistrationType::Pointer registrationMethod = RegistrationType::New();
// connect the images
registrationMethod->SetReference(imgReference);
registrationMethod->SetTarget(imgTarget);
// set the transformation centers
RegistrationType::PointType transCenter;
for( unsigned int j = 0; j < 2; j++ )
{
transCenter[j] = double(size[j]) / 2;
}
registrationMethod->SetTargetTransformationCenter( transCenter );
registrationMethod->SetReferenceTransformationCenter( transCenter );
// set translation scale
const double transScale = 100;
registrationMethod->SetTranslationScale( transScale );
// set metric related parameters
registrationMethod->GetMetric()->SetTargetStandardDeviation( 5.0 );
registrationMethod->GetMetric()->SetReferenceStandardDeviation( 5.0 );
registrationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 );
// do the registration
// reduce learning rate as we go
registrationMethod->SetNumberOfIterations( 500 );
registrationMethod->SetLearningRate( 1e-5 );
registrationMethod->StartRegistration();
registrationMethod->SetNumberOfIterations( 250 );
registrationMethod->SetLearningRate( 1e-7 );
registrationMethod->StartRegistration();
registrationMethod->SetNumberOfIterations( 125 );
registrationMethod->SetLearningRate( 1e-8 );
registrationMethod->StartRegistration();
// get the results
RegistrationType::ParametersType solution =
registrationMethod->GetParameters();
std::cout << "Solution is: " << solution << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
double trueParameters[6] = { 1, 0, 0, 1, 0, 0 };
trueParameters[4] = - displacement[0];
trueParameters[5] = - displacement[1];
for( unsigned int j = 0; j < 4; j++ )
{
if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 )
{
std::cout << j << " ";
std::cout << solution[j] << " ";
std::cout << trueParameters[j] << " ";
std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << " ";
std::cout << std::endl;
pass = false;
}
}
for( unsigned int j = 4; j < 6; j++ )
{
if( vnl_math_abs( solution[j] * transScale - trueParameters[j] ) > 1.0 )
{
std::cout << j << " ";
std::cout << solution[j] << " ";
std::cout << trueParameters[j] << " ";
std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << " ";
std::cout << std::endl;
pass = false;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg><commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 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.
=========================================================================*/
#include "itkPhysicalImage.h"
#include "itkImageRegionIterator.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "vnl/vnl_math.h"
#include <iostream>
int main()
{
//------------------------------------------------------------
// Create two simple images
// Two Gaussians with one translated (7,3) pixels from another
//------------------------------------------------------------
//Allocate Images
typedef itk::PhysicalImage<unsigned char,2> ReferenceType;
typedef itk::PhysicalImage<unsigned char,2> TargetType;
enum { ImageDimension = ReferenceType::ImageDimension };
ReferenceType::SizeType size = {{100,100}};
ReferenceType::IndexType index = {{0,0}};
ReferenceType::RegionType region;
region.SetSize( size );
region.SetIndex( index );
ReferenceType::Pointer imgReference = ReferenceType::New();
imgReference->SetLargestPossibleRegion( region );
imgReference->SetBufferedRegion( region );
imgReference->SetRequestedRegion( region );
imgReference->Allocate();
TargetType::Pointer imgTarget = TargetType::New();
imgTarget->SetLargestPossibleRegion( region );
imgTarget->SetBufferedRegion( region );
imgTarget->SetRequestedRegion( region );
imgTarget->Allocate();
// Fill images with a 2D gaussian
typedef itk::ImageRegionIterator<ReferenceType>
ReferenceIteratorType;
typedef itk::ImageRegionIterator<TargetType>
TargetIteratorType;
itk::Point<double,2> center;
center[0] = (double)region.GetSize()[0]/2.0;
center[1] = (double)region.GetSize()[1]/2.0;
const double s = (double)region.GetSize()[0]/2.0;
itk::Point<double,2> p;
itk::Vector<double,2> d;
// Set the displacement
itk::Vector<double,2> displacement;
displacement[0] = 7;
displacement[1] = 3;
ReferenceIteratorType ri(imgReference,region);
TargetIteratorType ti(imgTarget,region);
ri.Begin();
while(!ri.IsAtEnd())
{
p[0] = ri.GetIndex()[0];
p[1] = ri.GetIndex()[1];
d = p-center;
d += displacement;
const double x = d[0];
const double y = d[1];
ri.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
++ri;
}
ti.Begin();
while(!ti.IsAtEnd())
{
p[0] = ti.GetIndex()[0];
p[1] = ti.GetIndex()[1];
d = p-center;
const double x = d[0];
const double y = d[1];
ti.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
++ti;
}
//-----------------------------------------------------------
// Set up a the registrator
//-----------------------------------------------------------
typedef itk::ImageToImageAffineMutualInformationGradientDescentRegistration<
ReferenceType,TargetType> RegistrationType;
RegistrationType::Pointer registrationMethod = RegistrationType::New();
// connect the images
registrationMethod->SetReference(imgReference);
registrationMethod->SetTarget(imgTarget);
// set the transformation centers
RegistrationType::PointType transCenter;
for( unsigned int j = 0; j < 2; j++ )
{
transCenter[j] = double(size[j]) / 2;
}
registrationMethod->SetTargetTransformationCenter( transCenter );
registrationMethod->SetReferenceTransformationCenter( transCenter );
// set translation scale
const double transScale = 100;
registrationMethod->SetTranslationScale( transScale );
// set metric related parameters
registrationMethod->GetMetric()->SetTargetStandardDeviation( 5.0 );
registrationMethod->GetMetric()->SetReferenceStandardDeviation( 5.0 );
registrationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 );
// do the registration
// reduce learning rate as we go
registrationMethod->SetNumberOfIterations( 300 );
registrationMethod->SetLearningRate( 5e-5 );
registrationMethod->StartRegistration();
registrationMethod->SetNumberOfIterations( 300 );
registrationMethod->SetLearningRate( 1e-5 );
registrationMethod->StartRegistration();
registrationMethod->SetNumberOfIterations( 300 );
registrationMethod->SetLearningRate( 1e-6 );
registrationMethod->StartRegistration();
// get the results
RegistrationType::ParametersType solution =
registrationMethod->GetParameters();
std::cout << "Solution is: " << solution << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
double trueParameters[6] = { 1, 0, 0, 1, 0, 0 };
trueParameters[4] = - displacement[0];
trueParameters[5] = - displacement[1];
for( unsigned int j = 0; j < 4; j++ )
{
if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 )
{
std::cout << j << " ";
std::cout << solution[j] << " ";
std::cout << trueParameters[j] << " ";
std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << " ";
std::cout << std::endl;
pass = false;
}
}
for( unsigned int j = 4; j < 6; j++ )
{
if( vnl_math_abs( solution[j] * transScale - trueParameters[j] ) > 1.0 )
{
std::cout << j << " ";
std::cout << solution[j] << " ";
std::cout << trueParameters[j] << " ";
std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << " ";
std::cout << std::endl;
pass = false;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdfilter.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:19:23 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#include <tools/debug.hxx>
#include <osl/file.hxx>
#include <vos/module.hxx>
#include <svtools/pathoptions.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/progress.hxx>
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef MAC
#ifndef SVX_LIGHT
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "../ui/inc/DrawDocShell.hxx"
#endif
#include "../ui/inc/strings.hrc"
#endif //!SVX_LIGHT
#else //MAC
#ifndef SVX_LIGHT
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#include "strings.hrc"
#endif //!SVX_LIGHT
#endif //!MAC
#include "sdresid.hxx"
#include "pres.hxx"
#include "drawdoc.hxx"
#include "sdfilter.hxx"
// --------------
// - Namespaces -
// --------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::frame;
// ------------
// - SdFilter -
// ------------
SdFilter::SdFilter( SfxMedium& rMedium, ::sd::DrawDocShell& rDocShell, sal_Bool bShowProgress ) :
mrMedium( rMedium ),
mrDocShell( rDocShell ),
mrDocument( *rDocShell.GetDoc() ),
mxModel( rDocShell.GetModel() ),
mpProgress( NULL ),
mbIsDraw( rDocShell.GetDocumentType() == DOCUMENT_TYPE_DRAW ),
mbShowProgress( bShowProgress )
{
}
// -----------------------------------------------------------------------------
SdFilter::~SdFilter()
{
if( !mrDocShell.HasSpecialProgress() )
delete mpProgress;
}
// -----------------------------------------------------------------------------
::rtl::OUString SdFilter::ImplGetFullLibraryName( const ::rtl::OUString& rLibraryName ) const
{
String aTemp( ::rtl::OUString::createFromAscii( SVLIBRARY( "?" ) ) );
xub_StrLen nIndex = aTemp.Search( (sal_Unicode)'?' );
aTemp.Replace( nIndex, 1, rLibraryName );
::rtl::OUString aLibraryName( aTemp );
return aLibraryName;
}
// -----------------------------------------------------------------------------
::vos::OModule* SdFilter::OpenLibrary( const ::rtl::OUString& rLibraryName ) const
{
::rtl::OUString aDest;
::rtl::OUString aNormalizedPath;
::vos::OModule* pRet;
if ( ::osl::FileBase::getFileURLFromSystemPath( SvtPathOptions().GetModulePath(), aDest ) != ::osl::FileBase::E_None )
aDest = SvtPathOptions().GetModulePath();
aDest += ::rtl::OUString( sal_Unicode( '/' ) );
aDest += ::rtl::OUString( ImplGetFullLibraryName( rLibraryName ) );
::osl::FileBase::getSystemPathFromFileURL( aDest, aNormalizedPath );
if( !( pRet = new ::vos::OModule( aNormalizedPath ) )->isLoaded() )
delete pRet, pRet = NULL;
return pRet;
}
// -----------------------------------------------------------------------------
void SdFilter::CreateStatusIndicator()
{
// The status indicator must be retrieved from the provided medium arguments
const SfxUnoAnyItem* pStatusBarItem = static_cast<const SfxUnoAnyItem*>(
mrMedium.GetItemSet()->GetItem(SID_PROGRESS_STATUSBAR_CONTROL) );
if ( pStatusBarItem )
pStatusBarItem->GetValue() >>= mxStatusIndicator;
// try
// {
// if (mxModel.is())
// {
// Reference< XController > xController( mxModel->getCurrentController());
// if( xController.is())
// {
// Reference< XFrame > xFrame( xController->getFrame());
// if( xFrame.is())
// {
// Reference< XStatusIndicatorFactory > xFactory( xFrame, UNO_QUERY );
// if( xFactory.is())
// {
// mxStatusIndicator = xFactory->createStatusIndicator();
// }
// }
// }
// }
// }
// catch( Exception& )
// {
// }
}
// -----------------------------------------------------------------------------
void SdFilter::CreateProgress()
{
if( mrDocShell.HasSpecialProgress() )
mpProgress = mrDocShell.GetSpecialProgress();
else
{
mpProgress = new SfxProgress( &mrDocShell, String( SdResId( STR_OPEN_DOCUMENT ) ), 100 );
mpProgress->SetState( 0, 100 );
}
}
<commit_msg>INTEGRATION: CWS aw024 (1.10.12); FILE MERGED 2006/09/21 22:47:47 aw 1.10.12.4: RESYNC: (1.12-1.13); FILE MERGED 2005/11/18 14:18:07 aw 1.10.12.3: RESYNC: (1.11-1.12); FILE MERGED 2005/09/17 10:26:06 aw 1.10.12.2: RESYNC: (1.10-1.11); FILE MERGED 2005/08/04 14:49:36 sj 1.10.12.1: #48467# using GraphicExporter component for exports, graphic filter progress now works now via xStatusIndicater instead of callback mechanism<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdfilter.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:22:10 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_
#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
#endif
#include <tools/debug.hxx>
#include <osl/file.hxx>
#include <vos/module.hxx>
#include <svtools/pathoptions.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/progress.hxx>
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef MAC
#ifndef SVX_LIGHT
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "../ui/inc/DrawDocShell.hxx"
#endif
#include "../ui/inc/strings.hrc"
#endif //!SVX_LIGHT
#else //MAC
#ifndef SVX_LIGHT
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#include "strings.hrc"
#endif //!SVX_LIGHT
#endif //!MAC
#include "sdresid.hxx"
#include "pres.hxx"
#include "drawdoc.hxx"
#include "sdfilter.hxx"
// --------------
// - Namespaces -
// --------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::frame;
// ------------
// - SdFilter -
// ------------
SdFilter::SdFilter( SfxMedium& rMedium, ::sd::DrawDocShell& rDocShell, sal_Bool bShowProgress ) :
mrMedium( rMedium ),
mrDocShell( rDocShell ),
mrDocument( *rDocShell.GetDoc() ),
mxModel( rDocShell.GetModel() ),
mbIsDraw( rDocShell.GetDocumentType() == DOCUMENT_TYPE_DRAW ),
mbShowProgress( bShowProgress )
{
}
// -----------------------------------------------------------------------------
SdFilter::~SdFilter()
{
}
// -----------------------------------------------------------------------------
::rtl::OUString SdFilter::ImplGetFullLibraryName( const ::rtl::OUString& rLibraryName ) const
{
String aTemp( ::rtl::OUString::createFromAscii( SVLIBRARY( "?" ) ) );
xub_StrLen nIndex = aTemp.Search( (sal_Unicode)'?' );
aTemp.Replace( nIndex, 1, rLibraryName );
::rtl::OUString aLibraryName( aTemp );
return aLibraryName;
}
// -----------------------------------------------------------------------------
::vos::OModule* SdFilter::OpenLibrary( const ::rtl::OUString& rLibraryName ) const
{
::rtl::OUString aDest;
::rtl::OUString aNormalizedPath;
::vos::OModule* pRet;
if ( ::osl::FileBase::getFileURLFromSystemPath( SvtPathOptions().GetModulePath(), aDest ) != ::osl::FileBase::E_None )
aDest = SvtPathOptions().GetModulePath();
aDest += ::rtl::OUString( sal_Unicode( '/' ) );
aDest += ::rtl::OUString( ImplGetFullLibraryName( rLibraryName ) );
::osl::FileBase::getSystemPathFromFileURL( aDest, aNormalizedPath );
if( !( pRet = new ::vos::OModule( aNormalizedPath ) )->isLoaded() )
delete pRet, pRet = NULL;
return pRet;
}
// -----------------------------------------------------------------------------
void SdFilter::CreateStatusIndicator()
{
// The status indicator must be retrieved from the provided medium arguments
const SfxUnoAnyItem* pStatusBarItem = static_cast<const SfxUnoAnyItem*>(
mrMedium.GetItemSet()->GetItem(SID_PROGRESS_STATUSBAR_CONTROL) );
if ( pStatusBarItem )
pStatusBarItem->GetValue() >>= mxStatusIndicator;
// try
// {
// if (mxModel.is())
// {
// Reference< XController > xController( mxModel->getCurrentController());
// if( xController.is())
// {
// Reference< XFrame > xFrame( xController->getFrame());
// if( xFrame.is())
// {
// Reference< XStatusIndicatorFactory > xFactory( xFrame, UNO_QUERY );
// if( xFactory.is())
// {
// mxStatusIndicator = xFactory->createStatusIndicator();
// }
// }
// }
// }
// }
// catch( Exception& )
// {
// }
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: BreakDlg.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-01-20 11:29:55 $
*
* 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 SD_BREAK_DLG_HXX
#define SD_BREAK_DLG_HXX
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _PRGSBAR_HXX
#include <svtools/prgsbar.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
class SvdProgressInfo;
class SfxProgress;
namespace sd {
class DrawDocShell;
class DrawView;
/*************************************************************************
|*
|* Dialog zum aufbrechen von Metafiles
|*
\************************************************************************/
class BreakDlg
: public SfxModalDialog
{
public:
BreakDlg (
::Window* pWindow,
DrawView* pDrView,
DrawDocShell* pShell,
ULONG nSumActionCount,
ULONG nObjCount);
virtual ~BreakDlg();
short Execute();
private:
FixedText aFtObjInfo;
FixedText aFtActInfo;
FixedText aFtInsInfo;
FixedInfo aFiObjInfo;
FixedInfo aFiActInfo;
FixedInfo aFiInsInfo;
CancelButton aBtnCancel;
DrawView* pDrView;
BOOL bCancel;
Timer aTimer;
SvdProgressInfo *pProgrInfo;
Link aLink;
SfxProgress *mpProgress;
DECL_LINK( CancelButtonHdl, void* );
DECL_LINK( UpDate, void* );
DECL_LINK( InitialUpdate, Timer* );
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.562); FILE MERGED 2005/09/05 13:22:37 rt 1.2.562.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BreakDlg.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:02:12 $
*
* 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 SD_BREAK_DLG_HXX
#define SD_BREAK_DLG_HXX
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _PRGSBAR_HXX
#include <svtools/prgsbar.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
class SvdProgressInfo;
class SfxProgress;
namespace sd {
class DrawDocShell;
class DrawView;
/*************************************************************************
|*
|* Dialog zum aufbrechen von Metafiles
|*
\************************************************************************/
class BreakDlg
: public SfxModalDialog
{
public:
BreakDlg (
::Window* pWindow,
DrawView* pDrView,
DrawDocShell* pShell,
ULONG nSumActionCount,
ULONG nObjCount);
virtual ~BreakDlg();
short Execute();
private:
FixedText aFtObjInfo;
FixedText aFtActInfo;
FixedText aFtInsInfo;
FixedInfo aFiObjInfo;
FixedInfo aFiActInfo;
FixedInfo aFiInsInfo;
CancelButton aBtnCancel;
DrawView* pDrView;
BOOL bCancel;
Timer aTimer;
SvdProgressInfo *pProgrInfo;
Link aLink;
SfxProgress *mpProgress;
DECL_LINK( CancelButtonHdl, void* );
DECL_LINK( UpDate, void* );
DECL_LINK( InitialUpdate, Timer* );
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>#include <string>
#include <cassert>
#include <cstdarg>
#include <libport/cstdlib>
#include <iostream>
#include <stdexcept>
#include <sdk/config.h>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/file-system.hh>
#include <libport/foreach.hh>
#include <libport/path.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include <libport/windows.hh>
#include <libport/option-parser.hh>
#include <libport/xltdl.hh>
#include <urbi/exit.hh>
#include <urbi/package-info.hh>
#include <urbi/uclient.hh>
using namespace urbi;
using libport::program_name;
// List of module names.
typedef std::list<std::string> modules_type;
static UCallbackAction
onError(const UMessage& msg)
{
std::cerr << program_name()
<< ": load module error: " << msg.message << std::endl;
return URBI_CONTINUE;
}
static UCallbackAction
onDone(const UMessage&)
{
::exit(0);
}
static int
connect_plugin(const std::string& host, int port, const modules_type& modules)
{
UClient cl(host, port);
if (cl.error())
// UClient already displayed an error message.
::exit(1);
cl.setErrorCallback(callback(&onError));
cl.setCallback(callback(&onDone), "output");
foreach (const std::string& m, modules)
cl << "loadModule(\"" << m << "\");";
cl << "output << 1;";
while (true)
sleep(1);
return 0;
}
static void
usage(libport::OptionParser& parser)
{
std::cout <<
"usage: " << program_name() <<
" [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\n"
"Start an UObject in either remote or plugin mode.\n"
<< parser <<
"\n"
"MODULE_NAMES is a list of modules.\n"
"UOPTIONS are passed to urbi::main in remote and start modes.\n"
"\n"
"Exit values:\n"
" 0 success\n"
" " << EX_NOINPUT << " some of the MODULES are missing\n"
" " << EX_OSFILE << " libuobject is missing\n"
" * other kinds of errors\n"
;
::exit(EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit(EX_OK);
}
static
std::string
absolute(const std::string& s)
{
libport::path p = s;
if (!p.absolute_get())
p = libport::get_current_directory() / p;
return p.to_string();
}
static
int
ltdebug(unsigned verbosity, unsigned level, const char* format, va_list args)
{
int errors = 0;
if (level <= verbosity)
{
errors += fprintf(stderr, "%s: ", program_name().c_str()) < 0;
errors += vfprintf(stderr, format, args) < 0;
}
return errors;
}
typedef int (*umain_type)(const libport::cli_args_type& args,
bool block, bool errors);
int
main(int argc, char* argv[])
{
libport::program_initialize(argc, argv);
unsigned verbosity = 0;
libport::path urbi_root = libport::xgetenv("URBI_ROOT", URBI_ROOT);
enum ConnectMode
{
/// Start a new engine and plug the module
MODE_PLUGIN_START,
/// Load the module in a running engine as a plugin
MODE_PLUGIN_LOAD,
/// Connect the module to a running engine (remote uobject)
MODE_REMOTE
};
ConnectMode connect_mode = MODE_REMOTE;
/// Core dll to use.
std::string dll;
/// Server host name.
std::string host = "localhost";
/// Server port.
int port = urbi::UClient::URBI_PORT;
// The list of modules.
modules_type modules;
// The options passed to urbi::main.
libport::cli_args_type args;
libport::cli_args_type args4modules;
args << argv[0];
libport::OptionValue
arg_custom("start using the shared library FILE", "custom", 'c', "FILE"),
arg_debug("increase verbosity for debug", "debug", 0, "N"),
arg_pfile("file containing the port to listen to", "port-file", 0, "FILE");
libport::OptionFlag
arg_plugin("start as a plugin uobject on a running server", "plugin", 'p'),
arg_remote("start as a remote uobject", "remote", 'r'),
arg_start("start an urbi server and connect as plugin", "start", 's');
libport::OptionsEnd arg_end;
libport::OptionParser opt_parser;
opt_parser << "Urbi-Launch options:"
<< libport::opts::help
<< libport::opts::version
<< arg_custom
<< arg_debug
<< "Mode selection:"
<< arg_plugin
<< arg_remote
<< arg_start
<< "Urbi-Launch options for plugin mode:"
<< libport::opts::host
<< libport::opts::port
<< arg_pfile
<< arg_end;
try
{
args4modules = opt_parser(libport::program_arguments());
}
catch (libport::Error& e)
{
const libport::Error::errors_type& err = e.errors();
foreach (std::string wrong_arg, err)
libport::invalid_option(wrong_arg);
}
foreach (std::string& mod_arg, args4modules)
modules << absolute(mod_arg);
if (libport::opts::version.get())
version();
if (libport::opts::help.get())
usage(opt_parser);
if (arg_custom.filled())
dll = arg_custom.value();
if (arg_debug.filled())
verbosity = arg_debug.get<unsigned>(1);
if (libport::opts::host.filled())
{
host = libport::opts::host.value();
args << "--host" << host;
}
if (arg_plugin.get())
connect_mode = MODE_PLUGIN_LOAD;
if (libport::opts::port.filled())
{
port = libport::opts::port.get<int>();
args << "--port" << libport::opts::port.value();
}
if (arg_pfile.filled())
{
std::string my_arg = arg_pfile.value();
port = libport::file_contents_get<int>(my_arg);
args << "--port-file" << my_arg;
}
if (arg_remote.get())
connect_mode = MODE_REMOTE;
if (arg_start.get())
connect_mode = MODE_PLUGIN_START;
args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());
if (connect_mode == MODE_PLUGIN_LOAD)
return connect_plugin(host, port, modules);
if (dll.empty())
dll = urbi_root / "gostai" / "core" / URBI_HOST /
(connect_mode == MODE_REMOTE ? "remote" : "engine") / "libuobject";
/* The two other modes are handled the same way:
* -Dlopen the correct libuobject.
* -Dlopen the uobjects to load.
* -Call urbi::main found by dlsym() in libuobject.
*/
lt_dladd_log_function((lt_dllog_function*) <debug, (void*) verbosity);
lt_dlinit();
lt_dlhandle core = libport::xlt_dlopenext(dll, true, EX_OSFILE, verbosity);
foreach (const std::string& s, modules)
libport::xlt_dlopenext(s, false, EX_NOINPUT);
umain_type umain = libport::xlt_dlsym<umain_type>(core, "urbi_main_args");
umain(args, true, true);
}
<commit_msg>urbi-launch: refactoring.<commit_after>#include <string>
#include <cassert>
#include <cstdarg>
#include <libport/cstdlib>
#include <iostream>
#include <stdexcept>
#include <sdk/config.h>
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/file-system.hh>
#include <libport/foreach.hh>
#include <libport/path.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include <libport/windows.hh>
#include <libport/option-parser.hh>
#include <libport/xltdl.hh>
#include <urbi/exit.hh>
#include <urbi/package-info.hh>
#include <urbi/uclient.hh>
using namespace urbi;
using libport::program_name;
// List of module names.
typedef std::list<std::string> modules_type;
static UCallbackAction
onError(const UMessage& msg)
{
std::cerr << program_name()
<< ": load module error: " << msg.message << std::endl;
return URBI_CONTINUE;
}
static UCallbackAction
onDone(const UMessage&)
{
::exit(0);
}
static int
connect_plugin(const std::string& host, int port, const modules_type& modules)
{
UClient cl(host, port);
if (cl.error())
// UClient already displayed an error message.
::exit(1);
cl.setErrorCallback(callback(&onError));
cl.setCallback(callback(&onDone), "output");
foreach (const std::string& m, modules)
cl << "loadModule(\"" << m << "\");";
cl << "output << 1;";
while (true)
sleep(1);
return 0;
}
static void
usage(libport::OptionParser& parser)
{
std::cout <<
"usage: " << program_name() <<
" [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\n"
"Start an UObject in either remote or plugin mode.\n"
<< parser <<
"\n"
"MODULE_NAMES is a list of modules.\n"
"UOPTIONS are passed to urbi::main in remote and start modes.\n"
"\n"
"Exit values:\n"
" 0 success\n"
" " << EX_NOINPUT << " some of the MODULES are missing\n"
" " << EX_OSFILE << " libuobject is missing\n"
" * other kinds of errors\n"
;
::exit(EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit(EX_OK);
}
static
std::string
absolute(const std::string& s)
{
libport::path p = s;
if (!p.absolute_get())
p = libport::get_current_directory() / p;
return p.to_string();
}
static
int
ltdebug(unsigned verbosity, unsigned level, const char* format, va_list args)
{
int errors = 0;
if (level <= verbosity)
{
errors += fprintf(stderr, "%s: ", program_name().c_str()) < 0;
errors += vfprintf(stderr, format, args) < 0;
}
return errors;
}
typedef int (*umain_type)(const libport::cli_args_type& args,
bool block, bool errors);
int
main(int argc, char* argv[])
{
libport::program_initialize(argc, argv);
unsigned verbosity = 0;
enum ConnectMode
{
/// Start a new engine and plug the module
MODE_PLUGIN_START,
/// Load the module in a running engine as a plugin
MODE_PLUGIN_LOAD,
/// Connect the module to a running engine (remote uobject)
MODE_REMOTE
};
ConnectMode connect_mode = MODE_REMOTE;
/// Core dll to use.
std::string dll;
/// Server host name.
std::string host = "localhost";
/// Server port.
int port = urbi::UClient::URBI_PORT;
// The list of modules.
modules_type modules;
// The options passed to urbi::main.
libport::cli_args_type args;
libport::cli_args_type args4modules;
args << argv[0];
libport::OptionValue
arg_custom("start using the shared library FILE", "custom", 'c', "FILE"),
arg_debug("increase verbosity for debug", "debug", 0, "N"),
arg_pfile("file containing the port to listen to", "port-file", 0, "FILE");
libport::OptionFlag
arg_plugin("start as a plugin uobject on a running server", "plugin", 'p'),
arg_remote("start as a remote uobject", "remote", 'r'),
arg_start("start an urbi server and connect as plugin", "start", 's');
libport::OptionsEnd arg_end;
libport::OptionParser opt_parser;
opt_parser << "Urbi-Launch options:"
<< libport::opts::help
<< libport::opts::version
<< arg_custom
<< arg_debug
<< "Mode selection:"
<< arg_plugin
<< arg_remote
<< arg_start
<< "Urbi-Launch options for plugin mode:"
<< libport::opts::host
<< libport::opts::port
<< arg_pfile
<< arg_end;
try
{
args4modules = opt_parser(libport::program_arguments());
}
catch (libport::Error& e)
{
const libport::Error::errors_type& err = e.errors();
foreach (std::string wrong_arg, err)
libport::invalid_option(wrong_arg);
}
foreach (std::string& mod_arg, args4modules)
modules << absolute(mod_arg);
if (libport::opts::version.get())
version();
if (libport::opts::help.get())
usage(opt_parser);
if (arg_custom.filled())
dll = arg_custom.value();
if (arg_debug.filled())
verbosity = arg_debug.get<unsigned>(1);
if (libport::opts::host.filled())
{
host = libport::opts::host.value();
args << "--host" << host;
}
if (arg_plugin.get())
connect_mode = MODE_PLUGIN_LOAD;
if (libport::opts::port.filled())
{
port = libport::opts::port.get<int>();
args << "--port" << libport::opts::port.value();
}
if (arg_pfile.filled())
{
std::string my_arg = arg_pfile.value();
port = libport::file_contents_get<int>(my_arg);
args << "--port-file" << my_arg;
}
if (arg_remote.get())
connect_mode = MODE_REMOTE;
if (arg_start.get())
connect_mode = MODE_PLUGIN_START;
args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());
if (connect_mode == MODE_PLUGIN_LOAD)
return connect_plugin(host, port, modules);
libport::path urbi_root = libport::xgetenv("URBI_ROOT", URBI_ROOT);
libport::path coredir = urbi_root / "gostai" / "core" / URBI_HOST;
if (dll.empty())
dll = (coredir
/ (connect_mode == MODE_REMOTE ? "remote" : "engine")
/ "libuobject");
/* The two other modes are handled the same way:
* -Dlopen the correct libuobject.
* -Dlopen the uobjects to load.
* -Call urbi::main found by dlsym() in libuobject.
*/
lt_dladd_log_function((lt_dllog_function*) <debug, (void*) verbosity);
lt_dlinit();
lt_dlhandle core = libport::xlt_dlopenext(dll, true, EX_OSFILE, verbosity);
foreach (const std::string& s, modules)
libport::xlt_dlopenext(s, false, EX_NOINPUT);
umain_type umain = libport::xlt_dlsym<umain_type>(core, "urbi_main_args");
umain(args, true, true);
}
<|endoftext|>
|
<commit_before>#include "messages.h"
qint64 Messages::FileSendingContext::transferID;
QMap<qint64, std::shared_ptr<Messages::FileSendingContext>> Messages::FileSendingContext::transfers;
qint64 Messages::FileReceivingContext::transferID;
QMap<qint64, std::shared_ptr<Messages::FileReceivingContext>> Messages::FileReceivingContext::transfers;
Messages::Messages(peer *peerToConnect = nullptr, QObject *parent) : QObject(parent), mPeer(peerToConnect)
{
//here we create peerconnection session
}
Messages::~Messages()
{
}
Messages::ArmaMessage Messages::createRegularMessage(Session & session, const QString & message) {
return addMessageHeader(session, message.toUtf8(), Messages::MsgType::RegularMessage, Messages::MsgType::RegularMessageDH);
}
Messages::ArmaMessage Messages::createLoginMessage(QString & name, const QString & password, int port, bool reg) {
//TODO: certificate and port
ArmaMessage ret;
ret.append(reg ? "r" : "l");
ret.append(Messages::armaSeparator);
ret.append(name.toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(password.toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(QString::number(port).toUtf8().toBase64());
return ret;
}
bool Messages::isJsonMessage(const ArmaMessage& message) {
return !QJsonDocument::fromJson(message).isNull();
}
bool Messages::parseJsonUsers(ArmaMessage &message, QList<peer>& usersList) {
usersList.clear();
QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
if (jsonDoc.isNull()) {
return false;
}
QJsonObject jsonObject = jsonDoc.object();
if (jsonObject["users"].isArray()) {
QJsonArray users = jsonObject["users"].toArray();
foreach (QJsonValue user, users)
{
QJsonObject userObject = user.toObject();
peer p;
p.address = userObject["address"].toString();
p.name = userObject["nick"].toString();
p.listeningPort = userObject["port"].toInt();
usersList.append(p);
}
}
else {
return false;
}
return true;
}
bool Messages::parseMessage(std::function<Session &(QString & name)> sessions, const ArmaMessage & message, std::function<void(Session &, MsgType, const ReceivedMessage &)> callback) {
QString senderNick, receiverNick;
QByteArray dh;
QDateTime timestamp;
MsgType type;
QList<QByteArray> list = message.split(armaSeparator);
if (list.size() < 5) throw MessageException("incomplete message");
senderNick = QString::fromUtf8(QByteArray::fromBase64(list[0]));
receiverNick = QString::fromUtf8(QByteArray::fromBase64(list[1]));
Session & session = sessions(senderNick);
if (session.getMyName() != receiverNick) throw MessageException("Message not for this client.");
ReceivedMessage parsedMessage;
timestamp.setMSecsSinceEpoch(list[2].toLongLong());
parsedMessage.timestamp = timestamp;
type = static_cast<MsgType>(list[3][0] - 'A');
QByteArray messageText;
if(type == Messages::MsgType::PureDH)
{
dh = QByteArray::fromBase64(list[4]);
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;
QByteArray messageText;
try {
QByteArray a1 = message.left(contextDataLength);
QByteArray a2 = message.right(message.length() - contextDataLength);
messageText = sk.unprotect(a2, a1);
}
catch (KryptoException e) {
return false;
}
sk.setDH(dh);
sk.generateKey();
parsedMessage.messageText = messageText;
return true;
}
else if (type % 2) {
if (list.size() < 6) throw MessageException("incomplete message");
dh = QByteArray::fromBase64(list[4]);
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;
QByteArray messageText;
try {
QByteArray a1 = message.left(contextDataLength);
QByteArray a2 = message.right(message.length() - contextDataLength);
messageText = sk.unprotect(a2, a1);
}
catch (KryptoException e) {
return false;
}
sk.setDH(dh);
sk.generateKey();
parsedMessage.messageText = messageText;
}
//regularMessage
else {
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + 4; //number of separators
try{
QByteArray a1 = message.left(contextDataLength);
QByteArray a2 = message.right(message.length() - contextDataLength);
messageText = sk.unprotect(a2, a1);
}
catch (KryptoException e) {
return false;
}
parsedMessage.messageText = messageText;
}
callback(session, type, parsedMessage);
return true;
}
QByteArray Messages::addMessageHeader(Session & session, const QByteArray & payload, Messages::MsgType type, Messages::MsgType typeDH) {
QByteArray ret;
SessionKey & key = session.getKey();
ret.append(session.getMyName().toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(session.getPartnerName().toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(QString::number(QDateTime::currentMSecsSinceEpoch()));
ret.append(Messages::armaSeparator);
QByteArray dh = key.conditionalGetDH();
if (dh.length() > 0) {
ret.append('A' + typeDH);
ret.append(Messages::armaSeparator);
ret.append(dh.toBase64());
}
else {
ret.append('A' + type);
}
ret.append(Messages::armaSeparator);
ret.append(key.protect(payload, ret));
if (dh.length() > 0) key.generateKey();
return ret;
}
void Messages::FileSendingContext::sendFile(Session & s, const QString & path, std::function<void(const QByteArray &)> sender) {
QByteArray payload;
auto it = transfers.insert(++transferID, std::shared_ptr<FileSendingContext>(new FileSendingContext(s, path, sender)));
payload.append(QByteArray::number(transferID));
payload.append(Messages::armaSeparator);
payload.append(QByteArray::number((*it)->fileSize));
sender(Messages::addMessageHeader(s, payload, MsgType::FileContext, MsgType::FileContextDH));
}
void Messages::FileSendingContext::confirmFile(Session & s, const QByteArray & response) {
QList<QByteArray> list = response.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
auto it = transfers.find(id);
(*it)->destID = list[1].toLongLong();
(*it)->startSending();
}
void Messages::FileReceivingContext::receiveFile(Session & s, const QByteArray & payload, std::function<void(const QByteArray &)> sender) {
QList<QByteArray> list = payload.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
qint64 size = list[1].toLongLong();
QString path = "downloads/";
path.append(QString::number(++transferID));
path.append(".rec");
auto it = transfers.insert(transferID, std::shared_ptr<FileReceivingContext>(new FileReceivingContext(s, path)));
QByteArray response;
response.append(QByteArray::number(id));
response.append(Messages::armaSeparator);
response.append(QByteArray::number(transferID));
if(sender) sender(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));
else s.send(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));
}
void Messages::FileReceivingContext::receiveChunk(Session & s, const QByteArray & payload) {
QList<QByteArray> list = payload.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
qint64 start = list[1].toLongLong();
qint64 len = list[2].toLongLong();
auto it = transfers.find(id);
(*it)->parseChunk(start, len, payload.right(payload.length() - (list[0].length() + list[1].length() + list[2].length() + 3)));
}
Messages::FileSendingContext::FileSendingContext(Session & session, QString path, std::function<void(const QByteArray &)> dataSender) : session(session), path(path), dataSender(dataSender) {
QFile file(path);
if(!file.open(QIODevice::ReadWrite)) throw MessageException("Unable to open file!");
fileSize = file.size();
file.close();
}
bool Messages::FileSendingContext::startSending() {
qint64 chunks = (fileSize - 1) / Messages::maxChunkSize + 1;
qint64 threads = std::min(chunks, maxThreads);
qint64 done = 0;
for (qint64 i = 0; i < threads; ++i) {
workers.push_back(Worker(session, destID, path, dataSender));
// Load balancer
qint64 cChunks = ((chunks - 1) / threads + (((chunks - 1) % threads < i) ? 0 : 1));
qint64 start = done * Messages::maxChunkSize;
done += cChunks;
qint64 len = (i == threads - 1) ? (fileSize - start) : (cChunks * Messages::maxChunkSize);
futures.push_back(QtConcurrent::run(workers.back(), start, len));
}
return true;
}
void Messages::FileSendingContext::Worker::operator()(qint64 gstart, qint64 glen) {
QFile file(path);
file.open(QIODevice::ReadOnly);
file.seek(gstart);
do {
qint64 len = std::min(glen, maxChunkSize);
qint64 start = file.pos();
glen -= len;
QByteArray payload;
payload.append(QString::number(destID));
payload.append(Messages::armaSeparator);
payload.append(QString::number(start));
payload.append(Messages::armaSeparator);
payload.append(QString::number(len));
payload.append(Messages::armaSeparator);
payload.append(file.read(len));
QByteArray ret = addMessageHeader(session, payload, Messages::MsgType::FileMessage, Messages::MsgType::FileMessageDH);
dataSender(ret);
} while (glen > 0);
file.close();
}
Messages::FileReceivingContext::FileReceivingContext(Session & session, QString path) : session(session), path(path) {
QFile file(path);
if (!file.open(QIODevice::ReadWrite)) throw MessageException("Unable to open file!");
fileSize = file.size();
file.close();
}
void Messages::FileReceivingContext::parseChunk(qint64 start, qint64 len, const QByteArray & data) {
workers.push_back(Worker(session, path, fileSize));
futures.push_back(QtConcurrent::run(workers.back(), start, len, data));
}
void Messages::FileReceivingContext::parseChunk(const QByteArray & data) {
QList<QByteArray> list = data.split(Messages::armaSeparator);
qint64 start = list[0].toLongLong();
qint64 len = list[1].toLongLong();
parseChunk(start, len, data.right(data.length() - (list[0].length() + list[1].length() + 2)));
}
void Messages::FileReceivingContext::Worker::operator()(qint64 start, qint64 len, QByteArray data) {
//if (start + len > fileSize) throw MessageException("File chunk out of range.");
QFile file(path);
file.open(QIODevice::ReadWrite);
file.seek(start);
file.write(data);
file.close();
}
<commit_msg>gcc compatibility<commit_after>#include "messages.h"
const char Messages::armaSeparator;
const qint64 Messages::maxThreads;
const qint64 Messages::maxChunkSize;
qint64 Messages::FileSendingContext::transferID;
QMap<qint64, std::shared_ptr<Messages::FileSendingContext>> Messages::FileSendingContext::transfers;
qint64 Messages::FileReceivingContext::transferID;
QMap<qint64, std::shared_ptr<Messages::FileReceivingContext>> Messages::FileReceivingContext::transfers;
Messages::Messages(peer *peerToConnect = nullptr, QObject *parent) : QObject(parent), mPeer(peerToConnect)
{
//here we create peerconnection session
}
Messages::~Messages()
{
}
Messages::ArmaMessage Messages::createRegularMessage(Session & session, const QString & message) {
return addMessageHeader(session, message.toUtf8(), Messages::MsgType::RegularMessage, Messages::MsgType::RegularMessageDH);
}
Messages::ArmaMessage Messages::createLoginMessage(QString & name, const QString & password, int port, bool reg) {
//TODO: certificate and port
ArmaMessage ret;
ret.append(reg ? "r" : "l");
ret.append(Messages::armaSeparator);
ret.append(name.toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(password.toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(QString::number(port).toUtf8().toBase64());
return ret;
}
bool Messages::isJsonMessage(const ArmaMessage& message) {
return !QJsonDocument::fromJson(message).isNull();
}
bool Messages::parseJsonUsers(ArmaMessage &message, QList<peer>& usersList) {
usersList.clear();
QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
if (jsonDoc.isNull()) {
return false;
}
QJsonObject jsonObject = jsonDoc.object();
if (jsonObject["users"].isArray()) {
QJsonArray users = jsonObject["users"].toArray();
foreach (QJsonValue user, users)
{
QJsonObject userObject = user.toObject();
peer p;
p.address = userObject["address"].toString();
p.name = userObject["nick"].toString();
p.listeningPort = userObject["port"].toInt();
usersList.append(p);
}
}
else {
return false;
}
return true;
}
bool Messages::parseMessage(std::function<Session &(QString & name)> sessions, const ArmaMessage & message, std::function<void(Session &, MsgType, const ReceivedMessage &)> callback) {
QString senderNick, receiverNick;
QByteArray dh;
QDateTime timestamp;
MsgType type;
QList<QByteArray> list = message.split(armaSeparator);
if (list.size() < 5) throw MessageException("incomplete message");
senderNick = QString::fromUtf8(QByteArray::fromBase64(list[0]));
receiverNick = QString::fromUtf8(QByteArray::fromBase64(list[1]));
Session & session = sessions(senderNick);
if (session.getMyName() != receiverNick) throw MessageException("Message not for this client.");
ReceivedMessage parsedMessage;
timestamp.setMSecsSinceEpoch(list[2].toLongLong());
parsedMessage.timestamp = timestamp;
type = static_cast<MsgType>(list[3][0] - 'A');
QByteArray messageText;
if(type == Messages::MsgType::PureDH)
{
dh = QByteArray::fromBase64(list[4]);
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;
QByteArray messageText;
try {
QByteArray a1 = message.left(contextDataLength);
QByteArray a2 = message.right(message.length() - contextDataLength);
messageText = sk.unprotect(a2, a1);
}
catch (KryptoException e) {
return false;
}
sk.setDH(dh);
sk.generateKey();
parsedMessage.messageText = messageText;
return true;
}
else if (type % 2) {
if (list.size() < 6) throw MessageException("incomplete message");
dh = QByteArray::fromBase64(list[4]);
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;
QByteArray messageText;
try {
QByteArray a1 = message.left(contextDataLength);
QByteArray a2 = message.right(message.length() - contextDataLength);
messageText = sk.unprotect(a2, a1);
}
catch (KryptoException e) {
return false;
}
sk.setDH(dh);
sk.generateKey();
parsedMessage.messageText = messageText;
}
//regularMessage
else {
SessionKey& sk = session.getKey();
int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + 4; //number of separators
try{
QByteArray a1 = message.left(contextDataLength);
QByteArray a2 = message.right(message.length() - contextDataLength);
messageText = sk.unprotect(a2, a1);
}
catch (KryptoException e) {
return false;
}
parsedMessage.messageText = messageText;
}
callback(session, type, parsedMessage);
return true;
}
QByteArray Messages::addMessageHeader(Session & session, const QByteArray & payload, Messages::MsgType type, Messages::MsgType typeDH) {
QByteArray ret;
SessionKey & key = session.getKey();
ret.append(session.getMyName().toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(session.getPartnerName().toUtf8().toBase64());
ret.append(Messages::armaSeparator);
ret.append(QString::number(QDateTime::currentMSecsSinceEpoch()));
ret.append(Messages::armaSeparator);
QByteArray dh = key.conditionalGetDH();
if (dh.length() > 0) {
ret.append('A' + typeDH);
ret.append(Messages::armaSeparator);
ret.append(dh.toBase64());
}
else {
ret.append('A' + type);
}
ret.append(Messages::armaSeparator);
ret.append(key.protect(payload, ret));
if (dh.length() > 0) key.generateKey();
return ret;
}
void Messages::FileSendingContext::sendFile(Session & s, const QString & path, std::function<void(const QByteArray &)> sender) {
QByteArray payload;
auto it = transfers.insert(++transferID, std::shared_ptr<FileSendingContext>(new FileSendingContext(s, path, sender)));
payload.append(QByteArray::number(transferID));
payload.append(Messages::armaSeparator);
payload.append(QByteArray::number((*it)->fileSize));
sender(Messages::addMessageHeader(s, payload, MsgType::FileContext, MsgType::FileContextDH));
}
void Messages::FileSendingContext::confirmFile(Session & s, const QByteArray & response) {
QList<QByteArray> list = response.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
auto it = transfers.find(id);
(*it)->destID = list[1].toLongLong();
(*it)->startSending();
}
void Messages::FileReceivingContext::receiveFile(Session & s, const QByteArray & payload, std::function<void(const QByteArray &)> sender) {
QList<QByteArray> list = payload.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
qint64 size = list[1].toLongLong();
QString path = "downloads/";
path.append(QString::number(++transferID));
path.append(".rec");
auto it = transfers.insert(transferID, std::shared_ptr<FileReceivingContext>(new FileReceivingContext(s, path)));
QByteArray response;
response.append(QByteArray::number(id));
response.append(Messages::armaSeparator);
response.append(QByteArray::number(transferID));
if(sender) sender(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));
else s.send(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));
}
void Messages::FileReceivingContext::receiveChunk(Session & s, const QByteArray & payload) {
QList<QByteArray> list = payload.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
qint64 start = list[1].toLongLong();
qint64 len = list[2].toLongLong();
auto it = transfers.find(id);
(*it)->parseChunk(start, len, payload.right(payload.length() - (list[0].length() + list[1].length() + list[2].length() + 3)));
}
Messages::FileSendingContext::FileSendingContext(Session & session, QString path, std::function<void(const QByteArray &)> dataSender) : session(session), path(path), dataSender(dataSender) {
QFile file(path);
if(!file.open(QIODevice::ReadWrite)) throw MessageException("Unable to open file!");
fileSize = file.size();
file.close();
}
bool Messages::FileSendingContext::startSending() {
qint64 chunks = (fileSize - 1) / Messages::maxChunkSize + 1;
qint64 threads = std::min(chunks, maxThreads);
qint64 done = 0;
for (qint64 i = 0; i < threads; ++i) {
workers.push_back(Worker(session, destID, path, dataSender));
// Load balancer
qint64 cChunks = ((chunks - 1) / threads + (((chunks - 1) % threads < i) ? 0 : 1));
qint64 start = done * Messages::maxChunkSize;
done += cChunks;
qint64 len = (i == threads - 1) ? (fileSize - start) : (cChunks * Messages::maxChunkSize);
futures.push_back(QtConcurrent::run(workers.back(), start, len));
}
return true;
}
void Messages::FileSendingContext::Worker::operator()(qint64 gstart, qint64 glen) {
QFile file(path);
file.open(QIODevice::ReadOnly);
file.seek(gstart);
do {
qint64 len = std::min(glen, maxChunkSize);
qint64 start = file.pos();
glen -= len;
QByteArray payload;
payload.append(QString::number(destID));
payload.append(Messages::armaSeparator);
payload.append(QString::number(start));
payload.append(Messages::armaSeparator);
payload.append(QString::number(len));
payload.append(Messages::armaSeparator);
payload.append(file.read(len));
QByteArray ret = addMessageHeader(session, payload, Messages::MsgType::FileMessage, Messages::MsgType::FileMessageDH);
dataSender(ret);
} while (glen > 0);
file.close();
}
Messages::FileReceivingContext::FileReceivingContext(Session & session, QString path) : session(session), path(path) {
QFile file(path);
if (!file.open(QIODevice::ReadWrite)) throw MessageException("Unable to open file!");
fileSize = file.size();
file.close();
}
void Messages::FileReceivingContext::parseChunk(qint64 start, qint64 len, const QByteArray & data) {
workers.push_back(Worker(session, path, fileSize));
futures.push_back(QtConcurrent::run(workers.back(), start, len, data));
}
void Messages::FileReceivingContext::parseChunk(const QByteArray & data) {
QList<QByteArray> list = data.split(Messages::armaSeparator);
qint64 start = list[0].toLongLong();
qint64 len = list[1].toLongLong();
parseChunk(start, len, data.right(data.length() - (list[0].length() + list[1].length() + 2)));
}
void Messages::FileReceivingContext::Worker::operator()(qint64 start, qint64 len, QByteArray data) {
//if (start + len > fileSize) throw MessageException("File chunk out of range.");
QFile file(path);
file.open(QIODevice::ReadWrite);
file.seek(start);
file.write(data);
file.close();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "BcmEgress.h"
#include "fboss/agent/Constants.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmHost.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/hw/bcm/BcmWarmBootCache.h"
namespace facebook { namespace fboss {
using folly::IPAddress;
using folly::MacAddress;
bool BcmEgress::alreadyExists(const opennsl_l3_egress_t& newEgress) const {
if (id_ == INVALID) {
return false;
}
opennsl_l3_egress_t existingEgress;
auto rv = opennsl_l3_egress_get(hw_->getUnit(), id_, &existingEgress);
bcmCheckError(rv, "Egress object ", id_, " does not exist");
bool sameMacs = !memcmp(newEgress.mac_addr, existingEgress.mac_addr,
sizeof(newEgress.mac_addr));
return sameMacs && existingEgress.intf == newEgress.intf &&
existingEgress.port == newEgress.port &&
existingEgress.flags == newEgress.flags;
}
void BcmEgress::verifyDropEgress(int unit) {
const auto id = getDropEgressId();
opennsl_l3_egress_t egress;
opennsl_l3_egress_t_init(&egress);
auto ret = opennsl_l3_egress_get(unit, id, &egress);
bcmCheckError(ret, "failed to verify drop egress ", id);
if (!(egress.flags & OPENNSL_L3_DST_DISCARD)) {
throw FbossError("Egress ID ", id, " is not programmed as drop");
}
}
void BcmEgress::program(opennsl_if_t intfId, opennsl_vrf_t vrf,
const IPAddress& ip, const MacAddress* mac, opennsl_port_t port,
RouteForwardAction action) {
opennsl_l3_egress_t eObj;
opennsl_l3_egress_t_init(&eObj);
if (mac == nullptr) {
if (action == TO_CPU) {
eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);
} else {
eObj.flags |= OPENNSL_L3_DST_DISCARD;
}
} else {
memcpy(&eObj.mac_addr, mac->bytes(), sizeof(eObj.mac_addr));
eObj.port = port;
}
eObj.intf = intfId;
bool addOrUpdateEgress = false;
const auto warmBootCache = hw_->getWarmBootCache();
CHECK(warmBootCache);
auto egressId2EgressAndBoolCitr = warmBootCache->findEgress(vrf, ip);
if (egressId2EgressAndBoolCitr !=
warmBootCache->egressId2EgressAndBool_end()) {
// Lambda to compare with existing egress to know if should reprogram
auto equivalent = [] (const opennsl_l3_egress_t& newEgress,
const opennsl_l3_egress_t& existingEgress) {
auto puntToCPU = [=] (const opennsl_l3_egress_t& egress) {
// Check if both OPENNSL_L3_L2TOCPU and OPENNSL_L3_COPY_TO_CPU are set
static const auto kCPUFlags =
OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU;
return (egress.flags & kCPUFlags) == kCPUFlags;
};
if (!puntToCPU(newEgress) && !puntToCPU(existingEgress)) {
// Both new and existing egress point to a valid nexthop
// Compare mac, port and interface of egress objects
return !memcmp(newEgress.mac_addr, existingEgress.mac_addr,
sizeof(newEgress.mac_addr)) &&
existingEgress.intf == newEgress.intf &&
existingEgress.port == newEgress.port;
}
if (puntToCPU(existingEgress)) {
// If existing entry and new entry both point to CPU we
// consider them equal (i.e. no need to update h/w)
return puntToCPU(newEgress);
} else {
// Existing entry does not point to CPU while the new
// one does. This is because the new entry does not know
// the result of ARP/NDP resolution yet. Leave the entry
// in h/w intact
return true;
}
return false;
};
const auto& existingEgressId = egressId2EgressAndBoolCitr->first;
// Cache existing egress id
id_ = existingEgressId;
auto existingEgressObject = egressId2EgressAndBoolCitr->second.first;
if (!equivalent(eObj, existingEgressObject)) {
VLOG(1) << "Updating egress object for next hop : " << ip;
addOrUpdateEgress = true;
} else {
VLOG(1) << "Egress object for : " << ip << " already exists";
}
} else {
addOrUpdateEgress = true;
}
if (addOrUpdateEgress) {
if (egressId2EgressAndBoolCitr ==
warmBootCache->egressId2EgressAndBool_end()) {
VLOG(1) << "Adding egress object for next hop : " << ip;
}
uint32_t flags = 0;
if (id_ != INVALID) {
flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;
}
if (!alreadyExists(eObj)) {
/*
* Only program the HW if a identical egress object does not
* exist. Per BCM documentation updating entries like so should not
* be a problem. However we found that if we reprogrammed a already
* existing egress object with the same parameters forwarding to
* the corresponding IP address sometimes broke. BCM issue is being
* tracked in t4324084
*/
auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);
bcmCheckError(rc, "failed to program L3 egress object ", id_,
" ", (mac) ? mac->toString() : "ToCPU",
" on port ", port,
" on unit ", hw_->getUnit());
VLOG(3) << "programmed L3 egress object " << id_ << " for "
<< ((mac) ? mac->toString() : "to CPU") << " on unit "
<< hw_->getUnit() << " for ip: " << ip << " flags " << eObj.flags;
if (mac != nullptr) {
mac_ = *mac;
}
intfId_ = intfId;
} else {
// TODO(t10268453): How can we get here? The entries were not equivalent
// when we entered this ' if (addOrUpdateEgress) ' condition. Is the
// difference between what is in BcmWarmBootCache and what is in the
// hardware?
VLOG(1) << "Identical egress object for : " << ip << " pointing to "
<< (mac ? mac->toString() : "CPU ") << " already exists "
<< "skipping egress programming ";
}
}
if (egressId2EgressAndBoolCitr !=
warmBootCache->egressId2EgressAndBool_end()) {
warmBootCache->programmed(egressId2EgressAndBoolCitr);
}
CHECK_NE(id_, INVALID);
}
void BcmEgress::programToCPU() {
auto egressFromCache = hw_->getWarmBootCache()->getToCPUEgressId();
if (id_ == INVALID && egressFromCache != INVALID) {
id_ = egressFromCache;
return;
}
opennsl_l3_egress_t eObj;
opennsl_l3_egress_t_init(&eObj);
eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);
// BCM does not care about interface ID for punt to CPU egress object
uint32_t flags = 0;
if (id_ != INVALID) {
flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;
}
auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);
bcmCheckError(rc, "failed to program L3 egress object ", id_,
" to CPU on unit ", hw_->getUnit());
VLOG(3) << "programmed L3 egress object " << id_
<< " to CPU on unit " << hw_->getUnit();
}
BcmEgress::~BcmEgress() {
if (id_ == INVALID) {
return;
}
auto rc = opennsl_l3_egress_destroy(hw_->getUnit(), id_);
bcmLogFatal(rc, hw_, "failed to destroy L3 egress object ",
id_, " on unit ", hw_->getUnit());
VLOG(3) << "destroyed L3 egress object " << id_
<< " on unit " << hw_->getUnit();
}
void BcmEcmpEgress::program() {
opennsl_l3_egress_ecmp_t obj;
opennsl_l3_egress_ecmp_t_init(&obj);
auto n_path = paths_.size();
obj.max_paths = ((n_path + 3) >> 2) << 2; // multiple of 4
const auto warmBootCache = hw_->getWarmBootCache();
auto egressIds2EcmpCItr = warmBootCache->findEcmp(paths_);
if (egressIds2EcmpCItr != warmBootCache->egressIds2Ecmp_end()) {
const auto& existing = egressIds2EcmpCItr->second;
// TODO figure out why the following check fails
// i.e. the suggested max_paths is not the same
// as programmed max_paths. Note that this does not
// imply that less number of next hops got programmed
// but just that the max_paths did not get rounded to
// the next multiple of 4 as we desired.
// CHECK(obj.max_paths == existing.max_paths);
id_ = existing.ecmp_intf;
VLOG(1) << "Ecmp egress object for egress : " <<
BcmWarmBootCache::toEgressIdsStr(paths_)
<< " already exists ";
warmBootCache->programmed(egressIds2EcmpCItr);
} else {
VLOG(1) << "Adding ecmp egress with egress : " <<
BcmWarmBootCache::toEgressIdsStr(paths_);
if (id_ != INVALID) {
obj.flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;
obj.ecmp_intf = id_;
}
opennsl_if_t pathsArray[paths_.size()];
auto index = 0;
for (auto path: paths_) {
if (hw_->getHostTable()->egressIdPort(path)) {
pathsArray[index++] = path;
} else {
VLOG(1) << "Skipping unresolved egress : " << path << " while "
<< "programming ECMP group ";
}
}
auto ret = opennsl_l3_egress_ecmp_create(hw_->getUnit(), &obj, index,
pathsArray);
bcmCheckError(ret, "failed to program L3 ECMP egress object ", id_,
" with ", n_path, " paths");
id_ = obj.ecmp_intf;
VLOG(2) << "Programmed L3 ECMP egress object " << id_ << " for "
<< n_path << " paths";
}
CHECK_NE(id_, INVALID);
}
BcmEcmpEgress::~BcmEcmpEgress() {
if (id_ == INVALID) {
return;
}
opennsl_l3_egress_ecmp_t obj;
opennsl_l3_egress_ecmp_t_init(&obj);
obj.ecmp_intf = id_;
auto ret = opennsl_l3_egress_ecmp_destroy(hw_->getUnit(), &obj);
bcmLogFatal(ret, hw_, "failed to destroy L3 ECMP egress object ",
id_, " on unit ", hw_->getUnit());
VLOG(3) << "Destroyed L3 ECMP egress object " << id_
<< " on unit " << hw_->getUnit();
}
folly::dynamic BcmEgress::toFollyDynamic() const {
folly::dynamic egress = folly::dynamic::object;
egress[kEgressId] = getID();
egress[kMac] = mac_.toString();
egress[kIntfId] = intfId_;
return egress;
}
folly::dynamic BcmEcmpEgress::toFollyDynamic() const {
folly::dynamic ecmpEgress = folly::dynamic::object;
ecmpEgress[kEgressId] = getID();
folly::dynamic paths = folly::dynamic::array;
for (auto path: paths_) {
paths.push_back(path);
}
ecmpEgress[kPaths] = std::move(paths);
return ecmpEgress;
}
bool BcmEcmpEgress::pathUnreachableHwLocked(EgressId path) {
return removeEgressIdHwLocked(hw_->getUnit(), getID(), path);
}
bool BcmEcmpEgress::pathReachableHwLocked(EgressId path) {
return addEgressIdHwLocked(hw_->getUnit(), getID(), paths_, path);
}
bool BcmEcmpEgress::removeEgressIdHwLocked(
int unit,
EgressId ecmpId,
EgressId toRemove) {
// We don't really need the lock here so safe to call the
// stricter non locked version.
return removeEgressIdHwNotLocked(unit, ecmpId, toRemove);
}
}}
<commit_msg>Make message hub work with new TCP connections<commit_after>/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "BcmEgress.h"
#include "fboss/agent/Constants.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmHost.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/hw/bcm/BcmWarmBootCache.h"
namespace facebook { namespace fboss {
using folly::IPAddress;
using folly::MacAddress;
bool BcmEgress::alreadyExists(const opennsl_l3_egress_t& newEgress) const {
if (id_ == INVALID) {
return false;
}
opennsl_l3_egress_t existingEgress;
auto rv = opennsl_l3_egress_get(hw_->getUnit(), id_, &existingEgress);
bcmCheckError(rv, "Egress object ", id_, " does not exist");
bool sameMacs = !memcmp(newEgress.mac_addr, existingEgress.mac_addr,
sizeof(newEgress.mac_addr));
return sameMacs && existingEgress.intf == newEgress.intf &&
existingEgress.port == newEgress.port &&
existingEgress.flags == newEgress.flags;
}
void BcmEgress::verifyDropEgress(int unit) {
const auto id = getDropEgressId();
opennsl_l3_egress_t egress;
opennsl_l3_egress_t_init(&egress);
auto ret = opennsl_l3_egress_get(unit, id, &egress);
bcmCheckError(ret, "failed to verify drop egress ", id);
if (!(egress.flags & OPENNSL_L3_DST_DISCARD)) {
throw FbossError("Egress ID ", id, " is not programmed as drop");
}
}
void BcmEgress::program(opennsl_if_t intfId, opennsl_vrf_t vrf,
const IPAddress& ip, const MacAddress* mac, opennsl_port_t port,
RouteForwardAction action) {
opennsl_l3_egress_t eObj;
opennsl_l3_egress_t_init(&eObj);
if (mac == nullptr) {
if (action == TO_CPU) {
eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);
} else {
eObj.flags |= OPENNSL_L3_DST_DISCARD;
}
} else {
memcpy(&eObj.mac_addr, mac->bytes(), sizeof(eObj.mac_addr));
eObj.port = port;
}
eObj.intf = intfId;
bool addOrUpdateEgress = false;
const auto warmBootCache = hw_->getWarmBootCache();
CHECK(warmBootCache);
auto egressId2EgressAndBoolCitr = warmBootCache->findEgress(vrf, ip);
if (egressId2EgressAndBoolCitr !=
warmBootCache->egressId2EgressAndBool_end()) {
// Lambda to compare with existing egress to know if should reprogram
auto equivalent = [] (const opennsl_l3_egress_t& newEgress,
const opennsl_l3_egress_t& existingEgress) {
auto puntToCPU = [=] (const opennsl_l3_egress_t& egress) {
// Check if both OPENNSL_L3_L2TOCPU and OPENNSL_L3_COPY_TO_CPU are set
static const auto kCPUFlags =
OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU;
return (egress.flags & kCPUFlags) == kCPUFlags;
};
if (!puntToCPU(newEgress) && !puntToCPU(existingEgress)) {
// Both new and existing egress point to a valid nexthop
// Compare mac, port and interface of egress objects
return !memcmp(newEgress.mac_addr, existingEgress.mac_addr,
sizeof(newEgress.mac_addr)) &&
existingEgress.intf == newEgress.intf &&
existingEgress.port == newEgress.port;
}
if (puntToCPU(existingEgress)) {
// If existing entry and new entry both point to CPU we
// consider them equal (i.e. no need to update h/w)
return puntToCPU(newEgress);
} else {
// Existing entry does not point to CPU while the new
// one does. This is because the new entry does not know
// the result of ARP/NDP resolution yet. Leave the entry
// in h/w intact
return true;
}
return false;
};
const auto& existingEgressId = egressId2EgressAndBoolCitr->first;
// Cache existing egress id
id_ = existingEgressId;
auto existingEgressObject = egressId2EgressAndBoolCitr->second.first;
if (!equivalent(eObj, existingEgressObject)) {
VLOG(1) << "Updating egress object for next hop : " << ip;
addOrUpdateEgress = true;
} else {
VLOG(1) << "Egress object for : " << ip << " already exists";
}
} else {
addOrUpdateEgress = true;
}
if (addOrUpdateEgress) {
if (egressId2EgressAndBoolCitr ==
warmBootCache->egressId2EgressAndBool_end()) {
VLOG(1) << "Adding egress object for next hop : " << ip;
}
uint32_t flags = 0;
if (id_ != INVALID) {
flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;
}
if (!alreadyExists(eObj)) {
/*
* Only program the HW if a identical egress object does not
* exist. Per BCM documentation updating entries like so should not
* be a problem. However we found that if we reprogrammed a already
* existing egress object with the same parameters forwarding to
* the corresponding IP address sometimes broke. BCM issue is being
* tracked in t4324084
*/
auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);
bcmCheckError(rc, "failed to program L3 egress object ", id_,
" ", (mac) ? mac->toString() : "ToCPU",
" on port ", port,
" on unit ", hw_->getUnit());
VLOG(3) << "programmed L3 egress object " << id_ << " for "
<< ((mac) ? mac->toString() : "to CPU") << " on unit "
<< hw_->getUnit() << " for ip: " << ip << " flags " << eObj.flags
<< " towards port " << eObj.port;
if (mac != nullptr) {
mac_ = *mac;
}
intfId_ = intfId;
} else {
// TODO(t10268453): How can we get here? The entries were not equivalent
// when we entered this ' if (addOrUpdateEgress) ' condition. Is the
// difference between what is in BcmWarmBootCache and what is in the
// hardware?
VLOG(1) << "Identical egress object for : " << ip << " pointing to "
<< (mac ? mac->toString() : "CPU ") << " already exists "
<< "skipping egress programming ";
}
}
if (egressId2EgressAndBoolCitr !=
warmBootCache->egressId2EgressAndBool_end()) {
warmBootCache->programmed(egressId2EgressAndBoolCitr);
}
CHECK_NE(id_, INVALID);
}
void BcmEgress::programToCPU() {
auto egressFromCache = hw_->getWarmBootCache()->getToCPUEgressId();
if (id_ == INVALID && egressFromCache != INVALID) {
id_ = egressFromCache;
return;
}
opennsl_l3_egress_t eObj;
opennsl_l3_egress_t_init(&eObj);
eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);
// BCM does not care about interface ID for punt to CPU egress object
uint32_t flags = 0;
if (id_ != INVALID) {
flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;
}
auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);
bcmCheckError(rc, "failed to program L3 egress object ", id_,
" to CPU on unit ", hw_->getUnit());
VLOG(3) << "programmed L3 egress object " << id_
<< " to CPU on unit " << hw_->getUnit();
}
BcmEgress::~BcmEgress() {
if (id_ == INVALID) {
return;
}
auto rc = opennsl_l3_egress_destroy(hw_->getUnit(), id_);
bcmLogFatal(rc, hw_, "failed to destroy L3 egress object ",
id_, " on unit ", hw_->getUnit());
VLOG(3) << "destroyed L3 egress object " << id_
<< " on unit " << hw_->getUnit();
}
void BcmEcmpEgress::program() {
opennsl_l3_egress_ecmp_t obj;
opennsl_l3_egress_ecmp_t_init(&obj);
auto n_path = paths_.size();
obj.max_paths = ((n_path + 3) >> 2) << 2; // multiple of 4
const auto warmBootCache = hw_->getWarmBootCache();
auto egressIds2EcmpCItr = warmBootCache->findEcmp(paths_);
if (egressIds2EcmpCItr != warmBootCache->egressIds2Ecmp_end()) {
const auto& existing = egressIds2EcmpCItr->second;
// TODO figure out why the following check fails
// i.e. the suggested max_paths is not the same
// as programmed max_paths. Note that this does not
// imply that less number of next hops got programmed
// but just that the max_paths did not get rounded to
// the next multiple of 4 as we desired.
// CHECK(obj.max_paths == existing.max_paths);
id_ = existing.ecmp_intf;
VLOG(1) << "Ecmp egress object for egress : " <<
BcmWarmBootCache::toEgressIdsStr(paths_)
<< " already exists ";
warmBootCache->programmed(egressIds2EcmpCItr);
} else {
VLOG(1) << "Adding ecmp egress with egress : " <<
BcmWarmBootCache::toEgressIdsStr(paths_);
if (id_ != INVALID) {
obj.flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;
obj.ecmp_intf = id_;
}
opennsl_if_t pathsArray[paths_.size()];
auto index = 0;
for (auto path: paths_) {
if (hw_->getHostTable()->egressIdPort(path)) {
pathsArray[index++] = path;
} else {
VLOG(1) << "Skipping unresolved egress : " << path << " while "
<< "programming ECMP group ";
}
}
auto ret = opennsl_l3_egress_ecmp_create(hw_->getUnit(), &obj, index,
pathsArray);
bcmCheckError(ret, "failed to program L3 ECMP egress object ", id_,
" with ", n_path, " paths");
id_ = obj.ecmp_intf;
VLOG(2) << "Programmed L3 ECMP egress object " << id_ << " for "
<< n_path << " paths";
}
CHECK_NE(id_, INVALID);
}
BcmEcmpEgress::~BcmEcmpEgress() {
if (id_ == INVALID) {
return;
}
opennsl_l3_egress_ecmp_t obj;
opennsl_l3_egress_ecmp_t_init(&obj);
obj.ecmp_intf = id_;
auto ret = opennsl_l3_egress_ecmp_destroy(hw_->getUnit(), &obj);
bcmLogFatal(ret, hw_, "failed to destroy L3 ECMP egress object ",
id_, " on unit ", hw_->getUnit());
VLOG(3) << "Destroyed L3 ECMP egress object " << id_
<< " on unit " << hw_->getUnit();
}
folly::dynamic BcmEgress::toFollyDynamic() const {
folly::dynamic egress = folly::dynamic::object;
egress[kEgressId] = getID();
egress[kMac] = mac_.toString();
egress[kIntfId] = intfId_;
return egress;
}
folly::dynamic BcmEcmpEgress::toFollyDynamic() const {
folly::dynamic ecmpEgress = folly::dynamic::object;
ecmpEgress[kEgressId] = getID();
folly::dynamic paths = folly::dynamic::array;
for (auto path: paths_) {
paths.push_back(path);
}
ecmpEgress[kPaths] = std::move(paths);
return ecmpEgress;
}
bool BcmEcmpEgress::pathUnreachableHwLocked(EgressId path) {
return removeEgressIdHwLocked(hw_->getUnit(), getID(), path);
}
bool BcmEcmpEgress::pathReachableHwLocked(EgressId path) {
return addEgressIdHwLocked(hw_->getUnit(), getID(), paths_, path);
}
bool BcmEcmpEgress::removeEgressIdHwLocked(
int unit,
EgressId ecmpId,
EgressId toRemove) {
// We don't really need the lock here so safe to call the
// stricter non locked version.
return removeEgressIdHwNotLocked(unit, ecmpId, toRemove);
}
}}
<|endoftext|>
|
<commit_before>/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <optional>
#include <string>
#include <utility>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_split.h"
#include "fcp/base/monitoring.h"
#include "fcp/client/client_runner.h"
#include "fcp/client/client_runner_example_data.pb.h"
#include "fcp/client/fake_event_publisher.h"
#include "fcp/client/fl_runner.h"
ABSL_FLAG(std::string, server, "",
"Federated Server URI (supports https+test:// and https:// URIs");
ABSL_FLAG(std::string, api_key, "", "API Key");
ABSL_FLAG(std::string, test_cert, "",
"Path to test CA certificate PEM file; used for https+test:// URIs");
ABSL_FLAG(std::string, session, "", "Session name");
ABSL_FLAG(std::string, population, "", "Population name");
ABSL_FLAG(std::string, retry_token, "", "Retry token");
ABSL_FLAG(std::string, client_version, "", "Client version");
ABSL_FLAG(std::string, attestation_string, "", "Attestation string");
ABSL_FLAG(std::string, example_data_path, "",
"Path to a serialized ClientRunnerExampleData proto with client "
"example data. Falls back to --num_examples if unset.");
ABSL_FLAG(int, num_examples, 0,
"Number of (empty) examples each created iterator serves. Ignored if "
"--example_store_path is set.");
ABSL_FLAG(int, num_rounds, 1, "Number of rounds to train");
ABSL_FLAG(int, sleep_after_round_secs, 3,
"Number of seconds to sleep after each round.");
ABSL_FLAG(bool, use_http_federated_compute_protocol, false,
"Whether to enable the HTTP FederatedCompute protocol instead "
"of the gRPC FederatedTrainingApi protocol.");
static constexpr char kUsageString[] =
"Stand-alone Federated Client Executable.\n\n"
"Connects to the specified server, tries to retrieve a plan, run the\n"
"plan (feeding the specified number of empty examples), and report the\n"
"results of the computation back to the server.";
static absl::StatusOr<fcp::client::ClientRunnerExampleData> LoadExampleData(
const std::string& examples_path) {
std::ifstream examples_file(examples_path);
fcp::client::ClientRunnerExampleData data;
if (!data.ParseFromIstream(&examples_file) || !examples_file.eof()) {
return absl::InvalidArgumentError(
"Failed to parse ClientRunnerExampleData");
}
return data;
}
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(kUsageString);
absl::ParseCommandLine(argc, argv);
int num_rounds = absl::GetFlag(FLAGS_num_rounds);
std::string server = absl::GetFlag(FLAGS_server);
std::string session = absl::GetFlag(FLAGS_session);
std::string population = absl::GetFlag(FLAGS_population);
std::string client_version = absl::GetFlag(FLAGS_client_version);
std::string test_cert = absl::GetFlag(FLAGS_test_cert);
FCP_LOG(INFO) << "Running for " << num_rounds << " rounds:";
FCP_LOG(INFO) << " - server: " << server;
FCP_LOG(INFO) << " - session: " << session;
FCP_LOG(INFO) << " - population: " << population;
FCP_LOG(INFO) << " - client_version: " << client_version;
std::optional<fcp::client::ClientRunnerExampleData> example_data;
if (std::string path = absl::GetFlag(FLAGS_example_data_path);
!path.empty()) {
auto statusor = LoadExampleData(path);
if (!statusor.ok()) {
FCP_LOG(ERROR) << "Failed to load example data: " << statusor.status();
return 1;
}
example_data = *std::move(statusor);
}
bool success = false;
for (auto i = 0; i < num_rounds || num_rounds < 0; ++i) {
fcp::client::FederatedTaskEnvDepsImpl federated_task_env_deps_impl =
example_data ? fcp::client::FederatedTaskEnvDepsImpl(
*std::move(example_data), test_cert)
: fcp::client::FederatedTaskEnvDepsImpl(
absl::GetFlag(FLAGS_num_examples), test_cert);
fcp::client::FakeEventPublisher event_publisher(/*quiet=*/false);
fcp::client::FilesImpl files_impl;
fcp::client::LogManagerImpl log_manager_impl;
fcp::client::FlagsImpl flags;
flags.set_use_http_federated_compute_protocol(
absl::GetFlag(FLAGS_use_http_federated_compute_protocol));
auto fl_runner_result = RunFederatedComputation(
&federated_task_env_deps_impl, &event_publisher, &files_impl,
&log_manager_impl, &flags, server, absl::GetFlag(FLAGS_api_key),
test_cert, session, population, absl::GetFlag(FLAGS_retry_token),
client_version, absl::GetFlag(FLAGS_attestation_string));
if (fl_runner_result.ok()) {
FCP_LOG(INFO) << "Run finished successfully; result: "
<< fl_runner_result.value().DebugString();
success = true;
} else {
FCP_LOG(ERROR) << "Error during run: " << fl_runner_result.status();
}
int sleep_secs = absl::GetFlag(FLAGS_sleep_after_round_secs);
FCP_LOG(INFO) << "Sleeping for " << sleep_secs << " secs";
absl::SleepFor(absl::Seconds(sleep_secs));
}
return success ? 0 : 1;
}
<commit_msg>Rename `--num_examples` to `--num_empty_examples` to be more accurate.<commit_after>/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <optional>
#include <string>
#include <utility>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/flags/usage.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_split.h"
#include "fcp/base/monitoring.h"
#include "fcp/client/client_runner.h"
#include "fcp/client/client_runner_example_data.pb.h"
#include "fcp/client/fake_event_publisher.h"
#include "fcp/client/fl_runner.h"
ABSL_FLAG(std::string, server, "",
"Federated Server URI (supports https+test:// and https:// URIs");
ABSL_FLAG(std::string, api_key, "", "API Key");
ABSL_FLAG(std::string, test_cert, "",
"Path to test CA certificate PEM file; used for https+test:// URIs");
ABSL_FLAG(std::string, session, "", "Session name");
ABSL_FLAG(std::string, population, "", "Population name");
ABSL_FLAG(std::string, retry_token, "", "Retry token");
ABSL_FLAG(std::string, client_version, "", "Client version");
ABSL_FLAG(std::string, attestation_string, "", "Attestation string");
ABSL_FLAG(std::string, example_data_path, "",
"Path to a serialized ClientRunnerExampleData proto with client "
"example data. Falls back to --num_empty_examples if unset.");
ABSL_FLAG(int, num_empty_examples, 0,
"Number of (empty) examples each created iterator serves. Ignored if "
"--example_store_path is set.");
ABSL_FLAG(int, num_rounds, 1, "Number of rounds to train");
ABSL_FLAG(int, sleep_after_round_secs, 3,
"Number of seconds to sleep after each round.");
ABSL_FLAG(bool, use_http_federated_compute_protocol, false,
"Whether to enable the HTTP FederatedCompute protocol instead "
"of the gRPC FederatedTrainingApi protocol.");
static constexpr char kUsageString[] =
"Stand-alone Federated Client Executable.\n\n"
"Connects to the specified server, tries to retrieve a plan, run the\n"
"plan (feeding the specified number of empty examples), and report the\n"
"results of the computation back to the server.";
static absl::StatusOr<fcp::client::ClientRunnerExampleData> LoadExampleData(
const std::string& examples_path) {
std::ifstream examples_file(examples_path);
fcp::client::ClientRunnerExampleData data;
if (!data.ParseFromIstream(&examples_file) || !examples_file.eof()) {
return absl::InvalidArgumentError(
"Failed to parse ClientRunnerExampleData");
}
return data;
}
int main(int argc, char** argv) {
absl::SetProgramUsageMessage(kUsageString);
absl::ParseCommandLine(argc, argv);
int num_rounds = absl::GetFlag(FLAGS_num_rounds);
std::string server = absl::GetFlag(FLAGS_server);
std::string session = absl::GetFlag(FLAGS_session);
std::string population = absl::GetFlag(FLAGS_population);
std::string client_version = absl::GetFlag(FLAGS_client_version);
std::string test_cert = absl::GetFlag(FLAGS_test_cert);
FCP_LOG(INFO) << "Running for " << num_rounds << " rounds:";
FCP_LOG(INFO) << " - server: " << server;
FCP_LOG(INFO) << " - session: " << session;
FCP_LOG(INFO) << " - population: " << population;
FCP_LOG(INFO) << " - client_version: " << client_version;
std::optional<fcp::client::ClientRunnerExampleData> example_data;
if (std::string path = absl::GetFlag(FLAGS_example_data_path);
!path.empty()) {
auto statusor = LoadExampleData(path);
if (!statusor.ok()) {
FCP_LOG(ERROR) << "Failed to load example data: " << statusor.status();
return 1;
}
example_data = *std::move(statusor);
}
bool success = false;
for (auto i = 0; i < num_rounds || num_rounds < 0; ++i) {
fcp::client::FederatedTaskEnvDepsImpl federated_task_env_deps_impl =
example_data ? fcp::client::FederatedTaskEnvDepsImpl(
*std::move(example_data), test_cert)
: fcp::client::FederatedTaskEnvDepsImpl(
absl::GetFlag(FLAGS_num_empty_examples), test_cert);
fcp::client::FakeEventPublisher event_publisher(/*quiet=*/false);
fcp::client::FilesImpl files_impl;
fcp::client::LogManagerImpl log_manager_impl;
fcp::client::FlagsImpl flags;
flags.set_use_http_federated_compute_protocol(
absl::GetFlag(FLAGS_use_http_federated_compute_protocol));
auto fl_runner_result = RunFederatedComputation(
&federated_task_env_deps_impl, &event_publisher, &files_impl,
&log_manager_impl, &flags, server, absl::GetFlag(FLAGS_api_key),
test_cert, session, population, absl::GetFlag(FLAGS_retry_token),
client_version, absl::GetFlag(FLAGS_attestation_string));
if (fl_runner_result.ok()) {
FCP_LOG(INFO) << "Run finished successfully; result: "
<< fl_runner_result.value().DebugString();
success = true;
} else {
FCP_LOG(ERROR) << "Error during run: " << fl_runner_result.status();
}
int sleep_secs = absl::GetFlag(FLAGS_sleep_after_round_secs);
FCP_LOG(INFO) << "Sleeping for " << sleep_secs << " secs";
absl::SleepFor(absl::Seconds(sleep_secs));
}
return success ? 0 : 1;
}
<|endoftext|>
|
<commit_before><?hh // strict
namespace hhpack\process;
final class Pipe
{
private BufferedOutput $bufferedOutput;
public function __construct(
private resource $handle
)
{
$this->bufferedOutput = new BufferedOutput();
}
public function eof() : bool
{
return feof($this->handle);
}
public function read(int $length) : void
{
$chunk = fread($this->handle, $length);
$this->bufferedOutput->append($chunk);
}
public function getOutput() : BufferedOutput
{
return $this->bufferedOutput;
}
public function close() : void
{
fclose($this->handle);
}
}
<commit_msg>Remove old source<commit_after><|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2017 CPirc
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 <chrono>
#include <cinttypes>
#include <vector>
#include <algorithm> // std::reverse
#include "eval.h"
#include "move.h"
#include "position.h"
#include "search.h"
#define INF (30000)
/* MVV/LVA */
int mvv_lva(const Position& pos, Move m)
{
Piece from = get_piece_on_square(pos, from_square(m));
Piece dest = get_piece_on_square(pos, to_square(m));
return piecevals[OPENING][dest] - from;
}
/* Score a SearchStack. */
void score_moves(const Position& pos, SearchStack* ss, int size)
{
for (int i = 0; i < size; i++) {
Move move = ss->ml[i];
int mt = move_type(move);
if (mt == CAPTURE)
ss->score[i] = mvv_lva(pos, move);
else if (mt == PROM_CAPTURE)
ss->score[i] = mvv_lva(pos, move) + piecevals[OPENING][promotion_type(move)];
else if (mt == ENPASSANT)
ss->score[i] = piecevals[OPENING][PAWN] - PAWN + 10;
else
ss->score[i] = 0;
}
}
/* Return the best move from the search stack */
Move next_move(SearchStack* ss, int& size)
{
if (!size)
return 0;
// Find best move index
int best_index = 0;
for (int i = 1; i < size; ++i) {
if (ss->score[i] > ss->score[best_index]) {
best_index = i;
}
}
// Store the best move to return
Move best_move = ss->ml[best_index];
// Reduce ml/score size
--size;
// Bring the last move to current index
ss->ml[best_index] = ss->ml[size];
ss->score[best_index] = ss->score[size];
return best_move;
}
/* Quiescence alpha-beta search a search leaf node to reduce the horizon effect. */
int quiesce(SearchController& sc, Position& pos, int alpha, int beta, SearchStack* ss)
{
if (ss->ply >= MAX_PLY) {
return evaluate(pos);
}
// Check time left
clock_t current_time = clock() * 1000 / CLOCKS_PER_SEC;
if (current_time >= sc.search_end_time) {
return 0;
}
int movecount, value;
value = evaluate(pos);
if (value >= beta)
return beta;
if (value > alpha)
alpha = value;
movecount = generate_captures(pos, ss->ml);
++ss->stats->node_count;
score_moves(pos, ss, movecount);
Move move;
while ((move = next_move(ss, movecount))) {
Position npos = pos;
make_move(npos, move);
if (is_checked(npos, THEM)) {
continue;
}
value = -quiesce(sc, npos, -beta, -alpha, ss + 1);
if (value >= beta) {
return beta;
}
if (value > alpha) {
alpha = value;
}
}
return alpha;
}
/* Alpha-Beta search a position to return a score. */
int search(SearchController& sc, Position& pos, int depth, int alpha, int beta, SearchStack* ss, PV& pv)
{
if (depth <= 0) {
return quiesce(sc, pos, alpha, beta, ss);
}
if (ss->ply >= MAX_PLY) {
return evaluate(pos);
}
// Check time left
clock_t current_time = clock() * 1000 / CLOCKS_PER_SEC;
if (ss->ply && current_time >= sc.search_end_time) {
return 0;
}
// Update info
if (ss->stats->node_count%1048576 == 0) {
if (current_time > sc.search_start_time) {
printf("info nps %" PRIu64 "\n", 1000*(ss->stats->node_count)/(current_time - sc.search_start_time));
}
}
int movecount, value;
const bool in_check = is_checked(pos, US);
movecount = generate(pos, ss->ml);
++ss->stats->node_count;
score_moves(pos, ss, movecount);
int legal_moves = 0;
int best_value = -INF;
Move move;
PV child_pv;
while ((move = next_move(ss, movecount))) {
child_pv.clear();
Position npos = pos;
make_move(npos, move);
if (is_checked(npos, THEM)) {
continue;
}
++legal_moves;
value = -search(sc, npos, depth - 1, -beta, -alpha, ss + 1, child_pv);
if (value >= beta) {
#ifdef TESTING
++ss->stats->fail_highs;
if (legal_moves == 1)
++ss->stats->first_move_fail_highs;
#endif
return beta;
}
if (value > best_value) {
best_value = value;
child_pv.push_back(move);
pv = std::move(child_pv);
if (value > alpha) {
alpha = value;
}
}
}
if (!legal_moves) {
if (in_check)
return -INF + ss->ply;
else
return 0;
}
#ifdef TESTING
if (!ss->ply) {
printf("info string ordering = %lf\n", double(ss->stats->first_move_fail_highs) / ss->stats->fail_highs);
}
#endif
return alpha;
}
/* Reset the stats object to 0 so we can start recording */
void clear_stats(Stats& stats)
{
stats.node_count = 0;
#ifdef TESTING
stats.fail_highs = 0;
stats.first_move_fail_highs = 0;
#endif
}
/* Reset the search stack to default values */
void clear_ss(SearchStack* ss, int size)
{
for (std::uint8_t i = 0; i < size; ++i, ++ss) {
ss->ply = i;
}
}
/* Set the Stats pointer for all ply after 'stats' */
void set_stats(SearchStack* ss, Stats& stats)
{
SearchStack* end = ss - ss->ply + MAX_PLY;
for (; ss < end; ++ss) {
ss->stats = &stats;
}
}
/* Start searching a position and return the best move */
Move start_search(SearchController& sc)
{
Stats stats;
SearchStack ss[MAX_PLY];
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
clear_stats(stats);
clear_ss(ss, MAX_PLY);
set_stats(ss, stats);
/* Timing */
sc.search_start_time = 1000 * clock() / CLOCKS_PER_SEC;
if (sc.movetime) {
sc.search_end_time = sc.movetime/2;
} else if (sc.moves_per_session) {
sc.search_end_time = sc.our_clock/sc.moves_per_session + sc.increment;
} else {
sc.search_end_time = sc.our_clock/40 + sc.increment;
}
sc.search_end_time += sc.search_start_time;
char mstr[6];
Move best_move;
int best_score = -INF;
PV pv, depth_pv, child_pv;
/* Iterative deepening */
for (std::uint32_t depth = 1; depth < sc.max_depth; ++depth) {
int beta = INF;
int alpha = -INF;
int depth_best_score = search(sc, sc.pos, depth, alpha, beta, ss, depth_pv);
// Check time used
clock_t time_used = clock() * 1000 / CLOCKS_PER_SEC - sc.search_start_time;
// See if we ran out of time
if (depth > 1 && time_used >= sc.search_end_time - sc.search_start_time) {
break;
}
// Only update the best pv if we didn't run out of time
// It needs reversing due to the last in first out nature of push_back()
pv = depth_pv;
std::reverse(pv.begin(), pv.end());
best_score = depth_best_score;
// Update info
printf("info score cp %i depth %i nodes %" PRIu64 " time %lu pv ", best_score, depth, stats.node_count, time_used);
bool flipped = sc.pos.flipped;
for (Move move : pv) {
if (flipped) {
move = flip_move(move);
}
move_to_lan(mstr, move);
printf("%s ", mstr);
flipped ^= 1;
}
printf("\n");
}
if (pv.size() >= 1) {
best_move = pv[0];
if (sc.pos.flipped) {
best_move = flip_move(best_move);
}
move_to_lan(mstr, best_move);
printf("bestmove %s\n", mstr);
} else {
printf("bestmove 0000\n");
}
return (Move)0;
}
void search_thread(void* params)
{
SearchController *sc = (SearchController*)params;
start_search(*sc);
}
<commit_msg>Added check extensions<commit_after>/*
MIT License
Copyright (c) 2017 CPirc
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 <chrono>
#include <cinttypes>
#include <vector>
#include <algorithm> // std::reverse
#include "eval.h"
#include "move.h"
#include "position.h"
#include "search.h"
#define INF (30000)
/* MVV/LVA */
int mvv_lva(const Position& pos, Move m)
{
Piece from = get_piece_on_square(pos, from_square(m));
Piece dest = get_piece_on_square(pos, to_square(m));
return piecevals[OPENING][dest] - from;
}
/* Score a SearchStack. */
void score_moves(const Position& pos, SearchStack* ss, int size)
{
for (int i = 0; i < size; i++) {
Move move = ss->ml[i];
int mt = move_type(move);
if (mt == CAPTURE)
ss->score[i] = mvv_lva(pos, move);
else if (mt == PROM_CAPTURE)
ss->score[i] = mvv_lva(pos, move) + piecevals[OPENING][promotion_type(move)];
else if (mt == ENPASSANT)
ss->score[i] = piecevals[OPENING][PAWN] - PAWN + 10;
else
ss->score[i] = 0;
}
}
/* Return the best move from the search stack */
Move next_move(SearchStack* ss, int& size)
{
if (!size)
return 0;
// Find best move index
int best_index = 0;
for (int i = 1; i < size; ++i) {
if (ss->score[i] > ss->score[best_index]) {
best_index = i;
}
}
// Store the best move to return
Move best_move = ss->ml[best_index];
// Reduce ml/score size
--size;
// Bring the last move to current index
ss->ml[best_index] = ss->ml[size];
ss->score[best_index] = ss->score[size];
return best_move;
}
/* Quiescence alpha-beta search a search leaf node to reduce the horizon effect. */
int quiesce(SearchController& sc, Position& pos, int alpha, int beta, SearchStack* ss)
{
if (ss->ply >= MAX_PLY) {
return evaluate(pos);
}
// Check time left
clock_t current_time = clock() * 1000 / CLOCKS_PER_SEC;
if (current_time >= sc.search_end_time) {
return 0;
}
int movecount, value;
value = evaluate(pos);
if (value >= beta)
return beta;
if (value > alpha)
alpha = value;
movecount = generate_captures(pos, ss->ml);
++ss->stats->node_count;
score_moves(pos, ss, movecount);
Move move;
while ((move = next_move(ss, movecount))) {
Position npos = pos;
make_move(npos, move);
if (is_checked(npos, THEM)) {
continue;
}
value = -quiesce(sc, npos, -beta, -alpha, ss + 1);
if (value >= beta) {
return beta;
}
if (value > alpha) {
alpha = value;
}
}
return alpha;
}
/* Alpha-Beta search a position to return a score. */
int search(SearchController& sc, Position& pos, int depth, int alpha, int beta, SearchStack* ss, PV& pv)
{
const bool in_check = is_checked(pos, US);
// Check extensions
if (in_check)
depth++;
if (depth <= 0) {
return quiesce(sc, pos, alpha, beta, ss);
}
if (ss->ply >= MAX_PLY) {
return evaluate(pos);
}
// Check time left
clock_t current_time = clock() * 1000 / CLOCKS_PER_SEC;
if (ss->ply && current_time >= sc.search_end_time) {
return 0;
}
// Update info
if (ss->stats->node_count%1048576 == 0) {
if (current_time > sc.search_start_time) {
printf("info nps %" PRIu64 "\n", 1000*(ss->stats->node_count)/(current_time - sc.search_start_time));
}
}
int movecount, value;
movecount = generate(pos, ss->ml);
++ss->stats->node_count;
score_moves(pos, ss, movecount);
int legal_moves = 0;
int best_value = -INF;
Move move;
PV child_pv;
while ((move = next_move(ss, movecount))) {
child_pv.clear();
Position npos = pos;
make_move(npos, move);
if (is_checked(npos, THEM)) {
continue;
}
++legal_moves;
value = -search(sc, npos, depth - 1, -beta, -alpha, ss + 1, child_pv);
if (value >= beta) {
#ifdef TESTING
++ss->stats->fail_highs;
if (legal_moves == 1)
++ss->stats->first_move_fail_highs;
#endif
return beta;
}
if (value > best_value) {
best_value = value;
child_pv.push_back(move);
pv = std::move(child_pv);
if (value > alpha) {
alpha = value;
}
}
}
if (!legal_moves) {
if (in_check)
return -INF + ss->ply;
else
return 0;
}
#ifdef TESTING
if (!ss->ply) {
printf("info string ordering = %lf\n", double(ss->stats->first_move_fail_highs) / ss->stats->fail_highs);
}
#endif
return alpha;
}
/* Reset the stats object to 0 so we can start recording */
void clear_stats(Stats& stats)
{
stats.node_count = 0;
#ifdef TESTING
stats.fail_highs = 0;
stats.first_move_fail_highs = 0;
#endif
}
/* Reset the search stack to default values */
void clear_ss(SearchStack* ss, int size)
{
for (std::uint8_t i = 0; i < size; ++i, ++ss) {
ss->ply = i;
}
}
/* Set the Stats pointer for all ply after 'stats' */
void set_stats(SearchStack* ss, Stats& stats)
{
SearchStack* end = ss - ss->ply + MAX_PLY;
for (; ss < end; ++ss) {
ss->stats = &stats;
}
}
/* Start searching a position and return the best move */
Move start_search(SearchController& sc)
{
Stats stats;
SearchStack ss[MAX_PLY];
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
clear_stats(stats);
clear_ss(ss, MAX_PLY);
set_stats(ss, stats);
/* Timing */
sc.search_start_time = 1000 * clock() / CLOCKS_PER_SEC;
if (sc.movetime) {
sc.search_end_time = sc.movetime/2;
} else if (sc.moves_per_session) {
sc.search_end_time = sc.our_clock/sc.moves_per_session + sc.increment;
} else {
sc.search_end_time = sc.our_clock/40 + sc.increment;
}
sc.search_end_time += sc.search_start_time;
char mstr[6];
Move best_move;
int best_score = -INF;
PV pv, depth_pv, child_pv;
/* Iterative deepening */
for (std::uint32_t depth = 1; depth < sc.max_depth; ++depth) {
int beta = INF;
int alpha = -INF;
int depth_best_score = search(sc, sc.pos, depth, alpha, beta, ss, depth_pv);
// Check time used
clock_t time_used = clock() * 1000 / CLOCKS_PER_SEC - sc.search_start_time;
// See if we ran out of time
if (depth > 1 && time_used >= sc.search_end_time - sc.search_start_time) {
break;
}
// Only update the best pv if we didn't run out of time
// It needs reversing due to the last in first out nature of push_back()
pv = depth_pv;
std::reverse(pv.begin(), pv.end());
best_score = depth_best_score;
// Update info
printf("info score cp %i depth %i nodes %" PRIu64 " time %lu pv ", best_score, depth, stats.node_count, time_used);
bool flipped = sc.pos.flipped;
for (Move move : pv) {
if (flipped) {
move = flip_move(move);
}
move_to_lan(mstr, move);
printf("%s ", mstr);
flipped ^= 1;
}
printf("\n");
}
if (pv.size() >= 1) {
best_move = pv[0];
if (sc.pos.flipped) {
best_move = flip_move(best_move);
}
move_to_lan(mstr, best_move);
printf("bestmove %s\n", mstr);
} else {
printf("bestmove 0000\n");
}
return (Move)0;
}
void search_thread(void* params)
{
SearchController *sc = (SearchController*)params;
start_search(*sc);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "atom/browser/notifications/platform_notification_service.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/notifications/notification.h"
#include "atom/browser/notifications/notification_delegate.h"
#include "atom/browser/notifications/notification_presenter.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/notification_event_dispatcher.h"
#include "content/public/browser/render_process_host.h"
#include "third_party/blink/public/common/notifications/notification_resources.h"
#include "third_party/blink/public/common/notifications/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace atom {
namespace {
void OnWebNotificationAllowed(base::WeakPtr<Notification> notification,
const SkBitmap& icon,
const blink::PlatformNotificationData& data,
bool audio_muted,
bool allowed) {
if (!notification)
return;
if (allowed) {
atom::NotificationOptions options;
options.title = data.title;
options.msg = data.body;
options.tag = data.tag;
options.icon_url = data.icon;
options.icon = icon;
options.silent = audio_muted ? true : data.silent;
options.has_reply = false;
notification->Show(options);
} else {
notification->Destroy();
}
}
class NotificationDelegateImpl final : public atom::NotificationDelegate {
public:
explicit NotificationDelegateImpl(const std::string& notification_id)
: notification_id_(notification_id) {}
void NotificationDestroyed() override { delete this; }
void NotificationClick() override {
content::NotificationEventDispatcher::GetInstance()
->DispatchNonPersistentClickEvent(notification_id_, base::DoNothing());
}
void NotificationClosed() override {
content::NotificationEventDispatcher::GetInstance()
->DispatchNonPersistentCloseEvent(notification_id_, base::DoNothing());
}
void NotificationDisplayed() override {
content::NotificationEventDispatcher::GetInstance()
->DispatchNonPersistentShowEvent(notification_id_);
}
private:
std::string notification_id_;
DISALLOW_COPY_AND_ASSIGN(NotificationDelegateImpl);
};
} // namespace
PlatformNotificationService::PlatformNotificationService(
AtomBrowserClient* browser_client)
: browser_client_(browser_client) {}
PlatformNotificationService::~PlatformNotificationService() {}
void PlatformNotificationService::DisplayNotification(
content::RenderProcessHost* render_process_host,
content::BrowserContext* browser_context,
const std::string& notification_id,
const GURL& origin,
const blink::PlatformNotificationData& notification_data,
const blink::NotificationResources& notification_resources) {
auto* presenter = browser_client_->GetNotificationPresenter();
if (!presenter)
return;
NotificationDelegateImpl* delegate =
new NotificationDelegateImpl(notification_id);
auto notification = presenter->CreateNotification(delegate, notification_id);
if (notification) {
browser_client_->WebNotificationAllowed(
render_process_host->GetID(),
base::Bind(&OnWebNotificationAllowed, notification,
notification_resources.notification_icon,
notification_data));
}
}
void PlatformNotificationService::DisplayPersistentNotification(
content::BrowserContext* browser_context,
const std::string& notification_id,
const GURL& service_worker_scope,
const GURL& origin,
const blink::PlatformNotificationData& notification_data,
const blink::NotificationResources& notification_resources) {}
void PlatformNotificationService::ClosePersistentNotification(
content::BrowserContext* browser_context,
const std::string& notification_id) {}
void PlatformNotificationService::CloseNotification(
content::BrowserContext* browser_context,
const std::string& notification_id) {
auto* presenter = browser_client_->GetNotificationPresenter();
if (!presenter)
return;
presenter->CloseNotificationWithId(notification_id);
}
void PlatformNotificationService::GetDisplayedNotifications(
content::BrowserContext* browser_context,
DisplayedNotificationsCallback callback) {}
int64_t PlatformNotificationService::ReadNextPersistentNotificationId(
content::BrowserContext* browser_context) {
// Electron doesn't support persistent notifications.
return 0;
}
void PlatformNotificationService::RecordNotificationUkmEvent(
content::BrowserContext* browser_context,
const content::NotificationDatabaseData& data) {}
void PlatformNotificationService::ScheduleTrigger(
BrowserContext* browser_context,
base::Time timestamp) {}
base::Time PlatformNotificationService::ReadNextTriggerTimestamp(
BrowserContext* browser_context) {
return base::Time::Max();
}
} // namespace atom
<commit_msg>chore: add missing content:: namespace for BrowserContext in PlatformNotificationService<commit_after>// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "atom/browser/notifications/platform_notification_service.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/notifications/notification.h"
#include "atom/browser/notifications/notification_delegate.h"
#include "atom/browser/notifications/notification_presenter.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/notification_event_dispatcher.h"
#include "content/public/browser/render_process_host.h"
#include "third_party/blink/public/common/notifications/notification_resources.h"
#include "third_party/blink/public/common/notifications/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace atom {
namespace {
void OnWebNotificationAllowed(base::WeakPtr<Notification> notification,
const SkBitmap& icon,
const blink::PlatformNotificationData& data,
bool audio_muted,
bool allowed) {
if (!notification)
return;
if (allowed) {
atom::NotificationOptions options;
options.title = data.title;
options.msg = data.body;
options.tag = data.tag;
options.icon_url = data.icon;
options.icon = icon;
options.silent = audio_muted ? true : data.silent;
options.has_reply = false;
notification->Show(options);
} else {
notification->Destroy();
}
}
class NotificationDelegateImpl final : public atom::NotificationDelegate {
public:
explicit NotificationDelegateImpl(const std::string& notification_id)
: notification_id_(notification_id) {}
void NotificationDestroyed() override { delete this; }
void NotificationClick() override {
content::NotificationEventDispatcher::GetInstance()
->DispatchNonPersistentClickEvent(notification_id_, base::DoNothing());
}
void NotificationClosed() override {
content::NotificationEventDispatcher::GetInstance()
->DispatchNonPersistentCloseEvent(notification_id_, base::DoNothing());
}
void NotificationDisplayed() override {
content::NotificationEventDispatcher::GetInstance()
->DispatchNonPersistentShowEvent(notification_id_);
}
private:
std::string notification_id_;
DISALLOW_COPY_AND_ASSIGN(NotificationDelegateImpl);
};
} // namespace
PlatformNotificationService::PlatformNotificationService(
AtomBrowserClient* browser_client)
: browser_client_(browser_client) {}
PlatformNotificationService::~PlatformNotificationService() {}
void PlatformNotificationService::DisplayNotification(
content::RenderProcessHost* render_process_host,
content::BrowserContext* browser_context,
const std::string& notification_id,
const GURL& origin,
const blink::PlatformNotificationData& notification_data,
const blink::NotificationResources& notification_resources) {
auto* presenter = browser_client_->GetNotificationPresenter();
if (!presenter)
return;
NotificationDelegateImpl* delegate =
new NotificationDelegateImpl(notification_id);
auto notification = presenter->CreateNotification(delegate, notification_id);
if (notification) {
browser_client_->WebNotificationAllowed(
render_process_host->GetID(),
base::Bind(&OnWebNotificationAllowed, notification,
notification_resources.notification_icon,
notification_data));
}
}
void PlatformNotificationService::DisplayPersistentNotification(
content::BrowserContext* browser_context,
const std::string& notification_id,
const GURL& service_worker_scope,
const GURL& origin,
const blink::PlatformNotificationData& notification_data,
const blink::NotificationResources& notification_resources) {}
void PlatformNotificationService::ClosePersistentNotification(
content::BrowserContext* browser_context,
const std::string& notification_id) {}
void PlatformNotificationService::CloseNotification(
content::BrowserContext* browser_context,
const std::string& notification_id) {
auto* presenter = browser_client_->GetNotificationPresenter();
if (!presenter)
return;
presenter->CloseNotificationWithId(notification_id);
}
void PlatformNotificationService::GetDisplayedNotifications(
content::BrowserContext* browser_context,
DisplayedNotificationsCallback callback) {}
int64_t PlatformNotificationService::ReadNextPersistentNotificationId(
content::BrowserContext* browser_context) {
// Electron doesn't support persistent notifications.
return 0;
}
void PlatformNotificationService::RecordNotificationUkmEvent(
content::BrowserContext* browser_context,
const content::NotificationDatabaseData& data) {}
void PlatformNotificationService::ScheduleTrigger(
content::BrowserContext* browser_context,
base::Time timestamp) {}
base::Time PlatformNotificationService::ReadNextTriggerTimestamp(
content::BrowserContext* browser_context) {
return base::Time::Max();
}
} // namespace atom
<|endoftext|>
|
<commit_before><commit_msg>Update visitor_test.cpp<commit_after><|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include <memory>
#include <vector>
#include "modules/common/log.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
namespace apollo {
namespace prediction {
using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::math::LineSegment2d;
using ::apollo::common::math::Polygon2d;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::JunctionInfo;
using ::apollo::planning::ADCTrajectory;
void ADCTrajectoryContainer::Insert(
const ::google::protobuf::Message& message) {
adc_lane_ids_.clear();
adc_lane_seq_.clear();
adc_junction_polygon_ = Polygon2d{};
adc_trajectory_.CopyFrom(dynamic_cast<const ADCTrajectory&>(message));
ADEBUG << "Received a planning message ["
<< adc_trajectory_.ShortDebugString() << "].";
// Find junction
if (IsProtected()) {
SetJunctionPolygon();
}
ADEBUG << "Generate a polygon [" << adc_junction_polygon_.DebugString()
<< "].";
// Find ADC lane sequence
SetLaneSequence();
ADEBUG << "Generate an ADC lane id sequence [" << ToString(adc_lane_seq_)
<< "].";
}
bool ADCTrajectoryContainer::IsPointInJunction(const PathPoint& point) const {
if (adc_junction_polygon_.num_points() < 3) {
return false;
}
bool in_polygon = adc_junction_polygon_.IsPointIn({point.x(), point.y()});
bool on_virtual_lane = false;
if (point.has_lane_id()) {
on_virtual_lane = PredictionMap::IsVirtualLane(point.lane_id());
}
if (!on_virtual_lane) {
on_virtual_lane = PredictionMap::OnVirtualLane({point.x(), point.y()},
FLAGS_virtual_lane_radius);
}
return in_polygon && on_virtual_lane;
}
bool ADCTrajectoryContainer::IsProtected() const {
return adc_trajectory_.has_right_of_way_status() &&
adc_trajectory_.right_of_way_status() == ADCTrajectory::PROTECTED;
}
void ADCTrajectoryContainer::SetJunctionPolygon() {
std::shared_ptr<const JunctionInfo> junction_info(nullptr);
for (int i = 0; i < adc_trajectory_.trajectory_point_size(); ++i) {
double s = adc_trajectory_.trajectory_point(i).path_point().s();
if (s > FLAGS_adc_trajectory_search_length) {
break;
}
if (junction_info != nullptr) {
break;
}
double x = adc_trajectory_.trajectory_point(i).path_point().x();
double y = adc_trajectory_.trajectory_point(i).path_point().y();
std::vector<std::shared_ptr<const JunctionInfo>> junctions =
PredictionMap::GetJunctions({x, y}, FLAGS_junction_search_radius);
if (!junctions.empty() && junctions.front() != nullptr) {
junction_info = junctions.front();
}
}
if (junction_info != nullptr && junction_info->junction().has_polygon()) {
std::vector<Vec2d> vertices;
for (const auto& point : junction_info->junction().polygon().point()) {
vertices.emplace_back(point.x(), point.y());
}
if (vertices.size() >= 3) {
adc_junction_polygon_ = Polygon2d{vertices};
}
}
}
void ADCTrajectoryContainer::SetLaneSequence() {
for (const auto& lane : adc_trajectory_.lane_id()) {
if (!lane.id().empty()) {
adc_lane_seq_.emplace_back(lane.id());
}
}
adc_lane_ids_.clear();
adc_lane_ids_.insert(adc_lane_seq_.begin(), adc_lane_seq_.end());
}
std::string ADCTrajectoryContainer::ToString(
const std::unordered_set<std::string>& lane_ids) {
std::string str_lane_sequence = "";
auto it = lane_ids.begin();
if (it != lane_ids.end()) {
str_lane_sequence += (*it);
++it;
}
for (; it != lane_ids.end(); ++it) {
str_lane_sequence += ("->" + *it);
}
return str_lane_sequence;
}
std::string ADCTrajectoryContainer::ToString(
const std::vector<std::string>& lane_ids) {
std::string str_lane_sequence = "";
auto it = lane_ids.begin();
if (it != lane_ids.end()) {
str_lane_sequence += (*it);
++it;
}
for (; it != lane_ids.end(); ++it) {
str_lane_sequence += ("->" + *it);
}
return str_lane_sequence;
}
bool ADCTrajectoryContainer::HasOverlap(const LaneSequence& lane_sequence) {
for (const auto& lane_segment : lane_sequence.lane_segment()) {
std::string lane_id = lane_segment.lane_id();
if (adc_lane_ids_.find(lane_id) != adc_lane_ids_.end()) {
return true;
}
}
return false;
}
void ADCTrajectoryContainer::SetPosition(const Vec2d& position) {
for (auto it = adc_lane_seq_.begin(); it != adc_lane_seq_.end(); ++it) {
auto lane_info = PredictionMap::LaneById(*it);
if (lane_info != nullptr && lane_info->IsOnLane(position)) {
adc_lane_ids_.clear();
adc_lane_ids_.insert(it, adc_lane_seq_.end());
break;
}
}
ADEBUG << "Generate an ADC lane ids [" << ToString(adc_lane_ids_) << "].";
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: optimized adc lane sequence generation<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include <memory>
#include <vector>
#include "modules/common/log.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
namespace apollo {
namespace prediction {
using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::math::LineSegment2d;
using ::apollo::common::math::Polygon2d;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::JunctionInfo;
using ::apollo::planning::ADCTrajectory;
void ADCTrajectoryContainer::Insert(
const ::google::protobuf::Message& message) {
adc_lane_ids_.clear();
adc_lane_seq_.clear();
adc_junction_polygon_ = Polygon2d{};
adc_trajectory_.CopyFrom(dynamic_cast<const ADCTrajectory&>(message));
ADEBUG << "Received a planning message ["
<< adc_trajectory_.ShortDebugString() << "].";
// Find junction
if (IsProtected()) {
SetJunctionPolygon();
}
ADEBUG << "Generate a polygon [" << adc_junction_polygon_.DebugString()
<< "].";
// Find ADC lane sequence
SetLaneSequence();
ADEBUG << "Generate an ADC lane id sequence [" << ToString(adc_lane_seq_)
<< "].";
}
bool ADCTrajectoryContainer::IsPointInJunction(const PathPoint& point) const {
if (adc_junction_polygon_.num_points() < 3) {
return false;
}
bool in_polygon = adc_junction_polygon_.IsPointIn({point.x(), point.y()});
bool on_virtual_lane = false;
if (point.has_lane_id()) {
on_virtual_lane = PredictionMap::IsVirtualLane(point.lane_id());
}
if (!on_virtual_lane) {
on_virtual_lane = PredictionMap::OnVirtualLane({point.x(), point.y()},
FLAGS_virtual_lane_radius);
}
return in_polygon && on_virtual_lane;
}
bool ADCTrajectoryContainer::IsProtected() const {
return adc_trajectory_.has_right_of_way_status() &&
adc_trajectory_.right_of_way_status() == ADCTrajectory::PROTECTED;
}
void ADCTrajectoryContainer::SetJunctionPolygon() {
std::shared_ptr<const JunctionInfo> junction_info(nullptr);
for (int i = 0; i < adc_trajectory_.trajectory_point_size(); ++i) {
double s = adc_trajectory_.trajectory_point(i).path_point().s();
if (s > FLAGS_adc_trajectory_search_length) {
break;
}
if (junction_info != nullptr) {
break;
}
double x = adc_trajectory_.trajectory_point(i).path_point().x();
double y = adc_trajectory_.trajectory_point(i).path_point().y();
std::vector<std::shared_ptr<const JunctionInfo>> junctions =
PredictionMap::GetJunctions({x, y}, FLAGS_junction_search_radius);
if (!junctions.empty() && junctions.front() != nullptr) {
junction_info = junctions.front();
}
}
if (junction_info != nullptr && junction_info->junction().has_polygon()) {
std::vector<Vec2d> vertices;
for (const auto& point : junction_info->junction().polygon().point()) {
vertices.emplace_back(point.x(), point.y());
}
if (vertices.size() >= 3) {
adc_junction_polygon_ = Polygon2d{vertices};
}
}
}
void ADCTrajectoryContainer::SetLaneSequence() {
for (const auto& lane : adc_trajectory_.lane_id()) {
if (!lane.id().empty()) {
if (adc_lane_seq_.empty() || lane.id() != adc_lane_seq_.back()) {
adc_lane_seq_.emplace_back(lane.id());
}
}
}
adc_lane_ids_.clear();
adc_lane_ids_.insert(adc_lane_seq_.begin(), adc_lane_seq_.end());
}
std::string ADCTrajectoryContainer::ToString(
const std::unordered_set<std::string>& lane_ids) {
std::string str_lane_sequence = "";
auto it = lane_ids.begin();
if (it != lane_ids.end()) {
str_lane_sequence += (*it);
++it;
}
for (; it != lane_ids.end(); ++it) {
str_lane_sequence += ("->" + *it);
}
return str_lane_sequence;
}
std::string ADCTrajectoryContainer::ToString(
const std::vector<std::string>& lane_ids) {
std::string str_lane_sequence = "";
auto it = lane_ids.begin();
if (it != lane_ids.end()) {
str_lane_sequence += (*it);
++it;
}
for (; it != lane_ids.end(); ++it) {
str_lane_sequence += ("->" + *it);
}
return str_lane_sequence;
}
bool ADCTrajectoryContainer::HasOverlap(const LaneSequence& lane_sequence) {
for (const auto& lane_segment : lane_sequence.lane_segment()) {
std::string lane_id = lane_segment.lane_id();
if (adc_lane_ids_.find(lane_id) != adc_lane_ids_.end()) {
return true;
}
}
return false;
}
void ADCTrajectoryContainer::SetPosition(const Vec2d& position) {
for (auto it = adc_lane_seq_.begin(); it != adc_lane_seq_.end(); ++it) {
auto lane_info = PredictionMap::LaneById(*it);
if (lane_info != nullptr && lane_info->IsOnLane(position)) {
adc_lane_ids_.clear();
adc_lane_ids_.insert(it, adc_lane_seq_.end());
break;
}
}
ADEBUG << "Generate an ADC lane ids [" << ToString(adc_lane_ids_) << "].";
}
} // namespace prediction
} // namespace apollo
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2010 - 2011, Johannes Schlatow.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#define L10N // Localization complete.
#include <Context.h>
#include <text.h>
#include <i18n.h>
#include <Uri.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
Uri::Uri ()
{
_parsed = false;
}
////////////////////////////////////////////////////////////////////////////////
Uri::Uri (const Uri& other)
{
if (this != &other)
{
_data = other._data;
_host = other._host;
_path = other._path;
_user = other._user;
_port = other._port;
_protocol = other._protocol;
_parsed = other._parsed;
}
}
////////////////////////////////////////////////////////////////////////////////
Uri::Uri (const std::string& in, const std::string& configPrefix)
{
_data = in;
_parsed = false;
if (configPrefix != "")
expand(configPrefix);
}
////////////////////////////////////////////////////////////////////////////////
Uri::~Uri ()
{
}
////////////////////////////////////////////////////////////////////////////////
Uri& Uri::operator= (const Uri& other)
{
if (this != &other)
{
this->_data = other._data;
this->_host = other._host;
this->_path = other._path;
this->_user = other._user;
this->_port = other._port;
this->_protocol = other._protocol;
this->_parsed = other._parsed;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
Uri::operator std::string () const
{
return _data;
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::name () const
{
if (_path.length ())
{
std::string::size_type slash = _path.rfind ('/');
if (slash != std::string::npos)
return _path.substr (slash + 1, std::string::npos);
}
return _path;
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::parent () const
{
if (_path.length ())
{
std::string::size_type slash = _path.rfind ('/');
if (slash != std::string::npos)
return _path.substr (0, slash+1);
}
return "";
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::extension () const
{
if (_path.length ())
{
std::string::size_type dot = _path.rfind ('.');
if (dot != std::string::npos)
return _path.substr (dot + 1, std::string::npos);
}
return "";
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::is_directory () const
{
if (is_local ()) {
return Path (this->_data).is_directory ();
} else
return (_path == ".")
|| (_path == "")
|| (_path[_path.length()-1] == '/');
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::is_local () const
{
if (_parsed)
return (_protocol == "");
else
return ( (_data.find("://") == std::string::npos)
&& (_data.find(":") == std::string::npos) );
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::append (const std::string& path)
{
if (is_directory ())
{
this->_path += path;
return true;
}
else
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::expand (const std::string& configPrefix )
{
std::string tmp;
if (_data.length ())
{
// try to replace argument with uri from config
tmp = context.config.get (configPrefix + "." + _data + ".uri");
}
else
{
// get default target from config
tmp = context.config.get (configPrefix + ".default.uri");
}
if (tmp != "")
{
_data = tmp;
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::ToString ()
{
if (!_parsed)
return std::string ();
if (is_local ())
return _data;
std::string result;
result = _protocol + "://";
if (_user.length () > 0) {
// obscure password in _user
std::string::size_type pos = _user.find (":");
if (pos != std::string::npos) {
std::string::size_type len = _user.length () - pos - 1;
result += _user.replace (pos+1, len, len, '*') + "@";
}
else
result += _user + "@";
}
result += _host;
if (_port.length () > 0)
result += + ":" + _port;
result += "/" + _path;
return result;
}
////////////////////////////////////////////////////////////////////////////////
void Uri::parse ()
{
if (_parsed)
return;
if (is_local ())
{
_path = _data;
_parsed = true;
return;
}
std::string::size_type pos;
std::string _data = this->_data;
std::string pathDelimiter = "/";
_user = "";
_port = "";
// skip ^.*://
if ((pos = _data.find ("://")) != std::string::npos)
{
_protocol = _data.substr(0, pos);
_data = _data.substr (pos+3);
// standard syntax: protocol://[user@]host.xz[:port]/path/to/undo.data
pathDelimiter = "/";
}
else
{
_protocol = "ssh";
// scp-like syntax: [user@]host.xz:path/to/undo.data
pathDelimiter = ":";
}
// user delimited by single quotes?
if ( _data[0] == '\''
&& (pos = _data.find("'", 1)) != std::string::npos )
{
if (_data[pos+1] == '@')
{
// end of user name
_user = _data.substr (1, pos-1);
_data = _data.substr (pos+2);
}
else
{
throw std::string (format (STRING_URI_QUOTES, _data));
}
}
else
{
// find user name
if ((pos = _data.find ("@")) != std::string::npos)
{
_user = _data.substr (0, pos);
_data = _data.substr (pos+1);
}
}
// get host, port and path
if ((pos = _data.find (pathDelimiter)) != std::string::npos)
{
_host = _data.substr (0, pos);
_path = _data.substr (pos+1);
}
else
{
throw std::string (format (STRING_URI_BAD_FORMAT, _data));
}
// path is absolute for ssh:// syntax
if ( (_protocol == "ssh") && (pathDelimiter == "/") )
{
_path = "/" + _path;
}
// port specified?
// remark: this find() will never be != npos for scp-like syntax
// because we found pathDelimiter, which is ":", before
if ((pos = _host.find (":")) != std::string::npos)
{
_port = _host.substr (pos+1);
_host = _host.substr (0,pos);
}
_parsed = true;
}
////////////////////////////////////////////////////////////////////////////////
// vim: et ts=2 sw=2
<commit_msg>Bug<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2010 - 2011, Johannes Schlatow.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#define L10N // Localization complete.
#include <Context.h>
#include <text.h>
#include <i18n.h>
#include <Uri.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
Uri::Uri ()
{
_parsed = false;
}
////////////////////////////////////////////////////////////////////////////////
Uri::Uri (const Uri& other)
{
if (this != &other)
{
_data = other._data;
_host = other._host;
_path = other._path;
_user = other._user;
_port = other._port;
_protocol = other._protocol;
_parsed = other._parsed;
}
}
////////////////////////////////////////////////////////////////////////////////
Uri::Uri (const std::string& in, const std::string& configPrefix)
{
_data = in;
_parsed = false;
if (configPrefix != "")
expand(configPrefix);
}
////////////////////////////////////////////////////////////////////////////////
Uri::~Uri ()
{
}
////////////////////////////////////////////////////////////////////////////////
Uri& Uri::operator= (const Uri& other)
{
if (this != &other)
{
this->_data = other._data;
this->_host = other._host;
this->_path = other._path;
this->_user = other._user;
this->_port = other._port;
this->_protocol = other._protocol;
this->_parsed = other._parsed;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
Uri::operator std::string () const
{
return _data;
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::name () const
{
if (_path.length ())
{
std::string::size_type slash = _path.rfind ('/');
if (slash != std::string::npos)
return _path.substr (slash + 1, std::string::npos);
}
return _path;
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::parent () const
{
if (_path.length ())
{
std::string::size_type slash = _path.rfind ('/');
if (slash != std::string::npos)
return _path.substr (0, slash+1);
}
return "";
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::extension () const
{
if (_path.length ())
{
std::string::size_type dot = _path.rfind ('.');
if (dot != std::string::npos)
return _path.substr (dot + 1, std::string::npos);
}
return "";
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::is_directory () const
{
if (is_local ()) {
return Path (this->_data).is_directory ();
} else
return (_path == ".")
|| (_path == "")
|| (_path[_path.length()-1] == '/');
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::is_local () const
{
if (_parsed)
return (_protocol == "");
else
return ( (_data.find("://") == std::string::npos)
&& (_data.find(":") == std::string::npos) );
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::append (const std::string& path)
{
if (is_directory ())
{
this->_path += path;
return true;
}
else
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Uri::expand (const std::string& configPrefix )
{
std::string tmp;
if (_data.length ())
{
// try to replace argument with uri from config
tmp = context.config.get (configPrefix + "." + _data + ".uri");
}
else
{
// get default target from config
tmp = context.config.get (configPrefix + ".default.uri");
}
if (tmp != "")
{
_data = tmp;
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
std::string Uri::ToString ()
{
if (!_parsed)
return std::string ();
if (is_local ())
return _data;
std::string result;
result = _protocol + "://";
if (_user.length () > 0) {
// obscure password in _user
std::string::size_type pos = _user.find (":");
if (pos != std::string::npos) {
std::string::size_type len = _user.length () - pos - 1;
result += _user.replace (pos+1, len, len, '*') + "@";
}
else
result += _user + "@";
}
result += _host;
if (_port.length () > 0)
result += + ":" + _port;
result += "/" + _path;
return result;
}
////////////////////////////////////////////////////////////////////////////////
void Uri::parse ()
{
if (_parsed)
return;
if (is_local ())
{
_path = _data;
_parsed = true;
return;
}
std::string::size_type pos;
std::string _data = this->_data;
std::string pathDelimiter = "/";
_user = "";
_port = "";
// skip ^.*://
if ((pos = _data.find ("://")) != std::string::npos)
{
_protocol = _data.substr(0, pos);
_data = _data.substr (pos+3);
// standard syntax: protocol://[user@]host.xz[:port]/path/to/undo.data
pathDelimiter = "/";
}
else
{
_protocol = "ssh";
// scp-like syntax: [user@]host.xz:path/to/undo.data
pathDelimiter = ":";
}
// user delimited by single quotes?
if ( _data[0] == '\''
&& (pos = _data.find("'", 1)) != std::string::npos )
{
if (_data[pos+1] == '@')
{
// end of user name
_user = _data.substr (1, pos-1);
_data = _data.substr (pos+2);
}
else
{
throw std::string (format (STRING_URI_QUOTES, _data));
}
}
else
{
// find user name
if ((pos = _data.find ("@")) != std::string::npos)
{
_user = _data.substr (0, pos);
_data = _data.substr (pos+1);
}
}
// get host, port and path
if ((pos = _data.find (pathDelimiter)) != std::string::npos)
{
_host = _data.substr (0, pos);
_path = _data.substr (pos+1);
}
else
{
throw std::string (format (STRING_URI_BAD_FORMAT, _data));
}
// path is absolute for ssh:// syntax
if ( (_protocol == "ssh") && (pathDelimiter == "/") && (_path[0] != '~') )
{
_path = "/" + _path;
}
// port specified?
// remark: this find() will never be != npos for scp-like syntax
// because we found pathDelimiter, which is ":", before
if ((pos = _host.find (":")) != std::string::npos)
{
_port = _host.substr (pos+1);
_host = _host.substr (0,pos);
}
_parsed = true;
}
////////////////////////////////////////////////////////////////////////////////
// vim: et ts=2 sw=2
<|endoftext|>
|
<commit_before>/********************************************************************
* Author: Carlos Moreno
* Created: 2015-06-04
*
* Description:
*
* This is the file used for question 2 of assignment 1. You
* may also use it as sample / starting point to create the
* server for question 1. In particular, you are allowed to
* submit your code containing verbatim fragments from this
* file.
*
* Copytight and permissions:
* This file is for the exclusive purpose of our ECE-458
* assignment 2, and you are not allowed to use it for any
* other purpose.
*
********************************************************************/
#include <iostream>
#include <sstream>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cerrno>
#include<cstdlib>
using namespace std;
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <wait.h>
#include <unistd.h>
#include "crypto.h"
class connection_closed {};
class socket_error {};
void listen_connections (int port);
void process_connection (int client_socket);
string read_packet (int client_socket);
int main (int na, char * arg[])
{
listen_connections (10458);
return 0;
}
void listen_connections (int port)
{
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
socklen_t client_len;
server_socket = socket (AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons (port);
bind (server_socket, (struct sockaddr *) &server_address, sizeof(server_address));
listen (server_socket, 5);
while (true)
{
client_len = sizeof(client_address);
client_socket = accept (server_socket,
(struct sockaddr *) &client_address,
&client_len);
pid_t pid = fork();
if (pid == 0) // if we're the child process
{
close (server_socket); // only the parent listens for new connections
if (fork() == 0) // detach grandchild process -- parent returns immediately
{
usleep (10000); // Allow the parent to finish, so that the grandparent
// can continue listening for connections ASAP
process_connection (client_socket);
}
return;
}
else if (pid > 0) // parent process; close the socket and continue
{
int status = 0;
waitpid (pid, &status, 0);
close (client_socket);
}
else
{
cerr << "ERROR on fork()" << endl;
return;
}
}
}
void process_connection (int client_socket)
{
try
{
map<string,string> passwords;
passwords["user1"] = "password1";
passwords["user2"] = "password2";
// For the real server, this will be populated with the
// usernames and passwords from a text file.
const string & username = read_packet (client_socket);
const string & db_password = passwords[username];
cout<<"hi there" <<endl;
const string & R = cgipp::sha256("start");
char str[17];
static const char alphanum[] = "0123456789abcdefghi"
"pqrstuvwxyz";
for(int i = 0; i < 17; ++i){
str[i] = alphanum[rand()%(sizeof(alphanum)-1)];
}
str[17] = 0;
cout<< str<<endl;
send (client_socket, "ok\n", 4, MSG_NOSIGNAL);
while (true)
{
const string & password = read_packet (client_socket);
if (password == db_password)
{
send (client_socket, "ok\n", 4, MSG_NOSIGNAL);
}
else
{
send (client_socket, "failed\n", 8, MSG_NOSIGNAL);
}
}
close (client_socket);
}
catch (connection_closed)
{
}
catch (socket_error)
{
cerr << "Socket error" << endl;
}
}
string read_packet (int client_socket)
{
string msg;
const int size = 8192;
char buffer[size];
while (true)
{
int bytes_read = recv (client_socket, buffer, sizeof(buffer) - 2, 0);
// Though extremely unlikely in our setting --- connection from
// localhost, transmitting a small packet at a time --- this code
// takes care of fragmentation (one packet arriving could have
// just one fragment of the transmitted message)
if (bytes_read > 0)
{
buffer[bytes_read] = '\0';
buffer[bytes_read + 1] = '\0';
const char * packet = buffer;
while (*packet != '\0')
{
msg += packet;
packet += strlen(packet) + 1;
if (msg.length() > 1 && msg[msg.length() - 1] == '\n')
{
istringstream buf(msg);
string msg_token;
buf >> msg_token;
return msg_token;
}
}
}
else if (bytes_read == 0)
{
close (client_socket);
throw connection_closed();
}
else
{
cerr << "Error " << errno << endl;
throw socket_error();
}
}
throw connection_closed();
}
<commit_msg>read from urandom and convert to hex<commit_after>/********************************************************************
* Author: Carlos Moreno
* Created: 2015-06-04
*
* Description:
*
* This is the file used for question 2 of assignment 1. You
* may also use it as sample / starting point to create the
* server for question 1. In particular, you are allowed to
* submit your code containing verbatim fragments from this
* file.
*
* Copytight and permissions:
* This file is for the exclusive purpose of our ECE-458
* assignment 2, and you are not allowed to use it for any
* other purpose.
*
********************************************************************/
#include <iostream>
#include <sstream>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cerrno>
#include<cstdlib>
#include <fstream>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <wait.h>
#include <unistd.h>
#include "crypto.h"
class connection_closed {};
class socket_error {};
void listen_connections (int port);
void process_connection (int client_socket);
string read_packet (int client_socket);
int main (int na, char * arg[])
{
listen_connections (10458);
return 0;
}
void listen_connections (int port)
{
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
socklen_t client_len;
server_socket = socket (AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons (port);
bind (server_socket, (struct sockaddr *) &server_address, sizeof(server_address));
listen (server_socket, 5);
while (true)
{
client_len = sizeof(client_address);
client_socket = accept (server_socket,
(struct sockaddr *) &client_address,
&client_len);
pid_t pid = fork();
if (pid == 0) // if we're the child process
{
close (server_socket); // only the parent listens for new connections
if (fork() == 0) // detach grandchild process -- parent returns immediately
{
usleep (10000); // Allow the parent to finish, so that the grandparent
// can continue listening for connections ASAP
process_connection (client_socket);
}
return;
}
else if (pid > 0) // parent process; close the socket and continue
{
int status = 0;
waitpid (pid, &status, 0);
close (client_socket);
}
else
{
cerr << "ERROR on fork()" << endl;
return;
}
}
}
void process_connection (int client_socket)
{
try
{
map<string,string> passwords;
passwords["user1"] = "password1";
passwords["user2"] = "password2";
// For the real server, this will be populated with the
// usernames and passwords from a text file.
const string & username = read_packet (client_socket);
const string & db_password = passwords[username];
const string & R = cgipp::sha256("start");
cout<<R <<endl;
char str[17];
static const char alphanum[] = "0123456789abcdef";
/*
for(int i = 0; i < 17; ++i){
str[i] = alphanum[rand()%(sizeof(alphanum)-1)];
}
*/
FILE *fin;
if ((fin = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "%s: unable to open file\n", "/dev/urandom");
return;
}
int len = 16;
unsigned char buffer[len];
char hexbuf[len*2+1];
if(fread(buffer, 1, sizeof(buffer), fin) == sizeof(buffer)){
hexbuf[len*2+1] = 0;
for (int i = 0; i < sizeof(buffer); i++)
{
sprintf(&hexbuf[2 * i], "%02x", buffer[i]);
}
}
fclose(fin);
cout<<"hex: " <<hexbuf<<endl;
send (client_socket, "ok\n", 4, MSG_NOSIGNAL);
while (true)
{
const string & password = read_packet (client_socket);
if (password == db_password)
{
send (client_socket, "ok\n", 4, MSG_NOSIGNAL);
}
else
{
send (client_socket, "failed\n", 8, MSG_NOSIGNAL);
}
}
close (client_socket);
}
catch (connection_closed)
{
}
catch (socket_error)
{
cerr << "Socket error" << endl;
}
}
string read_packet (int client_socket)
{
string msg;
const int size = 8192;
char buffer[size];
while (true)
{
int bytes_read = recv (client_socket, buffer, sizeof(buffer) - 2, 0);
// Though extremely unlikely in our setting --- connection from
// localhost, transmitting a small packet at a time --- this code
// takes care of fragmentation (one packet arriving could have
// just one fragment of the transmitted message)
if (bytes_read > 0)
{
buffer[bytes_read] = '\0';
buffer[bytes_read + 1] = '\0';
const char * packet = buffer;
while (*packet != '\0')
{
msg += packet;
packet += strlen(packet) + 1;
if (msg.length() > 1 && msg[msg.length() - 1] == '\n')
{
istringstream buf(msg);
string msg_token;
buf >> msg_token;
return msg_token;
}
}
}
else if (bytes_read == 0)
{
close (client_socket);
throw connection_closed();
}
else
{
cerr << "Error " << errno << endl;
throw socket_error();
}
}
throw connection_closed();
}
<|endoftext|>
|
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 129
#define ACK 0
#define NAK 1
#define BUFSIZE 122
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(window[i-base].getDataBuffer().length() < BUFSIZE) {
break;
}
}
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
base = 0;
while(base * BUFSIZE < length) {
loadWindow();
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
for(int x = 0; x < WIN_SIZE; x++) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
memset(b, 0, BUFSIZE);
}
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== PACKET CREATION TESTING" << endl;
cout << "index: " << index << endl;
cout << "BUFSIZE: " << BUFSIZE << endl;
cout << "file index (index * BUFSIZE): " << index * BUFSIZE << endl;
cout << "file length: " << length << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<commit_msg>Fix the previous commit<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 129
#define ACK 0
#define NAK 1
#define BUFSIZE 122
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE) {
break;
}
}
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
base = 0;
while(base * BUFSIZE < length) {
loadWindow();
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
for(int x = 0; x < WIN_SIZE; x++) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
memset(b, 0, BUFSIZE);
}
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== PACKET CREATION TESTING" << endl;
cout << "index: " << index << endl;
cout << "BUFSIZE: " << BUFSIZE << endl;
cout << "file index (index * BUFSIZE): " << index * BUFSIZE << endl;
cout << "file length: " << length << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperTopic.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <functional>
#include <boost/test/unit_test.hpp>
#include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
BOOST_AUTO_TEST_SUITE(whisper)
BOOST_AUTO_TEST_CASE(topic)
{
cnote << "Testing Whisper...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
Host host1("Test", NetworkPreferences("127.0.0.1", 30303, false));
host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost());
host1.start();
bool host1Ready = false;
unsigned result = 0;
std::thread listener([&]()
{
setThreadName("other");
/// Only interested in odd packets
auto w = whost1->installWatch(BuildTopicMask("odd"));
host1Ready = true;
set<unsigned> received;
for (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout)
{
for (auto i: whost1->checkWatch(w))
{
Message msg = whost1->envelope(i).open(whost1->fullTopic(w));
last = RLP(msg.payload()).toInt<unsigned>();
if (received.count(last))
continue;
received.insert(last);
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
result += last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
Host host2("Test", NetworkPreferences("127.0.0.1", 30300, false));
host1.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost());
host2.start();
while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(5));
host2.addNode(host1.id(), bi::address::from_string("127.0.0.1"), 30303, 30303);
// wait for nodes to connect
this_thread::sleep_for(chrono::milliseconds(1000));
while (!host1Ready)
this_thread::sleep_for(chrono::milliseconds(10));
KeyPair us = KeyPair::create();
for (int i = 0; i < 10; ++i)
{
whost2->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
this_thread::sleep_for(chrono::milliseconds(250));
}
listener.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);
}
BOOST_AUTO_TEST_CASE(forwarding)
{
cnote << "Testing Whisper forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
// Host must be configured not to share peers.
Host host1("Listner", NetworkPreferences("127.0.0.1", 30303, false));
host1.setIdealPeerCount(0);
auto whost1 = host1.registerCapability(new WhisperHost());
host1.start();
while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
unsigned result = 0;
bool done = false;
bool startedListener = false;
std::thread listener([&]()
{
setThreadName("listener");
startedListener = true;
/// Only interested in odd packets
auto w = whost1->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: whost1->checkWatch(w))
{
Message msg = whost1->envelope(i).open(whost1->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
// Host must be configured not to share peers.
Host host2("Forwarder", NetworkPreferences("127.0.0.1", 30305, false));
host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost());
host2.start();
while (!host2.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
Public fwderid;
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
while (!startedListener)
this_thread::sleep_for(chrono::milliseconds(50));
this_thread::sleep_for(chrono::milliseconds(500));
host2.addNode(host1.id(), bi::address::from_string("127.0.0.1"), 30303, 30303);
startedForwarder = true;
/// Only interested in odd packets
auto w = whost2->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: whost2->checkWatch(w))
{
Message msg = whost2->envelope(i).open(whost2->fullTopic(w));
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(50));
Host ph("Sender", NetworkPreferences("127.0.0.1", 30300, false));
ph.setIdealPeerCount(1);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
ph.start();
ph.addNode(host2.id(), bi::address::from_string("127.0.0.1"), 30305, 30305);
while (!ph.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(10));
KeyPair us = KeyPair::create();
wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
listener.join();
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_CASE(asyncforwarding)
{
cnote << "Testing Whisper async forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 2;
unsigned result = 0;
bool done = false;
// Host must be configured not to share peers.
Host host1("Forwarder", NetworkPreferences("127.0.0.1", 30305, false));
host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost());
host1.start();
while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
this_thread::sleep_for(chrono::milliseconds(500));
// ph.addNode("127.0.0.1", 30303, 30303);
startedForwarder = true;
/// Only interested in odd packets
auto w = whost1->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: whost1->checkWatch(w))
{
Message msg = whost1->envelope(i).open(whost1->fullTopic(w));
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(2));
{
Host host2("Sender", NetworkPreferences("127.0.0.1", 30300, false));
host2.setIdealPeerCount(1);
shared_ptr<WhisperHost> whost2 = host2.registerCapability(new WhisperHost());
host2.start();
while (!host2.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
host2.addNode(host1.id(), bi::address::from_string("127.0.0.1"), 30305, 30305);
while (!host2.peerCount())
this_thread::sleep_for(chrono::milliseconds(5));
KeyPair us = KeyPair::create();
whost2->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
}
{
Host ph("Listener", NetworkPreferences("127.0.0.1", 30300, false));
ph.setIdealPeerCount(1);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
ph.start();
while (!ph.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
ph.addNode(host1.id(), bi::address::from_string("127.0.0.1"), 30305, 30305);
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
}
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>update whisper test to use fixture for new network code, to allow private addresses and encapsulate host/port information in NodeIPEndpoint.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperTopic.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <functional>
#include <boost/test/unit_test.hpp>
#include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
struct P2PFixture
{
P2PFixture() { dev::p2p::NodeIPEndpoint::test_allowLocal = true; }
~P2PFixture() { dev::p2p::NodeIPEndpoint::test_allowLocal = false; }
};
BOOST_FIXTURE_TEST_SUITE(whisper, P2PFixture)
BOOST_AUTO_TEST_CASE(topic)
{
cnote << "Testing Whisper...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
Host host1("Test", NetworkPreferences("127.0.0.1", 30303, false));
host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost());
host1.start();
bool host1Ready = false;
unsigned result = 0;
std::thread listener([&]()
{
setThreadName("other");
/// Only interested in odd packets
auto w = whost1->installWatch(BuildTopicMask("odd"));
host1Ready = true;
set<unsigned> received;
for (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout)
{
for (auto i: whost1->checkWatch(w))
{
Message msg = whost1->envelope(i).open(whost1->fullTopic(w));
last = RLP(msg.payload()).toInt<unsigned>();
if (received.count(last))
continue;
received.insert(last);
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
result += last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
Host host2("Test", NetworkPreferences("127.0.0.1", 30300, false));
host1.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost());
host2.start();
while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(5));
host2.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), 30303, 30303));
// wait for nodes to connect
this_thread::sleep_for(chrono::milliseconds(1000));
while (!host1Ready)
this_thread::sleep_for(chrono::milliseconds(10));
KeyPair us = KeyPair::create();
for (int i = 0; i < 10; ++i)
{
whost2->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
this_thread::sleep_for(chrono::milliseconds(250));
}
listener.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);
}
BOOST_AUTO_TEST_CASE(forwarding)
{
cnote << "Testing Whisper forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0;
// Host must be configured not to share peers.
Host host1("Listner", NetworkPreferences("127.0.0.1", 30303, false));
host1.setIdealPeerCount(0);
auto whost1 = host1.registerCapability(new WhisperHost());
host1.start();
while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
unsigned result = 0;
bool done = false;
bool startedListener = false;
std::thread listener([&]()
{
setThreadName("listener");
startedListener = true;
/// Only interested in odd packets
auto w = whost1->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: whost1->checkWatch(w))
{
Message msg = whost1->envelope(i).open(whost1->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
// Host must be configured not to share peers.
Host host2("Forwarder", NetworkPreferences("127.0.0.1", 30305, false));
host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost());
host2.start();
while (!host2.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
Public fwderid;
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
while (!startedListener)
this_thread::sleep_for(chrono::milliseconds(50));
this_thread::sleep_for(chrono::milliseconds(500));
host2.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), 30303, 30303));
startedForwarder = true;
/// Only interested in odd packets
auto w = whost2->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: whost2->checkWatch(w))
{
Message msg = whost2->envelope(i).open(whost2->fullTopic(w));
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(50));
Host ph("Sender", NetworkPreferences("127.0.0.1", 30300, false));
ph.setIdealPeerCount(1);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
ph.start();
ph.addNode(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), 30305, 30305));
while (!ph.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(10));
KeyPair us = KeyPair::create();
wh->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
listener.join();
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_CASE(asyncforwarding)
{
cnote << "Testing Whisper async forwarding...";
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 2;
unsigned result = 0;
bool done = false;
// Host must be configured not to share peers.
Host host1("Forwarder", NetworkPreferences("127.0.0.1", 30305, false));
host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost());
host1.start();
while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
bool startedForwarder = false;
std::thread forwarder([&]()
{
setThreadName("forwarder");
this_thread::sleep_for(chrono::milliseconds(500));
startedForwarder = true;
/// Only interested in odd packets
auto w = whost1->installWatch(BuildTopicMask("test"));
while (!done)
{
for (auto i: whost1->checkWatch(w))
{
Message msg = whost1->envelope(i).open(whost1->fullTopic(w));
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
}
this_thread::sleep_for(chrono::milliseconds(50));
}
});
while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(2));
{
Host host2("Sender", NetworkPreferences("127.0.0.1", 30300, false));
host2.setIdealPeerCount(1);
shared_ptr<WhisperHost> whost2 = host2.registerCapability(new WhisperHost());
host2.start();
while (!host2.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
host2.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), 30305, 30305));
while (!host2.peerCount())
this_thread::sleep_for(chrono::milliseconds(5));
KeyPair us = KeyPair::create();
whost2->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250));
}
{
Host ph("Listener", NetworkPreferences("127.0.0.1", 30300, false));
ph.setIdealPeerCount(1);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());
ph.start();
while (!ph.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
ph.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), 30305, 30305));
/// Only interested in odd packets
auto w = wh->installWatch(BuildTopicMask("test"));
for (int i = 0; i < 200 && !result; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open(wh->fullTopic(w));
unsigned last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from() << RLP(msg.payload()).toInt<unsigned>();
result = last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
}
done = true;
forwarder.join();
g_logVerbosity = oldLogVerbosity;
BOOST_REQUIRE_EQUAL(result, 1);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>
#ifdef CAD
#include "cad.h"
moab::DagMC* DAGMC;
void load_cad_geometry_c()
{
if(!DAGMC) {
DAGMC = new moab::DagMC();
}
moab::ErrorCode rval = DAGMC->load_file("dagmc.h5m");
MB_CHK_ERR_CONT(rval);
rval = DAGMC->init_OBBTree();
MB_CHK_ERR_CONT(rval);
int32_t cad_univ_id = 0; // universe is always 0 for CAD
// initialize cell objects
openmc::n_cells = DAGMC->num_entities(3);
for(int i = 0; i < openmc::n_cells; i++)
{
// set cell ids using global IDs
openmc::CADCell* c = new openmc::CADCell();
c->id_ = DAGMC->id_by_index(3, i+1);
c->dagmc_ptr = DAGMC;
c->universe_ = cad_univ_id; // set to zero for now
c->material_.push_back(40); // TEMPORARY
openmc::global_cells.push_back(c);
openmc::cell_map[c->id_] = c->id;
// Populate the Universe vector and dict
auto it = openmc::universe_map.find(cad_univ_id);
if (it == openmc::universe_map.end()) {
openmc::global_universes.push_back(new openmc::Universe());
openmc::global_universes.back()-> id = cad_univ_id;
openmc::global_universes.back()->cells.push_back(i);
openmc::universe_map[cad_univ_id] = openmc::global_universes.size() - 1;
}
else {
openmc::global_universes[it->second]->cells.push_back(i);
}
}
// initialize surface objects
openmc::n_surfaces = DAGMC->num_entities(2);
openmc::surfaces_c = new openmc::Surface*[openmc::n_surfaces];
for(int i = 0; i < openmc::n_surfaces; i++)
{
// set cell ids using global IDs
openmc::CADSurface* s = new openmc::CADSurface();
s->id = DAGMC->id_by_index(2, i+1);
s->dagmc_ptr = DAGMC;
s->bc = openmc::BC_TRANSMIT;
openmc::surfaces_c[i] = s;
openmc::surface_map[s->id] = s->id;
}
return;
}
void free_memory_cad_c()
{
delete DAGMC;
}
#endif
<commit_msg>Set material by property.<commit_after>
#ifdef CAD
#include "cad.h"
moab::DagMC* DAGMC;
void load_cad_geometry_c()
{
if(!DAGMC) {
DAGMC = new moab::DagMC();
}
int32_t cad_univ_id = 0; // universe is always 0 for CAD
moab::ErrorCode rval = DAGMC->load_file("dagmc.h5m");
MB_CHK_ERR_CONT(rval);
rval = DAGMC->init_OBBTree();
MB_CHK_ERR_CONT(rval);
std::vector< std::string > prop_keywords;
prop_keywords.push_back("mat");
std::map<std::string, std::string> ph;
DAGMC->parse_properties(prop_keywords, ph, ":");
MB_CHK_ERR_CONT(rval);
// initialize cell objects
openmc::n_cells = DAGMC->num_entities(3);
for(int i = 0; i < openmc::n_cells; i++)
{
moab::EntityHandle vol_handle = DAGMC->entity_by_index(3, i+1);
// set cell ids using global IDs
openmc::CADCell* c = new openmc::CADCell();
c->id_ = DAGMC->id_by_index(3, i+1);
c->dagmc_ptr = DAGMC;
c->universe_ = cad_univ_id; // set to zero for now
if(DAGMC->has_prop(vol_handle, "mat")){
std::string mat_value;
rval = DAGMC->prop_value(vol_handle, "mat", mat_value);
MB_CHK_ERR_CONT(rval);
int mat_id = std::stoi(mat_value);
c->material_.push_back(mat_id);
}
else {
c->material_.push_back(40); // TO-DO: add void material here
}
c->fill_ = openmc::C_NONE;
openmc::global_cells.push_back(c);
openmc::cell_map[c->id_] = c->id_;
// Populate the Universe vector and dict
auto it = openmc::universe_map.find(cad_univ_id);
if (it == openmc::universe_map.end()) {
openmc::global_universes.push_back(new openmc::Universe());
openmc::global_universes.back()-> id = cad_univ_id;
openmc::global_universes.back()->cells.push_back(i);
openmc::universe_map[cad_univ_id] = openmc::global_universes.size() - 1;
}
else {
openmc::global_universes[it->second]->cells.push_back(i);
}
}
// initialize surface objects
openmc::n_surfaces = DAGMC->num_entities(2);
openmc::surfaces_c = new openmc::Surface*[openmc::n_surfaces];
for(int i = 0; i < openmc::n_surfaces; i++)
{
// set cell ids using global IDs
openmc::CADSurface* s = new openmc::CADSurface();
s->id = DAGMC->id_by_index(2, i+1);
s->dagmc_ptr = DAGMC;
s->bc = openmc::BC_TRANSMIT;
openmc::surfaces_c[i] = s;
openmc::surface_map[s->id] = s->id;
}
return;
}
void free_memory_cad_c()
{
delete DAGMC;
}
#endif
<|endoftext|>
|
<commit_before>#include <boost/python.hpp>
#include <boost/optional/optional.hpp>
#include <nix.hpp>
#include <transmorgify.hpp>
#include <accessors.hpp>
#include <PyEntity.hpp>
using namespace boost::python;
using namespace nix;
using namespace base;
using namespace nixpy;
BOOST_PYTHON_MODULE(core)
{
PyFile::do_export();
PySection::do_export();
PyProperty::do_export();
PyValue::do_export();
PyBlock::do_export();
PySource::do_export();
PyDataArray::do_export();
PyDimensions::do_export();
PyEntityWithSources<ISimpleTag>::do_export("SimpleTag");
class_<SimpleTag, bases<EntityWithSources<ISimpleTag>>>("SimpleTag");
to_python_converter<std::vector<SimpleTag>, vector_transmogrify<SimpleTag>>();
to_python_converter<boost::optional<SimpleTag>, option_transmogrify<SimpleTag>>();
PyEntityWithSources<IDataTag>::do_export("DataTag");
class_<DataTag, bases<EntityWithSources<IDataTag>>>("DataTag");
to_python_converter<std::vector<DataTag>, vector_transmogrify<DataTag>>();
to_python_converter<boost::optional<DataTag>, option_transmogrify<DataTag>>();
class_<Feature>("Feature");
// TODO enum class LinkType
to_python_converter<boost::optional<std::string>, option_transmogrify<std::string>>();
option_transmogrify<std::string>::register_from_python();
to_python_converter<std::vector<std::string>, vector_transmogrify<std::string>>();
vector_transmogrify<std::string>::register_from_python();
to_python_converter<std::vector<double>, vector_transmogrify<double>>();
vector_transmogrify<double>::register_from_python();
to_python_converter<boost::optional<double>, option_transmogrify<double>>();
option_transmogrify<double>::register_from_python();
}
<commit_msg>core: configure doc strings<commit_after>#include <boost/python.hpp>
#include <boost/optional/optional.hpp>
#include <nix.hpp>
#include <transmorgify.hpp>
#include <accessors.hpp>
#include <PyEntity.hpp>
using namespace boost::python;
using namespace nix;
using namespace base;
using namespace nixpy;
BOOST_PYTHON_MODULE(core)
{
// set options for doc strings
// show user defined / show py signatures / don't show cpp signatures
docstring_options local_docstring_options(true, true, false);
PyFile::do_export();
PySection::do_export();
PyProperty::do_export();
PyValue::do_export();
PyBlock::do_export();
PySource::do_export();
PyDataArray::do_export();
PyDimensions::do_export();
PyEntityWithSources<ISimpleTag>::do_export("SimpleTag");
class_<SimpleTag, bases<EntityWithSources<ISimpleTag>>>("SimpleTag");
to_python_converter<std::vector<SimpleTag>, vector_transmogrify<SimpleTag>>();
to_python_converter<boost::optional<SimpleTag>, option_transmogrify<SimpleTag>>();
PyEntityWithSources<IDataTag>::do_export("DataTag");
class_<DataTag, bases<EntityWithSources<IDataTag>>>("DataTag");
to_python_converter<std::vector<DataTag>, vector_transmogrify<DataTag>>();
to_python_converter<boost::optional<DataTag>, option_transmogrify<DataTag>>();
class_<Feature>("Feature");
// TODO enum class LinkType
to_python_converter<boost::optional<std::string>, option_transmogrify<std::string>>();
option_transmogrify<std::string>::register_from_python();
to_python_converter<std::vector<std::string>, vector_transmogrify<std::string>>();
vector_transmogrify<std::string>::register_from_python();
to_python_converter<std::vector<double>, vector_transmogrify<double>>();
vector_transmogrify<double>::register_from_python();
to_python_converter<boost::optional<double>, option_transmogrify<double>>();
option_transmogrify<double>::register_from_python();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cplusplus.h"
#include "info.h"
class Cxx : public CPlusPlus
{
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (element->isSequence(interface) || element->isNative(interface))
{
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
writetab();
element->accept(this);
write(";\n");
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
Cxx(FILE* file, const char* stringTypeName = "char*", bool useExceptions = true) :
CPlusPlus(file, stringTypeName, useExceptions)
{
}
virtual void at(const StructType* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
if (!node->isLeaf())
{
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
}
virtual void at(const ExceptDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
virtual void at(const Interface* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("class %s", node->getName().c_str());
if (node->getExtends())
{
write(" : ");
prefix = "public ";
node->getExtends()->accept(this);
prefix = "";
}
if (!node->isLeaf())
{
writeln("");
writeln("{");
writeln("public:");
indent();
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
i != node->getMixins()->end();
++i)
{
writeln("// %s", (*i)->getName().c_str());
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
visitInterfaceElement(*i, *j);
}
}
writeln("static const char* iid()");
writeln("{");
indent();
writeln("static const char* const name = \"%s\";",
node->getQualifiedName().c_str());
writeln("return name;");
unindent();
writeln("}");
writeln("static const char* info()");
writeln("{");
indent();
writetab();
write("static const char* const info = ");
indent();
Info info(this, moduleName);
const_cast<Interface*>(node)->accept(&info);
write(";\n");
unindent();
writeln("return info;");
unindent();
writeln("}");
if (Interface* constructor = node->getConstructor())
{
// Process constructors.
constructorMode = true;
for (NodeList::iterator i = constructor->begin();
i != constructor->end();
++i)
{
writetab();
(*i)->accept(this);
}
constructorMode = false;
writeln("static Constructor* getConstructor()");
writeln("{");
indent();
writeln("return constructor;");
unindent();
writeln("}");
writeln("static void setConstructor(Constructor* ctor)");
writeln("{");
indent();
writeln("constructor = ctor;");
unindent();
writeln("}");
unindent();
writeln("private:");
indent();
writeln("static Constructor* constructor;");
}
unindent();
writetab();
write("}");
}
if (node->getConstructor())
{
write(";\n\n");
writetab();
write("%s::Constructor* %s::constructor __attribute__((weak))",
node->getName().c_str(), node->getName().c_str());
}
}
virtual void at(const NativeType* node)
{
if (node->getName() == "void_pointer")
{
write("void*");
}
else
{
write("%s", node->getName().c_str());
}
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
if (node->getName() == "TRUE")
{
write("true");
}
else if (node->getName() == "FALSE")
{
write("false");
}
else
{
write("%s", node->getName().c_str());
}
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
write("typedef ");
}
if (node->isInterface(node->getParent()))
{
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
else
{
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
at(static_cast<const Member*>(node));
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
}
virtual void at(const ConstDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("static const ");
at(static_cast<const Member*>(node));
write(" = ");
node->getExp()->accept(this);
}
virtual void at(const Attribute* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
CPlusPlus::getter(node);
write(" = 0");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
write(";\n");
writetab();
CPlusPlus::setter(node);
write(" = 0");
}
}
virtual void at(const OpDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
CPlusPlus::at(node);
if (!constructorMode)
{
write(" = 0");
}
else
{
writeln("");
writeln("{");
indent();
writeln("if (constructor)");
indent();
writetab();
write("constructor->createInstance(");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
if (i != node->begin())
{
write(", ");
}
write("%s", (*i)->getName().c_str());
}
write(");");
writeln("");
unindent();
unindent();
writeln("}");
}
}
};
class Import : public Visitor
{
FILE* file;
bool printed;
public:
Import(FILE* file) :
file(file),
printed(false)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Include* node)
{
if (1 < node->getRank())
{
return;
}
if (node->isSystem())
{
fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
else
{
fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
printed = true;
}
bool hasPrinted() const
{
return printed;
}
};
class Predeclaration : public Visitor
{
FILE* file;
public:
Predeclaration(FILE* file) :
file(file)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
if (!node->hasPredeclarations())
{
return;
}
if (0 < node->getName().size())
{
fprintf(file, "namespace %s\n", node->getName().c_str());
fprintf(file, "{\n");
visitChildren(node);
fprintf(file, "}\n\n");
}
else
{
visitChildren(node);
}
}
virtual void at(const Interface* node)
{
if (1 < node->getRank() || !node->isLeaf())
{
return;
}
fprintf(file, " class %s;\n", node->getName().c_str());
}
};
void printCxx(const std::string& filename, const char* stringTypeName, bool useExceptions)
{
printf("# %s\n", filename.c_str());
FILE* file = fopen(filename.c_str(), "w");
if (!file)
{
return;
}
std::string included = getIncludedName(filename);
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "#ifndef %s\n", included.c_str());
fprintf(file, "#define %s\n\n", included.c_str());
Import import(file);
getSpecification()->accept(&import);
if (import.hasPrinted())
{
fprintf(file, "\n");
}
if (!Node::getFlatNamespace())
{
Predeclaration predeclaration(file);
getSpecification()->accept(&predeclaration);
}
Cxx cxx(file, stringTypeName, useExceptions);
getSpecification()->accept(&cxx);
fprintf(file, "#endif // %s\n", included.c_str());
fclose(file);
}
<commit_msg>(createInstance) : Return 0 if constructor is not set.<commit_after>/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cplusplus.h"
#include "info.h"
class Cxx : public CPlusPlus
{
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (element->isSequence(interface) || element->isNative(interface))
{
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
writetab();
element->accept(this);
write(";\n");
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
Cxx(FILE* file, const char* stringTypeName = "char*", bool useExceptions = true) :
CPlusPlus(file, stringTypeName, useExceptions)
{
}
virtual void at(const StructType* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
if (!node->isLeaf())
{
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
}
virtual void at(const ExceptDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
virtual void at(const Interface* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("class %s", node->getName().c_str());
if (node->getExtends())
{
write(" : ");
prefix = "public ";
node->getExtends()->accept(this);
prefix = "";
}
if (!node->isLeaf())
{
writeln("");
writeln("{");
writeln("public:");
indent();
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
i != node->getMixins()->end();
++i)
{
writeln("// %s", (*i)->getName().c_str());
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
visitInterfaceElement(*i, *j);
}
}
writeln("static const char* iid()");
writeln("{");
indent();
writeln("static const char* const name = \"%s\";",
node->getQualifiedName().c_str());
writeln("return name;");
unindent();
writeln("}");
writeln("static const char* info()");
writeln("{");
indent();
writetab();
write("static const char* const info = ");
indent();
Info info(this, moduleName);
const_cast<Interface*>(node)->accept(&info);
write(";\n");
unindent();
writeln("return info;");
unindent();
writeln("}");
if (Interface* constructor = node->getConstructor())
{
// Process constructors.
constructorMode = true;
for (NodeList::iterator i = constructor->begin();
i != constructor->end();
++i)
{
writetab();
(*i)->accept(this);
}
constructorMode = false;
writeln("static Constructor* getConstructor()");
writeln("{");
indent();
writeln("return constructor;");
unindent();
writeln("}");
writeln("static void setConstructor(Constructor* ctor)");
writeln("{");
indent();
writeln("constructor = ctor;");
unindent();
writeln("}");
unindent();
writeln("private:");
indent();
writeln("static Constructor* constructor;");
}
unindent();
writetab();
write("}");
}
if (node->getConstructor())
{
write(";\n\n");
writetab();
write("%s::Constructor* %s::constructor __attribute__((weak))",
node->getName().c_str(), node->getName().c_str());
}
}
virtual void at(const NativeType* node)
{
if (node->getName() == "void_pointer")
{
write("void*");
}
else
{
write("%s", node->getName().c_str());
}
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
if (node->getName() == "TRUE")
{
write("true");
}
else if (node->getName() == "FALSE")
{
write("false");
}
else
{
write("%s", node->getName().c_str());
}
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
write("typedef ");
}
if (node->isInterface(node->getParent()))
{
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
else
{
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
at(static_cast<const Member*>(node));
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
}
virtual void at(const ConstDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("static const ");
at(static_cast<const Member*>(node));
write(" = ");
node->getExp()->accept(this);
}
virtual void at(const Attribute* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
CPlusPlus::getter(node);
write(" = 0");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
write(";\n");
writetab();
CPlusPlus::setter(node);
write(" = 0");
}
}
virtual void at(const OpDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
CPlusPlus::at(node);
if (!constructorMode)
{
write(" = 0");
}
else
{
writeln("");
writeln("{");
indent();
writeln("if (constructor)");
indent();
writetab();
write("constructor->createInstance(");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
if (i != node->begin())
{
write(", ");
}
write("%s", (*i)->getName().c_str());
}
write(");");
writeln("");
unindent();
writeln("else");
indent();
writeln("return 0;");
unindent();
unindent();
writeln("}");
}
}
};
class Import : public Visitor
{
FILE* file;
bool printed;
public:
Import(FILE* file) :
file(file),
printed(false)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Include* node)
{
if (1 < node->getRank())
{
return;
}
if (node->isSystem())
{
fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
else
{
fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
printed = true;
}
bool hasPrinted() const
{
return printed;
}
};
class Predeclaration : public Visitor
{
FILE* file;
public:
Predeclaration(FILE* file) :
file(file)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
if (!node->hasPredeclarations())
{
return;
}
if (0 < node->getName().size())
{
fprintf(file, "namespace %s\n", node->getName().c_str());
fprintf(file, "{\n");
visitChildren(node);
fprintf(file, "}\n\n");
}
else
{
visitChildren(node);
}
}
virtual void at(const Interface* node)
{
if (1 < node->getRank() || !node->isLeaf())
{
return;
}
fprintf(file, " class %s;\n", node->getName().c_str());
}
};
void printCxx(const std::string& filename, const char* stringTypeName, bool useExceptions)
{
printf("# %s\n", filename.c_str());
FILE* file = fopen(filename.c_str(), "w");
if (!file)
{
return;
}
std::string included = getIncludedName(filename);
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "#ifndef %s\n", included.c_str());
fprintf(file, "#define %s\n\n", included.c_str());
Import import(file);
getSpecification()->accept(&import);
if (import.hasPrinted())
{
fprintf(file, "\n");
}
if (!Node::getFlatNamespace())
{
Predeclaration predeclaration(file);
getSpecification()->accept(&predeclaration);
}
Cxx cxx(file, stringTypeName, useExceptions);
getSpecification()->accept(&cxx);
fprintf(file, "#endif // %s\n", included.c_str());
fclose(file);
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 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 "config.h"
#include "couch_btree.h"
#include "internal.h"
#include "util.h"
#include <libcouchstore/couch_db.h>
#include <platform/cb_malloc.h>
#include <getopt.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iomanip>
#include <string>
#include <sstream>
static void usage(void) {
printf("USAGE: couch_dbck [options] "
"source_filename [destination_filename]\n");
printf("\nOptions:\n");
printf(" -s, --stale "
"Recover from stale commits if corruption detected.\n");
printf(" -v, --verbose "
"Display detailed messages.\n");
printf(" -j, --json "
"Display corrupt document info as JSON objects "
"(one per line).\n");
exit(EXIT_FAILURE);
}
struct recovery_options {
// Source file name.
std::string src_filename;
// Destination (recovered) file name.
std::string dst_filename;
// If set, check whether or not doc body is corrupted.
bool detect_corrupt_docbody = true;
// If set, recover using old data from stale commits.
bool enable_rewind = false;
// If set, print out detailed messages.
bool verbose_msg = false;
// If set, print verbose messages as JSON objects.
bool json = false;
};
struct recover_file_hook_param {
// Number of documents referred to by index.
uint64_t num_visited_docs = 0;
// Number of corrupted documents.
uint64_t num_corrupted_docs = 0;
// Recovery options.
recovery_options* options = nullptr;
// DB handle for source file.
Db* db_src = nullptr;
};
std::string get_printable_string(const sized_buf& buf) {
std::string ret;
for (size_t i=0; i<buf.size; ++i) {
if (0x20 <= buf.buf[i] && buf.buf[i] <= 0x7d) {
// Printable character.
ret += buf.buf[i];
} else {
// Otherwise: dump hex.
std::stringstream ss;
ss << "(0x" << std::setfill('0') << std::setw(2)
<< std::hex << static_cast<size_t>(buf.buf[i]) << ") ";
ret += ss.str();
}
}
return ret;
}
static int recover_file_hook(Db* target,
DocInfo *docinfo,
sized_buf item,
void *ctx) {
(void)item;
recover_file_hook_param* param =
reinterpret_cast<recover_file_hook_param*>(ctx);
if (!docinfo) {
// End of compaction.
return 0;
}
param->num_visited_docs++;
couchstore_error_t errcode;
Doc* cur_doc;
if (docinfo->deleted) {
// Deleted doc.
return 0;
}
// Open doc body.
errcode = couchstore_open_doc_with_docinfo(
param->db_src, docinfo, &cur_doc, 0x0);
if (errcode != COUCHSTORE_SUCCESS) {
// Document is corrupted.
if (param->options->verbose_msg) {
std::string fmt;
if (param->options->json) {
fmt = "{"
R"("type":"corrupted document",)"
R"("error code":%d,)"
R"("error message":"%s",)"
R"("id":"%s",)"
R"("bp")" ":%" PRIu64 ","
R"("size":%zu,)"
R"("seq")" ":%" PRIu64
"}\n";
} else {
fmt = "Corrupted document "
"(error code %d, %s): "
"id '%s', "
"bp %" PRIu64 ", "
"size %zu, "
"seq %" PRIu64
"\n";
}
fprintf(stdout, fmt.c_str(),
errcode, couchstore_strerror(errcode),
get_printable_string(docinfo->id).c_str(),
docinfo->bp,
docinfo->size,
docinfo->db_seq);
}
param->num_corrupted_docs++;
} else {
couchstore_free_document(cur_doc);
}
return 0;
}
struct rewind_request {
// Recovery options.
recovery_options* options = nullptr;
// DB handle for source file.
Db *db_src = nullptr;
// DB handle for recovered file.
Db *db_recovered = nullptr;
// Total number of old documents recovered from all stale commits.
uint64_t total_num_docs_recovered = 0;
};
struct rewind_hook_param {
// Recovery options.
recovery_options* options = nullptr;
// DB handle for source file.
Db *db_src = nullptr;
// DB handle for recovered file.
Db *db_dst = nullptr;
// Number of documents recovered from this specific commit.
uint64_t num_docs_recovered = 0;
};
static int rewind_hook(Db *db,
int depth,
const DocInfo* doc_info,
uint64_t subtree_size,
const sized_buf* reduce_value,
void *ctx) {
rewind_hook_param* param =
reinterpret_cast<rewind_hook_param*>(ctx);
if (!doc_info) {
return 0;
}
DocInfo* doc_info_dst;
couchstore_error_t errcode;
errcode = couchstore_docinfo_by_id(param->db_dst,
doc_info->id.buf,
doc_info->id.size,
&doc_info_dst);
if (errcode != COUCHSTORE_SUCCESS) {
// The doc exists in stale commit (of corrupted file) only.
// Copy it into the destination file.
Doc* cur_doc;
errcode = couchstore_open_doc_with_docinfo(
param->db_src, (DocInfo*)doc_info, &cur_doc, 0x0);
if (errcode != COUCHSTORE_SUCCESS) {
return 0;
}
if (param->options->verbose_msg) {
std::string fmt;
if (param->options->json) {
fmt = "{"
R"("type":"recovered document",)"
R"("id":"%s",)"
R"("bp")" ":%" PRIu64 ","
R"("size")" ":%zu,"
R"("seq")" ":%" PRIu64
"}\n";
} else {
fmt = "Recovered document '%s', "
"prev bp %" PRIu64 ", "
"prev size %zu, "
"prev seq num %" PRIu64
"\n";
}
fprintf(stdout, fmt.c_str(),
get_printable_string(doc_info->id).c_str(),
doc_info->bp,
doc_info->size,
doc_info->db_seq);
}
couchstore_save_document(param->db_dst,
cur_doc,
(DocInfo*)doc_info,
COUCHSTORE_SEQUENCE_AS_IS);
param->num_docs_recovered++;
couchstore_free_document(cur_doc);
} else {
couchstore_free_docinfo(doc_info_dst);
}
return 0;
}
static void rewind_and_get_stale_data(rewind_request& rq) {
couchstore_error_t errcode;
size_t num_rewind = 0;
Db *db = nullptr;
errcode = couchstore_open_db_ex(rq.options->src_filename.c_str(),
COUCHSTORE_OPEN_FLAG_RDONLY,
couchstore_get_default_file_ops(),
&db);
while (errcode == COUCHSTORE_SUCCESS) {
errcode = couchstore_rewind_db_header(db);
if (errcode != COUCHSTORE_SUCCESS) {
db = nullptr;
break;
}
num_rewind++;
rewind_hook_param rewind_param;
rewind_param.options = rq.options;
rewind_param.db_dst = rq.db_recovered;
rewind_param.db_src = rq.db_src;
// Walk ID tree and find any documents
// that exist in stale commit only.
couchstore_walk_id_tree(db,
nullptr,
COUCHSTORE_TOLERATE_CORRUPTION,
rewind_hook,
&rewind_param);
if (rewind_param.num_docs_recovered) {
fprintf(stderr, "%" PRIu64 " documents recovered "
"from stale header #%zu.\n",
rewind_param.num_docs_recovered,
num_rewind);
rq.total_num_docs_recovered += rewind_param.num_docs_recovered;
}
};
if (!num_rewind) {
fprintf(stderr, "No stale header to read.\n");
}
if (db) {
couchstore_close_file(db);
couchstore_free_db(db);
}
}
static int recover_file(recovery_options& options) {
fprintf(stderr, "Recover from file %s to file %s\n",
options.src_filename.c_str(),
options.dst_filename.c_str());
if (options.src_filename == options.dst_filename) {
// Both filenames shouldn't be the same.
usage();
}
// Source (may be corrupted) DB.
Db *db_src = nullptr;
// DB after recovery.
Db *db_recovered = nullptr;
// Another handle for source DB.
Db *db_src_alt = nullptr;
couchstore_error_t errcode = COUCHSTORE_SUCCESS;
couchstore_error_t errcode_compaction = COUCHSTORE_SUCCESS;
bool error_detected = false;
recover_file_hook_param param;
param.options = &options;
// Open source file.
errcode = couchstore_open_db_ex(options.src_filename.c_str(),
COUCHSTORE_OPEN_FLAG_RDONLY,
couchstore_get_default_file_ops(),
&db_src);
error_pass(errcode);
// Open source file for rewind.
errcode = couchstore_open_db_ex(options.src_filename.c_str(),
COUCHSTORE_OPEN_FLAG_RDONLY,
couchstore_get_default_file_ops(),
&db_src_alt);
error_pass(errcode);
param.db_src = db_src_alt;
// Compact with recovery mode.
errcode_compaction = couchstore_compact_db_ex(
db_src,
options.dst_filename.c_str(),
COUCHSTORE_COMPACT_RECOVERY_MODE,
recover_file_hook,
nullptr,
¶m,
couchstore_get_default_file_ops());
// Open recovered file.
errcode = couchstore_open_db_ex(options.dst_filename.c_str(),
0x0,
couchstore_get_default_file_ops(),
&db_recovered);
DbInfo dbinfo;
couchstore_db_info(db_recovered, &dbinfo);
if (errcode_compaction == COUCHSTORE_SUCCESS) {
fprintf(stderr, "No corruption detected in index.\n");
} else {
fprintf(stderr,
"Corrupted index node detected "
"(error code %d, %s).\n",
errcode_compaction,
couchstore_strerror(errcode_compaction));
error_detected = true;
}
fprintf(stderr, "Total %" PRIu64 " documents are referred to by index.\n",
param.num_visited_docs);
if (param.num_corrupted_docs) {
fprintf(stderr, "Total %" PRIu64 " documents corrupted.\n",
param.num_corrupted_docs);
error_detected = true;
} else {
fprintf(stderr, "No corruption detected in documents.\n");
}
fprintf(stderr, "Total %" PRIu64 " documents recovered.\n",
dbinfo.doc_count);
// If error detected, and flag is set, traverse stale commits.
if (error_detected && options.enable_rewind) {
rewind_request rwrq;
rwrq.options = &options;
rwrq.db_recovered = db_recovered;
rwrq.db_src = db_src_alt;
fprintf(stderr,
"We are going to recover missing documents "
"from stale commits..\n");
rewind_and_get_stale_data(rwrq);
if (rwrq.total_num_docs_recovered) {
fprintf(stderr,
"Total %" PRIu64 " documents recovered "
"from stale headers.\n",
rwrq.total_num_docs_recovered);
error_pass(couchstore_commit(db_recovered));
}
}
cleanup:
if (db_src) {
couchstore_close_file(db_src);
couchstore_free_db(db_src);
}
if (db_recovered) {
couchstore_close_file(db_recovered);
couchstore_free_db(db_recovered);
}
if (db_src_alt) {
couchstore_close_file(db_src_alt);
couchstore_free_db(db_src_alt);
}
return errcode;
}
int main(int argc, char **argv)
{
struct option long_options[] =
{
{"stale", no_argument, 0, 's'},
{"verbose", no_argument, 0, 'v'},
{"json", no_argument, 0, 'j'},
{nullptr, 0, 0, 0}
};
recovery_options options;
int opt;
while ( (opt = getopt_long(argc, argv, "svj",
long_options, nullptr)) != -1 ) {
switch (opt) {
case 's': // stale
options.enable_rewind = true;
break;
case 'v': // verbose
options.verbose_msg = true;
break;
case 'j': // json
options.json = true;
break;
default:
usage();
}
}
if (argc - optind < 1) {
// After option fields, one or two more fields
// (for src/dst files) should exist.
usage();
}
options.src_filename = argv[optind];
if (argc - optind == 1) {
// Destination file name is not given, automatically set it.
options.dst_filename = options.src_filename + ".recovered";
} else {
options.dst_filename = argv[optind+1];
}
int errcode = recover_file(options);
if (errcode == 0) {
exit(EXIT_SUCCESS);
} else {
exit(EXIT_FAILURE);
}
}
<commit_msg>Fix Valgrind error in dbck<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 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 "config.h"
#include "couch_btree.h"
#include "internal.h"
#include "util.h"
#include <libcouchstore/couch_db.h>
#include <platform/cb_malloc.h>
#include <getopt.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iomanip>
#include <string>
#include <sstream>
static void usage(void) {
printf("USAGE: couch_dbck [options] "
"source_filename [destination_filename]\n");
printf("\nOptions:\n");
printf(" -s, --stale "
"Recover from stale commits if corruption detected.\n");
printf(" -v, --verbose "
"Display detailed messages.\n");
printf(" -j, --json "
"Display corrupt document info as JSON objects "
"(one per line).\n");
exit(EXIT_FAILURE);
}
struct recovery_options {
// Source file name.
std::string src_filename;
// Destination (recovered) file name.
std::string dst_filename;
// If set, check whether or not doc body is corrupted.
bool detect_corrupt_docbody = true;
// If set, recover using old data from stale commits.
bool enable_rewind = false;
// If set, print out detailed messages.
bool verbose_msg = false;
// If set, print verbose messages as JSON objects.
bool json = false;
};
struct recover_file_hook_param {
// Number of documents referred to by index.
uint64_t num_visited_docs = 0;
// Number of corrupted documents.
uint64_t num_corrupted_docs = 0;
// Recovery options.
recovery_options* options = nullptr;
// DB handle for source file.
Db* db_src = nullptr;
};
std::string get_printable_string(const sized_buf& buf) {
std::string ret;
for (size_t i=0; i<buf.size; ++i) {
if (0x20 <= buf.buf[i] && buf.buf[i] <= 0x7d) {
// Printable character.
ret += buf.buf[i];
} else {
// Otherwise: dump hex.
std::stringstream ss;
ss << "(0x" << std::setfill('0') << std::setw(2)
<< std::hex << static_cast<size_t>(buf.buf[i]) << ") ";
ret += ss.str();
}
}
return ret;
}
static int recover_file_hook(Db* target,
DocInfo *docinfo,
sized_buf item,
void *ctx) {
(void)item;
recover_file_hook_param* param =
reinterpret_cast<recover_file_hook_param*>(ctx);
if (!docinfo) {
// End of compaction.
return 0;
}
param->num_visited_docs++;
couchstore_error_t errcode;
Doc* cur_doc;
if (docinfo->deleted) {
// Deleted doc.
return 0;
}
// Open doc body.
errcode = couchstore_open_doc_with_docinfo(
param->db_src, docinfo, &cur_doc, 0x0);
if (errcode != COUCHSTORE_SUCCESS) {
// Document is corrupted.
if (param->options->verbose_msg) {
std::string fmt;
if (param->options->json) {
fmt = "{"
R"("type":"corrupted document",)"
R"("error code":%d,)"
R"("error message":"%s",)"
R"("id":"%s",)"
R"("bp")" ":%" PRIu64 ","
R"("size":%zu,)"
R"("seq")" ":%" PRIu64
"}\n";
} else {
fmt = "Corrupted document "
"(error code %d, %s): "
"id '%s', "
"bp %" PRIu64 ", "
"size %zu, "
"seq %" PRIu64
"\n";
}
fprintf(stdout, fmt.c_str(),
errcode, couchstore_strerror(errcode),
get_printable_string(docinfo->id).c_str(),
docinfo->bp,
docinfo->size,
docinfo->db_seq);
}
param->num_corrupted_docs++;
} else {
couchstore_free_document(cur_doc);
}
return 0;
}
struct rewind_request {
// Recovery options.
recovery_options* options = nullptr;
// DB handle for source file.
Db *db_src = nullptr;
// DB handle for recovered file.
Db *db_recovered = nullptr;
// Total number of old documents recovered from all stale commits.
uint64_t total_num_docs_recovered = 0;
};
struct rewind_hook_param {
// Recovery options.
recovery_options* options = nullptr;
// DB handle for source file.
Db *db_src = nullptr;
// DB handle for recovered file.
Db *db_dst = nullptr;
// Number of documents recovered from this specific commit.
uint64_t num_docs_recovered = 0;
};
static int rewind_hook(Db *db,
int depth,
const DocInfo* doc_info,
uint64_t subtree_size,
const sized_buf* reduce_value,
void *ctx) {
rewind_hook_param* param =
reinterpret_cast<rewind_hook_param*>(ctx);
if (!doc_info) {
return 0;
}
DocInfo* doc_info_dst;
couchstore_error_t errcode;
errcode = couchstore_docinfo_by_id(param->db_dst,
doc_info->id.buf,
doc_info->id.size,
&doc_info_dst);
if (errcode != COUCHSTORE_SUCCESS) {
// The doc exists in stale commit (of corrupted file) only.
// Copy it into the destination file.
Doc* cur_doc;
errcode = couchstore_open_doc_with_docinfo(
param->db_src, (DocInfo*)doc_info, &cur_doc, 0x0);
if (errcode != COUCHSTORE_SUCCESS) {
return 0;
}
if (param->options->verbose_msg) {
std::string fmt;
if (param->options->json) {
fmt = "{"
R"("type":"recovered document",)"
R"("id":"%s",)"
R"("bp")" ":%" PRIu64 ","
R"("size")" ":%zu,"
R"("seq")" ":%" PRIu64
"}\n";
} else {
fmt = "Recovered document '%s', "
"prev bp %" PRIu64 ", "
"prev size %zu, "
"prev seq num %" PRIu64
"\n";
}
fprintf(stdout, fmt.c_str(),
get_printable_string(doc_info->id).c_str(),
doc_info->bp,
doc_info->size,
doc_info->db_seq);
}
couchstore_save_document(param->db_dst,
cur_doc,
(DocInfo*)doc_info,
COUCHSTORE_SEQUENCE_AS_IS);
param->num_docs_recovered++;
couchstore_free_document(cur_doc);
} else {
couchstore_free_docinfo(doc_info_dst);
}
return 0;
}
static void rewind_and_get_stale_data(rewind_request& rq) {
couchstore_error_t errcode;
size_t num_rewind = 0;
Db *db = nullptr;
errcode = couchstore_open_db_ex(rq.options->src_filename.c_str(),
COUCHSTORE_OPEN_FLAG_RDONLY,
couchstore_get_default_file_ops(),
&db);
while (errcode == COUCHSTORE_SUCCESS) {
errcode = couchstore_rewind_db_header(db);
if (errcode != COUCHSTORE_SUCCESS) {
db = nullptr;
break;
}
num_rewind++;
rewind_hook_param rewind_param;
rewind_param.options = rq.options;
rewind_param.db_dst = rq.db_recovered;
rewind_param.db_src = rq.db_src;
// Walk ID tree and find any documents
// that exist in stale commit only.
couchstore_walk_id_tree(db,
nullptr,
COUCHSTORE_TOLERATE_CORRUPTION,
rewind_hook,
&rewind_param);
if (rewind_param.num_docs_recovered) {
fprintf(stderr, "%" PRIu64 " documents recovered "
"from stale header #%zu.\n",
rewind_param.num_docs_recovered,
num_rewind);
rq.total_num_docs_recovered += rewind_param.num_docs_recovered;
}
};
if (!num_rewind) {
fprintf(stderr, "No stale header to read.\n");
}
if (db) {
couchstore_close_file(db);
couchstore_free_db(db);
}
}
static int recover_file(recovery_options& options) {
fprintf(stderr, "Recover from file %s to file %s\n",
options.src_filename.c_str(),
options.dst_filename.c_str());
if (options.src_filename == options.dst_filename) {
// Both filenames shouldn't be the same.
usage();
}
// Source (may be corrupted) DB.
Db *db_src = nullptr;
// DB after recovery.
Db *db_recovered = nullptr;
// Another handle for source DB.
Db *db_src_alt = nullptr;
couchstore_error_t errcode = COUCHSTORE_SUCCESS;
couchstore_error_t errcode_compaction = COUCHSTORE_SUCCESS;
bool error_detected = false;
recover_file_hook_param param;
param.options = &options;
// Open source file.
errcode = couchstore_open_db_ex(options.src_filename.c_str(),
COUCHSTORE_OPEN_FLAG_RDONLY,
couchstore_get_default_file_ops(),
&db_src);
error_pass(errcode);
// Open source file for rewind.
errcode = couchstore_open_db_ex(options.src_filename.c_str(),
COUCHSTORE_OPEN_FLAG_RDONLY,
couchstore_get_default_file_ops(),
&db_src_alt);
error_pass(errcode);
param.db_src = db_src_alt;
// Compact with recovery mode.
errcode_compaction = couchstore_compact_db_ex(
db_src,
options.dst_filename.c_str(),
COUCHSTORE_COMPACT_RECOVERY_MODE,
recover_file_hook,
nullptr,
¶m,
couchstore_get_default_file_ops());
// Open recovered file.
errcode = couchstore_open_db_ex(options.dst_filename.c_str(),
0x0,
couchstore_get_default_file_ops(),
&db_recovered);
DbInfo dbinfo;
couchstore_db_info(db_recovered, &dbinfo);
if (errcode_compaction == COUCHSTORE_SUCCESS) {
fprintf(stderr, "No corruption detected in index.\n");
} else {
fprintf(stderr,
"Corrupted index node detected "
"(error code %d, %s).\n",
errcode_compaction,
couchstore_strerror(errcode_compaction));
error_detected = true;
}
fprintf(stderr, "Total %" PRIu64 " documents are referred to by index.\n",
param.num_visited_docs);
if (param.num_corrupted_docs) {
fprintf(stderr, "Total %" PRIu64 " documents corrupted.\n",
param.num_corrupted_docs);
error_detected = true;
} else {
fprintf(stderr, "No corruption detected in documents.\n");
}
fprintf(stderr, "Total %" PRIu64 " documents recovered.\n",
dbinfo.doc_count);
// If error detected, and flag is set, traverse stale commits.
if (error_detected && options.enable_rewind) {
rewind_request rwrq;
rwrq.options = &options;
rwrq.db_recovered = db_recovered;
rwrq.db_src = db_src_alt;
fprintf(stderr,
"We are going to recover missing documents "
"from stale commits..\n");
rewind_and_get_stale_data(rwrq);
if (rwrq.total_num_docs_recovered) {
fprintf(stderr,
"Total %" PRIu64 " documents recovered "
"from stale headers.\n",
rwrq.total_num_docs_recovered);
error_pass(couchstore_commit(db_recovered));
}
}
cleanup:
if (db_src) {
couchstore_close_file(db_src);
couchstore_free_db(db_src);
}
if (db_recovered) {
couchstore_close_file(db_recovered);
couchstore_free_db(db_recovered);
}
if (db_src_alt) {
couchstore_close_file(db_src_alt);
couchstore_free_db(db_src_alt);
}
return errcode;
}
int main(int argc, char **argv)
{
struct option long_options[] =
{
{"stale", no_argument, 0, 's'},
{"verbose", no_argument, 0, 'v'},
{"json", no_argument, 0, 'j'},
{nullptr, 0, 0, 0}
};
recovery_options options;
int opt;
while ( (opt = getopt_long(argc, argv, "svj",
long_options, nullptr)) != -1 ) {
switch (opt) {
case 's': // stale
options.enable_rewind = true;
break;
case 'v': // verbose
options.verbose_msg = true;
break;
case 'j': // json
options.json = true;
break;
default:
usage();
}
}
if (argc - optind < 1) {
// After option fields, one or two more fields
// (for src/dst files) should exist.
usage();
}
options.src_filename = argv[optind];
if (argc - optind == 1) {
// Destination file name is not given, automatically set it.
options.dst_filename = options.src_filename + ".recovered";
} else {
options.dst_filename = argv[optind+1];
}
int errcode = recover_file(options);
if (errcode == 0) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
<|endoftext|>
|
<commit_before>#include "CppUnitTest.h"
#include <string>
#include <vector>
#include <array>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace algo
{
template<class Traits>
class tokens
{
typedef vector<typename Traits::type> token_vector;
token_vector tokens_;
public:
typedef typename token_vector::iterator iterator;
typedef typename token_vector::const_iterator const_iterator;
typedef typename Traits::type token_type;
tokens() {}
explicit tokens(size_t count) : tokens_(count) {}
tokens(std::initializer_list<token_type> init) : tokens_(init) {}
bool empty() const { return tokens_.size() == 0; }
size_t size() const { return tokens_.size(); }
token_type& operator[](size_t i) { return tokens_[i]; };
const token_type& operator[](size_t i) const { return const_cast<tokens&>(*this)[i]; };
iterator begin() { return tokens_.begin(); }
const_iterator begin() const { return tokens_.begin(); }
const_iterator cbegin() const { return tokens_.cbegin(); }
iterator end() { return tokens_.end(); }
const_iterator end() const { return tokens_.end(); }
const_iterator cend() const { return tokens_.cend(); }
void from_string(string s)
{
auto newTokens = Traits::tokenize(s);
tokens_.insert(tokens_.end(), newTokens.begin(), newTokens.end());
}
};
}
namespace algo { namespace spec
{
struct s { string val; };
template<size_t N>
struct test_token_traits
{
typedef s type;
static array<s, N> tokenize(const string&) { return array<s, N>(); }
};
template<size_t N>
using test_tokens = tokens<test_token_traits<N>>;
TEST_CLASS(can_recognize_tokens)
{
public:
TEST_METHOD(should_not_have_any_tokens_when_default_constructed)
{
test_tokens<0> testTokens;
Assert::IsTrue(testTokens.empty());
}
TEST_METHOD(should_recognize_a_token_in_a_string)
{
test_tokens<1> testTokens;
testTokens.from_string("irrelevant");
Assert::IsFalse(testTokens.empty());
}
TEST_METHOD(should_recognize_more_than_one_token_in_a_string)
{
test_tokens<3> testTokens;
testTokens.from_string("irrelevant");
Assert::AreEqual(3U, testTokens.size());
}
TEST_METHOD(should_accumulate_tokens_from_successive_strings)
{
test_tokens<2> testTokens(3);
testTokens.from_string("irrelevant");
Assert::AreEqual(5U, testTokens.size());
}
TEST_METHOD(should_be_able_to_enumerate_tokens)
{
test_tokens<0> testTokens(3);
size_t i = 0;
for (s tok : testTokens) { ++i; }
Assert::AreEqual(3U, i);
}
TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_const_container)
{
const test_tokens<0> testTokens(3);
size_t i = 0;
for (const s tok : testTokens) { ++i; }
Assert::AreEqual(3U, i);
}
TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_non_const_container)
{
typedef test_tokens<0>::const_iterator const_iter;
test_tokens<0> testTokens(3);
size_t i = 0;
for (const_iter it = testTokens.cbegin(); it != testTokens.cend(); ++it) { ++i; }
Assert::AreEqual(3U, i);
}
TEST_METHOD(should_be_able_to_access_tokens_by_their_index)
{
test_tokens<0> testTokens = { { "one" }, { "two" }, { "three" } };
Assert::AreEqual("one", testTokens[0].val.c_str());
Assert::AreEqual("two", testTokens[1].val.c_str());
Assert::AreEqual("three", testTokens[2].val.c_str());
}
TEST_METHOD(should_be_able_to_access_tokens_from_a_const_container_by_ther_index)
{
const test_tokens<0> testTokens = { { "one" } };
Assert::AreEqual("one", testTokens[0].val.c_str());
}
};
}}
<commit_msg>rename a test<commit_after>#include "CppUnitTest.h"
#include <string>
#include <vector>
#include <array>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace algo
{
template<class Traits>
class tokens
{
typedef vector<typename Traits::type> token_vector;
token_vector tokens_;
public:
typedef typename token_vector::iterator iterator;
typedef typename token_vector::const_iterator const_iterator;
typedef typename Traits::type token_type;
tokens() {}
explicit tokens(size_t count) : tokens_(count) {}
tokens(std::initializer_list<token_type> init) : tokens_(init) {}
bool empty() const { return tokens_.size() == 0; }
size_t size() const { return tokens_.size(); }
token_type& operator[](size_t i) { return tokens_[i]; };
const token_type& operator[](size_t i) const { return const_cast<tokens&>(*this)[i]; };
iterator begin() { return tokens_.begin(); }
const_iterator begin() const { return tokens_.begin(); }
const_iterator cbegin() const { return tokens_.cbegin(); }
iterator end() { return tokens_.end(); }
const_iterator end() const { return tokens_.end(); }
const_iterator cend() const { return tokens_.cend(); }
void from_string(string s)
{
auto newTokens = Traits::tokenize(s);
tokens_.insert(tokens_.end(), newTokens.begin(), newTokens.end());
}
};
}
namespace algo { namespace spec
{
struct s { string val; };
template<size_t N>
struct test_token_traits
{
typedef s type;
static array<s, N> tokenize(const string&) { return array<s, N>(); }
};
template<size_t N>
using test_tokens = tokens<test_token_traits<N>>;
TEST_CLASS(can_recognize_tokens)
{
public:
TEST_METHOD(should_not_have_any_tokens_when_default_constructed)
{
test_tokens<0> testTokens;
Assert::IsTrue(testTokens.empty());
}
TEST_METHOD(should_recognize_a_token_in_a_string)
{
test_tokens<1> testTokens;
testTokens.from_string("irrelevant");
Assert::AreEqual(1U, testTokens.size());
}
TEST_METHOD(should_recognize_more_than_one_token_in_a_string)
{
test_tokens<3> testTokens;
testTokens.from_string("irrelevant");
Assert::AreEqual(3U, testTokens.size());
}
TEST_METHOD(should_accumulate_tokens_from_successive_strings)
{
test_tokens<2> testTokens(3);
testTokens.from_string("irrelevant");
Assert::AreEqual(5U, testTokens.size());
}
TEST_METHOD(should_be_able_to_enumerate_tokens)
{
test_tokens<0> testTokens(3);
size_t i = 0;
for (s tok : testTokens) { ++i; }
Assert::AreEqual(3U, i);
}
TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_const_container)
{
const test_tokens<0> testTokens(3);
size_t i = 0;
for (const s tok : testTokens) { ++i; }
Assert::AreEqual(3U, i);
}
TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_non_const_container)
{
typedef test_tokens<0>::const_iterator const_iter;
test_tokens<0> testTokens(3);
size_t i = 0;
for (const_iter it = testTokens.cbegin(); it != testTokens.cend(); ++it) { ++i; }
Assert::AreEqual(3U, i);
}
TEST_METHOD(should_be_able_to_access_tokens_by_their_index)
{
test_tokens<0> testTokens = { { "one" }, { "two" }, { "three" } };
Assert::AreEqual("one", testTokens[0].val.c_str());
Assert::AreEqual("two", testTokens[1].val.c_str());
Assert::AreEqual("three", testTokens[2].val.c_str());
}
TEST_METHOD(should_be_able_to_access_tokens_from_a_const_container_by_ther_index)
{
const test_tokens<0> testTokens = { { "one" } };
Assert::AreEqual("one", testTokens[0].val.c_str());
}
};
}}
<|endoftext|>
|
<commit_before>/*
* Copyright 2020 Tom van Dijk
*
* 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 <cassert>
#include <cstring>
#include <queue>
#include <stack>
#include "fpj.hpp"
#include "uintqueue.hpp"
namespace pg {
FPJSolver::FPJSolver(Oink *oink, Game *game) : Solver(oink, game)
{
}
FPJSolver::~FPJSolver()
{
}
/**
* Variation 1: greedy justification
*/
void
FPJSolver::runSeqGreedy()
{
/**
* Allocate and initialize data structures
*/
int *strategy = new int[nodecount()]; // the current strategy
bitset justified(nodecount()); // whether a vertex is justified
bitset distraction(nodecount()); // whether a vertex is won by the opponent
bitset parity(nodecount()); // optimization: precompute the parity of every vertex's priority
for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;
uintqueue Q(nodecount());
/**
* Initialize loop
*/
int cur_parity = parity[0]; // parity of current block
int i = 0; // the current vertex
for (;;) {
/**
* First detect if we are at the end of a block (vertices of same parity)
*/
bool blockended = false;
if (i == nodecount()) {
blockended = true;
} else {
if (disabled[i]) { i++; continue; }
if (parity[i] != cur_parity) blockended = true;
}
if (blockended) {
if (Q.nonempty()) {
/**
* First set as distraction
*/
for (unsigned int n=0; n<Q.size(); n++) distraction[Q[n]] = true;
/**
* We have to reset all justified vertices that are now no longer justified...
*/
while (!Q.empty()) {
const int v = Q.pop();
for (auto curedge = ins(v); *curedge != -1; curedge++) {
const int from = *curedge;
if (justified[from] and (strategy[from] == -1 or strategy[from] == v)) {
#ifndef NDEBUG
if (trace >= 2) logger << "\033[31;1mresetting\033[m " << label_vertex(from) << std::endl;
#endif
justified[from] = false;
distraction[from] = false; // reset it
Q.push(from);
if (from < i) i = from; // afterwards, continue at lowest unjustified vertex
}
}
}
#ifndef NDEBUG
if (trace) logger << "restarting after finding distractions of prio " << priority(i-1) << std::endl;
#endif
iterations++;
}
if (i == nodecount()) break; // in case the last block didn't result in unjustifications
// continue with the new block, update the current parity
cur_parity = parity[i];
}
// if the current vertex is justified, we don't need to check it
if (justified[i]) { i++; continue; }
justified[i] = true;
// compute one step winner of <i> and update the strategy
int onestep_winner, str = -1;
if (owner(i) == 0) {
// see if player Even can go to a vertex currently good for Even
onestep_winner = 1;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 0) {
// good for player Even
onestep_winner = 0;
// and set the strategy
str = to;
break;
}
}
} else {
// see if player Odd can go to a vertex currently good for Odd
onestep_winner = 0;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 1) {
// good for player Odd
onestep_winner = 1;
// and set the strategy
str = to;
break;
}
}
}
strategy[i] = str;
// evaluation stays the same
if (cur_parity != onestep_winner) {
Q.push(i); // add to Q
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified*\033[m " << label_vertex(i);
if (strategy[i] != -1) logger << " => " << label_vertex(strategy[i]);
logger << std::endl;
}
#endif
} else {
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified\033[m " << label_vertex(i);
if (strategy[i] != -1) logger << " => " << label_vertex(strategy[i]);
logger << std::endl;
}
#endif
}
i++;
}
// done
for (int v=0; v<nodecount(); v++) {
if (disabled[v]) continue;
const int winner = parity[v] ^ distraction[v];
oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);
}
// free allocated data structures
delete[] strategy;
logger << "solved with " << iterations << " iterations." << std::endl;
}
void
FPJSolver::runSeq()
{
/**
* Allocate and initialize data structures
*/
int *strategy = new int[nodecount()]; // the current strategy
bitset justified(nodecount()); // whether a vertex is justified
bitset distraction(nodecount()); // whether a vertex is won by the opponent
bitset parity(nodecount()); // optimization: precompute the parity of every vertex's priority
for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;
uintqueue Q(nodecount());
/**
* Initialize loop
*/
int cur_parity = parity[0]; // parity of current block
int i = 0; // the current vertex
int blockstart = 0; // first vertex of the current block
for (;;) {
/**
* First detect if we are at the end of a block (vertices of same parity)
*/
bool blockended = false;
if (i == nodecount()) {
blockended = true;
} else {
if (disabled[i]) { i++; continue; }
if (parity[i] != cur_parity) blockended = true;
}
if (blockended) {
if (Q.nonempty()) {
/**
* First set as justified and distraction
*/
for (unsigned int n=0; n<Q.size(); n++) {
const int v = Q[n];
justified[v] = true;
distraction[v] = true;
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified*\033[m " << label_vertex(v);
if (strategy[v] != -1) logger << " => " << label_vertex(strategy[v]);
logger << std::endl;
}
#endif
}
/**
* We have to reset all justified vertices that are now no longer justified...
*/
while (!Q.empty()) {
const int v = Q.pop();
for (auto curedge = ins(v); *curedge != -1; curedge++) {
const int from = *curedge;
if (justified[from]) {
if (strategy[from] == -1 or strategy[from] == v) {
#ifndef NDEBUG
if (trace >= 2) logger << "\033[31;1mresetting\033[m " << label_vertex(from) << std::endl;
#endif
justified[from] = false; // no longer justified
distraction[from] = false; // reset it
Q.push(from);
if (from < i) i = from; // afterwards, continue at lowest unjustified vertex
}
}
}
}
#ifndef NDEBUG
if (trace) logger << "restarting after finding distractions of prio " << priority(i-1) << std::endl;
#endif
iterations++;
if (i > blockstart) i = blockstart;
} else {
// We now know that the current strategy of all unjustified vertices of the block is justified
for (int v=blockstart; v<i; v++) {
if (!disabled[v] and !justified[v]) {
justified[v] = true;
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified\033[m " << label_vertex(v);
if (strategy[v] != -1) logger << " => " << label_vertex(strategy[v]);
logger << std::endl;
}
#endif
}
}
}
if (i == nodecount()) break; // in case the last block didn't result in unjustifications
// continue with the new block, update the current parity
cur_parity = parity[i];
blockstart = i;
}
// if the current vertex is justified, we don't need to check it
if (justified[i]) {
i++;
continue;
}
// compute one step winner of <i> and update the strategy
int onestep_winner, str = -1;
if (owner(i) == 0) {
// see if player Even can go to a vertex currently good for Even
onestep_winner = 1;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 0) {
// good for player Even
onestep_winner = 0;
// and set the strategy
str = to;
break;
}
}
} else {
// see if player Odd can go to a vertex currently good for Odd
onestep_winner = 0;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 1) {
// good for player Odd
onestep_winner = 1;
// and set the strategy
str = to;
break;
}
}
}
strategy[i] = str;
// evaluation stays the same
if (cur_parity != onestep_winner) {
Q.push(i); // add to the Queue, because all justified predecessors are now invalid
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified*\033[m " << label_vertex(i);
if (strategy[i] != -1) logger << " => " << label_vertex(strategy[i]);
logger << std::endl;
}
#endif
}
i++;
}
// done
for (int v=0; v<nodecount(); v++) {
if (disabled[v]) continue;
const int winner = parity[v] ^ distraction[v];
oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);
}
// free allocated data structures
delete[] strategy;
logger << "solved with " << iterations << " iterations." << std::endl;
}
void
FPJSolver::run()
{
if (greedy) runSeqGreedy();
else runSeq();
}
}
<commit_msg>FPJ: small performance enhancement<commit_after>/*
* Copyright 2020 Tom van Dijk
*
* 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 <cassert>
#include <cstring>
#include <queue>
#include <stack>
#include "fpj.hpp"
#include "uintqueue.hpp"
namespace pg {
FPJSolver::FPJSolver(Oink *oink, Game *game) : Solver(oink, game)
{
}
FPJSolver::~FPJSolver()
{
}
/**
* Variation 1: greedy justification
*/
void
FPJSolver::runSeqGreedy()
{
/**
* Allocate and initialize data structures
*/
int *strategy = new int[nodecount()]; // the current strategy
bitset justified(nodecount()); // whether a vertex is justified
bitset distraction(nodecount()); // whether a vertex is won by the opponent
bitset parity(nodecount()); // optimization: precompute the parity of every vertex's priority
for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;
uintqueue Q(nodecount());
/**
* Initialize loop
*/
bool blockchanged = false; // did the current block change (new distractions)
int cur_parity = parity[0]; // parity of current block
int i = 0; // the current vertex
for (;;) {
/**
* First detect if we are at the end of a block (vertices of same parity)
*/
bool blockended = false;
if (i == nodecount()) {
blockended = true;
} else {
if (disabled[i]) { i++; continue; }
if (parity[i] != cur_parity) blockended = true;
}
if (blockended) {
if (blockchanged) {
/**
* We have to reset all justified vertices that are now no longer justified...
*/
while (!Q.empty()) {
const int v = Q.pop();
for (auto curedge = ins(v); *curedge != -1; curedge++) {
const int from = *curedge;
if (justified[from]) {
if (strategy[from] == -1 or strategy[from] == v) {
#ifndef NDEBUG
if (trace >= 2) logger << "\033[31;1mresetting\033[m " << label_vertex(from) << std::endl;
#endif
justified[from] = false;
distraction[from] = false; // reset it
Q.push(from);
if (from < i) i = from; // afterwards, continue at lowest unjustified vertex
}
}
}
}
#ifndef NDEBUG
if (trace) logger << "restarting after finding distractions of prio " << priority(i-1) << std::endl;
#endif
iterations++;
blockchanged = false;
}
if (i == nodecount()) break; // in case the last block didn't result in unjustifications
// continue with the new block, update the current parity
cur_parity = parity[i];
}
// if the current vertex is justified, we don't need to check it
if (justified[i]) { i++; continue; }
justified[i] = true;
// compute one step winner of <i> and update the strategy
int onestep_winner, str = -1;
if (owner(i) == 0) {
// see if player Even can go to a vertex currently good for Even
onestep_winner = 1;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 0) {
// good for player Even
onestep_winner = 0;
// and set the strategy
str = to;
break;
}
}
} else {
// see if player Odd can go to a vertex currently good for Odd
onestep_winner = 0;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 1) {
// good for player Odd
onestep_winner = 1;
// and set the strategy
str = to;
break;
}
}
}
strategy[i] = str;
// evaluation stays the same
if (cur_parity != onestep_winner) {
Q.push(i); // add to the Queue, because all justified predecessors are now invalid
distraction[i] = true;
blockchanged = true;
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified*\033[m " << label_vertex(i);
if (strategy[i] != -1) logger << " => " << label_vertex(strategy[i]);
logger << std::endl;
}
#endif
} else {
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified\033[m " << label_vertex(i);
if (strategy[i] != -1) logger << " => " << label_vertex(strategy[i]);
logger << std::endl;
}
#endif
}
i++;
}
// done
for (int v=0; v<nodecount(); v++) {
if (disabled[v]) continue;
const int winner = parity[v] ^ distraction[v];
oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);
}
// free allocated data structures
delete[] strategy;
logger << "solved with " << iterations << " iterations." << std::endl;
}
void
FPJSolver::runSeq()
{
/**
* Allocate and initialize data structures
*/
int *strategy = new int[nodecount()]; // the current strategy
bitset justified(nodecount()); // whether a vertex is justified
bitset distraction(nodecount()); // whether a vertex is won by the opponent
bitset parity(nodecount()); // optimization: precompute the parity of every vertex's priority
for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;
uintqueue Q(nodecount());
/**
* Initialize loop
*/
bool blockchanged = false; // did the current block change (new distractions)
int cur_parity = parity[0]; // parity of current block
int i = 0; // the current vertex
int blockstart = 0; // first vertex of the current block
for (;;) {
/**
* First detect if we are at the end of a block (vertices of same parity)
*/
bool blockended = false;
if (i == nodecount()) {
blockended = true;
} else {
if (disabled[i]) { i++; continue; }
if (parity[i] != cur_parity) blockended = true;
}
if (blockended) {
if (blockchanged) {
/**
* We have to reset all justified vertices that are now no longer justified...
*/
while (!Q.empty()) {
const int v = Q.pop();
for (auto curedge = ins(v); *curedge != -1; curedge++) {
const int from = *curedge;
if (disabled[from]) continue;
if (justified[from]) {
if (strategy[from] == -1 or strategy[from] == v) {
#ifndef NDEBUG
if (trace >= 2) logger << "\033[31;1mresetting\033[m " << label_vertex(from) << std::endl;
#endif
justified[from] = false;
distraction[from] = false; // reset it
Q.push(from);
if (from < i) i = from; // afterwards, continue at lowest unjustified vertex
}
}
}
}
#ifndef NDEBUG
if (trace) logger << "restarting after finding distractions of prio " << priority(i-1) << std::endl;
#endif
iterations++;
blockchanged = false;
if (i > blockstart) i = blockstart;
} else {
// We now know that the current strategy of all unjustified vertices of the block is justified
for (int v=blockstart; v<i; v++) {
if (!disabled[v] and !justified[v]) {
justified[v] = true;
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified\033[m " << label_vertex(v);
if (strategy[v] != -1) logger << " => " << label_vertex(strategy[v]);
logger << std::endl;
}
#endif
}
}
}
if (i == nodecount()) break; // in case the last block didn't result in unjustifications
// continue with the new block, update the current parity
cur_parity = parity[i];
blockstart = i;
}
// if the current vertex is justified, we don't need to check it
if (justified[i]) {
i++;
continue;
}
// compute one step winner of <i> and update the strategy
int onestep_winner, str = -1;
if (owner(i) == 0) {
// see if player Even can go to a vertex currently good for Even
onestep_winner = 1;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 0) {
// good for player Even
onestep_winner = 0;
// and set the strategy
str = to;
break;
}
}
} else {
// see if player Odd can go to a vertex currently good for Odd
onestep_winner = 0;
for (auto curedge = outs(i); *curedge != -1; curedge++) {
int to = *curedge;
if (disabled[to]) continue;
const int winner_to = parity[to] ^ distraction[to];
if (winner_to == 1) {
// good for player Odd
onestep_winner = 1;
// and set the strategy
str = to;
break;
}
}
}
strategy[i] = str;
// evaluation stays the same
if (cur_parity != onestep_winner) {
Q.push(i); // add to the Queue, because all justified predecessors are now invalid
distraction[i] = true;
justified[i] = true;
blockchanged = true;
#ifndef NDEBUG
if (trace >= 2) {
logger << "\033[38;5;165;1mjustified*\033[m " << label_vertex(i);
if (strategy[i] != -1) logger << " => " << label_vertex(strategy[i]);
logger << std::endl;
}
#endif
}
i++;
}
// done
for (int v=0; v<nodecount(); v++) {
if (disabled[v]) continue;
const int winner = parity[v] ^ distraction[v];
oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);
}
// free allocated data structures
delete[] strategy;
logger << "solved with " << iterations << " iterations." << std::endl;
}
void
FPJSolver::run()
{
if (greedy) runSeqGreedy();
else runSeq();
}
}
<|endoftext|>
|
<commit_before>///
/// @file CpuInfo.cpp
/// @brief Get the CPUs cache sizes in bytes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/CpuInfo.hpp>
#include <cstddef>
#include <exception>
#include <vector>
#include <string>
#if defined(__APPLE__)
#if !defined(__has_include)
#define APPLE_SYSCTL
#elif __has_include(<sys/types.h>) && \
__has_include(<sys/sysctl.h>)
#define APPLE_SYSCTL
#endif
#endif
#if defined(_WIN32)
#include <windows.h>
#elif defined(APPLE_SYSCTL)
#include <sys/types.h>
#include <sys/sysctl.h>
#else // all other OSes
#include <fstream>
#include <sstream>
using namespace std;
namespace {
string getString(const string& filename)
{
ifstream file(filename);
string str;
if (file)
{
// https://stackoverflow.com/a/3177560/363778
stringstream trimmer;
trimmer << file.rdbuf();
trimmer >> str;
}
return str;
}
size_t getValue(const string& filename)
{
string str = getString(filename);
size_t val = stol(str);
if (!str.empty())
{
// Last character may be:
// 'K' = kilobytes
// 'M' = megabytes
// 'G' = gigabytes
if (str.back() == 'K')
val *= 1024;
if (str.back() == 'M')
val *= 1024 * 1024;
if (str.back() == 'G')
val *= 1024 * 1024 * 1024;
}
return val;
}
} // namespace
#endif
using namespace std;
namespace primesieve {
CpuInfo::CpuInfo()
: l1CacheSize_(0),
l2CacheSize_(0),
privateL2Cache_(false)
{
try
{
initCache();
if (!hasL1Cache() &&
l1CacheSize_ > 0)
{
string msg = "invalid L1 cache size: " + to_string(l1CacheSize_);
errors_.push_back(msg);
}
if (!hasL2Cache() &&
l2CacheSize_ > 0)
{
string msg = "invalid L2 cache size: " + to_string(l2CacheSize_);
errors_.push_back(msg);
}
}
catch (exception& e)
{
errors_.push_back(e.what());
}
}
size_t CpuInfo::l1CacheSize() const
{
return l1CacheSize_;
}
size_t CpuInfo::l2CacheSize() const
{
return l2CacheSize_;
}
bool CpuInfo::privateL2Cache() const
{
return privateL2Cache_;
}
vector<string> CpuInfo::getErrors() const
{
return errors_;
}
bool CpuInfo::hasL1Cache() const
{
return l1CacheSize_ >= (1 << 12) &&
l1CacheSize_ <= (1ull << 40);
}
bool CpuInfo::hasL2Cache() const
{
return l2CacheSize_ >= (1 << 12) &&
l2CacheSize_ <= (1ull << 40);
}
#if defined(APPLE_SYSCTL)
void CpuInfo::initCache()
{
size_t l1Length = sizeof(l1CacheSize_);
size_t l2Length = sizeof(l2CacheSize_);
sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0);
sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0);
size_t size = 0;
if (!sysctlbyname("hw.cacheconfig", NULL, &size, NULL, 0))
{
size_t n = size / sizeof(size);
vector<size_t> cacheconfig(n);
if (cacheconfig.size() > 2)
{
// https://developer.apple.com/library/content/releasenotes/Performance/RN-AffinityAPI/index.html
sysctlbyname("hw.cacheconfig" , &cacheconfig[0], &size, NULL, 0);
size_t l2CpuSharing = cacheconfig[2];
if (l2CpuSharing <= 1)
privateL2Cache_ = true;
else
{
size_t logicalcpu = 1;
size = sizeof(size);
sysctlbyname("hw.logicalcpu", &logicalcpu, &size, NULL, 0);
logicalcpu = max<size_t>(1, logicalcpu);
size_t physicalcpu = 1;
size = sizeof(size);
sysctlbyname("hw.physicalcpu", &physicalcpu, &size, NULL, 0);
physicalcpu = max<size_t>(1, physicalcpu);
if (l2CpuSharing <= logicalcpu / physicalcpu)
privateL2Cache_ = true;
}
}
}
}
#elif defined(_WIN32)
void CpuInfo::initCache()
{
typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
if (!glpi)
return;
DWORD bytes = 0;
glpi(0, &bytes);
if (!bytes)
return;
size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);
if (!glpi(&info[0], &bytes))
return;
for (size_t i = 0; i < size; i++)
{
if (info[i].Relationship == RelationCache &&
(info[i].Cache.Type == CacheData ||
info[i].Cache.Type == CacheUnified))
{
if (info[i].Cache.Level == 1)
l1CacheSize_ = info[i].Cache.Size;
if (info[i].Cache.Level == 2)
l2CacheSize_ = info[i].Cache.Size;
// If the CPU has an L3 cache we assume the L2 cache
// is private. This is more reliable than using
// GetLogicalProcessorInformationEx() and
// GROUP_AFFINITY.Mask
if (info[i].Cache.Level == 3)
privateL2Cache_ = true;
}
}
}
#else
/// This works on Linux and Android. We also use this
/// for all unknown OSes, it might work.
///
void CpuInfo::initCache()
{
for (int i = 0; i <= 3; i++)
{
string filename = "/sys/devices/system/cpu/cpu0/cache/index" + to_string(i);
string threadSiblingsList = "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list";
string cacheLevel = filename + "/level";
string cacheSize = filename + "/size";
string sharedCpuList = filename + "/shared_cpu_list";
string cacheType = filename + "/type";
size_t level = getValue(cacheLevel);
string type = getString(cacheType);
if (level == 1 &&
(type == "Data" ||
type == "Unified"))
{
l1CacheSize_ = getValue(cacheSize);
}
if (level == 2 &&
(type == "Data" ||
type == "Unified"))
{
l2CacheSize_ = getValue(cacheSize);
sharedCpuList = getString(sharedCpuList);
threadSiblingsList = getString(threadSiblingsList);
// https://lwn.net/Articles/254445/
if (sharedCpuList.empty())
privateL2Cache_ = true;
else if (sharedCpuList == threadSiblingsList)
privateL2Cache_ = true;
}
}
}
#endif
/// Singleton
const CpuInfo cpuInfo;
} // namespace
<commit_msg>Add Windows safety check<commit_after>///
/// @file CpuInfo.cpp
/// @brief Get the CPUs cache sizes in bytes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/CpuInfo.hpp>
#include <cstddef>
#include <exception>
#include <vector>
#include <string>
#if defined(__APPLE__)
#if !defined(__has_include)
#define APPLE_SYSCTL
#elif __has_include(<sys/types.h>) && \
__has_include(<sys/sysctl.h>)
#define APPLE_SYSCTL
#endif
#endif
#if defined(_WIN32)
#include <windows.h>
#elif defined(APPLE_SYSCTL)
#include <sys/types.h>
#include <sys/sysctl.h>
#else // all other OSes
#include <fstream>
#include <sstream>
using namespace std;
namespace {
string getString(const string& filename)
{
ifstream file(filename);
string str;
if (file)
{
// https://stackoverflow.com/a/3177560/363778
stringstream trimmer;
trimmer << file.rdbuf();
trimmer >> str;
}
return str;
}
size_t getValue(const string& filename)
{
string str = getString(filename);
size_t val = stol(str);
if (!str.empty())
{
// Last character may be:
// 'K' = kilobytes
// 'M' = megabytes
// 'G' = gigabytes
if (str.back() == 'K')
val *= 1024;
if (str.back() == 'M')
val *= 1024 * 1024;
if (str.back() == 'G')
val *= 1024 * 1024 * 1024;
}
return val;
}
} // namespace
#endif
using namespace std;
namespace primesieve {
CpuInfo::CpuInfo()
: l1CacheSize_(0),
l2CacheSize_(0),
privateL2Cache_(false)
{
try
{
initCache();
if (!hasL1Cache() &&
l1CacheSize_ > 0)
{
string msg = "invalid L1 cache size: " + to_string(l1CacheSize_);
errors_.push_back(msg);
}
if (!hasL2Cache() &&
l2CacheSize_ > 0)
{
string msg = "invalid L2 cache size: " + to_string(l2CacheSize_);
errors_.push_back(msg);
}
}
catch (exception& e)
{
errors_.push_back(e.what());
}
}
size_t CpuInfo::l1CacheSize() const
{
return l1CacheSize_;
}
size_t CpuInfo::l2CacheSize() const
{
return l2CacheSize_;
}
bool CpuInfo::privateL2Cache() const
{
return privateL2Cache_;
}
vector<string> CpuInfo::getErrors() const
{
return errors_;
}
bool CpuInfo::hasL1Cache() const
{
return l1CacheSize_ >= (1 << 12) &&
l1CacheSize_ <= (1ull << 40);
}
bool CpuInfo::hasL2Cache() const
{
return l2CacheSize_ >= (1 << 12) &&
l2CacheSize_ <= (1ull << 40);
}
#if defined(APPLE_SYSCTL)
void CpuInfo::initCache()
{
size_t l1Length = sizeof(l1CacheSize_);
size_t l2Length = sizeof(l2CacheSize_);
sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0);
sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0);
size_t size = 0;
if (!sysctlbyname("hw.cacheconfig", NULL, &size, NULL, 0))
{
size_t n = size / sizeof(size);
vector<size_t> cacheconfig(n);
if (cacheconfig.size() > 2)
{
// https://developer.apple.com/library/content/releasenotes/Performance/RN-AffinityAPI/index.html
sysctlbyname("hw.cacheconfig" , &cacheconfig[0], &size, NULL, 0);
size_t l2CpuSharing = cacheconfig[2];
if (l2CpuSharing <= 1)
privateL2Cache_ = true;
else
{
size_t logicalcpu = 1;
size = sizeof(size);
sysctlbyname("hw.logicalcpu", &logicalcpu, &size, NULL, 0);
logicalcpu = max<size_t>(1, logicalcpu);
size_t physicalcpu = 1;
size = sizeof(size);
sysctlbyname("hw.physicalcpu", &physicalcpu, &size, NULL, 0);
physicalcpu = max<size_t>(1, physicalcpu);
if (l2CpuSharing <= logicalcpu / physicalcpu)
privateL2Cache_ = true;
}
}
}
}
#elif defined(_WIN32)
void CpuInfo::initCache()
{
typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
if (!glpi)
return;
DWORD bytes = 0;
glpi(0, &bytes);
if (!bytes)
return;
size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);
if (!glpi(&info[0], &bytes))
return;
for (size_t i = 0; i < size; i++)
{
if (info[i].Relationship == RelationCache &&
(info[i].Cache.Type == CacheData ||
info[i].Cache.Type == CacheUnified))
{
if (info[i].Cache.Level == 1)
l1CacheSize_ = info[i].Cache.Size;
if (info[i].Cache.Level == 2)
l2CacheSize_ = info[i].Cache.Size;
// If the CPU has an L3 cache we assume the L2 cache
// is private. This is more reliable than using
// GetLogicalProcessorInformationEx() and
// GROUP_AFFINITY.Mask
if (info[i].Cache.Level == 3 &&
info[i].Cache.Size > 0)
privateL2Cache_ = true;
}
}
}
#else
/// This works on Linux and Android. We also use this
/// for all unknown OSes, it might work.
///
void CpuInfo::initCache()
{
for (int i = 0; i <= 3; i++)
{
string filename = "/sys/devices/system/cpu/cpu0/cache/index" + to_string(i);
string threadSiblingsList = "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list";
string cacheLevel = filename + "/level";
string cacheSize = filename + "/size";
string sharedCpuList = filename + "/shared_cpu_list";
string cacheType = filename + "/type";
size_t level = getValue(cacheLevel);
string type = getString(cacheType);
if (level == 1 &&
(type == "Data" ||
type == "Unified"))
{
l1CacheSize_ = getValue(cacheSize);
}
if (level == 2 &&
(type == "Data" ||
type == "Unified"))
{
l2CacheSize_ = getValue(cacheSize);
sharedCpuList = getString(sharedCpuList);
threadSiblingsList = getString(threadSiblingsList);
// https://lwn.net/Articles/254445/
if (sharedCpuList.empty())
privateL2Cache_ = true;
else if (sharedCpuList == threadSiblingsList)
privateL2Cache_ = true;
}
}
}
#endif
/// Singleton
const CpuInfo cpuInfo;
} // namespace
<|endoftext|>
|
<commit_before>// RenderObject.cpp
// nativeGraphics
#include "RenderObject.h"
#include "glsl_helper.h"
#include "obj_parser.h"
#include "transform.h"
#include "common.h"
#include "log.h"
RenderObject::RenderObject(const char *objFilename, const char *vertexShaderFilename, const char *fragmentShaderFilename) {
// Parse obj file into an interleaved float buffer
GLfloat * interleavedBuffer = getInterleavedBuffer((char *)resourceCallback(objFilename), numVertices, true, true);
glGenBuffers(1, &gVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, numVertices * (3+3+2) * sizeof(float), interleavedBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
checkGlError("VertexBuffer Generation");
free(interleavedBuffer);
// Compile and link shader program
gProgram = createProgram((char *)resourceCallback(vertexShaderFilename), (char *)resourceCallback(fragmentShaderFilename));
// Get uniform and attrib locations
gmvMatrixHandle = glGetUniformLocation(gProgram, "u_MVMatrix");
gmvpMatrixHandle = glGetUniformLocation(gProgram, "u_MVPMatrix");
gvPositionHandle = glGetAttribLocation(gProgram, "a_Position");
gvNormals = glGetAttribLocation(gProgram, "a_Normal");
gvTexCoords = glGetAttribLocation(gProgram, "a_TexCoordinate");
textureUniform = glGetUniformLocation(gProgram, "u_Texture");
checkGlError("glGetAttribLocation");
}
void RenderObject::AddTexture(const char *textureFilename) {
// Load textures
GLubyte *imageData = (GLubyte *)resourceCallback(textureFilename); // TODO: Free this
GLuint texName; // TODO
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); // TODO: hardcoded size
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
free(imageData);
checkGlError("AddTexture");
textures.push_back(texName);
}
void RenderObject::RenderFrame() {
if(numVertices == 0) {
LOGE("Setup not yet called.");
return;
}
glUseProgram(gProgram);
checkGlError("glUseProgram");
// Matrices setup
GLfloat* mv_Matrix = (GLfloat*)mvMatrix();
GLfloat* mvp_Matrix = (GLfloat*)mvpMatrix();
glUniformMatrix4fv(gmvMatrixHandle, 1, GL_FALSE, mv_Matrix);
glUniformMatrix4fv(gmvpMatrixHandle, 1, GL_FALSE, mvp_Matrix);
checkGlError("glUniformMatrix4fv");
delete mv_Matrix;
delete mvp_Matrix;
glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);
// Vertices
glEnableVertexAttribArray(gvPositionHandle);
glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) 0);
checkGlError("gvPositionHandle");
// Normals
glEnableVertexAttribArray(gvNormals);
glVertexAttribPointer(gvNormals, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) (3 * sizeof(GLfloat)));
checkGlError("gvNormals");
//Textures
glEnableVertexAttribArray(gvTexCoords);
glVertexAttribPointer(gvTexCoords, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid *) (6 * sizeof(GLfloat)));
checkGlError("gvTexCoords");
if (textures.size() > 0) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glUniform1i(textureUniform, 0);
checkGlError("texture");
}
glDrawArrays(GL_TRIANGLES, 0, numVertices);
checkGlError("glDrawArrays");
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
<commit_msg>Minor bug fix.<commit_after>// RenderObject.cpp
// nativeGraphics
#include "RenderObject.h"
#include "glsl_helper.h"
#include "obj_parser.h"
#include "transform.h"
#include "common.h"
#include "log.h"
RenderObject::RenderObject(const char *objFilename, const char *vertexShaderFilename, const char *fragmentShaderFilename) {
// Parse obj file into an interleaved float buffer
GLfloat * interleavedBuffer = getInterleavedBuffer((char *)resourceCallback(objFilename), numVertices, true, true);
glGenBuffers(1, &gVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, numVertices * (3+3+2) * sizeof(float), interleavedBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
checkGlError("VertexBuffer Generation");
free(interleavedBuffer);
// Compile and link shader program
gProgram = createProgram((char *)resourceCallback(vertexShaderFilename), (char *)resourceCallback(fragmentShaderFilename));
// Get uniform and attrib locations
gmvMatrixHandle = glGetUniformLocation(gProgram, "u_MVMatrix");
gmvpMatrixHandle = glGetUniformLocation(gProgram, "u_MVPMatrix");
gvPositionHandle = glGetAttribLocation(gProgram, "a_Position");
gvNormals = glGetAttribLocation(gProgram, "a_Normal");
gvTexCoords = glGetAttribLocation(gProgram, "a_TexCoordinate");
textureUniform = glGetUniformLocation(gProgram, "u_Texture");
checkGlError("glGetAttribLocation");
}
void RenderObject::AddTexture(const char *textureFilename) {
// Load textures
GLubyte *imageData = (GLubyte *)resourceCallback(textureFilename);
GLuint texName; // TODO
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); // TODO: hardcoded size
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
free(imageData);
checkGlError("AddTexture");
textures.push_back(texName);
}
void RenderObject::RenderFrame() {
if(numVertices == 0) {
LOGE("Setup not yet called.");
return;
}
glUseProgram(gProgram);
checkGlError("glUseProgram");
// Matrices setup
GLfloat* mv_Matrix = (GLfloat*)mvMatrix();
GLfloat* mvp_Matrix = (GLfloat*)mvpMatrix();
glUniformMatrix4fv(gmvMatrixHandle, 1, GL_FALSE, mv_Matrix);
glUniformMatrix4fv(gmvpMatrixHandle, 1, GL_FALSE, mvp_Matrix);
checkGlError("glUniformMatrix4fv");
delete mv_Matrix;
delete mvp_Matrix;
glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);
// Vertices
glEnableVertexAttribArray(gvPositionHandle);
glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) 0);
checkGlError("gvPositionHandle");
// Normals
glEnableVertexAttribArray(gvNormals);
glVertexAttribPointer(gvNormals, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) (3 * sizeof(GLfloat)));
checkGlError("gvNormals");
//Textures
if(textures.size() > 0) {
glEnableVertexAttribArray(gvTexCoords);
glVertexAttribPointer(gvTexCoords, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid *) (6 * sizeof(GLfloat)));
checkGlError("gvTexCoords");
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glUniform1i(textureUniform, 0);
checkGlError("texture");
}
glDrawArrays(GL_TRIANGLES, 0, numVertices);
checkGlError("glDrawArrays");
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.