text stringlengths 54 60.6k |
|---|
<commit_before>#include "stdafx.h"
#include "parser.hpp"
#include "tiny_obj_loader.h"
#include "matrix.hpp"
#include "geometry.hpp"
#include "curve.hpp"
#include "film.hpp"
#include "draw.hpp"
#include "profiler.hpp"
using namespace renderer;
using json = nlohmann::json;
void SDLExit(const char *msg)
{
printf("%s: %s\n", msg, SDL_GetError());
SDL_Quit();
exit(1);
}
//https://www.opengl.org/wiki/Tutorial1:_Creating_a_Cross_Platform_OpenGL_3.2_Context_in_SDL_(C_/_SDL)
int main(int argc, char *argv[])
{
SDL_Window * win = nullptr;
SDL_Renderer * rendererSDL = nullptr;
int width = 512, height = 512;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
SDLExit("Unable to initialize SDL");
checkSDLError(__LINE__);//on Win7 would cause a ERROR about SHCore.dll, just ignore it.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
checkSDLError(__LINE__);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
checkSDLError(__LINE__);
json config = readJson("config.json");
width = config["width"], height = config["height"];
std::string title = config["title"];
win = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if (!win)
SDLExit("Unable to create window");
SDL_GLContext glContext = SDL_GL_CreateContext(win);
checkSDLError(__LINE__);
SDLFilm film(width, height);
SceneParser parser;
SceneDesc desc = parser.parse(config);
desc.setFilm(&film);
desc.init();
SDL_SetWindowSize(win, desc.width, desc.height);
rendererSDL = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
SDL_Texture* texture = SDL_CreateTexture(rendererSDL, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, desc.width, desc.height);
checkSDLError(__LINE__);
film.texture = texture;
double angle = 0;
Renderer renderer(desc);
SDL_Point screenCenter = { width / 2, height / 2 };
SDL_RendererFlip flip = SDL_FLIP_NONE;
renderer.beginAsyncRender(desc);
while (1) {
SDL_Event e;
if (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
break;
}
}
SDL_Rect& updatedRect = static_cast<SDLFilm*>(desc.film)->lockRect;
renderer.getRenderRect(desc, &updatedRect.x, &updatedRect.y, &updatedRect.w, &updatedRect.h);
desc.film->beforeSet();
for (int x = updatedRect.x; x < updatedRect.x + updatedRect.w; x++) {
int _p = updatedRect.y * desc.width + x;
Color& c = renderer.colorArray[_p];
desc.film->set(x, updatedRect.y, c.rInt(), c.gInt(), c.bInt());
}
desc.film->afterSet();
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
int ret = SDL_RenderCopyEx(rendererSDL, texture, &updatedRect, &updatedRect, angle, &screenCenter, flip);
if (ret == -1)
SDLExit("SDL_RenderCopy failed");
SDL_RenderPresent(rendererSDL);
SDL_Delay(1);
}
renderer.endAsyncRender();
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(rendererSDL);
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
/*
Render Spline
int main(int argc, char ** argv) {
Parser parser;
//parser.parseFromFile("config.json");
std::vector<Point2dF> points = {
{-1.0f, 0.0f},
{-0.5f, 0.5f},
{0.5f, -0.5f},
{1.0f, 0.0f}
};
Spline spline;
spline.setOrder(3);
spline.setCtrlPoints(points);
spline.initSplineParam();
cil::CImg<unsigned char> img(500, 500, 1, 3);
for (int i = 0; i < img.width(); i++)
for (int j = 0; j < img.width(); j++)
img.atXYZC(i, j, 0, 0) = img.atXYZC(i, j, 0, 2) = img.atXYZC(i, j, 0, 2) = 0;
Point2dF result;
for (float t = 0; t < 1.0f; t += 0.01f) {
spline.interpolate(&result, t);
printf("%f,%f\n", result.x, result.y);
int x = int(((result.x + 1) / 2.f) *500);
int y = int((1.0f - ((result.y+1) /2.f)) * 500);
//img.atXYZC(x, y, 0, 0) = 255;
}
ImageFilm film(img.width(), img.height(), &img);
DrawPen pen;
pen.drawline(&film, 100, 100, 400, 300, Color(255, 0, 0));
pen.drawline(&film, 0, 100, 400, 300, Color(0, 255, 0));
img.display("");
return 0;
}
*/<commit_msg>no message<commit_after>#include "stdafx.h"
#include "parser.hpp"
#include "tiny_obj_loader.h"
#include "matrix.hpp"
#include "geometry.hpp"
#include "curve.hpp"
#include "film.hpp"
#include "draw.hpp"
#include "profiler.hpp"
using namespace renderer;
using json = nlohmann::json;
void SDLExit(const char *msg)
{
printf("%s: %s\n", msg, SDL_GetError());
SDL_Quit();
exit(1);
}
//https://www.opengl.org/wiki/Tutorial1:_Creating_a_Cross_Platform_OpenGL_3.2_Context_in_SDL_(C_/_SDL)
int main(int argc, char *argv[])
{
SDL_Window * win = nullptr;
SDL_Renderer * rendererSDL = nullptr;
int width = 512, height = 512;
if (SDL_Init(SDL_INIT_VIDEO) < 0)
SDLExit("Unable to initialize SDL");
checkSDLError(__LINE__);//on Win7 would cause a ERROR about SHCore.dll, just ignore it.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
checkSDLError(__LINE__);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
checkSDLError(__LINE__);
json config = readJson("config.json");
width = config["width"], height = config["height"];
std::string title = config["title"];
win = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if (!win)
SDLExit("Unable to create window");
SDL_GLContext glContext = SDL_GL_CreateContext(win);
checkSDLError(__LINE__);
SDLFilm film(width, height);
SceneParser parser;
SceneDesc desc = parser.parse(config);
desc.setFilm(&film);
desc.init();
SDL_SetWindowSize(win, desc.width, desc.height);
rendererSDL = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
SDL_Texture* texture = SDL_CreateTexture(rendererSDL, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, desc.width, desc.height);
checkSDLError(__LINE__);
film.texture = texture;
Renderer renderer(desc);
double angle = 0;
SDL_Point screenCenter = { width / 2, height / 2 };
SDL_RendererFlip flip = SDL_FLIP_NONE;
renderer.beginAsyncRender(desc);
while (1) {
SDL_Event e;
if (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
break;
}
}
SDL_Rect& updatedRect = static_cast<SDLFilm*>(desc.film)->lockRect;
renderer.getRenderRect(desc, &updatedRect.x, &updatedRect.y, &updatedRect.w, &updatedRect.h);
desc.film->beforeSet();
for (int x = updatedRect.x; x < updatedRect.x + updatedRect.w; x++) {
int _p = updatedRect.y * desc.width + x;
Color& c = renderer.colorArray[_p];
desc.film->set(x, updatedRect.y, c.rInt(), c.gInt(), c.bInt());
}
desc.film->afterSet();
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
int ret = SDL_RenderCopyEx(rendererSDL, texture, &updatedRect, &updatedRect, angle, &screenCenter, flip);
if (ret == -1)
SDLExit("SDL_RenderCopy failed");
SDL_RenderPresent(rendererSDL);
SDL_Delay(1);
}
renderer.endAsyncRender();
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(rendererSDL);
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
/*
Render Spline
int main(int argc, char ** argv) {
Parser parser;
//parser.parseFromFile("config.json");
std::vector<Point2dF> points = {
{-1.0f, 0.0f},
{-0.5f, 0.5f},
{0.5f, -0.5f},
{1.0f, 0.0f}
};
Spline spline;
spline.setOrder(3);
spline.setCtrlPoints(points);
spline.initSplineParam();
cil::CImg<unsigned char> img(500, 500, 1, 3);
for (int i = 0; i < img.width(); i++)
for (int j = 0; j < img.width(); j++)
img.atXYZC(i, j, 0, 0) = img.atXYZC(i, j, 0, 2) = img.atXYZC(i, j, 0, 2) = 0;
Point2dF result;
for (float t = 0; t < 1.0f; t += 0.01f) {
spline.interpolate(&result, t);
printf("%f,%f\n", result.x, result.y);
int x = int(((result.x + 1) / 2.f) *500);
int y = int((1.0f - ((result.y+1) /2.f)) * 500);
//img.atXYZC(x, y, 0, 0) = 255;
}
ImageFilm film(img.width(), img.height(), &img);
DrawPen pen;
pen.drawline(&film, 100, 100, 400, 300, Color(255, 0, 0));
pen.drawline(&film, 0, 100, 400, 300, Color(0, 255, 0));
img.display("");
return 0;
}
*/<|endoftext|> |
<commit_before>
// This file is part of node-lmdb, the Node.js binding for lmdb
// Copyright (c) 2013 Timur Kristóf
// Licensed to you under the terms of the MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "node-lmdb.h"
#include <string.h>
#include <stdio.h>
void setupExportMisc(Handle<Object> exports) {
Local<Object> versionObj = Nan::New<Object>();
int major, minor, patch;
char *str = mdb_version(&major, &minor, &patch);
versionObj->Set(Nan::New<String>("versionString").ToLocalChecked(), Nan::New<String>(str).ToLocalChecked());
versionObj->Set(Nan::New<String>("major").ToLocalChecked(), Nan::New<Integer>(major));
versionObj->Set(Nan::New<String>("minor").ToLocalChecked(), Nan::New<Integer>(minor));
versionObj->Set(Nan::New<String>("patch").ToLocalChecked(), Nan::New<Integer>(patch));
exports->Set(Nan::New<String>("version").ToLocalChecked(), versionObj);
}
void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Local<Object> options) {
Local<Value> opt = options->Get(Nan::New<String>(name).ToLocalChecked());
if (opt->IsBoolean() ? opt->BooleanValue() : defaultValue) {
*flags |= flag;
}
}
argtokey_callback_t argToKey(const Local<Value> &val, MDB_val &key, bool keyIsUint32) {
// Check key type
if (keyIsUint32 && !val->IsUint32()) {
Nan::ThrowError("Invalid key. keyIsUint32 specified on the database, but the given key was not an unsigned 32-bit integer");
return nullptr;
}
if (!keyIsUint32 && !val->IsString()) {
Nan::ThrowError("Invalid key. String key expected, because keyIsUint32 isn't specified on the database.");
return nullptr;
}
// Handle uint32_t key
if (keyIsUint32) {
uint32_t *v = new uint32_t;
*v = val->Uint32Value();
key.mv_size = sizeof(uint32_t);
key.mv_data = v;
return ([](MDB_val &key) -> void {
delete (uint32_t*)key.mv_data;
});
}
// Handle string key
CustomExternalStringResource::writeTo(val->ToString(), &key);
return ([](MDB_val &key) -> void {
delete[] (uint16_t*)key.mv_data;
});
return nullptr;
}
Local<Value> keyToHandle(MDB_val &key, bool keyIsUint32) {
if (keyIsUint32) {
return Nan::New<Integer>(*((uint32_t*)key.mv_data));
}
else {
return valToString(key);
}
}
Local<Value> valToString(MDB_val &data) {
auto resource = new CustomExternalStringResource(&data);
auto str = Nan::New<v8::String>(resource);
return str.ToLocalChecked();
}
Local<Value> valToBinary(MDB_val &data) {
// FIXME: It'd be better not to copy buffers, but I'm not sure
// about the ownership semantics of MDB_val, so let' be safe.
return Nan::CopyBuffer(
(char*)data.mv_data,
data.mv_size
).ToLocalChecked();
}
Local<Value> valToNumber(MDB_val &data) {
return Nan::New<Number>(*((double*)data.mv_data));
}
Local<Value> valToBoolean(MDB_val &data) {
return Nan::New<Boolean>(*((bool*)data.mv_data));
}
void consoleLog(const char *msg) {
Local<String> str = Nan::New("console.log('").ToLocalChecked();
str = String::Concat(str, Nan::New<String>(msg).ToLocalChecked());
str = String::Concat(str, Nan::New("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLog(Local<Value> val) {
Local<String> str = Nan::New<String>("console.log('").ToLocalChecked();
str = String::Concat(str, val->ToString());
str = String::Concat(str, Nan::New<String>("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLogN(int n) {
char c[20];
memset(c, 0, 20 * sizeof(char));
sprintf(c, "%d", n);
consoleLog(c);
}
/*
Writing string to LMDB.
Making LMDB compatible with other languages by converting strings to UTF-8.
Alas, this means no zero-copy semantics because strings are UTF-16 in Javascript.
*/
void CustomExternalStringResource::writeTo(Handle<String> str, MDB_val *val) {
String::Utf8Value utf8(str);
char *inp = *utf8;
int len = strlen(inp);
char *d = new char[len];
strcpy(d, inp);
val->mv_data = d;
val->mv_size = len;
}
/*
Reading string from LMDB.
It will be utf-8 encoded, so decoding here into utf-16.
*/
CustomExternalStringResource::CustomExternalStringResource(MDB_val *val) {
Local<String> str = String::New((char*)val->mv_data);
int len = str->Length();
uint16_t *d = new uint16_t[len];
str->Write(d);
d[len-1] = 0;
this->d = d;
this->l = len;
}
CustomExternalStringResource::~CustomExternalStringResource() {
// TODO: alter this if zero-copy semantics is reintroduced above
delete [] d;
}
void CustomExternalStringResource::Dispose() {
// No need to do anything, the data is owned by LMDB, not us
// But actually need to delete the string resource itself:
// the docs say that "The default implementation will use the delete operator."
// while initially I thought this means using delete on the string,
// apparently they meant just calling the destructor of this class.
delete this;
}
const uint16_t *CustomExternalStringResource::data() const {
return this->d;
}
size_t CustomExternalStringResource::length() const {
return this->l;
}
<commit_msg>Prepend 0 correctly?<commit_after>
// This file is part of node-lmdb, the Node.js binding for lmdb
// Copyright (c) 2013 Timur Kristóf
// Licensed to you under the terms of the MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "node-lmdb.h"
#include <string.h>
#include <stdio.h>
void setupExportMisc(Handle<Object> exports) {
Local<Object> versionObj = Nan::New<Object>();
int major, minor, patch;
char *str = mdb_version(&major, &minor, &patch);
versionObj->Set(Nan::New<String>("versionString").ToLocalChecked(), Nan::New<String>(str).ToLocalChecked());
versionObj->Set(Nan::New<String>("major").ToLocalChecked(), Nan::New<Integer>(major));
versionObj->Set(Nan::New<String>("minor").ToLocalChecked(), Nan::New<Integer>(minor));
versionObj->Set(Nan::New<String>("patch").ToLocalChecked(), Nan::New<Integer>(patch));
exports->Set(Nan::New<String>("version").ToLocalChecked(), versionObj);
}
void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Local<Object> options) {
Local<Value> opt = options->Get(Nan::New<String>(name).ToLocalChecked());
if (opt->IsBoolean() ? opt->BooleanValue() : defaultValue) {
*flags |= flag;
}
}
argtokey_callback_t argToKey(const Local<Value> &val, MDB_val &key, bool keyIsUint32) {
// Check key type
if (keyIsUint32 && !val->IsUint32()) {
Nan::ThrowError("Invalid key. keyIsUint32 specified on the database, but the given key was not an unsigned 32-bit integer");
return nullptr;
}
if (!keyIsUint32 && !val->IsString()) {
Nan::ThrowError("Invalid key. String key expected, because keyIsUint32 isn't specified on the database.");
return nullptr;
}
// Handle uint32_t key
if (keyIsUint32) {
uint32_t *v = new uint32_t;
*v = val->Uint32Value();
key.mv_size = sizeof(uint32_t);
key.mv_data = v;
return ([](MDB_val &key) -> void {
delete (uint32_t*)key.mv_data;
});
}
// Handle string key
CustomExternalStringResource::writeTo(val->ToString(), &key);
return ([](MDB_val &key) -> void {
delete[] (uint16_t*)key.mv_data;
});
return nullptr;
}
Local<Value> keyToHandle(MDB_val &key, bool keyIsUint32) {
if (keyIsUint32) {
return Nan::New<Integer>(*((uint32_t*)key.mv_data));
}
else {
return valToString(key);
}
}
Local<Value> valToString(MDB_val &data) {
auto resource = new CustomExternalStringResource(&data);
auto str = Nan::New<v8::String>(resource);
return str.ToLocalChecked();
}
Local<Value> valToBinary(MDB_val &data) {
// FIXME: It'd be better not to copy buffers, but I'm not sure
// about the ownership semantics of MDB_val, so let' be safe.
return Nan::CopyBuffer(
(char*)data.mv_data,
data.mv_size
).ToLocalChecked();
}
Local<Value> valToNumber(MDB_val &data) {
return Nan::New<Number>(*((double*)data.mv_data));
}
Local<Value> valToBoolean(MDB_val &data) {
return Nan::New<Boolean>(*((bool*)data.mv_data));
}
void consoleLog(const char *msg) {
Local<String> str = Nan::New("console.log('").ToLocalChecked();
str = String::Concat(str, Nan::New<String>(msg).ToLocalChecked());
str = String::Concat(str, Nan::New("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLog(Local<Value> val) {
Local<String> str = Nan::New<String>("console.log('").ToLocalChecked();
str = String::Concat(str, val->ToString());
str = String::Concat(str, Nan::New<String>("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLogN(int n) {
char c[20];
memset(c, 0, 20 * sizeof(char));
sprintf(c, "%d", n);
consoleLog(c);
}
/*
Writing string to LMDB.
Making LMDB compatible with other languages by converting strings to UTF-8.
Alas, this means no zero-copy semantics because strings are UTF-16 in Javascript.
*/
void CustomExternalStringResource::writeTo(Handle<String> str, MDB_val *val) {
String::Utf8Value utf8(str);
char *inp = *utf8;
int len = strlen(inp);
char *d = new char[len];
strcpy(d, inp);
val->mv_data = d;
val->mv_size = len;
}
/*
Reading string from LMDB.
It will be utf-8 encoded, so decoding here into utf-16.
*/
CustomExternalStringResource::CustomExternalStringResource(MDB_val *val) {
// appending '\0' to input to feed into String::New
char *tmp = new char[val->mv_size + 1];
memcpy(tmp, val->mv_data, val->mv_size);
tmp[val->mv_size] = 0;
// convert utf8 -> utf16
Local<String> jsString = String::New(tmp);
delete [] tmp;
// write into output buffer
int len = jsString->Length();
uint16_t *d = new uint16_t[len];
jsString->Write(d);
this->d = d;
this->l = len;
}
CustomExternalStringResource::~CustomExternalStringResource() {
// TODO: alter this if zero-copy semantics is reintroduced above
delete [] d;
}
void CustomExternalStringResource::Dispose() {
// No need to do anything, the data is owned by LMDB, not us
// But actually need to delete the string resource itself:
// the docs say that "The default implementation will use the delete operator."
// while initially I thought this means using delete on the string,
// apparently they meant just calling the destructor of this class.
delete this;
}
const uint16_t *CustomExternalStringResource::data() const {
return this->d;
}
size_t CustomExternalStringResource::length() const {
return this->l;
}
<|endoftext|> |
<commit_before>#include <sys/mount.h>
#include <v8.h>
#include <node.h>
v8::Handle<v8::Value> Mount(const v8::Arguments &args) {
v8::HandleScope scope;
if (args.Length() < 3) {
// TODO: make it raise a proper exception
return v8::ThrowException(v8::String::New("`mount` needs at least 3 parameters"));
}
bool callback = false;
v8::Local<v8::Function> cb;
v8::Handle<v8::Array> options;
if(args.Length() == 4) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[3]);
options = v8::Array::New(0);
} else if(args.Length() == 5) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[4]);
if (args[3]->IsArray()) {
options = v8::Handle<v8::Array>::Cast(args[3]);
}
}
int mask = 0;
for (unsigned int i = 0; i < options->Length(); i++) {
v8::Local<v8::String> opt = v8::Local<v8::String>::Cast(options->Get(i));
if(opt == v8::String::New("bind")) {
mask |= MS_BIND;
} else if(opt == v8::String::New("readonly")) {
mask |= MS_RDONLY;
} else if(opt == v8::String::New("remount")) {
mask |= MS_REMOUNT;
}
}
v8::String::Utf8Value device(args[0]->ToString());
v8::String::Utf8Value path(args[1]->ToString());
v8::String::Utf8Value type(args[2]->ToString());
bool mountAction = (mount(*device, *path, *type, mask, NULL) == 0) ? true : false;
v8::Local<v8::Value> mounted = v8::Local<v8::Value>::New(v8::Boolean::New(mountAction));
if(callback) {
const unsigned argc = 1;
v8::Local<v8::Value> argv[argc] = {mounted};
cb->Call(v8::Context::GetCurrent()->Global(), argc, argv);
}
return mounted;
}
v8::Handle<v8::Value> Unmount(const v8::Arguments &args) {
v8::HandleScope scope;
if (args.Length() < 1) {
return v8::ThrowException(v8::String::New("`umount` needs at least 1 parameter"));
}
bool callback = false;
v8::Local<v8::Function> cb;
if(args.Length() == 2) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[1]);
}
v8::String::Utf8Value path(args[0]->ToString());
bool mountAction = (umount(*path) == 0) ? true : false;
v8::Local<v8::Value> mounted = v8::Local<v8::Value>::New(v8::Boolean::New(mountAction));
if(callback) {
const unsigned argc = 1;
v8::Local<v8::Value> argv[argc] = {mounted};
cb->Call(v8::Context::GetCurrent()->Global(), argc, argv);
}
return mounted;
}
void init (v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
exports->Set(v8::String::NewSymbol("mount"), v8::FunctionTemplate::New(Mount)->GetFunction());
exports->Set(v8::String::NewSymbol("unmount"), v8::FunctionTemplate::New(Unmount)->GetFunction());
}
NODE_MODULE(mount, init)
<commit_msg>Added 6th parameter<commit_after>#include <sys/mount.h>
#include <v8.h>
#include <node.h>
#include <errno.h>
#include <string.h>
#include <iostream>
v8::Handle<v8::Value> Mount(const v8::Arguments &args) {
v8::HandleScope scope;
if (args.Length() < 3) {
// TODO: make it raise a proper exception
return v8::ThrowException(v8::String::New("`mount` needs at least 3 parameters"));
}
bool callback = false;
v8::Local<v8::Function> cb;
v8::Handle<v8::Array> options;
v8::Local<v8::String> data;
if(args.Length() == 4) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[3]);
options = v8::Array::New(0);
} else if(args.Length() == 5) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[4]);
if (args[3]->IsArray()) {
options = v8::Handle<v8::Array>::Cast(args[3]);
}
} else if(args.Length() == 6) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[5]);
if (args[3]->IsArray()) {
options = v8::Handle<v8::Array>::Cast(args[3]);
}
if (args[4]->IsString()) {
data = v8::Local<v8::String>::Cast(args[4]);
}
}
int mask = 0;
for (unsigned int i = 0; i < options->Length(); i++) {
v8::Local<v8::String> opt = v8::Local<v8::String>::Cast(options->Get(i));
if(opt == v8::String::New("bind")) {
mask |= MS_BIND;
} else if(opt == v8::String::New("readonly")) {
mask |= MS_RDONLY;
} else if(opt == v8::String::New("remount")) {
mask |= MS_REMOUNT;
}
}
v8::String::Utf8Value device(args[0]->ToString());
v8::String::Utf8Value path(args[1]->ToString());
v8::String::Utf8Value type(args[2]->ToString());
int mountNum = mount(*device, *path, *type, mask, *data);
bool mountAction = (mountNum == 0) ? true : false;
v8::Local<v8::Value> mounted = v8::Local<v8::Value>::New(v8::Boolean::New(mountAction));
if(callback) {
const unsigned argc = 1;
v8::Local<v8::Value> argv[argc] = {mounted};
cb->Call(v8::Context::GetCurrent()->Global(), argc, argv);
}
return mounted;
}
v8::Handle<v8::Value> Unmount(const v8::Arguments &args) {
v8::HandleScope scope;
if (args.Length() < 1) {
return v8::ThrowException(v8::String::New("`umount` needs at least 1 parameter"));
}
bool callback = false;
v8::Local<v8::Function> cb;
if(args.Length() == 2) {
callback = true;
cb = v8::Local<v8::Function>::Cast(args[1]);
}
v8::String::Utf8Value path(args[0]->ToString());
bool mountAction = (umount(*path) == 0) ? true : false;
v8::Local<v8::Value> mounted = v8::Local<v8::Value>::New(v8::Boolean::New(mountAction));
if(callback) {
const unsigned argc = 1;
v8::Local<v8::Value> argv[argc] = {mounted};
cb->Call(v8::Context::GetCurrent()->Global(), argc, argv);
}
return mounted;
}
void init (v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
exports->Set(v8::String::NewSymbol("mount"), v8::FunctionTemplate::New(Mount)->GetFunction());
exports->Set(v8::String::NewSymbol("unmount"), v8::FunctionTemplate::New(Unmount)->GetFunction());
}
NODE_MODULE(mount, init)
<|endoftext|> |
<commit_before>/* Copyright 2013-2014 Dietrich Epp.
This file is part of Oubliette. Oubliette is licensed under the terms
of the 2-clause BSD license. For more information, see LICENSE.txt. */
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <assert.h>
#include "defs.hpp"
#include "pack.hpp"
namespace pack {
// Rect, sorts from biggest to smallest.
struct rect {
size rectsize;
std::size_t index;
bool operator<(const rect &other) const;
};
bool rect::operator<(const rect &other) const
{
if (rectsize.width > other.rectsize.width)
return true;
if (rectsize.width < other.rectsize.width)
return false;
return rectsize.height > other.rectsize.width;
}
// Metrics for how good a packing is.
struct metrics {
int area;
int nonsquare;
metrics();
metrics(const size &size);
bool operator<(const metrics &other) const;
};
metrics::metrics()
{
}
metrics::metrics(const size &size)
: area(size.width * size.height),
nonsquare(std::abs(size.width - size.height))
{
}
bool metrics::operator<(const metrics &other) const
{
if (area < other.area)
return true;
if (area > other.area)
return false;
return nonsquare < other.nonsquare;
}
// Packing state.
struct packer {
std::vector<int> frontier;
packing result;
std::vector<rect> rects;
bool try_pack(int width, int height);
};
bool packer::try_pack(int width, int height)
{
frontier.clear();
frontier.resize(height, 0);
result.locations.resize(rects.size());
result.packsize.width = width;
result.packsize.height = height;
int ypos = 0;
for (auto rect : rects) {
int sw = rect.rectsize.width, sh = rect.rectsize.height;
std::size_t index = rect.index;
if (ypos + sw > height)
ypos = 0;
while (ypos + sh <= height && frontier[ypos] + sw > width)
ypos++;
if (ypos + sh > height)
return false;
int xpos = frontier[ypos];
for (int i = 0; i < ypos + sh; i++) {
if (frontier[i] < xpos + sw)
frontier[i] = xpos + sw;
}
assert(0 <= ypos && ypos <= height - sh);
assert(0 <= xpos && xpos <= width - sw);
result.locations[index].x = xpos;
result.locations[index].y = ypos;
ypos += sh;
}
return true;
}
packing pack(const std::vector<size> &rects)
{
packer packer;
std::size_t rectarea = 0;
packer.rects.reserve(rects.size());
for (std::size_t i = 0; i < rects.size(); i++) {
rect r;
r.rectsize = rects[i];
r.index = i;
packer.rects.push_back(r);
rectarea += static_cast<std::size_t>(rects[i].width) *
static_cast<std::size_t>(rects[i].height);
}
std::sort(packer.rects.begin(), packer.rects.end());
bool havepacking = false;
packing bestpacking;
for (int i = 4; i < 10; i++) {
int height = 1 << i;
bool success = false;
for (int j = 4; j < 10; j++) {
int width = 1 << j;
if (rectarea > static_cast<std::size_t>(1) << (i + j))
continue;
if (packer.try_pack(width, height)) {
success = true;
break;
}
}
if (!success)
continue;
if (havepacking) {
metrics curmetrics(packer.result.packsize);
metrics bestmetrics(bestpacking.packsize);
if (curmetrics < bestmetrics) {
packing temp(std::move(bestpacking));
bestpacking = std::move(packer.result);
packer.result = std::move(temp);
}
} else {
bestpacking = std::move(packer.result);
havepacking = true;
}
}
if (!havepacking)
core::die("Could not pack sprites.");
return bestpacking;
}
}
<commit_msg>Fix bug in comparison function<commit_after>/* Copyright 2013-2014 Dietrich Epp.
This file is part of Oubliette. Oubliette is licensed under the terms
of the 2-clause BSD license. For more information, see LICENSE.txt. */
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <assert.h>
#include "defs.hpp"
#include "pack.hpp"
namespace pack {
// Rect, sorts from biggest to smallest.
struct rect {
size rectsize;
std::size_t index;
bool operator<(const rect &other) const;
};
bool rect::operator<(const rect &other) const
{
if (rectsize.width > other.rectsize.width)
return true;
if (rectsize.width < other.rectsize.width)
return false;
return rectsize.height > other.rectsize.height;
}
// Metrics for how good a packing is.
struct metrics {
int area;
int nonsquare;
metrics();
metrics(const size &size);
bool operator<(const metrics &other) const;
};
metrics::metrics()
{
}
metrics::metrics(const size &size)
: area(size.width * size.height),
nonsquare(std::abs(size.width - size.height))
{
}
bool metrics::operator<(const metrics &other) const
{
if (area < other.area)
return true;
if (area > other.area)
return false;
return nonsquare < other.nonsquare;
}
// Packing state.
struct packer {
std::vector<int> frontier;
packing result;
std::vector<rect> rects;
bool try_pack(int width, int height);
};
bool packer::try_pack(int width, int height)
{
frontier.clear();
frontier.resize(height, 0);
result.locations.resize(rects.size());
result.packsize.width = width;
result.packsize.height = height;
int ypos = 0;
for (auto rect : rects) {
int sw = rect.rectsize.width, sh = rect.rectsize.height;
std::size_t index = rect.index;
if (ypos + sw > height)
ypos = 0;
while (ypos + sh <= height && frontier[ypos] + sw > width)
ypos++;
if (ypos + sh > height)
return false;
int xpos = frontier[ypos];
for (int i = 0; i < ypos + sh; i++) {
if (frontier[i] < xpos + sw)
frontier[i] = xpos + sw;
}
assert(0 <= ypos && ypos <= height - sh);
assert(0 <= xpos && xpos <= width - sw);
result.locations[index].x = xpos;
result.locations[index].y = ypos;
ypos += sh;
}
return true;
}
packing pack(const std::vector<size> &rects)
{
packer packer;
std::size_t rectarea = 0;
packer.rects.reserve(rects.size());
for (std::size_t i = 0; i < rects.size(); i++) {
rect r;
r.rectsize = rects[i];
r.index = i;
packer.rects.push_back(r);
rectarea += static_cast<std::size_t>(rects[i].width) *
static_cast<std::size_t>(rects[i].height);
}
std::sort(packer.rects.begin(), packer.rects.end());
bool havepacking = false;
packing bestpacking;
for (int i = 4; i < 10; i++) {
int height = 1 << i;
bool success = false;
for (int j = 4; j < 10; j++) {
int width = 1 << j;
if (rectarea > static_cast<std::size_t>(1) << (i + j))
continue;
if (packer.try_pack(width, height)) {
success = true;
break;
}
}
if (!success)
continue;
if (havepacking) {
metrics curmetrics(packer.result.packsize);
metrics bestmetrics(bestpacking.packsize);
if (curmetrics < bestmetrics) {
packing temp(std::move(bestpacking));
bestpacking = std::move(packer.result);
packer.result = std::move(temp);
}
} else {
bestpacking = std::move(packer.result);
havepacking = true;
}
}
if (!havepacking)
core::die("Could not pack sprites.");
return bestpacking;
}
}
<|endoftext|> |
<commit_before>/**
* \file perft.cc
* \author Jason Fernandez
* \date 11/10/2022
*/
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include "argparse/argparse.hpp"
#include "chess/position.h"
#include "chess/movegen.h"
/**
* @brief PERFormance Test
*/
class Perft final {
public:
/**
* Run the performance test, computing the number of nodes
* in the subtree below each move
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
std::size_t Divide(chess::Position* pos, std::size_t depth) {
if (pos->ToMove() == chess::Player::kWhite) {
return Divide_<chess::Player::kWhite>(pos, depth);
} else {
return Divide_<chess::Player::kBlack>(pos, depth);
}
}
/**
* Run the performance test
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
std::size_t Run(chess::Position* pos, std::size_t depth) {
max_depth_ = depth;
node_count_ = 0;
if (pos->ToMove() == chess::Player::kWhite) {
Trace<chess::Player::kWhite>(pos, 0);
} else {
Trace<chess::Player::kBlack>(pos, 0);
}
return node_count_;
}
private:
/**
* Run divide() on the specified player
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
template <chess::Player P>
std::size_t Divide_(chess::Position* pos, std::size_t depth) {
max_depth_ = depth == 0 ? depth : (depth-1);
std::size_t total_nodes = 0;
std::uint32_t moves[chess::kMaxMoves];
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
for (std::size_t i = 0; i < n_moves; i++) {
node_count_ = 0;
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, 0);
Trace<chess::util::opponent<P>()>(pos, 1);
pos->UnMakeMove<P>(move, 0);
chess::Square orig = chess::util::ExtractFrom(move);
chess::Square dest = chess::util::ExtractTo(move);
std::cout << chess::kSquareStr[orig]
<< chess::kSquareStr[dest] << ": " << node_count_
<< std::endl;
total_nodes += node_count_;
}
return total_nodes;
}
/**
* @brief Internal recursive routine
*
* @tparam P The player whose turn it is at this depth
*
* @param pos The current position
* @param depth The current depth
*/
template <chess::Player P>
void Trace(chess::Position* pos, std::uint32_t depth) {
if (depth >= max_depth_) {
node_count_++;
} else {
std::uint32_t moves[chess::kMaxMoves];
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
if (n_moves == 0) {
node_count_++;
} else {
for (std::size_t i = 0; i < n_moves; i++) {
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, depth);
Trace<chess::util::opponent<P>()>(pos, depth+1);
pos->UnMakeMove<P>(move, depth);
}
}
}
}
/**
* Maximum recursive trace depth
*/
std::size_t max_depth_;
/**
* The total number of nodes visited
*/
std::size_t node_count_;
};
/**
* @brief Parse command line and run this program
*
* @param parser Command line parser
*
* @return True on success
*/
bool go(const argparse::ArgumentParser& parser) {
const auto max_depth = parser.get<std::size_t>("--depth");
const auto do_divide = parser.get<bool>("--divide");
const auto fen = parser.get<std::string>("--fen");
chess::Position position;
chess::Position::FenError error = position.Reset(fen);
if (error != chess::Position::FenError::kSuccess) {
std::cout << chess::Position::ErrorToString(error) << std::endl;
return false;
}
Perft perft;
const auto start = std::chrono::steady_clock::now();
const std::size_t node_count =
do_divide ? perft.Divide(&position, max_depth) :
perft.Run(&position, max_depth);
const auto stop = std::chrono::steady_clock::now();
std::size_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(
stop - start).count();
std::cout << "Nodes=" << node_count << " Time=" << ms << "ms"
<< std::endl;
return true;
}
int main(int argc, char** argv) {
argparse::ArgumentParser parser("perft");
parser.add_argument("--depth")
.help("The maximum recursive trace depth, in plies")
.scan<'u', std::size_t>()
.required();
parser.add_argument("--divide")
.help("If true, generate divide() results")
.default_value(false)
.implicit_value(true);
parser.add_argument("--fen")
.help("The root position in Forsyth-Edwards notation")
.default_value(std::string());
try {
parser.parse_args(argc, argv);
} catch (const std::runtime_error& error) {
std::cerr << error.what() << std::endl;
std::cerr << parser;
return EXIT_FAILURE;
}
return go(parser) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>Fix depth counting in divide algorithm<commit_after>/**
* \file perft.cc
* \author Jason Fernandez
* \date 11/10/2022
*/
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include "argparse/argparse.hpp"
#include "chess/position.h"
#include "chess/movegen.h"
/**
* @brief PERFormance Test
*/
class Perft final {
public:
/**
* Run the performance test, computing the number of nodes
* in the subtree below each move
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
std::size_t Divide(chess::Position* pos, std::size_t depth) {
if (pos->ToMove() == chess::Player::kWhite) {
return Divide_<chess::Player::kWhite>(pos, depth);
} else {
return Divide_<chess::Player::kBlack>(pos, depth);
}
}
/**
* Run the performance test
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
std::size_t Run(chess::Position* pos, std::size_t depth) {
max_depth_ = depth;
node_count_ = 0;
if (pos->ToMove() == chess::Player::kWhite) {
Trace<chess::Player::kWhite>(pos, 0);
} else {
Trace<chess::Player::kBlack>(pos, 0);
}
return node_count_;
}
private:
/**
* Run divide() on the specified player
*
* @param pos The root position
* @param depth Maximum recursive depth, in plies
*
* @return The total node count
*/
template <chess::Player P>
std::size_t Divide_(chess::Position* pos, std::size_t depth) {
max_depth_ = depth;
std::size_t total_nodes = 0;
std::uint32_t moves[chess::kMaxMoves];
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
for (std::size_t i = 0; i < n_moves; i++) {
node_count_ = 0;
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, 0);
Trace<chess::util::opponent<P>()>(pos, 1);
pos->UnMakeMove<P>(move, 0);
chess::Square orig = chess::util::ExtractFrom(move);
chess::Square dest = chess::util::ExtractTo(move);
std::cout << chess::kSquareStr[orig]
<< chess::kSquareStr[dest] << ": " << node_count_
<< std::endl;
total_nodes += node_count_;
}
return total_nodes;
}
/**
* @brief Internal recursive routine
*
* @tparam P The player whose turn it is at this depth
*
* @param pos The current position
* @param depth The current depth
*/
template <chess::Player P>
void Trace(chess::Position* pos, std::uint32_t depth) {
if (depth >= max_depth_) {
node_count_++;
} else {
std::uint32_t moves[chess::kMaxMoves];
const std::size_t n_moves = !pos->InCheck<P>() ?
chess::GenerateLegalMoves<P>(*pos, moves) :
chess::GenerateCheckEvasions<P>(*pos, moves);
if (n_moves == 0) {
node_count_++;
} else {
for (std::size_t i = 0; i < n_moves; i++) {
const std::uint32_t move = moves[i];
pos->MakeMove<P>(move, depth);
Trace<chess::util::opponent<P>()>(pos, depth+1);
pos->UnMakeMove<P>(move, depth);
}
}
}
}
/**
* Maximum recursive trace depth
*/
std::size_t max_depth_;
/**
* The total number of nodes visited
*/
std::size_t node_count_;
};
/**
* @brief Parse command line and run this program
*
* @param parser Command line parser
*
* @return True on success
*/
bool go(const argparse::ArgumentParser& parser) {
const auto max_depth = parser.get<std::size_t>("--depth");
const auto do_divide = parser.get<bool>("--divide");
const auto fen = parser.get<std::string>("--fen");
chess::Position position;
chess::Position::FenError error = position.Reset(fen);
if (error != chess::Position::FenError::kSuccess) {
std::cout << chess::Position::ErrorToString(error) << std::endl;
return false;
}
Perft perft;
const auto start = std::chrono::steady_clock::now();
const std::size_t node_count =
do_divide ? perft.Divide(&position, max_depth) :
perft.Run(&position, max_depth);
const auto stop = std::chrono::steady_clock::now();
std::size_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(
stop - start).count();
std::cout << "Nodes=" << node_count << " Time=" << ms << "ms"
<< std::endl;
return true;
}
int main(int argc, char** argv) {
argparse::ArgumentParser parser("perft");
parser.add_argument("--depth")
.help("The maximum recursive trace depth, in plies")
.scan<'u', std::size_t>()
.required();
parser.add_argument("--divide")
.help("If true, generate divide() results")
.default_value(false)
.implicit_value(true);
parser.add_argument("--fen")
.help("The root position in Forsyth-Edwards notation")
.default_value(std::string());
try {
parser.parse_args(argc, argv);
} catch (const std::runtime_error& error) {
std::cerr << error.what() << std::endl;
std::cerr << parser;
return EXIT_FAILURE;
}
return go(parser) ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <queue>
#include "omp.h"
// Contains the various options the user can pass ptgz.
struct Settings {
Settings(): extract(),
compress(),
verbose(),
output() {}
bool extract;
bool compress;
bool verbose;
bool output;
std::string name;
};
// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
if (argc == 1) {
std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
exit(0);
}
if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
exit(0);
}
}
// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
// instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
// Get all passed arguments
std::queue<std::string> settings;
for (int i = 1; i < argc; ++i) {
settings.push(argv[i]);
}
// Continue to check until there are no more passed arguments.
while (!settings.empty()) {
std::string arg = settings.front();
if (arg == "-x") {
if ((*instance).compress) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).extract = true;
} else if (arg == "-c") {
if ((*instance).extract) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).compress = true;
} else if (arg == "-v"){
(*instance).verbose = true;
} else if (arg == "-o") {
(*instance).output = true;
} else {
if (settings.size() > 1) {
std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).output = true;
(*instance).name = arg;
}
settings.pop();
}
if (!(*instance).output) {
std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
exit(0);
}
}
// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
findAll(numFiles, filePath.c_str());
} else {
*numFiles += 1;
}
}
}
closedir(dir);
}
}
// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// cwd (const char *) current working directory.
// rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
} else {
filePaths->push_back(rootPath + fileBuff);
}
}
}
closedir(dir);
}
}
// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// name (std::string) user given name for storage file.
// verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
std::random_shuffle(filePaths->begin(), filePaths->end());
unsigned long long int filePathSize = filePaths->size();
unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
std::vector<std::string> *tarNames = new std::vector<std::string>(filePaths->size());
// Gzips the blocks of files into a single compressed file
std::cout << "3.1 Gzipping Blocks" << std::endl;
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
unsigned long long int start = blockSize * i;
if (start < filePathSize) {
// Store the name of each file for a block owned by each thread.
// Each thread will use the file to tar and gzip compress their block.
std::ofstream tmp;
tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
tmp << filePaths->at(j) + "\n";
}
if (verbose) {
std::cout << gzCommand + "\n";
}
tmp.close();
system(gzCommand.c_str());
tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
}
}
// Combines gzipped blocks together into a single tarball.
// Write tarball names into an idx file for extraction.
std::ofstream idx, tmp;
idx.open(name + ".ptgz.idx", std::ios_base::app);
std::cout << "3.2 Combining Blocks Together" << std::endl;
std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
idx << tarNames->at(i) + "\n";
}
idx << name + ".ptgz.idx" + "\n";
idx.close();
if (verbose) {
std::cout << tarCommand + "\n";
}
system(tarCommand.c_str());
// Removes all temporary blocks and idx file.
std::cout << "3.3 Removing Temporary Blocks" << std::endl;
#pragma omp parallel for schedule(static)
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
std::string rmCommand = "rm " + tarNames->at(i);
if (verbose) {
std::cout << rmCommand + "\n";
}
system(rmCommand.c_str());
}
std::string rmCommand;
if (verbose) {
std::cout << "rm " + name + ".ptgz.idx\n";
}
rmCommand = "rm " + name + ".ptgz.idx";
system(rmCommand.c_str());
if (verbose) {
std::cout << "rm *" + name + ".ptgz.tmp\n";
}
rmCommand = "rm *" + name + ".ptgz.tmp";
system(rmCommand.c_str());
tarNames->clear();
delete(tarNames);
}
void extraction() {
}
char cwd [PATH_MAX];
// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
Settings *instance = new Settings;
int *numFiles = new int(0);
std::vector<std::string> *filePaths = new std::vector<std::string>();
helpCheck(argc, argv);
getSettings(argc, argv, instance);
getcwd(cwd, PATH_MAX);
if ((*instance).compress) {
std::cout << "1. Searching File Tree" << std::endl;
findAll(numFiles, cwd);
std::cout << "2. Gathering Files" << std::endl;
getPaths(filePaths, cwd, "");
std::cout << "3. Starting File Compression" << std::endl;
compression(filePaths, (*instance).name, (*instance).verbose);
} else {
extraction();
}
std::cout << "4. Cleaning Up" << std::endl;
delete(instance);
delete(numFiles);
filePaths->clear();
delete(filePaths);
return 0;
}
<commit_msg>Moved tmp remove into for loop. Still getting missing operand error.<commit_after>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <queue>
#include "omp.h"
// Contains the various options the user can pass ptgz.
struct Settings {
Settings(): extract(),
compress(),
verbose(),
output() {}
bool extract;
bool compress;
bool verbose;
bool output;
std::string name;
};
// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
if (argc == 1) {
std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
exit(0);
}
if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
exit(0);
}
}
// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
// instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
// Get all passed arguments
std::queue<std::string> settings;
for (int i = 1; i < argc; ++i) {
settings.push(argv[i]);
}
// Continue to check until there are no more passed arguments.
while (!settings.empty()) {
std::string arg = settings.front();
if (arg == "-x") {
if ((*instance).compress) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).extract = true;
} else if (arg == "-c") {
if ((*instance).extract) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).compress = true;
} else if (arg == "-v"){
(*instance).verbose = true;
} else if (arg == "-o") {
(*instance).output = true;
} else {
if (settings.size() > 1) {
std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).output = true;
(*instance).name = arg;
}
settings.pop();
}
if (!(*instance).output) {
std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
exit(0);
}
}
// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
findAll(numFiles, filePath.c_str());
} else {
*numFiles += 1;
}
}
}
closedir(dir);
}
}
// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// cwd (const char *) current working directory.
// rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
} else {
filePaths->push_back(rootPath + fileBuff);
}
}
}
closedir(dir);
}
}
// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// name (std::string) user given name for storage file.
// verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
std::random_shuffle(filePaths->begin(), filePaths->end());
unsigned long long int filePathSize = filePaths->size();
unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
std::vector<std::string> *tarNames = new std::vector<std::string>(filePaths->size());
// Gzips the blocks of files into a single compressed file
std::cout << "3.1 Gzipping Blocks" << std::endl;
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
unsigned long long int start = blockSize * i;
if (start < filePathSize) {
// Store the name of each file for a block owned by each thread.
// Each thread will use the file to tar and gzip compress their block.
std::ofstream tmp;
tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
tmp << filePaths->at(j) + "\n";
}
if (verbose) {
std::cout << gzCommand + "\n";
}
tmp.close();
system(gzCommand.c_str());
tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
}
}
// Combines gzipped blocks together into a single tarball.
// Write tarball names into an idx file for extraction.
std::ofstream idx, tmp;
idx.open(name + ".ptgz.idx", std::ios_base::app);
std::cout << "3.2 Combining Blocks Together" << std::endl;
std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
idx << tarNames->at(i) + "\n";
}
idx << name + ".ptgz.idx" + "\n";
idx.close();
if (verbose) {
std::cout << tarCommand + "\n";
}
system(tarCommand.c_str());
// Removes all temporary blocks and idx file.
std::cout << "3.3 Removing Temporary Blocks" << std::endl;
#pragma omp parallel for schedule(static)
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
std::string rmCommand = "rm " + tarNames->at(i);
if (verbose) {
std::cout << rmCommand + "\n";
}
system(rmCommand.c_str());
rmCommand = "rm " + std::to_string(i) + "." + name + ".ptgz.tmp";
if (verbose) {
std::cout << rmCommand + "\n";
}
system(rmCommand.c_str());
}
std::string rmCommand;
if (verbose) {
std::cout << "rm " + name + ".ptgz.idx\n";
}
rmCommand = "rm " + name + ".ptgz.idx";
system(rmCommand.c_str());
tarNames->clear();
delete(tarNames);
}
void extraction() {
}
char cwd [PATH_MAX];
// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
Settings *instance = new Settings;
int *numFiles = new int(0);
std::vector<std::string> *filePaths = new std::vector<std::string>();
helpCheck(argc, argv);
getSettings(argc, argv, instance);
getcwd(cwd, PATH_MAX);
if ((*instance).compress) {
std::cout << "1. Searching File Tree" << std::endl;
findAll(numFiles, cwd);
std::cout << "2. Gathering Files" << std::endl;
getPaths(filePaths, cwd, "");
std::cout << "3. Starting File Compression" << std::endl;
compression(filePaths, (*instance).name, (*instance).verbose);
} else {
extraction();
}
std::cout << "4. Cleaning Up" << std::endl;
delete(instance);
delete(numFiles);
filePaths->clear();
delete(filePaths);
return 0;
}
<|endoftext|> |
<commit_before>#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdlib.h>
#include <stdio.h>
#include "test.h"
// TODO: this is all hacky test code - refactor into nicely modularized code
SDL_Surface *display_surf;
bool init_video(int w, int h, int bpp, bool fullscreen)
{
Uint32 flags = SDL_HWSURFACE | SDL_OPENGL;
if (fullscreen) {
flags |= SDL_FULLSCREEN;
}
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
display_surf = SDL_SetVideoMode(w, h, bpp, flags);
if (!display_surf) {
return false;
}
glClearColor(0, 0.0f, 0, 0);
glClearDepth(1.0f);
glViewport(0, 0, w, h);
// viewer projection
glMatrixMode(GL_PROJECTION);
gluPerspective(20, 1, 0.1, 20);
// viewer position
glMatrixMode(GL_MODELVIEW);
glTranslatef(0, 0, -20);
// object position
glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
glRotatef(30.0f, 0.0f, 1.0f, 0.0f);
glEnable(GL_DEPTH_TEST);
// for drawing outlines
glPolygonOffset(1.0, 2);
glEnable(GL_POLYGON_OFFSET_FILL);
return true;
}
void draw_quad(float r, float g, float b, bool outline, const float *quad)
{
// TODO: get rid of GL_QUADS, use triangle strip?
glBegin(outline ? GL_LINE_LOOP : GL_QUADS);
glColor3f(r, g, b);
glVertex3fv(&quad[0 * 3]);
glVertex3fv(&quad[1 * 3]);
glVertex3fv(&quad[2 * 3]);
glVertex3fv(&quad[3 * 3]);
glEnd();
}
void draw_cube(float r, float g, float b, bool outline)
{
static const float cube_quads[][4*3] = {
{0,0,0, 1,0,0, 1,1,0, 0,1,0},
{0,0,1, 1,0,1, 1,1,1, 0,1,1},
{0,0,0, 1,0,0, 1,0,1, 0,0,1},
{0,1,0, 1,1,0, 1,1,1, 0,1,1},
{0,0,0, 0,0,1, 0,1,1, 0,1,0},
{1,0,0, 1,0,1, 1,1,1, 1,1,0}
};
for (int i = 0; i < 6; i++) {
draw_quad(r, g, b, outline, cube_quads[i]);
}
}
void draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
for (int z = 0; z < 3; z++) {
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
glPushMatrix();
glTranslatef(x, y, z);
draw_cube(1.0f, 0.0f, 0.0f, false);
draw_cube(1.0f, 1.0f, 1.0f, true);
glPopMatrix();
}
}
}
SDL_GL_SwapBuffers();
}
void event_loop()
{
SDL_Event e;
while (1) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
return; // exit event loop
}
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_ESCAPE) {
return; // exit event loop
}
// TODO: other keyboard events
}
}
draw();
}
}
extern "C" int main(int argc, char **argv)
{
printf("Version: %d.%d%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE);
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
printf("SDL_Init(SDL_INIT_EVERYTHING) failed: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
const SDL_VideoInfo *vid_info = SDL_GetVideoInfo();
printf("Current video mode is %dx%dx%d\n", vid_info->current_w, vid_info->current_h, vid_info->vfmt->BitsPerPixel);
int w = vid_info->current_w;
int h = vid_info->current_h;
int bpp = vid_info->vfmt->BitsPerPixel;
bool fullscreen = true;
// TODO: read w, h, bpp from config file to override defaults
SDL_WM_SetCaption("NarfBlock", "NarfBlock");
if (!init_video(w, h, bpp, fullscreen)) {
fprintf(stderr, "Error: could not set OpenGL video mode %dx%d@%d bpp\n", w, h, bpp);
SDL_Quit();
return 1;
}
event_loop();
SDL_Quit();
return 0;
}
<commit_msg>Quick and dirty world renderer (very inefficient)<commit_after>#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "test.h"
// TODO: this is all hacky test code - refactor into nicely modularized code
class Display {
public:
SDL_Surface *surf;
int width;
int height;
};
class Camera {
public:
// position
float x;
float y;
float z;
// view angles in radians
float yaw;
float pitch;
};
class Block {
public:
// TODO: for now just store a color for testing purposes
float r;
float g;
float b;
unsigned solid:1;
};
Display display;
Camera cam;
const float movespeed = 0.1f;
Block *world;
#define WORLD_X_MAX 100
#define WORLD_Y_MAX 100
#define WORLD_Z_MAX 100
Block *get_block(int x, int y, int z)
{
assert(x >= 0 && y >= 0 && z >= 0);
assert(x < WORLD_X_MAX && y < WORLD_Y_MAX && z < WORLD_Z_MAX);
return &world[z * WORLD_X_MAX * WORLD_Y_MAX + y * WORLD_X_MAX + x];
}
float clampf(float val, float min, float max)
{
if (val < min) val = min;
if (val > max) val = max;
return val;
}
bool init_video(int w, int h, int bpp, bool fullscreen)
{
Uint32 flags = SDL_HWSURFACE | SDL_OPENGL;
if (fullscreen) {
flags |= SDL_FULLSCREEN;
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
display.surf = SDL_SetVideoMode(w, h, bpp, flags);
if (!display.surf) {
return false;
}
display.width = w;
display.height = h;
glViewport(0, 0, w, h);
// viewer projection
glMatrixMode(GL_PROJECTION);
float fovx = 90.0f; // degrees
float fovy = 60.0f; // degrees
float aspect = (float)w / (float)h ; // TODO: include fovx in calculation
gluPerspective(fovy, aspect, 0.1, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
// for drawing outlines
glPolygonOffset(1.0, 2);
glEnable(GL_POLYGON_OFFSET_FILL);
return true;
}
void draw_quad(float r, float g, float b, bool outline, const float *quad)
{
// TODO: get rid of GL_QUADS, use triangle strip?
glBegin(outline ? GL_LINE_LOOP : GL_QUADS);
glColor3f(r, g, b);
glVertex3fv(&quad[0 * 3]);
glVertex3fv(&quad[1 * 3]);
glVertex3fv(&quad[2 * 3]);
glVertex3fv(&quad[3 * 3]);
glEnd();
}
void draw_cube(float r, float g, float b, bool outline)
{
static const float cube_quads[][4*3] = {
{0,0,0, 1,0,0, 1,1,0, 0,1,0},
{0,0,1, 1,0,1, 1,1,1, 0,1,1},
{0,0,0, 1,0,0, 1,0,1, 0,0,1},
{0,1,0, 1,1,0, 1,1,1, 0,1,1},
{0,0,0, 0,0,1, 0,1,1, 0,1,0},
{1,0,0, 1,0,1, 1,1,1, 1,1,0}
};
for (int i = 0; i < 6; i++) {
draw_quad(r, g, b, outline, cube_quads[i]);
}
}
void draw()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// camera
glLoadIdentity();
glRotatef(cam.pitch * 180.0f / M_PI, 1.0f, 0.0f, 0.0f);
glRotatef(cam.yaw * 180.0f / M_PI, 0.0f, 1.0f, 0.0f);
glTranslatef(-cam.x, -cam.y, -cam.z);
// draw blocks
for (int z = 0; z < WORLD_Z_MAX; z++) {
for (int y = 0; y < WORLD_Y_MAX; y++) {
for (int x = 0; x < WORLD_X_MAX; x++) {
Block *b = get_block(x, y, z);
if (b->solid) {
glPushMatrix();
glTranslatef(x, y, z);
// TODO: don't render sides of the cube that are obscured by other solid cubes?
draw_cube(b->r, b->g, b->b, false);
// TODO: highlight cube selected by mouse
//draw_cube(0.0f, 0.0f, 0.0f, true);
glPopMatrix();
}
}
}
}
SDL_GL_SwapBuffers();
}
void event_loop()
{
SDL_Event e;
bool firstmove = true;
while (1) {
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT:
return; // exit event loop
case SDL_KEYDOWN:
switch (e.key.keysym.sym) {
case SDLK_ESCAPE:
return; // exit event loop
// TODO: move all this movement code into a time-dependent movement function
// TODO: decouple player direction and camera direction
case SDLK_w: // move forward
cam.x -= cosf(cam.yaw + M_PI / 2) * movespeed;
cam.z -= sinf(cam.yaw + M_PI / 2) * movespeed;
break;
case SDLK_s: // move backward
cam.x += cosf(cam.yaw + M_PI / 2) * movespeed;
cam.z += sinf(cam.yaw + M_PI / 2) * movespeed;
break;
case SDLK_a: // strafe left
cam.x -= cosf(cam.yaw) * movespeed;
cam.z -= sinf(cam.yaw) * movespeed;
break;
case SDLK_d: // strafe right
cam.x += cosf(cam.yaw) * movespeed;
cam.z += sinf(cam.yaw) * movespeed;
break;
case SDLK_SPACE: // jump
cam.y += 3.0f; // more like jetpack... move to time-dependent function and check for solid ground before jumping
break;
}
// TODO: other keyboard events
break;
case SDL_MOUSEMOTION:
if (firstmove) {
// ignore the initial motion event when the mouse is centered
firstmove = false;
} else {
cam.yaw += ((float)e.motion.xrel / (float)display.width);
cam.yaw = fmodf(cam.yaw, M_PI * 2.0f);
cam.pitch += ((float)e.motion.yrel / (float)display.height);
cam.pitch = clampf(cam.pitch, -M_PI / 2, M_PI / 2);
break;
}
}
}
cam.y -= 1.0f; // crappy framerate-dependent gravity
if (cam.y < 3.0f) {
cam.y = 3.0f;
}
draw();
}
}
float randf(float min, float max)
{
return ((float)rand() / (float)RAND_MAX) * (max - min + 1.0f) + min;
}
int randi(int min, int max)
{
return (int)randf(min, max); // HAX
}
void gen_world()
{
world = (Block*)calloc(WORLD_X_MAX * WORLD_Y_MAX * WORLD_Z_MAX, sizeof(Block));
// first fill a plane at y = 0
for (int z = 0; z < WORLD_Z_MAX; z++) {
for (int x = 0; x < WORLD_X_MAX; x++) {
Block *b = get_block(x, 0, z);
b->r = randf(0.0f, 0.05f);
b->g = randf(0.9f, 1.0f);
b->b = randf(0.0f, 0.05f);
b->solid = 1;
}
}
// generate some random blocks above the ground
for (int i = 0; i < 50; i++) {
int x = randi(0, WORLD_X_MAX - 1);
int y = randi(1, 10);
int z = randi(0, WORLD_Z_MAX - 1);
Block *b = get_block(x, y, z);
b->r = randf(0.0f, 1.0f);
b->g = randf(0.0f, 1.0f);
b->b = randf(0.0f, 1.0f);
b->solid = 1;
}
}
extern "C" int main(int argc, char **argv)
{
printf("Version: %d.%d%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE);
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
printf("SDL_Init(SDL_INIT_EVERYTHING) failed: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
const SDL_VideoInfo *vid_info = SDL_GetVideoInfo();
printf("Current video mode is %dx%dx%d\n", vid_info->current_w, vid_info->current_h, vid_info->vfmt->BitsPerPixel);
int w = vid_info->current_w;
int h = vid_info->current_h;
int bpp = vid_info->vfmt->BitsPerPixel;
bool fullscreen = true;
// TODO: read w, h, bpp from config file to override defaults
SDL_WM_SetCaption("NarfBlock", "NarfBlock");
if (!init_video(w, h, bpp, fullscreen)) {
fprintf(stderr, "Error: could not set OpenGL video mode %dx%d@%d bpp\n", w, h, bpp);
SDL_Quit();
return 1;
}
// initial camera position
cam.x = 15.0f;
cam.y = 3.0f;
cam.z = 10.0f;
// initialize camera to look at origin
cam.yaw = atan2f(cam.z, cam.x) - M_PI / 2;
cam.pitch = 0.0f;
srand(0x1234);
gen_world();
SDL_ShowCursor(0);
SDL_WM_GrabInput(SDL_GRAB_ON);
SDL_EnableKeyRepeat(1, 1); // hack
event_loop();
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <ctime>
#include <string>
#include <cstdio>
#include <boost/limits.hpp>
#include <boost/version.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/time.hpp"
#ifndef _WIN32
#include <unistd.h>
#endif
namespace libtorrent
{
namespace aux
{
// used to cache the current time
// every 100 ms. This is cheaper
// than a system call and can be
// used where more accurate time
// is not necessary
ptime g_current_time;
}
ptime const& TORRENT_EXPORT time_now() { return aux::g_current_time; }
char const* time_now_string()
{
// time_t t = std::time(0);
// tm* timeinfo = std::localtime(&t);
// static char str[200];
// std::strftime(str, 200, "%b %d %X", timeinfo);
// return str;
static const ptime start = time_now_hires();
static char ret[200];
int t = total_milliseconds(time_now_hires() - start);
int h = t / 1000 / 60 / 60;
t -= h * 60 * 60 * 1000;
int m = t / 1000 / 60;
t -= m * 60 * 1000;
int s = t / 1000;
t -= s * 1000;
int ms = t;
snprintf(ret, sizeof(ret), "%02d:%02d:%02d.%03d", h, m, s, ms);
return ret;
}
std::string log_time()
{
static const ptime start = time_now_hires();
char ret[200];
snprintf(ret, sizeof(ret), "%"PRId64, total_microseconds(time_now_hires() - start));
return ret;
}
}
#if defined TORRENT_USE_BOOST_DATE_TIME
#include <boost/date_time/microsec_time_clock.hpp>
namespace libtorrent
{
ptime time_now_hires()
{ return boost::date_time::microsec_clock<ptime>::universal_time(); }
ptime min_time()
{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
ptime max_time()
{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
time_duration seconds(int s) { return boost::posix_time::seconds(s); }
time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
time_duration microsec(int s) { return boost::posix_time::microsec(s); }
time_duration minutes(int s) { return boost::posix_time::minutes(s); }
time_duration hours(int s) { return boost::posix_time::hours(s); }
int total_seconds(time_duration td)
{ return td.total_seconds(); }
int total_milliseconds(time_duration td)
{ return td.total_milliseconds(); }
boost::int64_t total_microseconds(time_duration td)
{ return td.total_microseconds(); }
}
#else // TORRENT_USE_BOOST_DATE_TIME
namespace libtorrent
{
ptime min_time() { return ptime(0); }
ptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); }
}
#if defined TORRENT_USE_ABSOLUTE_TIME
#include <mach/mach_time.h>
#include <boost/cstdint.hpp>
#include "libtorrent/assert.hpp"
// high precision timer for darwin intel and ppc
namespace libtorrent
{
ptime time_now_hires()
{
static mach_timebase_info_data_t timebase_info = {0,0};
if (timebase_info.denom == 0)
mach_timebase_info(&timebase_info);
boost::uint64_t at = mach_absolute_time();
// make sure we don't overflow
TORRENT_ASSERT((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
return ptime(at / 1000 * timebase_info.numer / timebase_info.denom);
}
}
#elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include "libtorrent/assert.hpp"
namespace libtorrent
{
namespace aux
{
boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
#ifdef TORRENT_DEBUG
// make sure we don't overflow
boost::int64_t ret = (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
TORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));
#endif
return (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
}
boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
#ifdef TORRENT_DEBUG
// make sure we don't overflow
boost::int64_t ret = (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
TORRENT_ASSERT((ms >= 0 && ms <= ret)
|| (ms < 0 && ms > ret));
#endif
return (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
}
}
ptime time_now_hires()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return ptime(now.QuadPart);
}
}
#elif defined TORRENT_USE_CLOCK_GETTIME
#include <time.h>
#include "libtorrent/assert.hpp"
namespace libtorrent
{
ptime time_now_hires()
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000);
}
}
#elif defined TORRENT_USE_SYSTEM_TIME
#include <kernel/OS.h>
namespace libtorrent
{
ptime time_now_hires()
{ return ptime(system_time()); }
}
#endif // TORRENT_USE_SYSTEM_TIME
#endif // TORRENT_USE_BOOST_DATE_TIME
<commit_msg>fix windows DLL build<commit_after>/*
Copyright (c) 2009, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <ctime>
#include <string>
#include <cstdio>
#include <boost/limits.hpp>
#include <boost/version.hpp>
#include "libtorrent/config.hpp"
#include "libtorrent/time.hpp"
#ifndef _WIN32
#include <unistd.h>
#endif
namespace libtorrent
{
namespace aux
{
// used to cache the current time
// every 100 ms. This is cheaper
// than a system call and can be
// used where more accurate time
// is not necessary
ptime g_current_time;
}
TORRENT_EXPORT ptime const& time_now() { return aux::g_current_time; }
char const* time_now_string()
{
// time_t t = std::time(0);
// tm* timeinfo = std::localtime(&t);
// static char str[200];
// std::strftime(str, 200, "%b %d %X", timeinfo);
// return str;
static const ptime start = time_now_hires();
static char ret[200];
int t = total_milliseconds(time_now_hires() - start);
int h = t / 1000 / 60 / 60;
t -= h * 60 * 60 * 1000;
int m = t / 1000 / 60;
t -= m * 60 * 1000;
int s = t / 1000;
t -= s * 1000;
int ms = t;
snprintf(ret, sizeof(ret), "%02d:%02d:%02d.%03d", h, m, s, ms);
return ret;
}
std::string log_time()
{
static const ptime start = time_now_hires();
char ret[200];
snprintf(ret, sizeof(ret), "%"PRId64, total_microseconds(time_now_hires() - start));
return ret;
}
}
#if defined TORRENT_USE_BOOST_DATE_TIME
#include <boost/date_time/microsec_time_clock.hpp>
namespace libtorrent
{
ptime time_now_hires()
{ return boost::date_time::microsec_clock<ptime>::universal_time(); }
ptime min_time()
{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
ptime max_time()
{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
time_duration seconds(int s) { return boost::posix_time::seconds(s); }
time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
time_duration microsec(int s) { return boost::posix_time::microsec(s); }
time_duration minutes(int s) { return boost::posix_time::minutes(s); }
time_duration hours(int s) { return boost::posix_time::hours(s); }
int total_seconds(time_duration td)
{ return td.total_seconds(); }
int total_milliseconds(time_duration td)
{ return td.total_milliseconds(); }
boost::int64_t total_microseconds(time_duration td)
{ return td.total_microseconds(); }
}
#else // TORRENT_USE_BOOST_DATE_TIME
namespace libtorrent
{
ptime min_time() { return ptime(0); }
ptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); }
}
#if defined TORRENT_USE_ABSOLUTE_TIME
#include <mach/mach_time.h>
#include <boost/cstdint.hpp>
#include "libtorrent/assert.hpp"
// high precision timer for darwin intel and ppc
namespace libtorrent
{
ptime time_now_hires()
{
static mach_timebase_info_data_t timebase_info = {0,0};
if (timebase_info.denom == 0)
mach_timebase_info(&timebase_info);
boost::uint64_t at = mach_absolute_time();
// make sure we don't overflow
TORRENT_ASSERT((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
return ptime(at / 1000 * timebase_info.numer / timebase_info.denom);
}
}
#elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include "libtorrent/assert.hpp"
namespace libtorrent
{
namespace aux
{
boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
#ifdef TORRENT_DEBUG
// make sure we don't overflow
boost::int64_t ret = (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
TORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));
#endif
return (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
}
boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
#ifdef TORRENT_DEBUG
// make sure we don't overflow
boost::int64_t ret = (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
TORRENT_ASSERT((ms >= 0 && ms <= ret)
|| (ms < 0 && ms > ret));
#endif
return (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
}
}
ptime time_now_hires()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return ptime(now.QuadPart);
}
}
#elif defined TORRENT_USE_CLOCK_GETTIME
#include <time.h>
#include "libtorrent/assert.hpp"
namespace libtorrent
{
ptime time_now_hires()
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000);
}
}
#elif defined TORRENT_USE_SYSTEM_TIME
#include <kernel/OS.h>
namespace libtorrent
{
ptime time_now_hires()
{ return ptime(system_time()); }
}
#endif // TORRENT_USE_SYSTEM_TIME
#endif // TORRENT_USE_BOOST_DATE_TIME
<|endoftext|> |
<commit_before>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#define _STRING(x) #x
#define STRING(x) _STRING(x)
#include <sstream>
#include <v8.h>
#ifdef FASTCGI
# include <fcgi_stdio.h>
#endif
#include "js_system.h"
#include "js_io.h"
#include "js_socket.h"
#include "js_common.h"
#include "js_macros.h"
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlopen(x,y) (void*)LoadLibrary(x)
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
# define dlclose(x) FreeLibrary((HMODULE)x)
#endif
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit;
char * cfgfile = NULL;
char * execfile = NULL;
v8::Persistent<v8::Context> context;
int total = 0;
void js_error(const char * message) {
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(message);
fun->Call(context->ToObject(), 1, data);
}
void js_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
msgstring += ss.str();
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
}
js_error(msgstring.c_str());
}
v8::Handle<v8::String> js_read(const char* name) {
FILE* file = fopen(name, "rb");
if (file == NULL) { return v8::Handle<v8::String>(); }
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
int js_execute(const char * str, bool change) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = js_read(str);
if (source.IsEmpty()) {
std::string s = "Error reading '";
s += str;
s += "'\n";
js_error(s.c_str());
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
js_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr((char *)str, '/');
if (end == NULL) {
end = strrchr((char *)str, '\\');
}
if (end != NULL && change) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
free(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
js_exception(&try_catch);
return 1;
}
}
return 0;
}
int js_library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
void * handle;
std::string error;
if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) {
error = "Cannot load shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
void (*func) (v8::Handle<v8::Object>);
if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) {
dlclose(handle);
error = "Cannot initialize shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
func(v8::Context::GetCurrent()->Global());
return 0;
} else {
return js_execute(path.c_str(), false);
}
}
int js_autoload() {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (js_library(*name)) { return 1; }
}
return 0;
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_execute(*file, true);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
v8::HandleScope handle_scope;
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
void main_finish() {
v8::HandleScope handle_scope;
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
}
int main_execute() {
v8::HandleScope handle_scope;
char * name = execfile;
if (name == NULL) { // try the PATH_TRANSLATED env var
v8::Handle<v8::Context> test = v8::Context::GetCurrent();
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value jsname(pt);
name = *jsname;
}
}
if (name == NULL) {
js_error("Nothing to do.\n");
return 1;
} else {
return js_execute(name, true);
}
}
int main_prepare(char ** envp) {
__onexit = v8::Array::New();
v8::Handle<v8::Object> g = context->Global();
g->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
g->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
g->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
g->Set(JS_STR("global"), g);
g->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, g);
setup_io(g);
setup_socket(g);
if (js_execute(cfgfile, false)) {
js_error("Cannot load configuration, quitting...\n");
return 1;
}
if (js_autoload()) {
js_error("Cannot load default libraries, quitting...\n");
return 1;
}
return 0;
}
int main_initialize(int argc, char ** argv) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
cfgfile = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfgfile = argv[i+1];
argptr = 0;
i++;
}
}
if (argptr) { execfile = argv[argptr]; }
FILE* file = fopen(cfgfile, "rb");
if (file == NULL) {
printf("Invalid configuration file.\n");
return 1;
}
fclose(file);
return 0;
}
int main_cycle(char ** envp) {
int result = 0;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
result = main_prepare(envp);
if (result == 0) {
result = main_execute();
}
main_finish();
return result;
}
int main(int argc, char ** argv, char ** envp) {
int result = 0;
result = main_initialize(argc, argv);
if (result) { exit(1); }
#ifdef FASTCGI
while(FCGI_Accept() >= 0) {
#endif
result = main_cycle(envp);
#ifdef FASTCGI
FCGI_SetExitStatus(result);
#endif
#ifdef FASTCGI
}
#endif
return result;
}
<commit_msg>dll/so unloading<commit_after>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#define _STRING(x) #x
#define STRING(x) _STRING(x)
#include <sstream>
#include <v8.h>
#ifdef FASTCGI
# include <fcgi_stdio.h>
#endif
#include "js_system.h"
#include "js_io.h"
#include "js_socket.h"
#include "js_common.h"
#include "js_macros.h"
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlopen(x,y) (void*)LoadLibrary(x)
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
# define dlclose(x) FreeLibrary((HMODULE)x)
#endif
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit; /* what to do on exit */
char * cfgfile = NULL; /* config file */
char * execfile = NULL; /* command-line specified file */
void ** handles; /* shared libraries */
int handlecount = 0;
int total = 0; /* fcgi debug */
void js_error(const char * message) {
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(message);
fun->Call(context->ToObject(), 1, data);
}
void js_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
msgstring += ss.str();
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
}
js_error(msgstring.c_str());
}
v8::Handle<v8::String> js_read(const char* name) {
FILE* file = fopen(name, "rb");
if (file == NULL) { return v8::Handle<v8::String>(); }
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
int js_execute(const char * str, bool change) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = js_read(str);
if (source.IsEmpty()) {
std::string s = "Error reading '";
s += str;
s += "'\n";
js_error(s.c_str());
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
js_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr((char *)str, '/');
if (end == NULL) {
end = strrchr((char *)str, '\\');
}
if (end != NULL && change) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
free(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
js_exception(&try_catch);
return 1;
}
}
return 0;
}
int js_library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
void * handle;
std::string error;
if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) {
error = "Cannot load shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
void (*func) (v8::Handle<v8::Object>);
if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) {
dlclose(handle);
error = "Cannot initialize shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
handlecount++;
handles = (void **) realloc(handles, sizeof(void*) * handlecount);
handles[handlecount-1] = handle;
func(v8::Context::GetCurrent()->Global());
return 0;
} else {
return js_execute(path.c_str(), false);
}
}
int js_autoload() {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (js_library(*name)) { return 1; }
}
return 0;
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_execute(*file, true);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
v8::HandleScope handle_scope;
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
void main_finish() {
v8::HandleScope handle_scope;
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
for (int i=0;i<handlecount;i++) {
dlclose(handles[i]);
}
handlecount = 0;
free(handles);
handles = NULL;
}
int main_execute() {
v8::HandleScope handle_scope;
char * name = execfile;
if (name == NULL) { // try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value jsname(pt);
name = *jsname;
}
}
if (name == NULL) {
js_error("Nothing to do.\n");
return 1;
} else {
return js_execute(name, true);
}
}
int main_prepare(char ** envp) {
__onexit = v8::Array::New();
v8::Handle<v8::Object> g = v8::Context::GetCurrent()->Global();
g->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
g->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
g->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
g->Set(JS_STR("total"), JS_INT(total++));
g->Set(JS_STR("global"), g);
g->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, g);
setup_io(g);
setup_socket(g);
if (js_execute(cfgfile, false)) {
js_error("Cannot load configuration, quitting...\n");
return 1;
}
if (js_autoload()) {
js_error("Cannot load default libraries, quitting...\n");
return 1;
}
return 0;
}
int main_initialize(int argc, char ** argv) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
cfgfile = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfgfile = argv[i+1];
argptr = 0;
i++;
}
}
if (argptr) { execfile = argv[argptr]; }
FILE* file = fopen(cfgfile, "rb");
if (file == NULL) {
printf("Invalid configuration file.\n");
return 1;
}
fclose(file);
return 0;
}
int main_cycle(char ** envp) {
int result = 0;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
result = main_prepare(envp);
if (result == 0) {
result = main_execute();
}
main_finish();
return result;
}
int main(int argc, char ** argv, char ** envp) {
int result = 0;
result = main_initialize(argc, argv);
if (result) { exit(1); }
#ifdef FASTCGI
while(FCGI_Accept() >= 0) {
#endif
result = main_cycle(envp);
#ifdef FASTCGI
FCGI_SetExitStatus(result);
#endif
#ifdef FASTCGI
}
#endif
return result;
}
<|endoftext|> |
<commit_before>#include <tinyxml.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <list>
#include <vector>
#include <unordered_map>
#include <functional>
#include <algorithm>
#include "zone.h"
#include "world.h"
#include "room.h"
#include "staticObject.h"
#include "event.h"
#include "utils.h"
#include "serializationHelpers.hpp"
static int zone_saves;
Zone::Zone()
{
_vnumrange.min = 0;
_vnumrange.max = 0;
_goldbonus = 0;
_expbonus = 0;
_resetfreq = 240;
_resetmsg = "With a pop, the area resets around you.";
_lastreset=time(NULL);
_creation = time(NULL);
_opened = 0;
_flags = 0;
}
Zone::~Zone()
{
for(auto it: _virtualobjs)
{
delete it;
}
for (auto it: _objects)
{
delete it;
}
for (auto it: _roomobjs)
{
delete it;
}
for (auto it: _mobobjs)
{
delete it;
}
}
std::string Zone::GetName() const
{
return _name;
}
void Zone::SetName(const std::string &name)
{
_name=name;
}
void Zone::SetRange(int min, int max)
{
_vnumrange.min = min;
_vnumrange.max = max;
}
int Zone::GetMinVnum()
{
return _vnumrange.min;
}
int Zone::GetMaxVnum()
{
return _vnumrange.max;
}
Room* Zone::AddRoom()
{
World* world = World::GetPtr();
Room* room = NULL;
VNUM num = 0;
if (_rnums.empty())
{
CalculateVnumRanges();
if (_rnums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
room = new Room();
num = _rnums.top();
_rnums.pop();
room->SetOnum(num);
room->SetZone(this);
_rooms[num] = room;
_roomobjs.push_back(room);
world->AddRoom(room);
return room;
}
Room* Zone::AddRoom(VNUM num)
{
World* world = World::GetPtr();
VNUM cur = 0;
std::stack<VNUM> temp;
Room* room = NULL;
BOOL found = false;
if (_rnums.empty())
{
CalculateVnumRanges();
if (_rnums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
room = new Room();
while (!_rnums.empty())
{
cur = _rnums.top();
_rnums.pop();
if (cur == num)
{
found = true;
continue;
}
temp.push(cur);
}
if (!found)
{
throw(std::runtime_error("That num wasn't found."));
}
_rnums = temp;
room->SetOnum(num);
room->SetZone(this);
_rooms[num] = room;
_roomobjs.push_back(room);
world->AddRoom(room);
return room;
}
BOOL Zone::RemoveRoom(VNUM num)
{
std::vector<Room*>::iterator it, itEnd;
if (_rooms.count(num))
{
itEnd = _roomobjs.end();
for (it = _roomobjs.begin(); it != itEnd; ++it)
{
if ((*it)->GetOnum() == num)
{
_roomobjs.erase(it);
delete _rooms[num];
_rooms.erase(num);
return true;
}
}
}
return false;
}
void Zone::GetRooms(std::vector<Room*> *rooms)
{
std::copy(_roomobjs.begin(), _roomobjs.end(), std::back_inserter(*rooms));
}
BOOL Zone::RoomExists(VNUM num)
{
return (_rooms.count(num) ? true : false);
}
StaticObject* Zone::AddVirtual()
{
World* world = World::GetPtr();
StaticObject* obj = NULL;
VNUM num = 0;
if (_onums.empty())
{
CalculateVnumRanges();
if (_onums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
obj = new StaticObject();
num = _onums.top();
_onums.pop();
obj->SetOnum(num);
_virtuals[num] = obj;
_virtualobjs.push_back(obj);
world->AddVirtual(obj);
return obj;
}
BOOL Zone::RemoveVirtual(VNUM num)
{
std::vector<StaticObject*>::iterator it, itEnd;
itEnd = _virtualobjs.end();
for (it = _virtualobjs.begin(); it != itEnd; ++it)
{
if ((*it)->GetOnum() == num)
{
_virtualobjs.erase(it);
delete _virtualobjs[num];
_virtuals.erase(num);
return true;
}
}
return false;
}
StaticObject* Zone::GetVirtual(VNUM num)
{
if (VirtualExists(num))
{
return _virtuals[num];
}
return nullptr;
}
void Zone::GetVirtuals(std::vector<StaticObject*>* objects)
{
for (auto it: _virtuals)
{
objects->push_back(it.second);
}
}
BOOL Zone::VirtualExists(VNUM num)
{
return (_virtuals.count(num) ? true : false);
}
Npc* Zone::AddNpc()
{
World* world = World::GetPtr();
Npc* mob = nullptr;
VNUM num = 0;
if (_mnums.empty())
{
CalculateVnumRanges();
if (_mnums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
mob = new Npc();
num = _mnums.top();
_mnums.pop();
mob->SetOnum(num);
_mobs[num] = mob;
_mobobjs.push_back(mob);
world->AddNpc(mob);
return mob;
}
BOOL Zone::RemoveNpc(VNUM num)
{
std::vector<Npc*>::iterator it, itEnd;
itEnd = _mobobjs.end();
for (it = _mobobjs.begin(); it != itEnd; ++it)
{
if ((*it)->GetOnum() == num)
{
_mobobjs.erase(it);
delete _mobs[num];
_mobs.erase(num);
return true;
}
}
return false;
}
Npc* Zone::GetNpc(VNUM num)
{
if (NpcExists(num))
{
return _mobs[num];
}
return nullptr;
}
void Zone::GetNpcs(std::vector<Npc*>* npcs)
{
std::copy(_mobobjs.begin(), _mobobjs.end(), std::back_inserter(*npcs));
}
BOOL Zone::NpcExists(VNUM num)
{
return (_mobs.count(num) ? true : false);
}
Npc* Zone::CreateNpc(VNUM num, Room* origin)
{
Npc* templ = GetNpc(num);
Npc* ret = nullptr;
if (!templ)
{
return nullptr;
}
ret = new Npc();
templ->Copy(ret);
ret->SetOrigin(origin);
ret->EnterGame();
ret->InitializeUuid();
if (!ret->MoveTo(origin))
{
delete ret;
return nullptr;
}
return ret;
}
void Zone::CalculateVnumRanges()
{
int i = 0; //for counter
//find all empty virtual objects.
for (i = _vnumrange.min; i != _vnumrange.max; ++i)
{
if (!VirtualExists(i))
{
if (_onums.size() == VNUMKEEP)
{
break;
}
_onums.push(i);
}
}
//find all empty room objects.
for (i = _vnumrange.min; i != _vnumrange.max; ++i)
{
if (!RoomExists(i))
{
if (_rnums.size() == VNUMKEEP)
{
break;
}
_rnums.push(i);
}
}
//find all empty npc objects
for (i = _vnumrange.min; i != _vnumrange.max; ++i)
{
if (_mnums.size() == VNUMKEEP)
{
break;
}
if (!NpcExists(i))
{
_mnums.push(i);
}
}
}
void Zone::Update()
{
}
void Zone::Serialize(TiXmlElement* root)
{
root->SetAttribute("name", _name.c_str());
root->SetAttribute("flags", _flags);
root->SetAttribute("creation", _creation);
root->SetAttribute("opened", _opened);
root->SetAttribute("resetmsg", _resetmsg.c_str());
root->SetAttribute("resetfreq", _resetfreq);
root->SetAttribute("expbonus", _expbonus);
root->SetAttribute("goldbonus", _goldbonus);
root->SetAttribute("minvnum", _vnumrange.min);
root->SetAttribute("maxvnum", _vnumrange.max);
SerializeList<StaticObject, std::vector<StaticObject*>, std::vector<StaticObject*>::iterator>("vobjes", "vobj", root, _virtualobjs);
SerializeList<Room, std::vector<Room*>, std::vector<Room*>::iterator>("rooms", "room", root, _roomobjs);
SerializeList<Npc, std::vector<Npc*>, std::vector<Npc*>::iterator>("npcs", "npc", root, _mobobjs);
}
void Zone::Deserialize(TiXmlElement* zone)
{
unsigned int u = 0;
World* world = World::GetPtr();
_name = zone->Attribute("name");
zone->Attribute("flags", &_flags);
zone->Attribute("creation", &u);
_creation = u;
zone->Attribute("opened", &u);
_opened = u;
_resetmsg = zone->Attribute("resetmsg");
zone->Attribute("resetfreq", &_resetfreq);
zone->Attribute("expbonus", &_expbonus);
zone->Attribute("goldbonus", &_goldbonus);
zone->Attribute("minvnum", &(_vnumrange.min));
zone->Attribute("maxvnum", &(_vnumrange.max));
DeserializeList<StaticObject, std::vector<StaticObject*> >(zone, "vobjes", _virtualobjs);
DeserializeList<Room, std::vector<Room*> >(zone, "rooms", _roomobjs);
DeserializeList<Npc, std::vector<Npc*> >(zone, "npcs", _mobobjs);
for (auto it: _roomobjs)
{
world->AddRoom(it);
_rooms[it->GetOnum()] = it;
it->SetZone(this);
}
for (auto it: _virtualobjs)
{
_virtuals[it->GetOnum()] = it;
world->AddVirtual(it);
}
}
BOOL InitializeZones()
{
World* world = World::GetPtr();
point p;
struct stat FInfo;
world->WriteLog("Initializing areas.");
if ((stat(AREA_STARTFILE,&FInfo))!=-1)
{
Zone::LoadZones();
}
else
{
#ifdef NO_INIT_DEFAULTS
world->WriteLog("No area file exists, and NO_INIT_DEFAULTS was enabled, exiting.");
return false;
}
#else
world->WriteLog("No area found, creating default.");
//no zones and rooms exist, create a first zone/room.
Zone*zone=new Zone();
if (!zone)
{
return false;
}
zone->SetName("Start");
if (!world->AddZone(zone))
{
return false;
}
zone->SetRange(1, 100);
zone->CalculateVnumRanges();
Room* room = zone->AddRoom(ROOM_START);
room->SetName("A blank room");
room->SetCoord(p);
if (!Zone::SaveZones())
{
return false;
}
}
#endif
zone_saves = 0;
world->events.AddCallback("WorldPulse",
std::bind(&Zone::Autosave, std::placeholders::_1, std::placeholders::_2));
world->events.AddCallback("Shutdown",
std::bind(&Zone::Shutdown, std::placeholders::_1, std::placeholders::_2));
world->events.AddCallback("Copyover",
std::bind(&Zone::Shutdown, std::placeholders::_1, std::placeholders::_2));
return true;
}
BOOL Zone::SaveZones()
{
World* world = World::GetPtr();
std::vector<Zone*> *zones=new std::vector<Zone*>();
std::string path;
world->GetZones(zones);
if (zones->size())
{
for (Zone* zone:*zones)
{
TiXmlDocument doc;
TiXmlElement* zelement = new TiXmlElement("zone");
TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", "");
doc.LinkEndChild(decl);
zone->Serialize(zelement);
doc.LinkEndChild(zelement);
path = AREA_DIR+zone->GetName();
Lower(path);
doc.SaveFile(path.c_str());
}
}
delete zones;
return true;
}
BOOL Zone::LoadZones()
{
World* world = World::GetPtr();
Zone* zone=nullptr;
TiXmlElement* root = nullptr;
TiXmlNode* node = nullptr;
dirent* cdir = NULL;
DIR* dir = opendir(AREA_DIR);
if (!dir)
{
return false;
}
while ((cdir = readdir(dir)))
{
if (cdir->d_name[0] == '.')
{
continue;
}
TiXmlDocument doc((std::string(AREA_DIR)+cdir->d_name).c_str());
if (!doc.LoadFile())
{
closedir(dir);
return false;
}
zone = new Zone();
node = doc.FirstChild("zone");
if (!node)
{
closedir(dir);
return false;
}
root = node->ToElement();
zone->Deserialize(root);
world->AddZone(zone);
}
return true;
}
CEVENT(Zone, Autosave)
{
zone_saves++;
if (zone_saves >= 100)
{
Zone::SaveZones();
zone_saves = 0;
}
}
CEVENT(Zone, Shutdown)
{
Zone::SaveZones();
}
<commit_msg>Deserialized NPCS register themselves with world now as well.<commit_after>#include <tinyxml.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <list>
#include <vector>
#include <unordered_map>
#include <functional>
#include <algorithm>
#include "zone.h"
#include "world.h"
#include "room.h"
#include "staticObject.h"
#include "event.h"
#include "utils.h"
#include "serializationHelpers.hpp"
static int zone_saves;
Zone::Zone()
{
_vnumrange.min = 0;
_vnumrange.max = 0;
_goldbonus = 0;
_expbonus = 0;
_resetfreq = 240;
_resetmsg = "With a pop, the area resets around you.";
_lastreset=time(NULL);
_creation = time(NULL);
_opened = 0;
_flags = 0;
}
Zone::~Zone()
{
for(auto it: _virtualobjs)
{
delete it;
}
for (auto it: _objects)
{
delete it;
}
for (auto it: _roomobjs)
{
delete it;
}
for (auto it: _mobobjs)
{
delete it;
}
}
std::string Zone::GetName() const
{
return _name;
}
void Zone::SetName(const std::string &name)
{
_name=name;
}
void Zone::SetRange(int min, int max)
{
_vnumrange.min = min;
_vnumrange.max = max;
}
int Zone::GetMinVnum()
{
return _vnumrange.min;
}
int Zone::GetMaxVnum()
{
return _vnumrange.max;
}
Room* Zone::AddRoom()
{
World* world = World::GetPtr();
Room* room = NULL;
VNUM num = 0;
if (_rnums.empty())
{
CalculateVnumRanges();
if (_rnums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
room = new Room();
num = _rnums.top();
_rnums.pop();
room->SetOnum(num);
room->SetZone(this);
_rooms[num] = room;
_roomobjs.push_back(room);
world->AddRoom(room);
return room;
}
Room* Zone::AddRoom(VNUM num)
{
World* world = World::GetPtr();
VNUM cur = 0;
std::stack<VNUM> temp;
Room* room = NULL;
BOOL found = false;
if (_rnums.empty())
{
CalculateVnumRanges();
if (_rnums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
room = new Room();
while (!_rnums.empty())
{
cur = _rnums.top();
_rnums.pop();
if (cur == num)
{
found = true;
continue;
}
temp.push(cur);
}
if (!found)
{
throw(std::runtime_error("That num wasn't found."));
}
_rnums = temp;
room->SetOnum(num);
room->SetZone(this);
_rooms[num] = room;
_roomobjs.push_back(room);
world->AddRoom(room);
return room;
}
BOOL Zone::RemoveRoom(VNUM num)
{
std::vector<Room*>::iterator it, itEnd;
if (_rooms.count(num))
{
itEnd = _roomobjs.end();
for (it = _roomobjs.begin(); it != itEnd; ++it)
{
if ((*it)->GetOnum() == num)
{
_roomobjs.erase(it);
delete _rooms[num];
_rooms.erase(num);
return true;
}
}
}
return false;
}
void Zone::GetRooms(std::vector<Room*> *rooms)
{
std::copy(_roomobjs.begin(), _roomobjs.end(), std::back_inserter(*rooms));
}
BOOL Zone::RoomExists(VNUM num)
{
return (_rooms.count(num) ? true : false);
}
StaticObject* Zone::AddVirtual()
{
World* world = World::GetPtr();
StaticObject* obj = NULL;
VNUM num = 0;
if (_onums.empty())
{
CalculateVnumRanges();
if (_onums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
obj = new StaticObject();
num = _onums.top();
_onums.pop();
obj->SetOnum(num);
_virtuals[num] = obj;
_virtualobjs.push_back(obj);
world->AddVirtual(obj);
return obj;
}
BOOL Zone::RemoveVirtual(VNUM num)
{
std::vector<StaticObject*>::iterator it, itEnd;
itEnd = _virtualobjs.end();
for (it = _virtualobjs.begin(); it != itEnd; ++it)
{
if ((*it)->GetOnum() == num)
{
_virtualobjs.erase(it);
delete _virtualobjs[num];
_virtuals.erase(num);
return true;
}
}
return false;
}
StaticObject* Zone::GetVirtual(VNUM num)
{
if (VirtualExists(num))
{
return _virtuals[num];
}
return nullptr;
}
void Zone::GetVirtuals(std::vector<StaticObject*>* objects)
{
for (auto it: _virtuals)
{
objects->push_back(it.second);
}
}
BOOL Zone::VirtualExists(VNUM num)
{
return (_virtuals.count(num) ? true : false);
}
Npc* Zone::AddNpc()
{
World* world = World::GetPtr();
Npc* mob = nullptr;
VNUM num = 0;
if (_mnums.empty())
{
CalculateVnumRanges();
if (_mnums.empty())
{
throw(std::runtime_error("No more vnums available"));
}
}
mob = new Npc();
num = _mnums.top();
_mnums.pop();
mob->SetOnum(num);
_mobs[num] = mob;
_mobobjs.push_back(mob);
world->AddNpc(mob);
return mob;
}
BOOL Zone::RemoveNpc(VNUM num)
{
std::vector<Npc*>::iterator it, itEnd;
itEnd = _mobobjs.end();
for (it = _mobobjs.begin(); it != itEnd; ++it)
{
if ((*it)->GetOnum() == num)
{
_mobobjs.erase(it);
delete _mobs[num];
_mobs.erase(num);
return true;
}
}
return false;
}
Npc* Zone::GetNpc(VNUM num)
{
if (NpcExists(num))
{
return _mobs[num];
}
return nullptr;
}
void Zone::GetNpcs(std::vector<Npc*>* npcs)
{
std::copy(_mobobjs.begin(), _mobobjs.end(), std::back_inserter(*npcs));
}
BOOL Zone::NpcExists(VNUM num)
{
return (_mobs.count(num) ? true : false);
}
Npc* Zone::CreateNpc(VNUM num, Room* origin)
{
Npc* templ = GetNpc(num);
Npc* ret = nullptr;
if (!templ)
{
return nullptr;
}
ret = new Npc();
templ->Copy(ret);
ret->SetOrigin(origin);
ret->EnterGame();
ret->InitializeUuid();
if (!ret->MoveTo(origin))
{
delete ret;
return nullptr;
}
return ret;
}
void Zone::CalculateVnumRanges()
{
int i = 0; //for counter
//find all empty virtual objects.
for (i = _vnumrange.min; i != _vnumrange.max; ++i)
{
if (!VirtualExists(i))
{
if (_onums.size() == VNUMKEEP)
{
break;
}
_onums.push(i);
}
}
//find all empty room objects.
for (i = _vnumrange.min; i != _vnumrange.max; ++i)
{
if (!RoomExists(i))
{
if (_rnums.size() == VNUMKEEP)
{
break;
}
_rnums.push(i);
}
}
//find all empty npc objects
for (i = _vnumrange.min; i != _vnumrange.max; ++i)
{
if (_mnums.size() == VNUMKEEP)
{
break;
}
if (!NpcExists(i))
{
_mnums.push(i);
}
}
}
void Zone::Update()
{
}
void Zone::Serialize(TiXmlElement* root)
{
root->SetAttribute("name", _name.c_str());
root->SetAttribute("flags", _flags);
root->SetAttribute("creation", _creation);
root->SetAttribute("opened", _opened);
root->SetAttribute("resetmsg", _resetmsg.c_str());
root->SetAttribute("resetfreq", _resetfreq);
root->SetAttribute("expbonus", _expbonus);
root->SetAttribute("goldbonus", _goldbonus);
root->SetAttribute("minvnum", _vnumrange.min);
root->SetAttribute("maxvnum", _vnumrange.max);
SerializeList<StaticObject, std::vector<StaticObject*>, std::vector<StaticObject*>::iterator>("vobjes", "vobj", root, _virtualobjs);
SerializeList<Room, std::vector<Room*>, std::vector<Room*>::iterator>("rooms", "room", root, _roomobjs);
SerializeList<Npc, std::vector<Npc*>, std::vector<Npc*>::iterator>("npcs", "npc", root, _mobobjs);
}
void Zone::Deserialize(TiXmlElement* zone)
{
unsigned int u = 0;
World* world = World::GetPtr();
_name = zone->Attribute("name");
zone->Attribute("flags", &_flags);
zone->Attribute("creation", &u);
_creation = u;
zone->Attribute("opened", &u);
_opened = u;
_resetmsg = zone->Attribute("resetmsg");
zone->Attribute("resetfreq", &_resetfreq);
zone->Attribute("expbonus", &_expbonus);
zone->Attribute("goldbonus", &_goldbonus);
zone->Attribute("minvnum", &(_vnumrange.min));
zone->Attribute("maxvnum", &(_vnumrange.max));
DeserializeList<StaticObject, std::vector<StaticObject*> >(zone, "vobjes", _virtualobjs);
DeserializeList<Room, std::vector<Room*> >(zone, "rooms", _roomobjs);
DeserializeList<Npc, std::vector<Npc*> >(zone, "npcs", _mobobjs);
for (auto it: _roomobjs)
{
world->AddRoom(it);
_rooms[it->GetOnum()] = it;
it->SetZone(this);
}
for (auto it: _virtualobjs)
{
_virtuals[it->GetOnum()] = it;
world->AddVirtual(it);
}
for (auto it: _mobobjs)
{
world->AddNpc(it);
_mobs[it->GetOnum()] = it;
}
}
BOOL InitializeZones()
{
World* world = World::GetPtr();
point p;
struct stat FInfo;
world->WriteLog("Initializing areas.");
if ((stat(AREA_STARTFILE,&FInfo))!=-1)
{
Zone::LoadZones();
}
else
{
#ifdef NO_INIT_DEFAULTS
world->WriteLog("No area file exists, and NO_INIT_DEFAULTS was enabled, exiting.");
return false;
}
#else
world->WriteLog("No area found, creating default.");
//no zones and rooms exist, create a first zone/room.
Zone*zone=new Zone();
if (!zone)
{
return false;
}
zone->SetName("Start");
if (!world->AddZone(zone))
{
return false;
}
zone->SetRange(1, 100);
zone->CalculateVnumRanges();
Room* room = zone->AddRoom(ROOM_START);
room->SetName("A blank room");
room->SetCoord(p);
if (!Zone::SaveZones())
{
return false;
}
}
#endif
zone_saves = 0;
world->events.AddCallback("WorldPulse",
std::bind(&Zone::Autosave, std::placeholders::_1, std::placeholders::_2));
world->events.AddCallback("Shutdown",
std::bind(&Zone::Shutdown, std::placeholders::_1, std::placeholders::_2));
world->events.AddCallback("Copyover",
std::bind(&Zone::Shutdown, std::placeholders::_1, std::placeholders::_2));
return true;
}
BOOL Zone::SaveZones()
{
World* world = World::GetPtr();
std::vector<Zone*> *zones=new std::vector<Zone*>();
std::string path;
world->GetZones(zones);
if (zones->size())
{
for (Zone* zone:*zones)
{
TiXmlDocument doc;
TiXmlElement* zelement = new TiXmlElement("zone");
TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", "");
doc.LinkEndChild(decl);
zone->Serialize(zelement);
doc.LinkEndChild(zelement);
path = AREA_DIR+zone->GetName();
Lower(path);
doc.SaveFile(path.c_str());
}
}
delete zones;
return true;
}
BOOL Zone::LoadZones()
{
World* world = World::GetPtr();
Zone* zone=nullptr;
TiXmlElement* root = nullptr;
TiXmlNode* node = nullptr;
dirent* cdir = NULL;
DIR* dir = opendir(AREA_DIR);
if (!dir)
{
return false;
}
while ((cdir = readdir(dir)))
{
if (cdir->d_name[0] == '.')
{
continue;
}
TiXmlDocument doc((std::string(AREA_DIR)+cdir->d_name).c_str());
if (!doc.LoadFile())
{
closedir(dir);
return false;
}
zone = new Zone();
node = doc.FirstChild("zone");
if (!node)
{
closedir(dir);
return false;
}
root = node->ToElement();
zone->Deserialize(root);
world->AddZone(zone);
}
return true;
}
CEVENT(Zone, Autosave)
{
zone_saves++;
if (zone_saves >= 100)
{
Zone::SaveZones();
zone_saves = 0;
}
}
CEVENT(Zone, Shutdown)
{
Zone::SaveZones();
}
<|endoftext|> |
<commit_before>#pragma once
#include "../../Include/CallResult.h"
#include "../../Asm/IAsmHelper.h"
#include "../Process.h"
#include <type_traits>
// TODO: Find more elegant way to deduce calling convention
// than defining each one manually
namespace blackbone
{
template<typename R, typename... Args>
class RemoteFunctionBase
{
public:
using ReturnType = std::conditional_t<std::is_same_v<R, void>, int, R>;
struct CallArguments
{
CallArguments( const Args&... args )
: arguments{ AsmVariant( args )... }
{
}
template<size_t... S>
CallArguments( const std::tuple<Args...>& args, std::index_sequence<S...> )
: arguments{ std::get<S>( args )... }
{
}
CallArguments( const std::initializer_list<AsmVariant>& args )
: arguments{ args }
{
// Since initializer_list can't be moved from, dataStruct types must be fixed
for (auto& arg : arguments)
{
if (!arg.buf.empty())
arg.imm_val = reinterpret_cast<uintptr_t>(arg.buf.data());
}
}
// Manually set argument to custom value
void set( int pos, const AsmVariant& newVal )
{
if (arguments.size() > static_cast<size_t>(pos))
arguments[pos] = newVal;
}
std::vector<AsmVariant> arguments;
};
public:
RemoteFunctionBase( Process& proc, ptr_t ptr, eCalligConvention conv )
: _process( proc )
, _ptr( ptr )
, _conv( conv )
{
static_assert(
(... && !std::is_reference_v<Args>),
"Please replace reference type with pointer type in function type specification"
);
}
call_result_t<ReturnType> Call( CallArguments& args, ThreadPtr contextThread = nullptr )
{
ReturnType result = {};
uint64_t tmpResult = 0;
NTSTATUS status = STATUS_SUCCESS;
auto a = AsmFactory::GetAssembler( _process.core().isWow64() );
// Ensure RPC environment exists
auto mode = contextThread == _process.remote().getWorker() ? Worker_CreateNew : Worker_None;
status = _process.remote().CreateRPCEnvironment( mode, contextThread != nullptr );
if (!NT_SUCCESS( status ))
return call_result_t<ReturnType>( result, status );
// FPU check
constexpr bool isFloat = std::is_same_v<ReturnType, float>;
constexpr bool isDouble = std::is_same_v<ReturnType, double> || std::is_same_v<ReturnType, long double>;
// Deduce return type
eReturnType retType = rt_int32;
if constexpr (isFloat)
retType = rt_float;
else if constexpr (isDouble)
retType = rt_double;
else if constexpr (sizeof( ReturnType ) == sizeof( uint64_t ))
retType = rt_int64;
else if constexpr (!std::is_reference_v<ReturnType> && sizeof( ReturnType ) > sizeof( uint64_t ))
retType = rt_struct;
_process.remote().PrepareCallAssembly( *a, _ptr, args.arguments, _conv, retType );
// Choose execution thread
if (!contextThread)
{
status = _process.remote().ExecInNewThread( (*a)->make(), (*a)->getCodeSize(), tmpResult );
}
else if (contextThread == _process.remote().getWorker())
{
status = _process.remote().ExecInWorkerThread( (*a)->make(), (*a)->getCodeSize(), tmpResult );
}
else
{
status = _process.remote().ExecInAnyThread( (*a)->make(), (*a)->getCodeSize(), tmpResult, contextThread );
}
// Get function return value
if (!NT_SUCCESS( status ) || !NT_SUCCESS( status = _process.remote().GetCallResult( result ) ))
return call_result_t<ReturnType>( result, status );
// Update arguments
for (auto& arg : args.arguments)
if (arg.type == AsmVariant::dataPtr)
_process.memory().Read( arg.new_imm_val, arg.size, reinterpret_cast<void*>(arg.imm_val) );
return call_result_t<ReturnType>( result, STATUS_SUCCESS );
}
bool valid() const { return _ptr != 0; }
explicit operator bool() const { return valid(); }
private:
Process& _process;
ptr_t _ptr = 0;
eCalligConvention _conv = cc_cdecl;
};
// Remote function pointer
template<typename Fn>
class RemoteFunction;
#define DECLPFN(CALL_OPT, CALL_DEF) \
template<typename R, typename... Args> \
class RemoteFunction < R( CALL_OPT*)(Args...) > : public RemoteFunctionBase<R, Args...> \
{ \
public: \
RemoteFunction( Process& proc, ptr_t ptr ) \
: RemoteFunctionBase( proc, ptr, CALL_DEF ) { } \
\
RemoteFunction( Process& proc, R( *ptr )(Args...) ) \
: RemoteFunctionBase( proc, reinterpret_cast<ptr_t>(ptr), CALL_DEF ) { } \
\
call_result_t<ReturnType> Call( const Args&... args ) \
{ \
CallArguments a( args... ); \
return RemoteFunctionBase::Call( a ); \
} \
\
call_result_t<ReturnType> Call( const std::tuple<Args...>& args, ThreadPtr contextThread = nullptr ) \
{ \
CallArguments a( args, std::index_sequence_for<Args...>() ); \
return RemoteFunctionBase::Call( a, contextThread ); \
} \
\
call_result_t<ReturnType> Call( const std::initializer_list<AsmVariant>& args, ThreadPtr contextThread = nullptr ) \
{ \
CallArguments a( args ); \
return RemoteFunctionBase::Call( a, contextThread ); \
} \
\
call_result_t<ReturnType> Call( CallArguments& args, ThreadPtr contextThread = nullptr ) \
{ \
return RemoteFunctionBase::Call( args, contextThread ); \
} \
\
call_result_t<ReturnType> operator()( const Args&... args ) \
{ \
CallArguments a( args... ); \
return RemoteFunctionBase::Call( a ); \
} \
\
auto MakeArguments( const Args&... args ) \
{ \
return RemoteFunctionBase::CallArguments( args... ); \
} \
\
auto MakeArguments( const std::initializer_list<AsmVariant>& args ) \
{ \
return RemoteFunctionBase::CallArguments( args ); \
} \
\
auto MakeArguments( const std::tuple<Args...>& args ) \
{ \
return RemoteFunctionBase::CallArguments( args, std::index_sequence_for<Args...>() ); \
} \
\
bool valid() const { return RemoteFunctionBase::valid(); } \
explicit operator bool() { return RemoteFunctionBase::valid(); } \
};
//
// Calling convention specialization
//
DECLPFN( __cdecl, cc_cdecl );
// Under AMD64 these will be same declarations as __cdecl, so compilation will fail.
#ifdef USE32
DECLPFN( __stdcall, cc_stdcall );
DECLPFN( __thiscall, cc_thiscall );
DECLPFN( __fastcall, cc_fastcall );
#endif
/// <summary>
/// Get remote function object
/// </summary>
/// <param name="ptr">Function address in the remote process</param>
/// <returns>Function object</returns>
template<typename T>
RemoteFunction<T> MakeRemoteFunction( Process& process, ptr_t ptr )
{
return RemoteFunction<T>( process, ptr );
}
/// <summary>
/// Get remote function object
/// </summary>
/// <param name="ptr">Function address in the remote process</param>
/// <returns>Function object</returns>
template<typename T>
RemoteFunction<T> MakeRemoteFunction( Process& process, T ptr )
{
return RemoteFunction<T>( process, ptr );
}
/// <summary>
/// Get remote function object
/// </summary>
/// <param name="modName">Remote module name</param>
/// <param name="name_ord">Function name or ordinal</param>
/// <returns>Function object</returns>
template<typename T>
RemoteFunction<T> MakeRemoteFunction( Process& process, const std::wstring& modName, const char* name_ord )
{
auto ptr = process.modules().GetExport( modName, name_ord );
return RemoteFunction<T>( process, ptr ? ptr->procAddress : 0 );
}
}<commit_msg>got rid of remote function macro<commit_after>#pragma once
#include "../../Include/CallResult.h"
#include "../../Asm/IAsmHelper.h"
#include "../Process.h"
#include <type_traits>
// TODO: Find more elegant way to deduce calling convention
// than defining each one manually
namespace blackbone
{
template<eCalligConvention Conv, typename R, typename... Args>
class RemoteFunctionBase
{
public:
using ReturnType = std::conditional_t<std::is_same_v<R, void>, int, R>;
struct CallArguments
{
CallArguments( const Args&... args )
: arguments{ AsmVariant( args )... }
{
}
template<size_t... S>
CallArguments( const std::tuple<Args...>& args, std::index_sequence<S...> )
: arguments{ std::get<S>( args )... }
{
}
CallArguments( const std::initializer_list<AsmVariant>& args )
: arguments{ args }
{
// Since initializer_list can't be moved from, dataStruct types must be fixed
for (auto& arg : arguments)
{
if (!arg.buf.empty())
arg.imm_val = reinterpret_cast<uintptr_t>(arg.buf.data());
}
}
// Manually set argument to custom value
void set( int pos, const AsmVariant& newVal )
{
if (arguments.size() > static_cast<size_t>(pos))
arguments[pos] = newVal;
}
std::vector<AsmVariant> arguments;
};
public:
RemoteFunctionBase( Process& proc, ptr_t ptr )
: _process( proc )
, _ptr( ptr )
{
static_assert(
(... && !std::is_reference_v<Args>),
"Please replace reference type with pointer type in function type specification"
);
}
call_result_t<ReturnType> Call( CallArguments& args, ThreadPtr contextThread = nullptr )
{
ReturnType result = {};
uint64_t tmpResult = 0;
NTSTATUS status = STATUS_SUCCESS;
auto a = AsmFactory::GetAssembler( _process.core().isWow64() );
// Ensure RPC environment exists
auto mode = contextThread == _process.remote().getWorker() ? Worker_CreateNew : Worker_None;
status = _process.remote().CreateRPCEnvironment( mode, contextThread != nullptr );
if (!NT_SUCCESS( status ))
return call_result_t<ReturnType>( result, status );
// FPU check
constexpr bool isFloat = std::is_same_v<ReturnType, float>;
constexpr bool isDouble = std::is_same_v<ReturnType, double> || std::is_same_v<ReturnType, long double>;
// Deduce return type
eReturnType retType = rt_int32;
if constexpr (isFloat)
retType = rt_float;
else if constexpr (isDouble)
retType = rt_double;
else if constexpr (sizeof( ReturnType ) == sizeof( uint64_t ))
retType = rt_int64;
else if constexpr (!std::is_reference_v<ReturnType> && sizeof( ReturnType ) > sizeof( uint64_t ))
retType = rt_struct;
_process.remote().PrepareCallAssembly( *a, _ptr, args.arguments, Conv, retType );
// Choose execution thread
if (!contextThread)
{
status = _process.remote().ExecInNewThread( (*a)->make(), (*a)->getCodeSize(), tmpResult );
}
else if (contextThread == _process.remote().getWorker())
{
status = _process.remote().ExecInWorkerThread( (*a)->make(), (*a)->getCodeSize(), tmpResult );
}
else
{
status = _process.remote().ExecInAnyThread( (*a)->make(), (*a)->getCodeSize(), tmpResult, contextThread );
}
// Get function return value
if (!NT_SUCCESS( status ) || !NT_SUCCESS( status = _process.remote().GetCallResult( result ) ))
return call_result_t<ReturnType>( result, status );
// Update arguments
for (auto& arg : args.arguments)
if (arg.type == AsmVariant::dataPtr)
_process.memory().Read( arg.new_imm_val, arg.size, reinterpret_cast<void*>(arg.imm_val) );
return call_result_t<ReturnType>( result, STATUS_SUCCESS );
}
call_result_t<ReturnType> Call( const Args&... args )
{
CallArguments a( args... );
return Call( a, nullptr );
}
call_result_t<ReturnType> Call( const std::tuple<Args...>& args, ThreadPtr contextThread = nullptr )
{
CallArguments a( args, std::index_sequence_for<Args...>() );
return Call( a, contextThread );
}
call_result_t<ReturnType> Call( const std::initializer_list<AsmVariant>& args, ThreadPtr contextThread = nullptr )
{
CallArguments a( args );
return Call( a, contextThread );
}
call_result_t<ReturnType> operator()( const Args&... args )
{
CallArguments a( args... );
return Call( a );
}
auto MakeArguments( const Args&... args )
{
return CallArguments( args... );
}
auto MakeArguments( const std::initializer_list<AsmVariant>& args )
{
return CallArguments( args );
}
auto MakeArguments( const std::tuple<Args...>& args )
{
return CallArguments( args, std::index_sequence_for<Args...>() );
}
bool valid() const { return _ptr != 0; }
explicit operator bool() const { return valid(); }
private:
Process& _process;
ptr_t _ptr = 0;
};
// Remote function pointer
template<typename Fn>
class RemoteFunction;
//
// Calling convention specialization
//
template<typename R, typename... Args> \
class RemoteFunction <R( __cdecl* )(Args...)> : public RemoteFunctionBase<cc_cdecl, R, Args...>
{
public:
using RemoteFunctionBase::RemoteFunctionBase;
RemoteFunction( Process& proc, R( __cdecl* ptr )(Args...) )
: RemoteFunctionBase( proc, reinterpret_cast<ptr_t>(ptr) )
{
}
};
// Under AMD64 these will be same declarations as __cdecl, so compilation will fail.
#ifdef USE32
template<typename R, typename... Args>
class RemoteFunction <R( __stdcall* )(Args...)> : public RemoteFunctionBase<cc_stdcall, R, Args...>
{
public:
using RemoteFunctionBase::RemoteFunctionBase;
RemoteFunction( Process& proc, R( __stdcall* ptr )(Args...) )
: RemoteFunctionBase( proc, reinterpret_cast<ptr_t>(ptr) )
{
}
};
template<typename R, typename... Args>
class RemoteFunction <R( __thiscall* )(Args...)> : public RemoteFunctionBase<cc_thiscall, R, Args...>
{
public:
using RemoteFunctionBase::RemoteFunctionBase;
RemoteFunction( Process& proc, R( __thiscall* ptr )(Args...) )
: RemoteFunctionBase( proc, reinterpret_cast<ptr_t>(ptr) )
{
}
};
template<typename R, typename... Args>
class RemoteFunction <R( __fastcall* )(Args...)> : public RemoteFunctionBase<cc_fastcall, R, Args...>
{
public:
using RemoteFunctionBase::RemoteFunctionBase;
RemoteFunction( Process& proc, R( __fastcall* ptr )(Args...) )
: RemoteFunctionBase( proc, reinterpret_cast<ptr_t>(ptr) )
{
}
};
#endif
/// <summary>
/// Get remote function object
/// </summary>
/// <param name="ptr">Function address in the remote process</param>
/// <returns>Function object</returns>
template<typename T>
RemoteFunction<T> MakeRemoteFunction( Process& process, ptr_t ptr )
{
return RemoteFunction<T>( process, ptr );
}
/// <summary>
/// Get remote function object
/// </summary>
/// <param name="ptr">Function address in the remote process</param>
/// <returns>Function object</returns>
template<typename T>
RemoteFunction<T> MakeRemoteFunction( Process& process, T ptr )
{
return RemoteFunction<T>( process, ptr );
}
/// <summary>
/// Get remote function object
/// </summary>
/// <param name="modName">Remote module name</param>
/// <param name="name_ord">Function name or ordinal</param>
/// <returns>Function object</returns>
template<typename T>
RemoteFunction<T> MakeRemoteFunction( Process& process, const std::wstring& modName, const char* name_ord )
{
auto ptr = process.modules().GetExport( modName, name_ord );
return RemoteFunction<T>( process, ptr ? ptr->procAddress : 0 );
}
}<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RL78/L1C グループ・ペリフェラル
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "L1C/system.hpp"
#include "L1C/port.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ペリフェラル種別
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class peripheral : uint8_t {
ITM, ///< 12ビットインターバルタイマー
ADC, ///< A/D コンバーター
I2C, ///< I2C インターフェース
SAU00, ///< シリアル・アレイ・ユニット00
SAU01, ///< シリアル・アレイ・ユニット01
SAU02, ///< シリアル・アレイ・ユニット02
SAU03, ///< シリアル・アレイ・ユニット03
SAU10, ///< シリアル・アレイ・ユニット10
SAU11, ///< シリアル・アレイ・ユニット11
SAU12, ///< シリアル・アレイ・ユニット12
SAU13, ///< シリアル・アレイ・ユニット13
TAU00, ///< タイマー・アレイ・ユニット00
TAU01, ///< タイマー・アレイ・ユニット01
TAU02, ///< タイマー・アレイ・ユニット02
TAU03, ///< タイマー・アレイ・ユニット03
TAU04, ///< タイマー・アレイ・ユニット04
TAU05, ///< タイマー・アレイ・ユニット05
TAU06, ///< タイマー・アレイ・ユニット06
TAU07, ///< タイマー・アレイ・ユニット07
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 機能マネージメント
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct manage {
//-------------------------------------------------------------//
/*!
@brief ペリフェラル有効(無効)
@param[in] per ペリフェラル型
@param[in] ena 無効の場合「false」
*/
//-------------------------------------------------------------//
static void enable(peripheral per, bool ena = true)
{
static uint8_t sau_refc = 0;
static uint8_t tau_refc = 0;
switch(per) {
case peripheral::ITM:
PER1.TMKAEN = ena;
break;
case peripheral::ADC:
PER0.ADCEN = ena;
break;
case peripheral::SAU00:
case peripheral::SAU01:
case peripheral::SAU02:
case peripheral::SAU03:
{
uint8_t refc = 1 << (static_cast<uint8_t>(per) - static_cast<uint8_t>(peripheral::SAU00));
if(ena) sau_refc |= refc;
else sau_refc &= ~refc;
if(sau_refc & 0b00001111) {
PER0.SAU0EN = 1;
} else {
PER0.SAU0EN = 0;
}
}
break;
case peripheral::SAU10:
case peripheral::SAU11:
case peripheral::SAU12:
case peripheral::SAU13:
{
uint8_t refc = 1 << (static_cast<uint8_t>(per) - static_cast<uint8_t>(peripheral::SAU00));
if(ena) sau_refc |= refc;
else sau_refc &= ~refc;
if(sau_refc & 0b11110000) {
PER0.SAU1EN = 1;
} else {
PER0.SAU1EN = 0;
}
}
break;
case peripheral::TAU00:
case peripheral::TAU01:
case peripheral::TAU02:
case peripheral::TAU03:
case peripheral::TAU04:
case peripheral::TAU05:
case peripheral::TAU06:
case peripheral::TAU07:
{
uint8_t refc = 1 << (static_cast<uint8_t>(per) - static_cast<uint8_t>(peripheral::TAU00));
if(ena) tau_refc |= refc;
else tau_refc &= ~refc;
if(tau_refc) {
PER0.TAU0EN = 1;
} else {
PER0.TAU0EN = 0;
}
}
break;
default:
break;
}
}
//-------------------------------------------------------------//
/*!
@brief UART ポートの設定
@param[in] per ペリフェラル型
@return SAUxx 型では無い場合「false」
*/
//-------------------------------------------------------------//
static bool set_uart_port(peripheral per)
{
switch(per) {
case peripheral::SAU00: // UART0-TX TxD0 (P26)
PM2.B6 = 0; // output
PU2.B6 = 0; // pullup offline
P2.B6 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU01: // UART0-RX RxD0 (P25)
PM2.B5 = 1; // input
PU2.B5 = 0; // pullup offline
P2.B5 = 1; // ポートレジスター RxD 切り替え
break;
case peripheral::SAU02: // UART1-TX TxD1 (P02)
PM0.B2 = 0; // output
PU0.B2 = 0; // pullup offline
P0.B2 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU03: // UART1-RX RxD1 (P01)
PM0.B1 = 1; // input
PU0.B1 = 0; // pullup offline
P0.B1 = 1; // ポートレジスター RxD 切り替え
break;
case peripheral::SAU10: // UART2-TX TxD2 (P12)
PM1.B2 = 0; // output
PU1.B2 = 0; // pullup offline
P1.B2 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU11: // UART2-RX RxD2 (P11)
PM1.B1 = 1; // input
PU1.B1 = 0; // pullup offline
P1.B1 = 1; // ポートレジスター RxD 切り替え
break;
case peripheral::SAU12: // UART3-TX TxD3 (P35)
PM3.B5 = 0; // output
PU3.B5 = 0; // pullup offline
P3.B5 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU13: // UART3-RX RxD3 (P34)
PM3.B4 = 1; // input
PU3.B4 = 0; // pullup offline
P3.B4 = 1; // ポートレジスター RxD 切り替え
break;
default:
return false;
}
return true;
}
};
}
<commit_msg>update TAU manage<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RL78/L1C グループ・ペリフェラル
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "L1C/system.hpp"
#include "L1C/port.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ペリフェラル種別
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class peripheral : uint8_t {
ITM, ///< 12ビットインターバルタイマー
ADC, ///< A/D コンバーター
I2C, ///< I2C インターフェース
SAU00, ///< シリアル・アレイ・ユニット00
SAU01, ///< シリアル・アレイ・ユニット01
SAU02, ///< シリアル・アレイ・ユニット02
SAU03, ///< シリアル・アレイ・ユニット03
SAU10, ///< シリアル・アレイ・ユニット10
SAU11, ///< シリアル・アレイ・ユニット11
SAU12, ///< シリアル・アレイ・ユニット12
SAU13, ///< シリアル・アレイ・ユニット13
TAU00, ///< タイマー・アレイ・ユニット00
TAU01, ///< タイマー・アレイ・ユニット01
TAU02, ///< タイマー・アレイ・ユニット02
TAU03, ///< タイマー・アレイ・ユニット03
TAU04, ///< タイマー・アレイ・ユニット04
TAU05, ///< タイマー・アレイ・ユニット05
TAU06, ///< タイマー・アレイ・ユニット06
TAU07, ///< タイマー・アレイ・ユニット07
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 機能マネージメント
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct manage {
//-------------------------------------------------------------//
/*!
@brief ペリフェラル有効(無効)
@param[in] per ペリフェラル型
@param[in] ena 無効の場合「false」
*/
//-------------------------------------------------------------//
static void enable(peripheral per, bool ena = true)
{
static uint8_t sau_refc = 0;
static uint8_t tau_refc = 0;
switch(per) {
case peripheral::ITM:
PER1.TMKAEN = ena;
break;
case peripheral::ADC:
PER0.ADCEN = ena;
break;
case peripheral::SAU00:
case peripheral::SAU01:
case peripheral::SAU02:
case peripheral::SAU03:
{
uint8_t refc = 1 << (static_cast<uint8_t>(per) - static_cast<uint8_t>(peripheral::SAU00));
if(ena) sau_refc |= refc;
else sau_refc &= ~refc;
if(sau_refc & 0b00001111) {
PER0.SAU0EN = 1;
} else {
PER0.SAU0EN = 0;
}
}
break;
case peripheral::SAU10:
case peripheral::SAU11:
case peripheral::SAU12:
case peripheral::SAU13:
{
uint8_t refc = 1 << (static_cast<uint8_t>(per) - static_cast<uint8_t>(peripheral::SAU00));
if(ena) sau_refc |= refc;
else sau_refc &= ~refc;
if(sau_refc & 0b11110000) {
PER0.SAU1EN = 1;
} else {
PER0.SAU1EN = 0;
}
}
break;
case peripheral::TAU00:
case peripheral::TAU01:
case peripheral::TAU02:
case peripheral::TAU03:
case peripheral::TAU04:
case peripheral::TAU05:
case peripheral::TAU06:
case peripheral::TAU07:
{
uint8_t refc = 1 << (static_cast<uint8_t>(per) - static_cast<uint8_t>(peripheral::TAU00));
if(ena) tau_refc |= refc;
else tau_refc &= ~refc;
if(tau_refc) {
PER0.TAU0EN = 1;
} else {
PER0.TAU0EN = 0;
}
}
break;
default:
break;
}
}
//-------------------------------------------------------------//
/*!
@brief UART ポートの設定
@param[in] per ペリフェラル型
@return SAUxx 型では無い場合「false」
*/
//-------------------------------------------------------------//
static bool set_uart_port(peripheral per)
{
switch(per) {
case peripheral::SAU00: // UART0-TX TxD0 (P26)
PM2.B6 = 0; // output
PU2.B6 = 0; // pullup offline
P2.B6 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU01: // UART0-RX RxD0 (P25)
PM2.B5 = 1; // input
PU2.B5 = 0; // pullup offline
P2.B5 = 1; // ポートレジスター RxD 切り替え
break;
case peripheral::SAU02: // UART1-TX TxD1 (P02)
PM0.B2 = 0; // output
PU0.B2 = 0; // pullup offline
P0.B2 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU03: // UART1-RX RxD1 (P01)
PM0.B1 = 1; // input
PU0.B1 = 0; // pullup offline
P0.B1 = 1; // ポートレジスター RxD 切り替え
break;
case peripheral::SAU10: // UART2-TX TxD2 (P12)
PM1.B2 = 0; // output
PU1.B2 = 0; // pullup offline
P1.B2 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU11: // UART2-RX RxD2 (P11)
PM1.B1 = 1; // input
PU1.B1 = 0; // pullup offline
P1.B1 = 1; // ポートレジスター RxD 切り替え
break;
case peripheral::SAU12: // UART3-TX TxD3 (P35)
PM3.B5 = 0; // output
PU3.B5 = 0; // pullup offline
P3.B5 = 1; // ポートレジスター TxD 切り替え
break;
case peripheral::SAU13: // UART3-RX RxD3 (P34)
PM3.B4 = 1; // input
PU3.B4 = 0; // pullup offline
P3.B4 = 1; // ポートレジスター RxD 切り替え
break;
default:
return false;
}
return true;
}
//-------------------------------------------------------------//
/*!
@brief TAU ポートの設定
@param[in] per ペリフェラル型
@param[in] dir 出力の場合「true」
@return SAUxx 型では無い場合「false」
*/
//-------------------------------------------------------------//
static bool set_tau_port(peripheral per, bool dir)
{
switch(per) {
case peripheral::TAU00:
PM0.B3 = !dir;
P0.B3 = 0;
break;
case peripheral::TAU01:
PM3.B2 = !dir;
P3.B2 = 0;
break;
case peripheral::TAU02:
PM0.B5 = !dir;
P5.B5 = 0;
break;
case peripheral::TAU03:
PM3.B0 = !dir;
P3.B0 = 0;
break;
case peripheral::TAU04:
PM2.B2 = !dir;
P2.B2 = 0;
break;
case peripheral::TAU05:
PM2.B7 = !dir;
P2.B7 = 0;
break;
case peripheral::TAU06:
PM0.B7 = !dir;
P0.B7 = 0;
break;
case peripheral::TAU07:
PM2.B3 = !dir;
P2.B3 = 0;
break;
default:
return false;
}
return true;
}
};
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ContextHelper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:23:06 $
*
* 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_chart2.hxx"
#include "ContextHelper.hxx"
#include <cppuhelper/component_context.hxx>
#include <vector>
using namespace ::com::sun::star;
namespace chart
{
namespace ContextHelper
{
uno::Reference< uno::XComponentContext >
createContext(
const tContextEntryMapType & rMap,
const uno::Reference< uno::XComponentContext > & rDelegateContext )
{
::std::vector< ::cppu::ContextEntry_Init > aVec( rMap.size());
for( tContextEntryMapType::const_iterator aIt = rMap.begin();
aIt != rMap.end();
++aIt )
{
aVec.push_back( ::cppu::ContextEntry_Init( (*aIt).first, (*aIt).second) );
}
return ::cppu::createComponentContext( & aVec[0], aVec.size(), rDelegateContext );
}
} // namespace ContextHelper
} // namespace chart
<commit_msg>INTEGRATION: CWS changefileheader (1.3.170); FILE MERGED 2008/03/28 16:44:21 rt 1.3.170.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ContextHelper.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ContextHelper.hxx"
#include <cppuhelper/component_context.hxx>
#include <vector>
using namespace ::com::sun::star;
namespace chart
{
namespace ContextHelper
{
uno::Reference< uno::XComponentContext >
createContext(
const tContextEntryMapType & rMap,
const uno::Reference< uno::XComponentContext > & rDelegateContext )
{
::std::vector< ::cppu::ContextEntry_Init > aVec( rMap.size());
for( tContextEntryMapType::const_iterator aIt = rMap.begin();
aIt != rMap.end();
++aIt )
{
aVec.push_back( ::cppu::ContextEntry_Init( (*aIt).first, (*aIt).second) );
}
return ::cppu::createComponentContext( & aVec[0], aVec.size(), rDelegateContext );
}
} // namespace ContextHelper
} // namespace chart
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_READER_HPP
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_READER_HPP
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include "../config.hpp"
#include "../input_error.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
std::FILE* file_open( const char* filename )
{
errno = 0;
#if defined( _MSC_VER )
std::FILE* file;
if(::fopen_s( &file, filename, "rb" ) == 0 )
#else
if( auto* file = std::fopen( filename, "rb" ) )
#endif
{
return file;
}
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fopen() file " << filename << " for reading" );
}
struct file_close
{
void operator()( FILE* f ) const
{
std::fclose( f );
}
};
class file_reader
{
public:
explicit file_reader( const char* filename )
: m_source( filename ),
m_file( file_open( m_source ) )
{
}
file_reader( FILE* file, const char* filename )
: m_source( filename ),
m_file( file )
{
}
file_reader( const file_reader& ) = delete;
void operator=( const file_reader& ) = delete;
std::size_t size() const
{
errno = 0;
if( std::fseek( m_file.get(), 0, SEEK_END ) != 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fseek() to end of file " << m_source ); // LCOV_EXCL_LINE
}
errno = 0;
const auto s = std::ftell( m_file.get() );
if( s < 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to ftell() file size of file " << m_source ); // LCOV_EXCL_LINE
}
errno = 0;
if( std::fseek( m_file.get(), 0, SEEK_SET ) != 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fseek() to beginning of file " << m_source ); // LCOV_EXCL_LINE
}
return std::size_t( s );
}
std::string read() const
{
std::string nrv;
nrv.resize( size() );
errno = 0;
if( ( nrv.size() != 0 ) && ( std::fread( &nrv[ 0 ], nrv.size(), 1, m_file.get() ) != 1 ) ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fread() file " << m_source << " size " << nrv.size() ); // LCOV_EXCL_LINE
}
return nrv;
}
private:
const char* const m_source;
const std::unique_ptr< std::FILE, file_close > m_file;
};
} // namespace internal
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
<commit_msg>Add missing inline to avoid linking error.<commit_after>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_READER_HPP
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_READER_HPP
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include "../config.hpp"
#include "../input_error.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
inline std::FILE* file_open( const char* filename )
{
errno = 0;
#if defined( _MSC_VER )
std::FILE* file;
if(::fopen_s( &file, filename, "rb" ) == 0 )
#else
if( auto* file = std::fopen( filename, "rb" ) )
#endif
{
return file;
}
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fopen() file " << filename << " for reading" );
}
struct file_close
{
void operator()( FILE* f ) const
{
std::fclose( f );
}
};
class file_reader
{
public:
explicit file_reader( const char* filename )
: m_source( filename ),
m_file( file_open( m_source ) )
{
}
file_reader( FILE* file, const char* filename )
: m_source( filename ),
m_file( file )
{
}
file_reader( const file_reader& ) = delete;
void operator=( const file_reader& ) = delete;
std::size_t size() const
{
errno = 0;
if( std::fseek( m_file.get(), 0, SEEK_END ) != 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fseek() to end of file " << m_source ); // LCOV_EXCL_LINE
}
errno = 0;
const auto s = std::ftell( m_file.get() );
if( s < 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to ftell() file size of file " << m_source ); // LCOV_EXCL_LINE
}
errno = 0;
if( std::fseek( m_file.get(), 0, SEEK_SET ) != 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fseek() to beginning of file " << m_source ); // LCOV_EXCL_LINE
}
return std::size_t( s );
}
std::string read() const
{
std::string nrv;
nrv.resize( size() );
errno = 0;
if( ( nrv.size() != 0 ) && ( std::fread( &nrv[ 0 ], nrv.size(), 1, m_file.get() ) != 1 ) ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fread() file " << m_source << " size " << nrv.size() ); // LCOV_EXCL_LINE
}
return nrv;
}
private:
const char* const m_source;
const std::unique_ptr< std::FILE, file_close > m_file;
};
} // namespace internal
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
<|endoftext|> |
<commit_before> /*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2015 Wu Lin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
*/
#include <shogun/lib/config.h>
#include <algorithm>
#include <shogun/optimization/lbfgs/LBFGSMinimizer.h>
using namespace shogun;
LBFGSMinimizer::LBFGSMinimizer()
:FirstOrderMinimizer()
{
init();
}
LBFGSMinimizer::~LBFGSMinimizer()
{
}
LBFGSMinimizer::LBFGSMinimizer(FirstOrderCostFunction *fun)
:FirstOrderMinimizer(fun)
{
init();
}
void LBFGSMinimizer::init()
{
set_lbfgs_parameters();
}
void LBFGSMinimizer::set_lbfgs_parameters(
int m,
int max_linesearch,
ELBFGSLineSearch linesearch,
int max_iterations,
float64_t delta,
int past,
float64_t epsilon,
float64_t min_step,
float64_t max_step,
float64_t ftol,
float64_t wolfe,
float64_t gtol,
float64_t xtol,
float64_t orthantwise_c,
int orthantwise_start,
int orthantwise_end)
{
m_m = m;
m_max_linesearch = max_linesearch;
m_linesearch = linesearch;
m_max_iterations = max_iterations;
m_delta = delta;
m_past = past;
m_epsilon = epsilon;
m_min_step = min_step;
m_max_step = max_step;
m_ftol = ftol;
m_wolfe = wolfe;
m_gtol = gtol;
m_xtol = xtol;
m_orthantwise_c = orthantwise_c;
m_orthantwise_start = orthantwise_start;
m_orthantwise_end = orthantwise_end;
}
void LBFGSMinimizer::init_minimization()
{
REQUIRE(m_fun, "Cost function not set!\n");
m_target_variable=m_fun->obtain_variable_reference();
REQUIRE(m_target_variable.vlen>0,"Target variable from cost function must not empty!\n");
}
float64_t LBFGSMinimizer::minimize()
{
lbfgs_parameter_t lbfgs_param;
lbfgs_param.m = m_m;
lbfgs_param.max_linesearch = m_max_linesearch;
lbfgs_param.linesearch = m_linesearch;
lbfgs_param.max_iterations = m_max_iterations;
lbfgs_param.delta = m_delta;
lbfgs_param.past = m_past;
lbfgs_param.epsilon = m_epsilon;
lbfgs_param.min_step = m_min_step;
lbfgs_param.max_step = m_max_step;
lbfgs_param.ftol = m_ftol;
lbfgs_param.wolfe = m_wolfe;
lbfgs_param.gtol = m_gtol;
lbfgs_param.xtol = m_xtol;
lbfgs_param.orthantwise_c = m_orthantwise_c;
lbfgs_param.orthantwise_start = m_orthantwise_start;
lbfgs_param.orthantwise_end = m_orthantwise_end;
init_minimization();
float64_t cost=0.0;
int error_code=lbfgs(m_target_variable.vlen, m_target_variable.vector,
&cost, LBFGSMinimizer::evaluate,
NULL, this, &lbfgs_param);
if(error_code!=0 && error_code!=LBFGS_ALREADY_MINIMIZED)
{
SG_SWARNING("Error(s) happened during L-BFGS optimization (error code:%d)\n",
error_code);
}
return cost;
}
float64_t LBFGSMinimizer::evaluate(void *obj, const float64_t *variable,
float64_t *gradient, const int dim, const float64_t step)
{
/* Note that parameters = parameters_pre_iter - step * gradient_pre_iter */
LBFGSMinimizer * obj_prt
= static_cast<LBFGSMinimizer *>(obj);
REQUIRE(obj_prt, "The instance object passed to L-BFGS optimizer should not be NULL\n");
//get the gradient wrt variable_new
SGVector<float64_t> grad=obj_prt->m_fun->get_gradient();
REQUIRE(grad.vlen==dim,
"The length of gradient (%d) and the length of variable (%d) do not match\n",
grad.vlen,dim);
std::copy(grad.vector,grad.vector+dim,gradient);
float64_t cost=obj_prt->m_fun->get_cost();
return cost;
}
<commit_msg>added some comments<commit_after> /*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2015 Wu Lin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
*/
#include <shogun/lib/config.h>
#include <algorithm>
#include <shogun/optimization/lbfgs/LBFGSMinimizer.h>
#include <shogun/optimization/FirstOrderBoundConstraintsCostFunction.h>
using namespace shogun;
LBFGSMinimizer::LBFGSMinimizer()
:FirstOrderMinimizer()
{
init();
}
LBFGSMinimizer::~LBFGSMinimizer()
{
}
LBFGSMinimizer::LBFGSMinimizer(FirstOrderCostFunction *fun)
:FirstOrderMinimizer(fun)
{
FirstOrderBoundConstraintsCostFunction* bound_constraints_fun
=dynamic_cast<FirstOrderBoundConstraintsCostFunction *>(m_fun);
if(m_fun && bound_constraints_fun)
{
SG_SWARNING("The minimizer does not support constrained minimization. All constraints will be ignored.\n")
}
init();
}
void LBFGSMinimizer::init()
{
set_lbfgs_parameters();
}
void LBFGSMinimizer::set_lbfgs_parameters(
int m,
int max_linesearch,
ELBFGSLineSearch linesearch,
int max_iterations,
float64_t delta,
int past,
float64_t epsilon,
float64_t min_step,
float64_t max_step,
float64_t ftol,
float64_t wolfe,
float64_t gtol,
float64_t xtol,
float64_t orthantwise_c,
int orthantwise_start,
int orthantwise_end)
{
m_m = m;
m_max_linesearch = max_linesearch;
m_linesearch = linesearch;
m_max_iterations = max_iterations;
m_delta = delta;
m_past = past;
m_epsilon = epsilon;
m_min_step = min_step;
m_max_step = max_step;
m_ftol = ftol;
m_wolfe = wolfe;
m_gtol = gtol;
m_xtol = xtol;
m_orthantwise_c = orthantwise_c;
m_orthantwise_start = orthantwise_start;
m_orthantwise_end = orthantwise_end;
}
void LBFGSMinimizer::init_minimization()
{
REQUIRE(m_fun, "Cost function not set!\n");
m_target_variable=m_fun->obtain_variable_reference();
REQUIRE(m_target_variable.vlen>0,"Target variable from cost function must not empty!\n");
}
float64_t LBFGSMinimizer::minimize()
{
lbfgs_parameter_t lbfgs_param;
lbfgs_param.m = m_m;
lbfgs_param.max_linesearch = m_max_linesearch;
lbfgs_param.linesearch = m_linesearch;
lbfgs_param.max_iterations = m_max_iterations;
lbfgs_param.delta = m_delta;
lbfgs_param.past = m_past;
lbfgs_param.epsilon = m_epsilon;
lbfgs_param.min_step = m_min_step;
lbfgs_param.max_step = m_max_step;
lbfgs_param.ftol = m_ftol;
lbfgs_param.wolfe = m_wolfe;
lbfgs_param.gtol = m_gtol;
lbfgs_param.xtol = m_xtol;
lbfgs_param.orthantwise_c = m_orthantwise_c;
lbfgs_param.orthantwise_start = m_orthantwise_start;
lbfgs_param.orthantwise_end = m_orthantwise_end;
init_minimization();
float64_t cost=0.0;
int error_code=lbfgs(m_target_variable.vlen, m_target_variable.vector,
&cost, LBFGSMinimizer::evaluate,
NULL, this, &lbfgs_param);
if(error_code!=0 && error_code!=LBFGS_ALREADY_MINIMIZED)
{
SG_SWARNING("Error(s) happened during L-BFGS optimization (error code:%d)\n",
error_code);
}
return cost;
}
float64_t LBFGSMinimizer::evaluate(void *obj, const float64_t *variable,
float64_t *gradient, const int dim, const float64_t step)
{
/* Note that parameters = parameters_pre_iter - step * gradient_pre_iter */
LBFGSMinimizer * obj_prt
= static_cast<LBFGSMinimizer *>(obj);
REQUIRE(obj_prt, "The instance object passed to L-BFGS optimizer should not be NULL\n");
//get the gradient wrt variable_new
SGVector<float64_t> grad=obj_prt->m_fun->get_gradient();
REQUIRE(grad.vlen==dim,
"The length of gradient (%d) and the length of variable (%d) do not match\n",
grad.vlen,dim);
std::copy(grad.vector,grad.vector+dim,gradient);
float64_t cost=obj_prt->m_fun->get_cost();
return cost;
}
<|endoftext|> |
<commit_before>
#include "CTypeEffect.h"
CTypeEffect::CTypeEffect(CPlayer* follower)
{
mFollower = follower;
mDirection = mFollower->GetPlayerRotation();
SetCenter(mFollower->GetCenter());
SetPosition(mFollower->GetPlayerPosition().GetX() - 65.f, mFollower->GetPlayerPosition().GetY() - 80.f);
mAnimation = NNAnimation::Create(30, 0.03f,
L"Sprite/WindSkill/wind_003_001.png",
L"Sprite/WindSkill/wind_003_002.png",
L"Sprite/WindSkill/wind_003_003.png",
L"Sprite/WindSkill/wind_003_004.png",
L"Sprite/WindSkill/wind_003_005.png",
L"Sprite/WindSkill/wind_003_006.png",
L"Sprite/WindSkill/wind_003_007.png",
L"Sprite/WindSkill/wind_003_008.png",
L"Sprite/WindSkill/wind_003_009.png",
L"Sprite/WindSkill/wind_003_010.png",
L"Sprite/WindSkill/wind_003_011.png",
L"Sprite/WindSkill/wind_003_012.png",
L"Sprite/WindSkill/wind_003_013.png",
L"Sprite/WindSkill/wind_003_014.png",
L"Sprite/WindSkill/wind_003_015.png",
L"Sprite/WindSkill/wind_003_016.png",
L"Sprite/WindSkill/wind_003_017.png",
L"Sprite/WindSkill/wind_003_018.png",
L"Sprite/WindSkill/wind_003_019.png",
L"Sprite/WindSkill/wind_003_020.png",
L"Sprite/WindSkill/wind_003_021.png",
L"Sprite/WindSkill/wind_003_022.png",
L"Sprite/WindSkill/wind_003_023.png",
L"Sprite/WindSkill/wind_003_024.png",
L"Sprite/WindSkill/wind_003_025.png",
L"Sprite/WindSkill/wind_003_026.png",
L"Sprite/WindSkill/wind_003_027.png",
L"Sprite/WindSkill/wind_003_028.png",
L"Sprite/WindSkill/wind_003_029.png",
L"Sprite/WindSkill/wind_003_030.png");
mMoveSpeed = 00.0f;
mLifeTime = mAnimation->GetPlayTime();
AddChild(mAnimation);
}
CTypeEffect::~CTypeEffect()
{
}
void CTypeEffect::Render()
{
IEffect::Render();
}
void CTypeEffect::Update(float dTime)
{
IEffect::Update(dTime);
SetPosition(mFollower->GetPlayerPosition());
mMoveSpeed += 600.f * dTime;
this->SetPosition(this->GetPositionX() + mMoveSpeed * std::cosf(mDirection) * dTime, this->GetPositionY() + mMoveSpeed * std::sinf(mDirection) * dTime);
if (mLifeTime < mNowLifeTime)
mIsEnd = true;
}<commit_msg># CTypeEffect object speed bug fix<commit_after>
#include "CTypeEffect.h"
CTypeEffect::CTypeEffect(CPlayer* follower)
{
mFollower = follower;
mDirection = mFollower->GetPlayerRotation();
SetCenter(mFollower->GetCenter());
SetPosition(mFollower->GetPlayerPosition().GetX() - 65.f, mFollower->GetPlayerPosition().GetY() - 80.f);
mAnimation = NNAnimation::Create(30, 0.03f,
L"Sprite/WindSkill/wind_003_001.png",
L"Sprite/WindSkill/wind_003_002.png",
L"Sprite/WindSkill/wind_003_003.png",
L"Sprite/WindSkill/wind_003_004.png",
L"Sprite/WindSkill/wind_003_005.png",
L"Sprite/WindSkill/wind_003_006.png",
L"Sprite/WindSkill/wind_003_007.png",
L"Sprite/WindSkill/wind_003_008.png",
L"Sprite/WindSkill/wind_003_009.png",
L"Sprite/WindSkill/wind_003_010.png",
L"Sprite/WindSkill/wind_003_011.png",
L"Sprite/WindSkill/wind_003_012.png",
L"Sprite/WindSkill/wind_003_013.png",
L"Sprite/WindSkill/wind_003_014.png",
L"Sprite/WindSkill/wind_003_015.png",
L"Sprite/WindSkill/wind_003_016.png",
L"Sprite/WindSkill/wind_003_017.png",
L"Sprite/WindSkill/wind_003_018.png",
L"Sprite/WindSkill/wind_003_019.png",
L"Sprite/WindSkill/wind_003_020.png",
L"Sprite/WindSkill/wind_003_021.png",
L"Sprite/WindSkill/wind_003_022.png",
L"Sprite/WindSkill/wind_003_023.png",
L"Sprite/WindSkill/wind_003_024.png",
L"Sprite/WindSkill/wind_003_025.png",
L"Sprite/WindSkill/wind_003_026.png",
L"Sprite/WindSkill/wind_003_027.png",
L"Sprite/WindSkill/wind_003_028.png",
L"Sprite/WindSkill/wind_003_029.png",
L"Sprite/WindSkill/wind_003_030.png");
mMoveSpeed = 0.0f;
mLifeTime = mAnimation->GetPlayTime();
AddChild(mAnimation);
}
CTypeEffect::~CTypeEffect()
{
}
void CTypeEffect::Render()
{
IEffect::Render();
}
void CTypeEffect::Update(float dTime)
{
IEffect::Update(dTime);
mMoveSpeed += 600.f * dTime;
this->SetPosition(this->GetPositionX() + mMoveSpeed * std::cosf(mDirection) * dTime, this->GetPositionY() + mMoveSpeed * std::sinf(mDirection) * dTime);
if (mLifeTime < mNowLifeTime)
mIsEnd = true;
}<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "keystore.h"
#include "script.h"
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
bool fCompressed = false;
CSecret secret = key.GetSecret(fCompressed);
{
LOCK(cs_KeyStore);
mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
}
return true;
}
bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
return error("CBasicKeyStore::AddCScript() : redeemScripts > %i bytes are invalid", MAX_SCRIPT_ELEMENT_SIZE);
{
LOCK(cs_KeyStore);
mapScripts[redeemScript.GetID()] = redeemScript;
}
return true;
}
bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
bool result;
{
LOCK(cs_KeyStore);
result = (mapScripts.count(hash) > 0);
}
return result;
}
bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
{
LOCK(cs_KeyStore);
ScriptMap::const_iterator mi = mapScripts.find(hash);
if (mi != mapScripts.end())
{
redeemScriptOut = (*mi).second;
return true;
}
}
return false;
}
bool CCryptoKeyStore::SetCrypted()
{
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
}
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.SetPubKey(vchPubKey);
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CPubKey vchPubKey = key.GetPubKey();
bool fCompressed;
if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.SetPubKey(vchPubKey);
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
CKey key;
if (!key.SetSecret(mKey.second.first, mKey.second.second))
return false;
const CPubKey vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
bool fCompressed;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<commit_msg>Delete keystore.cpp<commit_after><|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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 "boost/python.hpp"
#include "GafferBindings/PlugBinding.h"
#include "GafferImage/ImagePlug.h"
#include "GafferImageBindings/ImagePlugBinding.h"
using namespace boost::python;
using namespace GafferBindings;
using namespace GafferImage;
namespace
{
IECore::FloatVectorDataPtr channelData( const ImagePlug &plug, const std::string &channelName, const Imath::V2i &tile, bool copy )
{
IECorePython::ScopedGILRelease gilRelease;
IECore::ConstFloatVectorDataPtr d = plug.channelData( channelName, tile );
return copy ? d->copy() : boost::const_pointer_cast<IECore::FloatVectorData>( d );
}
IECore::ImagePrimitivePtr image( const ImagePlug &plug )
{
IECorePython::ScopedGILRelease gilRelease;
return plug.image();
}
} // namespace
void GafferImageBindings::bindImagePlug()
{
PlugClass<ImagePlug>()
.def(
init< const std::string &, Gaffer::Plug::Direction, unsigned >
(
(
arg( "name" ) = Gaffer::GraphComponent::defaultName<ImagePlug>(),
arg( "direction" ) = Gaffer::Plug::In,
arg( "flags" ) = Gaffer::Plug::Default
)
)
)
.def( "channelData", &channelData, ( arg( "_copy" ) = true ) )
.def( "channelDataHash", &ImagePlug::channelDataHash )
.def( "image", &image )
.def( "imageHash", &ImagePlug::imageHash )
.def( "tileSize", &ImagePlug::tileSize ).staticmethod( "tileSize" )
.def( "tileIndex", &ImagePlug::tileIndex ).staticmethod( "tileIndex" )
.def( "tileOrigin", &ImagePlug::tileOrigin ).staticmethod( "tileOrigin" )
;
}
<commit_msg>ImagePlug bindings : Fix GIL management bugs<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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 "boost/python.hpp"
#include "GafferBindings/PlugBinding.h"
#include "GafferImage/ImagePlug.h"
#include "GafferImageBindings/ImagePlugBinding.h"
using namespace boost::python;
using namespace GafferBindings;
using namespace GafferImage;
namespace
{
IECore::FloatVectorDataPtr channelData( const ImagePlug &plug, const std::string &channelName, const Imath::V2i &tile, bool copy )
{
IECorePython::ScopedGILRelease gilRelease;
IECore::ConstFloatVectorDataPtr d = plug.channelData( channelName, tile );
return copy ? d->copy() : boost::const_pointer_cast<IECore::FloatVectorData>( d );
}
IECore::MurmurHash channelDataHash( const ImagePlug &plug, const std::string &channelName, const Imath::V2i &tileOrigin )
{
IECorePython::ScopedGILRelease gilRelease;
return plug.channelDataHash( channelName, tileOrigin );
}
IECore::ImagePrimitivePtr image( const ImagePlug &plug )
{
IECorePython::ScopedGILRelease gilRelease;
return plug.image();
}
IECore::MurmurHash imageHash( const ImagePlug &plug )
{
IECorePython::ScopedGILRelease gilRelease;
return plug.imageHash();
}
} // namespace
void GafferImageBindings::bindImagePlug()
{
PlugClass<ImagePlug>()
.def(
init< const std::string &, Gaffer::Plug::Direction, unsigned >
(
(
arg( "name" ) = Gaffer::GraphComponent::defaultName<ImagePlug>(),
arg( "direction" ) = Gaffer::Plug::In,
arg( "flags" ) = Gaffer::Plug::Default
)
)
)
.def( "channelData", &channelData, ( arg( "_copy" ) = true ) )
.def( "channelDataHash", &channelDataHash )
.def( "image", &image )
.def( "imageHash", &imageHash )
.def( "tileSize", &ImagePlug::tileSize ).staticmethod( "tileSize" )
.def( "tileIndex", &ImagePlug::tileIndex ).staticmethod( "tileIndex" )
.def( "tileOrigin", &ImagePlug::tileOrigin ).staticmethod( "tileOrigin" )
;
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <complex>
#include <stdlib.h>
#include "eFFT.h"
#define M_PI 3.141592653589793
eFFT::eFFT(){
}
eFFT::~eFFT(){
}
int * eFFT::rrotate(int * input,unsigned int bits, int n){
int lsb=0;
for(int i=0;i<n;i++){
lsb=(input[i])&1;
lsb<<=(bits-1);
input[i]=lsb|((input[i])>>1);
}
return input;
}
int * eFFT::bitrev(int * order, unsigned int bits, int n){
int r;
int p;
for(int k=0;k<n;k++){
r=0;
p=0;
for(int i=bits-1;i>=0;i--){
int x=pow(2,i);
x&=k;
x>>=i;
p=x<<((bits-1)-(i));
r|=p;
}
order[k]=r;
}
return order;
}
std::complex<double> * eFFT::butterfly(std::complex<double> * input, int siglen, int norm, int sign){
std::complex<double> normalise = std::complex<double>(norm, 0);
unsigned int poww = ceil(log2(siglen));
int N = pow(2, poww);
unsigned int bits = log2(N);
int * order = new int[N];
std::complex<double> * output;
output = (std::complex<double>*)realloc(input, N * sizeof(std::complex<double>));
for (int i = siglen; i < N; i++){
//Zero Padding if required
output[i] = std::complex<double>(0, 0);
}
int inc = 0;
std::complex<double> tempup;
std::complex<double> tempdown;
std::complex<double> outputup;
std::complex<double> outputdown;
std::complex<double> twid;
order = bitrev(order, bits, N);
for (int i = 1; i < bits + 1; i++){
inc = N / pow(2, i);
int *w = new int[N / 2];
int incre = 0;
for (int j = 0; j < (N / 2); j++){
if ((j%inc == 0) && (j != 0)){
incre = (incre + inc) % (N / 2);
}
w[j] = incre;
}
incre = 0;
int wc = 0;
for (int k = 0,wc=0; k < N; k += 2,wc++){
tempup = output[order[k]];
tempdown = output[order[k + 1]];
twid = std::complex<double>(cos(2 * M_PI*w[wc] / N), sign*sin(2 * M_PI*w[wc] / N));
outputup = tempup + (tempdown*twid);
outputdown = tempup -(tempdown*twid);
output[order[k]] = outputup;
output[order[k + 1]] = outputdown;
}
order=rrotate(order,bits,N);
}
//Re-Order
std::complex<double> * spectra = new std::complex<double>[N];
for (int p = 0; p < N; p++){
spectra[p] = output[order[p]]/normalise;
}
return spectra;
}
std::complex<double> * eFFT::fft(std::complex<double> * input,int length){
std::complex<double> * spectra = butterfly(input, length, 1, -1);
return spectra;
}
std::complex<double> * eFFT::ifft(std::complex<double> * input,int length){
std::complex<double> * temporal = butterfly(input, length, length, 1);
return temporal;
}<commit_msg>Fixed key issues<commit_after>#include <cmath>
#include <complex>
#include <stdlib.h>
#include "eFFT.h"
#define M_PI 3.141592653589793
namespace eFFT
{
int * eFFT::rrotate(int * input,unsigned int bits, int n){
int lsb=0;
for(int i=0;i<n;i++){
lsb=(input[i])&1;
lsb<<=(bits-1);
input[i]=lsb|((input[i])>>1);
}
return input;
}
int * eFFT::bitrev(int * order, unsigned int bits, int n){
int r;
int p;
for(int k=0;k<n;k++){
r=0;
p=0;
for(int i=bits-1;i>=0;i--){
int x=pow(2,i);
x&=k;
x>>=i;
p=x<<((bits-1)-(i));
r|=p;
}
order[k]=r;
}
return order;
}
std::complex<double> * eFFT::butterfly(std::complex<double> * input, int siglen, int norm, int sign){
std::complex<double> normalise = std::complex<double>(norm, 0);
unsigned int poww = ceil(log2(siglen));
int N = pow(2, poww);
unsigned int bits = log2(N);
int * order = new int[N];
std::complex<double> * output;
output = (std::complex<double>*)realloc(input, N * sizeof(std::complex<double>));
for (int i = siglen; i < N; i++){
//Zero Padding if required
output[i] = std::complex<double>(0, 0);
}
int inc = 0;
std::complex<double> tempup;
std::complex<double> tempdown;
std::complex<double> outputup;
std::complex<double> outputdown;
std::complex<double> twid;
order = bitrev(order, bits, N);
for (int i = 1; i < bits + 1; i++){
inc = N / pow(2, i);
int *w = new int[N / 2];
int incre = 0;
for (int j = 0; j < (N / 2); j++){
if ((j%inc == 0) && (j != 0)){
incre = (incre + inc) % (N / 2);
}
w[j] = incre;
}
incre = 0;
int wc = 0;
for (int k = 0,wc=0; k < N; k += 2,wc++){
tempup = output[order[k]];
tempdown = output[order[k + 1]];
twid = std::complex<double>(cos(2 * M_PI*w[wc] / N), sign*sin(2 * M_PI*w[wc] / N));
outputup = tempup + (tempdown*twid);
outputdown = tempup -(tempdown*twid);
output[order[k]] = outputup;
output[order[k + 1]] = outputdown;
}
order=rrotate(order,bits,N);
}
//Re-Order
std::complex<double> * spectra = new std::complex<double>[N];
for (int p = 0; p < N; p++){
spectra[p] = output[order[p]]/normalise;
}
return spectra;
}
std::complex<double> * eFFT::fft(std::complex<double> * input,int length){
std::complex<double> * spectra = butterfly(input, length, 1, -1);
return spectra;
}
std::complex<double> * eFFT::ifft(std::complex<double> * input,int length){
std::complex<double> * temporal = butterfly(input, length, length, 1);
return temporal;
}
}
<|endoftext|> |
<commit_before>#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
/*class Node{
public:
Node *up, *down, *left, *right;
int state;
enum State { WALL, SPACE, START, END };
};*/
typedef struct {
bool passed;
char state;
int preR, preC;
enum State { WALL, SPACE, START, END };
} Node;
void DFS(vector<vector<Node> > &all_nodes, int preR, int preC, int incR, int incC){
int r = preR + incR, c = preC +incC;
if(r<0 || r>=all_nodes.size() || c <0 || c>=all_nodes[0].size() | all_nodes[r][c].passed ){
return;
}
all_nodes[r][c].passed = true;
all_nodes[r][c].preR = preR; all_nodes[r][c].preC = preC;
if( all_nodes[r][c].state == 'E' ){
cout<< "foundE";
return;
}
DFS(all_nodes,r,c,-1,0);
DFS(all_nodes,r,c,0,-1);
DFS(all_nodes,r,c,1,0);
DFS(all_nodes,r,c,0,1);
}
int main(){
vector<vector<Node> > all_nodes;
string line;
while(getline(cin, line)){
istringstream iss(line);
vector<Node> line_ins;
for(int i= 0 ;i<line.length();i++){
Node tmp; tmp.state = line[i];
line_ins.push_back(tmp);
}
all_nodes.push_back(line_ins);
}
int rSize = all_nodes.size();
int cSize = all_nodes[0].size();
int rStart =0, cStart =0;
for(int i = 0 ;i<rSize;i++){
for(int j = 0;j<cSize;j++){
all_nodes[i][j].passed=false;
if(all_nodes[i][j].state=='S'){
rStart = i; cStart =j;
}
}
}
DFS(all_nodes,rStart, cStart,0,0);
return 0;
}
<commit_msg>Finished cpp wt typedef struct node<commit_after>#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
/*class Node{
public:
Node *up, *down, *left, *right;
int state;
enum State { WALL, SPACE, START, END };
};*/
typedef struct {
bool passed;
char state;
int preR, preC;
enum State { WALL, SPACE, START, END };
} Node;
bool DFS(vector<vector<Node> > &all_nodes, int preR, int preC, int incR, int incC){
int r = preR + incR, c = preC +incC;
if(r<0 || r>=all_nodes.size() || c <0 || c>=all_nodes[0].size() || all_nodes[r][c].passed ){
return false;
}
all_nodes[r][c].passed = true;
if(all_nodes[r][c].state =='|' || all_nodes[r][c].state=='-'){
return false;
}
all_nodes[r][c].preR = preR; all_nodes[r][c].preC = preC;
if( all_nodes[r][c].state == 'E' ){
return true;
}
if(DFS(all_nodes,r,c,-1,0) || DFS(all_nodes,r,c,0,-1) || DFS(all_nodes,r,c,1,0) || DFS(all_nodes,r,c,0,1)){
return true;
}
return false;
}
int main(){
vector<vector<Node> > all_nodes;
string line;
while(getline(cin, line)){
istringstream iss(line);
vector<Node> line_ins;
for(int i= 0 ;i<line.length();i++){
Node tmp; tmp.state = line[i];
line_ins.push_back(tmp);
}
all_nodes.push_back(line_ins);
}
int rSize = all_nodes.size();
int cSize = all_nodes[0].size();
int rStart =0, cStart =0;
int rEnd =0, cEnd =0;
for(int i = 0 ;i<rSize;i++){
for(int j = 0;j<cSize;j++){
all_nodes[i][j].passed=false;
if(all_nodes[i][j].state=='S'){
rStart = i; cStart =j;
}
if(all_nodes[i][j].state=='E'){
rEnd =i; cEnd=j;
}
}
}
if(DFS(all_nodes,rStart, cStart,0,0)){
int rTmp=rEnd, cTmp=cEnd;
while(rTmp!=rStart || cTmp!=cStart){
if(all_nodes[rTmp][cTmp].state!='E' && all_nodes[rTmp][cTmp].state!='S'){
all_nodes[rTmp][cTmp].state = 'a';
}
int r=all_nodes[rTmp][cTmp].preR,c=all_nodes[rTmp][cTmp].preC;
rTmp=r;cTmp=c;
}
}else{
cout << "No answer";
}
for(int i = 0 ;i<rSize;i++){
for(int j = 0;j<cSize;j++){
cout<<all_nodes[i][j].state;
}
cout<<endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qversitorganizerimporter.h"
#include "qversitorganizerimporter_p.h"
#include "qversitdocument.h"
#include "qversitproperty.h"
#include "qmobilityglobal.h"
QTM_USE_NAMESPACE
/*!
\class QVersitOrganizerImporter
\brief The QVersitOrganizerImporter class converts \l{QVersitDocument}{QVersitDocuments} to
\l{QOrganizerItem}{QOrganizerItems}.
\ingroup versit
\inmodule QtVersit
This class is used to convert a \l QVersitDocument (which may be produced by a
QVersitReader) to lists of \l{QOrganizerItem}{QOrganizerItems} (which may be saved into a
QOrganizerManager. Unless there is an error, there is a one-to-one mapping between
sub-documents of the input Versit document and QOrganizerItems.
*/
/*!
\class QVersitOrganizerImporterPropertyHandler
\brief The QVersitOrganizerImporterPropertyHandler class is an interface for specifying
custom import behaviour for vCard properties.
\ingroup versit-extension
\inmodule QtVersit
For general information on extending Qt Versit, see the document on \l{Versit Plugins}.
\sa QVersitOrganizerImporter
*/
/*!
\fn QVersitOrganizerImporterPropertyHandler::~QVersitOrganizerImporterPropertyHandler()
Frees any memory in use by this handler.
*/
/*!
\fn void QVersitOrganizerImporterPropertyHandler::propertyProcessed(const QVersitDocument& document, const QVersitProperty& property, const QOrganizerItem& item, bool* alreadyProcessed, QList<QOrganizerItemDetail>* updatedDetails)
Process \a property and provide a list of updated details by adding them to \a updatedDetails.
This function is called on every QVersitProperty encountered during an import, after the property
has been processed by the QVersitOrganizerImporter. An implementation of this function can be
made to provide support for vCard properties not supported by QVersitOrganizerImporter.
The supplied \a document is the container for the \a property. \a alreadyProcessed is true if the
QVersitOrganizerImporter or another handler was successful in processing the property. If it is
false and the handler processes the property, it should be set to true to inform later handlers
that the property requires no further processing. \a item holds the state of the item before the
property was processed by the importer. \a updatedDetails is initially filled with a list of
details that the importer will update, and can be modified (by removing, modifying or
adding details to the list)
*/
/*!
\fn void QVersitOrganizerImporterPropertyHandler::subDocumentProcessed(const QVersitDocument& topLevel, const QVersitDocument& subDocument, QOrganizerItem* item)
Perform any final processing on the \a item generated by the \a subDocument. \a topLevel is the
container within which \a subDocument was found. This can be implemented by the handler to clear
any internal state before moving onto the next document.
This function is called after all QVersitProperties have been handled by the
QVersitOrganizerImporter.
*/
/*!
\enum QVersitOrganizerImporter::Error
This enum specifies an error that occurred during the most recent call to importDocuments()
\value NoError The most recent operation was successful
\value InvalidDocumentError One of the documents is not an iCalendar file
\value EmptyDocumentError One of the documents is empty
*/
/*! Constructs a new importer */
QVersitOrganizerImporter::QVersitOrganizerImporter()
: d(new QVersitOrganizerImporterPrivate)
{
}
/*!
* Constructs a new importer for the given \a profile. The profile strings should be one of those
* defined by QVersitOrganizerHandlerFactory, or a value otherwise agreed to by a \l{Versit
* Plugins}{Versit plugin}.
*
* The profile determines which plugins will be loaded to supplement the importer.
*/
QVersitOrganizerImporter::QVersitOrganizerImporter(const QString& profile)
: d(new QVersitOrganizerImporterPrivate(profile))
{
}
/*! Frees the memory used by the importer */
QVersitOrganizerImporter::~QVersitOrganizerImporter()
{
delete d;
}
/*!
* Converts \a document into a corresponding list of QOrganizerItems. After calling this, the
* converted organizer items can be retrieved by calling items().
*
* Returns true on success. The document should contain at least one subdocument. In the
* importing process, each subdocument roughly corresponds to a QOrganizerItem. If any of the
* subdocuments cannot be imported as organizer items (eg. they don't conform to the iCalendar
* format), false is returned and errorMap() will return a list describing the errors that occurred.
* The successfully imported items will still be available via items().
*
* \sa items(), errorMap()
*/
bool QVersitOrganizerImporter::importDocument(const QVersitDocument& document)
{
d->mItems.clear();
d->mErrors.clear();
bool ok = true;
if (document.type() != QVersitDocument::ICalendar20Type
|| document.componentType() != QLatin1String("VCALENDAR")) {
d->mErrors.insert(-1, QVersitOrganizerImporter::InvalidDocumentError);
return false;
}
const QList<QVersitDocument> subDocuments = document.subDocuments();
if (subDocuments.isEmpty()) {
d->mErrors.insert(-1, QVersitOrganizerImporter::EmptyDocumentError);
return false;
}
int documentIndex = 0;
foreach (const QVersitDocument& subDocument, subDocuments) {
QOrganizerItem item;
QVersitOrganizerImporter::Error error;
if (d->importDocument(document, subDocument, &item, &error)) {
d->mItems.append(item);
} else {
// importDocument can return false with no error if it's a non-document component
if (error != QVersitOrganizerImporter::NoError) {
d->mErrors.insert(documentIndex, error);
ok = false;
}
}
documentIndex++;
}
return ok;
}
/*!
* Returns the organizer items imported in the most recent call to importDocuments().
*
* \sa importDocument()
*/
QList<QOrganizerItem> QVersitOrganizerImporter::items() const
{
return d->mItems;
}
/*!
* Returns the map of errors encountered in the most recent call to importDocuments(). The key is
* the index into the input list of documents and the value is the error that occurred on that
* document.
*
* \sa importDocument()
*/
QMap<int, QVersitOrganizerImporter::Error> QVersitOrganizerImporter::errorMap() const
{
return d->mErrors;
}
/*!
* Sets \a handler to be the handler for processing QVersitProperties, or 0 to have no handler.
*
* Does not take ownership of the handler. The client should ensure the handler remains valid for
* the lifetime of the importer.
*
* Only one property handler can be set. If another property handler was previously set, it will no
* longer be associated with the importer.
*/
void QVersitOrganizerImporter::setPropertyHandler(QVersitOrganizerImporterPropertyHandler* handler)
{
d->mPropertyHandler = handler;
}
<commit_msg>Fix documentation relating to QVOI::errorMap()<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qversitorganizerimporter.h"
#include "qversitorganizerimporter_p.h"
#include "qversitdocument.h"
#include "qversitproperty.h"
#include "qmobilityglobal.h"
QTM_USE_NAMESPACE
/*!
\class QVersitOrganizerImporter
\brief The QVersitOrganizerImporter class converts \l{QVersitDocument}{QVersitDocuments} to
\l{QOrganizerItem}{QOrganizerItems}.
\ingroup versit
\inmodule QtVersit
This class is used to convert a \l QVersitDocument (which may be produced by a
QVersitReader) to lists of \l{QOrganizerItem}{QOrganizerItems} (which may be saved into a
QOrganizerManager. Unless there is an error, there is a one-to-one mapping between
sub-documents of the input Versit document and QOrganizerItems.
*/
/*!
\class QVersitOrganizerImporterPropertyHandler
\brief The QVersitOrganizerImporterPropertyHandler class is an interface for specifying
custom import behaviour for vCard properties.
\ingroup versit-extension
\inmodule QtVersit
For general information on extending Qt Versit, see the document on \l{Versit Plugins}.
\sa QVersitOrganizerImporter
*/
/*!
\fn QVersitOrganizerImporterPropertyHandler::~QVersitOrganizerImporterPropertyHandler()
Frees any memory in use by this handler.
*/
/*!
\fn void QVersitOrganizerImporterPropertyHandler::propertyProcessed(const QVersitDocument& document, const QVersitProperty& property, const QOrganizerItem& item, bool* alreadyProcessed, QList<QOrganizerItemDetail>* updatedDetails)
Process \a property and provide a list of updated details by adding them to \a updatedDetails.
This function is called on every QVersitProperty encountered during an import, after the property
has been processed by the QVersitOrganizerImporter. An implementation of this function can be
made to provide support for vCard properties not supported by QVersitOrganizerImporter.
The supplied \a document is the container for the \a property. \a alreadyProcessed is true if the
QVersitOrganizerImporter or another handler was successful in processing the property. If it is
false and the handler processes the property, it should be set to true to inform later handlers
that the property requires no further processing. \a item holds the state of the item before the
property was processed by the importer. \a updatedDetails is initially filled with a list of
details that the importer will update, and can be modified (by removing, modifying or
adding details to the list)
*/
/*!
\fn void QVersitOrganizerImporterPropertyHandler::subDocumentProcessed(const QVersitDocument& topLevel, const QVersitDocument& subDocument, QOrganizerItem* item)
Perform any final processing on the \a item generated by the \a subDocument. \a topLevel is the
container within which \a subDocument was found. This can be implemented by the handler to clear
any internal state before moving onto the next document.
This function is called after all QVersitProperties have been handled by the
QVersitOrganizerImporter.
*/
/*!
\enum QVersitOrganizerImporter::Error
This enum specifies an error that occurred during the most recent call to importDocument()
\value NoError The most recent operation was successful
\value InvalidDocumentError One of the documents is not an iCalendar file
\value EmptyDocumentError One of the documents is empty
*/
/*! Constructs a new importer */
QVersitOrganizerImporter::QVersitOrganizerImporter()
: d(new QVersitOrganizerImporterPrivate)
{
}
/*!
* Constructs a new importer for the given \a profile. The profile strings should be one of those
* defined by QVersitOrganizerHandlerFactory, or a value otherwise agreed to by a \l{Versit
* Plugins}{Versit plugin}.
*
* The profile determines which plugins will be loaded to supplement the importer.
*/
QVersitOrganizerImporter::QVersitOrganizerImporter(const QString& profile)
: d(new QVersitOrganizerImporterPrivate(profile))
{
}
/*! Frees the memory used by the importer */
QVersitOrganizerImporter::~QVersitOrganizerImporter()
{
delete d;
}
/*!
* Converts \a document into a corresponding list of QOrganizerItems. After calling this, the
* converted organizer items can be retrieved by calling items().
*
* Returns true on success. The document should contain at least one subdocument. In the
* importing process, each subdocument roughly corresponds to a QOrganizerItem. If any of the
* subdocuments cannot be imported as organizer items (eg. they don't conform to the iCalendar
* format), false is returned and errorMap() will return a list describing the errors that occurred.
* The successfully imported items will still be available via items().
*
* \sa items(), errorMap()
*/
bool QVersitOrganizerImporter::importDocument(const QVersitDocument& document)
{
d->mItems.clear();
d->mErrors.clear();
bool ok = true;
if (document.type() != QVersitDocument::ICalendar20Type
|| document.componentType() != QLatin1String("VCALENDAR")) {
d->mErrors.insert(-1, QVersitOrganizerImporter::InvalidDocumentError);
return false;
}
const QList<QVersitDocument> subDocuments = document.subDocuments();
if (subDocuments.isEmpty()) {
d->mErrors.insert(-1, QVersitOrganizerImporter::EmptyDocumentError);
return false;
}
int documentIndex = 0;
foreach (const QVersitDocument& subDocument, subDocuments) {
QOrganizerItem item;
QVersitOrganizerImporter::Error error;
if (d->importDocument(document, subDocument, &item, &error)) {
d->mItems.append(item);
} else {
// importDocument can return false with no error if it's a non-document component
if (error != QVersitOrganizerImporter::NoError) {
d->mErrors.insert(documentIndex, error);
ok = false;
}
}
documentIndex++;
}
return ok;
}
/*!
* Returns the organizer items imported in the most recent call to importDocument().
*
* \sa importDocument()
*/
QList<QOrganizerItem> QVersitOrganizerImporter::items() const
{
return d->mItems;
}
/*!
* Returns the map of errors encountered in the most recent call to importDocument().
*
* The key is the zero based index of the sub document within the container document, or -1 for an error
* with the container document itself. The value is the error that occurred on that document.
*
* \sa importDocument()
*/
QMap<int, QVersitOrganizerImporter::Error> QVersitOrganizerImporter::errorMap() const
{
return d->mErrors;
}
/*!
* Sets \a handler to be the handler for processing QVersitProperties, or 0 to have no handler.
*
* Does not take ownership of the handler. The client should ensure the handler remains valid for
* the lifetime of the importer.
*
* Only one property handler can be set. If another property handler was previously set, it will no
* longer be associated with the importer.
*/
void QVersitOrganizerImporter::setPropertyHandler(QVersitOrganizerImporterPropertyHandler* handler)
{
d->mPropertyHandler = handler;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "rdoprocess_shape_MJ.h"
#include "rdoprocess_method_proc2rdo_MJ.h"
#include "rdoprocess_shape_process_MJ.h"
#include "rdoprocess_shape_create_MJ.h"
#include "rdoprocess_shape_decide.h"
#include "rdoprocess_shape_terminate_MJ.h"
#include "rdoprocess_shape_resource.h"
// ----------------------------------------------------------------------------
// ---------- RPObjectFlowChart_MJ
// ----------------------------------------------------------------------------
RPObjectFlowChart_MJ::RPObjectFlowChart_MJ( RPObject* parent ):
RPObjectFlowChart( parent ),
RPObject_MJ( get_this() )
{
/*
RPShapeCreateMJ* shape_create = new RPShapeCreateMJ( this );
shape_create->setPosition( 100, 100 );
shape_create->gamount = 1000;
shape_create->gname = "_";
shape_create->setName( std::string("_") );
shape_create->gtype = 2;
shape_create->gmin = 10;
shape_create->gmax = 30;
RPShapeProcessMJ* shape_process = new RPShapeProcessMJ( this );
shape_process->setPosition( 100, 150 );
shape_process->setName( std::string("_") );
shape_process->gtype = 3;
shape_process->gexp = 7;
shape_process = new RPShapeProcessMJ( this );
shape_process->setPosition( 100, 200 );
shape_process->gtype = 1;
shape_process->gdisp = 2;
shape_process->gexp = 15;
shape_process = new RPShapeProcessMJ( this );
shape_process->setPosition( 100, 250 );
shape_process->setName( std::string("_") );
shape_process->gtype = 3;
shape_process->gexp = 5;
RPShapeTerminateMJ* shape_terminate = new RPShapeTerminateMJ( this );
shape_terminate->setPosition( 100, 200 );
shape_terminate->setName( std::string("") );
RPShapeResource_MJ* shape_resource = new RPShapeResource_MJ( this );
shape_resource->setPosition( 100, 250 );
shape_resource = new RPShapeResource_MJ( this );
shape_resource->setPosition( 100, 300 );
*/
}
RPObject* RPObjectFlowChart_MJ::newObject( RPObject* _parent )
{
return new RPObjectFlowChart_MJ( _parent );
}
rpMethod::RPMethod* RPObjectFlowChart_MJ::getMethod()
{
return proc2rdo;
}
<commit_msg> - удалено лишнее<commit_after>#include "stdafx.h"
#include "rdoprocess_shape_MJ.h"
#include "rdoprocess_method_proc2rdo_MJ.h"
#include "rdoprocess_shape_process_MJ.h"
#include "rdoprocess_shape_create_MJ.h"
#include "rdoprocess_shape_decide.h"
#include "rdoprocess_shape_terminate_MJ.h"
#include "rdoprocess_shape_resource.h"
// ----------------------------------------------------------------------------
// ---------- RPObjectFlowChart_MJ
// ----------------------------------------------------------------------------
RPObjectFlowChart_MJ::RPObjectFlowChart_MJ( RPObject* parent ):
RPObjectFlowChart( parent ),
RPObject_MJ( get_this() )
{}
RPObject* RPObjectFlowChart_MJ::newObject( RPObject* _parent )
{
return new RPObjectFlowChart_MJ( _parent );
}
rpMethod::RPMethod* RPObjectFlowChart_MJ::getMethod()
{
return proc2rdo;
}
<|endoftext|> |
<commit_before>/*
* Read a Standard MIDI File. Externally-assigned function pointers are
* called upon recognizing things in the file. See midifile(3).
*/
/*****************************************************************************
* Change Log
* Date | who : Change
*-----------+-----------------------------------------------------------------
* 2-Mar-92 | GWL : created changelog; MIDIFILE_ERROR to satisfy compiler
*****************************************************************************/
#include "stdio.h"
#include "mfmidi.h"
#include "string.h"
#include "assert.h"
#define MIDIFILE_ERROR -1
/* public stuff */
extern int abort_flag;
void Midifile_reader::midifile()
{
int ntrks;
midifile_error = 0;
ntrks = readheader();
if (midifile_error) return;
if (ntrks <= 0) {
mferror("No tracks!");
/* no need to return since midifile_error is set */
}
while (ntrks-- > 0 && !midifile_error) readtrack();
}
int Midifile_reader::readmt(const char *s, int skip)
/* read through the "MThd" or "MTrk" header string */
/* if skip == 1, we attempt to skip initial garbage. */
{
assert(strlen(s) == 4); // must be "MThd" or "MTrk"
int nread = 0;
char b[4];
char buff[32];
int c;
const char *errmsg = "expecting ";
retry:
while ( nread<4 ) {
c = Mf_getc();
if ( c == EOF ) {
errmsg = "EOF while expecting ";
goto err;
}
b[nread++] = c;
}
/* See if we found the 4 characters we're looking for */
if ( s[0]==b[0] && s[1]==b[1] && s[2]==b[2] && s[3]==b[3] )
return(0);
if ( skip ) {
/* If we are supposed to skip initial garbage, */
/* try again with the next character. */
b[0]=b[1];
b[1]=b[2];
b[2]=b[3];
nread = 3;
goto retry;
}
err:
#pragma warning(disable: 4996) // strcpy is safe since strings have known lengths
(void) strcpy(buff,errmsg);
(void) strcat(buff,s);
#pragma warning(default: 4996) // turn it back on
mferror(buff);
return(0);
}
int Midifile_reader::egetc()
/* read a single character and abort on EOF */
{
int c = Mf_getc();
if ( c == EOF ) {
mferror("premature EOF");
return EOF;
}
Mf_toberead--;
return(c);
}
int Midifile_reader::readheader()
/* read a header chunk */
{
int format, ntrks, division;
if ( readmt("MThd",Mf_skipinit) == EOF )
return(0);
Mf_toberead = read32bit();
if (midifile_error) return MIDIFILE_ERROR;
format = read16bit();
if (midifile_error) return MIDIFILE_ERROR;
ntrks = read16bit();
if (midifile_error) return MIDIFILE_ERROR;
division = read16bit();
if (midifile_error) return MIDIFILE_ERROR;
Mf_header(format,ntrks,division);
/* flush any extra stuff, in case the length of header is not 6 */
while ( Mf_toberead > 0 && !midifile_error)
(void) egetc();
return(ntrks);
}
void Midifile_reader::readtrack()
/* read a track chunk */
{
/* This array is indexed by the high half of a status byte. It's */
/* value is either the number of bytes needed (1 or 2) for a channel */
/* message, or 0 (meaning it's not a channel message). */
static int chantype[] = {
0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 through 0x70 */
2, 2, 2, 2, 1, 1, 2, 0 /* 0x80 through 0xf0 */
};
long lookfor, lng;
int c, c1, type;
int sysexcontinue = 0; /* 1 if last message was an unfinished sysex */
int running = 0; /* 1 when running status used */
int status = 0; /* (possibly running) status byte */
int needed;
if ( readmt("MTrk",0) == EOF )
return;
Mf_toberead = read32bit();
if (midifile_error) return;
Mf_currtime = 0L;
Mf_starttrack();
while ( Mf_toberead > 0 ) {
Mf_currtime += readvarinum(); /* delta time */
if (midifile_error) return;
c = egetc();
if (midifile_error) return;
if ( sysexcontinue && c != 0xf7 ) {
mferror("didn't find expected continuation of a sysex");
return;
}
if ( (c & 0x80) == 0 ) { /* running status? */
if ( status == 0 ) {
mferror("unexpected running status");
return;
}
running = 1;
} else {
status = c;
running = 0;
}
needed = chantype[ (status>>4) & 0xf ];
if ( needed ) { /* ie. is it a channel message? */
if ( running )
c1 = c;
else {
c1 = egetc();
if (midifile_error) return;
}
chanmessage( status, c1, (needed>1) ? egetc() : 0 );
if (midifile_error) return;
continue;;
}
switch ( c ) {
case 0xff: /* meta event */
type = egetc();
if (midifile_error) return;
/* watch out - Don't combine the next 2 statements */
lng = readvarinum();
if (midifile_error) return;
lookfor = Mf_toberead - lng;
msginit();
while ( Mf_toberead > lookfor ) {
unsigned char c = egetc();
if (midifile_error) return;
msgadd(c);
}
metaevent(type);
break;
case 0xf0: /* start of system exclusive */
/* watch out - Don't combine the next 2 statements */
lng = readvarinum();
if (midifile_error) return;
lookfor = Mf_toberead - lng;
msginit();
msgadd(0xf0);
while ( Mf_toberead > lookfor ) {
c = egetc();
if (midifile_error) return;
msgadd(c);
}
if ( c==0xf7 || Mf_nomerge==0 )
sysex();
else
sysexcontinue = 1; /* merge into next msg */
break;
case 0xf7: /* sysex continuation or arbitrary stuff */
/* watch out - Don't combine the next 2 statements */
lng = readvarinum();
if (midifile_error) return;
lookfor = Mf_toberead - lng;
if ( ! sysexcontinue )
msginit();
while ( Mf_toberead > lookfor ) {
c = egetc();
if (midifile_error) return;
msgadd(c);
}
if ( ! sysexcontinue ) {
Mf_arbitrary(msgleng(), msg());
}
else if ( c == 0xf7 ) {
sysex();
sysexcontinue = 0;
}
break;
default:
badbyte(c);
break;
}
}
Mf_endtrack();
return;
}
void Midifile_reader::badbyte(int c)
{
char buff[32];
#pragma warning(disable: 4996) // safe in this case
(void) sprintf(buff,"unexpected byte: 0x%02x",c);
#pragma warning(default: 4996)
mferror(buff);
}
void Midifile_reader::metaevent(int type)
{
int leng = msgleng();
// made this unsigned to avoid sign extend
unsigned char *m = msg();
switch ( type ) {
case 0x00:
Mf_seqnum(to16bit(m[0],m[1]));
break;
case 0x01: /* Text event */
case 0x02: /* Copyright notice */
case 0x03: /* Sequence/Track name */
case 0x04: /* Instrument name */
case 0x05: /* Lyric */
case 0x06: /* Marker */
case 0x07: /* Cue point */
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
/* These are all text events */
Mf_text(type,leng,m);
break;
case 0x20:
Mf_chanprefix(m[0]);
break;
case 0x21:
Mf_portprefix(m[0]);
break;
case 0x2f: /* End of Track */
Mf_eot();
break;
case 0x51: /* Set tempo */
Mf_tempo(to32bit(0,m[0],m[1],m[2]));
break;
case 0x54:
Mf_smpte(m[0],m[1],m[2],m[3],m[4]);
break;
case 0x58:
Mf_timesig(m[0],m[1],m[2],m[3]);
break;
case 0x59:
Mf_keysig(m[0],m[1]);
break;
case 0x7f:
Mf_sqspecific(leng,m);
break;
default:
Mf_metamisc(type,leng,m);
}
}
void Midifile_reader::sysex()
{
Mf_sysex(msgleng(), msg());
}
void Midifile_reader::chanmessage(int status, int c1, int c2)
{
int chan = status & 0xf;
switch ( status & 0xf0 ) {
case NOTEOFF:
Mf_off(chan,c1,c2);
break;
case NOTEON:
Mf_on(chan,c1,c2);
break;
case PRESSURE:
Mf_pressure(chan,c1,c2);
break;
case CONTROLLER:
Mf_controller(chan,c1,c2);
break;
case PITCHBEND:
Mf_pitchbend(chan,c1,c2);
break;
case PROGRAM:
Mf_program(chan,c1);
break;
case CHANPRESSURE:
Mf_chanpressure(chan,c1);
break;
}
}
/* readvarinum - read a varying-length number, and return the */
/* number of characters it took. */
long Midifile_reader::readvarinum()
{
long value;
int c;
c = egetc();
if (midifile_error) return 0;
value = (long) c;
if ( c & 0x80 ) {
value &= 0x7f;
do {
c = egetc();
if (midifile_error) return 0;
value = (value << 7) + (c & 0x7f);
} while (c & 0x80);
}
return (value);
}
long Midifile_reader::to32bit(int c1, int c2, int c3, int c4)
{
long value = 0L;
value = (c1 & 0xff);
value = (value<<8) + (c2 & 0xff);
value = (value<<8) + (c3 & 0xff);
value = (value<<8) + (c4 & 0xff);
return (value);
}
int Midifile_reader::to16bit(int c1, int c2)
{
return ((c1 & 0xff ) << 8) + (c2 & 0xff);
}
long Midifile_reader::read32bit()
{
int c1, c2, c3, c4;
c1 = egetc(); if (midifile_error) return 0;
c2 = egetc(); if (midifile_error) return 0;
c3 = egetc(); if (midifile_error) return 0;
c4 = egetc(); if (midifile_error) return 0;
return to32bit(c1,c2,c3,c4);
}
int Midifile_reader::read16bit()
{
int c1, c2;
c1 = egetc(); if (midifile_error) return 0;
c2 = egetc(); if (midifile_error) return 0;
return to16bit(c1,c2);
}
void Midifile_reader::mferror(const char *s)
{
Mf_error(s);
midifile_error = 1;
}
/* The code below allows collection of a system exclusive message of */
/* arbitrary length. The Msgbuff is expanded as necessary. The only */
/* visible data/routines are msginit(), msgadd(), msg(), msgleng(). */
#define MSGINCREMENT 128
Midifile_reader::Midifile_reader()
{
Mf_nomerge = 0;
Mf_currtime = 0L;
Mf_skipinit = 0;
Mf_toberead = 0;
Msgbuff = 0; /* message buffer */
Msgsize = 0; /* Size of currently allocated Msg */
Msgindex = 0; /* index of next available location in Msg */
}
void Midifile_reader::finalize()
{
if (Msgbuff) Mf_free(Msgbuff, Msgsize);
Msgbuff = NULL;
}
void Midifile_reader::msginit()
{
Msgindex = 0;
}
unsigned char *Midifile_reader::msg()
{
return(Msgbuff);
}
int Midifile_reader::msgleng()
{
return(Msgindex);
}
void Midifile_reader::msgadd(int c)
{
/* If necessary, allocate larger message buffer. */
if ( Msgindex >= Msgsize )
msgenlarge();
Msgbuff[Msgindex++] = c;
}
void Midifile_reader::msgenlarge()
{
unsigned char *newmess;
unsigned char *oldmess = Msgbuff;
int oldleng = Msgsize;
Msgsize += MSGINCREMENT;
newmess = (unsigned char *) Mf_malloc((sizeof(unsigned char) * Msgsize) );
/* copy old message into larger new one */
if ( oldmess != 0 ) {
memcpy(newmess, oldmess, oldleng);
Mf_free(oldmess, oldleng);
}
Msgbuff = newmess;
}
<commit_msg>initialise members of classes<commit_after>/*
* Read a Standard MIDI File. Externally-assigned function pointers are
* called upon recognizing things in the file. See midifile(3).
*/
/*****************************************************************************
* Change Log
* Date | who : Change
*-----------+-----------------------------------------------------------------
* 2-Mar-92 | GWL : created changelog; MIDIFILE_ERROR to satisfy compiler
*****************************************************************************/
#include "stdio.h"
#include "mfmidi.h"
#include "string.h"
#include "assert.h"
#define MIDIFILE_ERROR -1
/* public stuff */
extern int abort_flag;
void Midifile_reader::midifile()
{
int ntrks;
midifile_error = 0;
ntrks = readheader();
if (midifile_error) return;
if (ntrks <= 0) {
mferror("No tracks!");
/* no need to return since midifile_error is set */
}
while (ntrks-- > 0 && !midifile_error) readtrack();
}
int Midifile_reader::readmt(const char *s, int skip)
/* read through the "MThd" or "MTrk" header string */
/* if skip == 1, we attempt to skip initial garbage. */
{
assert(strlen(s) == 4); // must be "MThd" or "MTrk"
int nread = 0;
char b[4];
char buff[32];
int c;
const char *errmsg = "expecting ";
retry:
while ( nread<4 ) {
c = Mf_getc();
if ( c == EOF ) {
errmsg = "EOF while expecting ";
goto err;
}
b[nread++] = c;
}
/* See if we found the 4 characters we're looking for */
if ( s[0]==b[0] && s[1]==b[1] && s[2]==b[2] && s[3]==b[3] )
return(0);
if ( skip ) {
/* If we are supposed to skip initial garbage, */
/* try again with the next character. */
b[0]=b[1];
b[1]=b[2];
b[2]=b[3];
nread = 3;
goto retry;
}
err:
#pragma warning(disable: 4996) // strcpy is safe since strings have known lengths
(void) strcpy(buff,errmsg);
(void) strcat(buff,s);
#pragma warning(default: 4996) // turn it back on
mferror(buff);
return(0);
}
int Midifile_reader::egetc()
/* read a single character and abort on EOF */
{
int c = Mf_getc();
if ( c == EOF ) {
mferror("premature EOF");
return EOF;
}
Mf_toberead--;
return(c);
}
int Midifile_reader::readheader()
/* read a header chunk */
{
int format, ntrks, division;
if ( readmt("MThd",Mf_skipinit) == EOF )
return(0);
Mf_toberead = read32bit();
if (midifile_error) return MIDIFILE_ERROR;
format = read16bit();
if (midifile_error) return MIDIFILE_ERROR;
ntrks = read16bit();
if (midifile_error) return MIDIFILE_ERROR;
division = read16bit();
if (midifile_error) return MIDIFILE_ERROR;
Mf_header(format,ntrks,division);
/* flush any extra stuff, in case the length of header is not 6 */
while ( Mf_toberead > 0 && !midifile_error)
(void) egetc();
return(ntrks);
}
void Midifile_reader::readtrack()
/* read a track chunk */
{
/* This array is indexed by the high half of a status byte. It's */
/* value is either the number of bytes needed (1 or 2) for a channel */
/* message, or 0 (meaning it's not a channel message). */
static int chantype[] = {
0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 through 0x70 */
2, 2, 2, 2, 1, 1, 2, 0 /* 0x80 through 0xf0 */
};
long lookfor, lng;
int c, c1, type;
int sysexcontinue = 0; /* 1 if last message was an unfinished sysex */
int running = 0; /* 1 when running status used */
int status = 0; /* (possibly running) status byte */
int needed;
if ( readmt("MTrk",0) == EOF )
return;
Mf_toberead = read32bit();
if (midifile_error) return;
Mf_currtime = 0L;
Mf_starttrack();
while ( Mf_toberead > 0 ) {
Mf_currtime += readvarinum(); /* delta time */
if (midifile_error) return;
c = egetc();
if (midifile_error) return;
if ( sysexcontinue && c != 0xf7 ) {
mferror("didn't find expected continuation of a sysex");
return;
}
if ( (c & 0x80) == 0 ) { /* running status? */
if ( status == 0 ) {
mferror("unexpected running status");
return;
}
running = 1;
} else {
status = c;
running = 0;
}
needed = chantype[ (status>>4) & 0xf ];
if ( needed ) { /* ie. is it a channel message? */
if ( running )
c1 = c;
else {
c1 = egetc();
if (midifile_error) return;
}
chanmessage( status, c1, (needed>1) ? egetc() : 0 );
if (midifile_error) return;
continue;;
}
switch ( c ) {
case 0xff: /* meta event */
type = egetc();
if (midifile_error) return;
/* watch out - Don't combine the next 2 statements */
lng = readvarinum();
if (midifile_error) return;
lookfor = Mf_toberead - lng;
msginit();
while ( Mf_toberead > lookfor ) {
unsigned char c = egetc();
if (midifile_error) return;
msgadd(c);
}
metaevent(type);
break;
case 0xf0: /* start of system exclusive */
/* watch out - Don't combine the next 2 statements */
lng = readvarinum();
if (midifile_error) return;
lookfor = Mf_toberead - lng;
msginit();
msgadd(0xf0);
while ( Mf_toberead > lookfor ) {
c = egetc();
if (midifile_error) return;
msgadd(c);
}
if ( c==0xf7 || Mf_nomerge==0 )
sysex();
else
sysexcontinue = 1; /* merge into next msg */
break;
case 0xf7: /* sysex continuation or arbitrary stuff */
/* watch out - Don't combine the next 2 statements */
lng = readvarinum();
if (midifile_error) return;
lookfor = Mf_toberead - lng;
if ( ! sysexcontinue )
msginit();
while ( Mf_toberead > lookfor ) {
c = egetc();
if (midifile_error) return;
msgadd(c);
}
if ( ! sysexcontinue ) {
Mf_arbitrary(msgleng(), msg());
}
else if ( c == 0xf7 ) {
sysex();
sysexcontinue = 0;
}
break;
default:
badbyte(c);
break;
}
}
Mf_endtrack();
return;
}
void Midifile_reader::badbyte(int c)
{
char buff[32];
#pragma warning(disable: 4996) // safe in this case
(void) sprintf(buff,"unexpected byte: 0x%02x",c);
#pragma warning(default: 4996)
mferror(buff);
}
void Midifile_reader::metaevent(int type)
{
int leng = msgleng();
// made this unsigned to avoid sign extend
unsigned char *m = msg();
switch ( type ) {
case 0x00:
Mf_seqnum(to16bit(m[0],m[1]));
break;
case 0x01: /* Text event */
case 0x02: /* Copyright notice */
case 0x03: /* Sequence/Track name */
case 0x04: /* Instrument name */
case 0x05: /* Lyric */
case 0x06: /* Marker */
case 0x07: /* Cue point */
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x0e:
case 0x0f:
/* These are all text events */
Mf_text(type,leng,m);
break;
case 0x20:
Mf_chanprefix(m[0]);
break;
case 0x21:
Mf_portprefix(m[0]);
break;
case 0x2f: /* End of Track */
Mf_eot();
break;
case 0x51: /* Set tempo */
Mf_tempo(to32bit(0,m[0],m[1],m[2]));
break;
case 0x54:
Mf_smpte(m[0],m[1],m[2],m[3],m[4]);
break;
case 0x58:
Mf_timesig(m[0],m[1],m[2],m[3]);
break;
case 0x59:
Mf_keysig(m[0],m[1]);
break;
case 0x7f:
Mf_sqspecific(leng,m);
break;
default:
Mf_metamisc(type,leng,m);
}
}
void Midifile_reader::sysex()
{
Mf_sysex(msgleng(), msg());
}
void Midifile_reader::chanmessage(int status, int c1, int c2)
{
int chan = status & 0xf;
switch ( status & 0xf0 ) {
case NOTEOFF:
Mf_off(chan,c1,c2);
break;
case NOTEON:
Mf_on(chan,c1,c2);
break;
case PRESSURE:
Mf_pressure(chan,c1,c2);
break;
case CONTROLLER:
Mf_controller(chan,c1,c2);
break;
case PITCHBEND:
Mf_pitchbend(chan,c1,c2);
break;
case PROGRAM:
Mf_program(chan,c1);
break;
case CHANPRESSURE:
Mf_chanpressure(chan,c1);
break;
}
}
/* readvarinum - read a varying-length number, and return the */
/* number of characters it took. */
long Midifile_reader::readvarinum()
{
long value;
int c;
c = egetc();
if (midifile_error) return 0;
value = (long) c;
if ( c & 0x80 ) {
value &= 0x7f;
do {
c = egetc();
if (midifile_error) return 0;
value = (value << 7) + (c & 0x7f);
} while (c & 0x80);
}
return (value);
}
long Midifile_reader::to32bit(int c1, int c2, int c3, int c4)
{
long value = 0L;
value = (c1 & 0xff);
value = (value<<8) + (c2 & 0xff);
value = (value<<8) + (c3 & 0xff);
value = (value<<8) + (c4 & 0xff);
return (value);
}
int Midifile_reader::to16bit(int c1, int c2)
{
return ((c1 & 0xff ) << 8) + (c2 & 0xff);
}
long Midifile_reader::read32bit()
{
int c1, c2, c3, c4;
c1 = egetc(); if (midifile_error) return 0;
c2 = egetc(); if (midifile_error) return 0;
c3 = egetc(); if (midifile_error) return 0;
c4 = egetc(); if (midifile_error) return 0;
return to32bit(c1,c2,c3,c4);
}
int Midifile_reader::read16bit()
{
int c1, c2;
c1 = egetc(); if (midifile_error) return 0;
c2 = egetc(); if (midifile_error) return 0;
return to16bit(c1,c2);
}
void Midifile_reader::mferror(const char *s)
{
Mf_error(s);
midifile_error = 1;
}
/* The code below allows collection of a system exclusive message of */
/* arbitrary length. The Msgbuff is expanded as necessary. The only */
/* visible data/routines are msginit(), msgadd(), msg(), msgleng(). */
#define MSGINCREMENT 128
Midifile_reader::Midifile_reader()
{
Mf_nomerge = 0;
Mf_currtime = 0L;
Mf_skipinit = 0;
Mf_toberead = 0;
Msgbuff = 0; /* message buffer */
Msgsize = 0; /* Size of currently allocated Msg */
Msgindex = 0; /* index of next available location in Msg */
midifile_error = 0;
}
void Midifile_reader::finalize()
{
if (Msgbuff) Mf_free(Msgbuff, Msgsize);
Msgbuff = NULL;
}
void Midifile_reader::msginit()
{
Msgindex = 0;
}
unsigned char *Midifile_reader::msg()
{
return(Msgbuff);
}
int Midifile_reader::msgleng()
{
return(Msgindex);
}
void Midifile_reader::msgadd(int c)
{
/* If necessary, allocate larger message buffer. */
if ( Msgindex >= Msgsize )
msgenlarge();
Msgbuff[Msgindex++] = c;
}
void Midifile_reader::msgenlarge()
{
unsigned char *newmess;
unsigned char *oldmess = Msgbuff;
int oldleng = Msgsize;
Msgsize += MSGINCREMENT;
newmess = (unsigned char *) Mf_malloc((sizeof(unsigned char) * Msgsize) );
/* copy old message into larger new one */
if ( oldmess != 0 ) {
memcpy(newmess, oldmess, oldleng);
Mf_free(oldmess, oldleng);
}
Msgbuff = newmess;
}
<|endoftext|> |
<commit_before>#include "storage_engine/compression.h"
#include "util.h"
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <zlib.h>
#include <cstring>
using namespace Akumuli;
int main(int argc, char** argv) {
if (argc == 1) {
return 1;
}
std::string file_name(argv[1]);
std::fstream input(file_name, std::ios::binary|std::ios::in|std::ios::out);
UncompressedChunk header;
double tx;
aku_Timestamp ts;
while(input) {
input.read(reinterpret_cast<char*>(&ts), sizeof(ts));
if (input) {
input.read(reinterpret_cast<char*>(&tx), sizeof(tx));
}
if (input) {
header.timestamps.push_back(ts);
header.values.push_back(tx);
}
}
for (size_t i = 1; i < header.timestamps.size(); i++) {
if (header.timestamps.at(i) < header.timestamps.at(i-1)) {
return -1;
}
}
ByteVector buffer(32 + header.timestamps.size()*32, 0);
StorageEngine::DataBlockWriter writer(42, buffer.data(), static_cast<int>(buffer.size()));
size_t commit_size = 0;
for (u32 i = 0; i < header.timestamps.size(); i++) {
aku_Status status = writer.put(header.timestamps.at(i), header.values.at(i));
if (status != AKU_SUCCESS) {
AKU_PANIC("Can't compress data: " + std::to_string(status));
}
commit_size = writer.commit();
}
StorageEngine::DataBlockReader reader(buffer.data(), commit_size);
for (u32 i = 0; i < header.timestamps.size(); i++) {
aku_Timestamp ts;
double tx;
aku_Status status;
std::tie(status, ts, tx) = reader.next();
if (status != AKU_SUCCESS) {
AKU_PANIC("Can't decompress data: " + std::to_string(status));
}
if (ts != header.timestamps.at(i)) {
AKU_PANIC("Bad timestamp at: " + std::to_string(i));
}
if (tx != header.values.at(i)) {
AKU_PANIC("Bad value at: " + std::to_string(i));
}
}
return 0;
}
<commit_msg>Test improved<commit_after>#include "storage_engine/compression.h"
#include "util.h"
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <zlib.h>
#include <cstring>
using namespace Akumuli;
int main(int argc, char** argv) {
if (argc == 1) {
return 1;
}
std::string file_name(argv[1]);
std::fstream input(file_name, std::ios::binary|std::ios::in|std::ios::out);
UncompressedChunk header;
double tx;
aku_Timestamp ts;
while(input) {
input.read(reinterpret_cast<char*>(&ts), sizeof(ts));
if (input) {
input.read(reinterpret_cast<char*>(&tx), sizeof(tx));
}
if (input) {
header.timestamps.push_back(ts);
header.values.push_back(tx);
}
}
for (size_t i = 1; i < header.timestamps.size(); i++) {
if (header.timestamps.at(i) < header.timestamps.at(i-1)) {
return -1;
}
}
ByteVector buffer(4096, 0);
StorageEngine::DataBlockWriter writer(42, buffer.data(), static_cast<int>(buffer.size()));
u32 nelements = 0;
size_t commit_size = 0;
for (u32 i = 0; i < header.timestamps.size(); i++) {
aku_Status status = writer.put(header.timestamps.at(i), header.values.at(i));
if (status == AKU_EOVERFLOW) {
nelements = i;
break;
} else if (status != AKU_SUCCESS) {
AKU_PANIC("Can't compress data: " + std::to_string(status));
}
}
commit_size = writer.commit();
StorageEngine::DataBlockReader reader(buffer.data(), commit_size);
// Only first `nelements` was written to `buffer`.
for (u32 i = 0; i < nelements; i++) {
aku_Timestamp ts;
double tx;
aku_Status status;
std::tie(status, ts, tx) = reader.next();
if (status != AKU_SUCCESS) {
AKU_PANIC("Can't decompress data: " + std::to_string(status));
}
if (ts != header.timestamps.at(i)) {
AKU_PANIC("Bad timestamp at: " + std::to_string(i));
}
if (tx != header.values.at(i)) {
AKU_PANIC("Bad value at: " + std::to_string(i));
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, 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 Willow Garage, 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.
*
* $Id$
*
*/
#include <pcl/pcl_config.h>
#ifdef HAVE_QHULL
#ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_
#define PCL_SURFACE_IMPL_CONVEX_HULL_H_
#include "pcl/surface/convex_hull.h"
#include <pcl/common/common.h>
#include <pcl/common/eigen.h>
#include <pcl/common/transforms.h>
#include <pcl/common/io.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#ifdef HAVE_QHULL_2011
# include "libqhull/libqhull.h"
# include "libqhull/mem.h"
# include "libqhull/qset.h"
# include "libqhull/geom.h"
# include "libqhull/merge.h"
# include "libqhull/poly.h"
# include "libqhull/io.h"
# include "libqhull/stat.h"
#else
# include "qhull/qhull.h"
# include "qhull/mem.h"
# include "qhull/qset.h"
# include "qhull/geom.h"
# include "qhull/merge.h"
# include "qhull/poly.h"
# include "qhull/io.h"
# include "qhull/stat.h"
#endif
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons,
bool fill_polygon_data)
{
// FInd the principal directions
EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
Eigen::Vector4f xyz_centroid;
compute3DCentroid (*input_, *indices_, xyz_centroid);
computeCovarianceMatrix (*input_, *indices_, xyz_centroid, covariance_matrix);
EIGEN_ALIGN16 Eigen::Vector3f eigen_values;
EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors;
pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values);
Eigen::Affine3f transform1;
transform1.setIdentity ();
int dim = 3;
if (eigen_values[0] / eigen_values[2] < 1.0e-5)
{
// We have points laying on a plane, using 2d convex hull
// Compute transformation bring eigen_vectors.col(i) to z-axis
eigen_vectors.col (2) = eigen_vectors.col (0).cross (eigen_vectors.col (1));
eigen_vectors.col (1) = eigen_vectors.col (2).cross (eigen_vectors.col (0));
transform1 (0, 2) = eigen_vectors (0, 0);
transform1 (1, 2) = eigen_vectors (1, 0);
transform1 (2, 2) = eigen_vectors (2, 0);
transform1 (0, 1) = eigen_vectors (0, 1);
transform1 (1, 1) = eigen_vectors (1, 1);
transform1 (2, 1) = eigen_vectors (2, 1);
transform1 (0, 0) = eigen_vectors (0, 2);
transform1 (1, 0) = eigen_vectors (1, 2);
transform1 (2, 0) = eigen_vectors (2, 2);
transform1 = transform1.inverse ();
dim = 2;
}
else
transform1.setIdentity ();
dim_ = dim;
PointCloud cloud_transformed;
pcl::demeanPointCloud (*input_, *indices_, xyz_centroid, cloud_transformed);
pcl::transformPointCloud (cloud_transformed, cloud_transformed, transform1);
// True if qhull should free points in qh_freeqhull() or reallocation
boolT ismalloc = True;
// output from qh_produce_output(), use NULL to skip qh_produce_output()
FILE *outfile = NULL;
std::string flags_str;
flags_str = "qhull Tc";
if (compute_area_)
{
flags_str.append (" FA");
outfile = stderr;
}
// option flags for qhull, see qh_opt.htm
//char flags[] = "qhull Tc FA";
char * flags = (char *)flags_str.c_str();
// error messages from qhull code
FILE *errfile = stderr;
// 0 if no error from qhull
int exitcode;
// Array of coordinates for each point
coordT *points = (coordT *)calloc (cloud_transformed.points.size () * dim, sizeof(coordT));
for (size_t i = 0; i < cloud_transformed.points.size (); ++i)
{
points[i * dim + 0] = (coordT)cloud_transformed.points[i].x;
points[i * dim + 1] = (coordT)cloud_transformed.points[i].y;
if (dim > 2)
points[i * dim + 2] = (coordT)cloud_transformed.points[i].z;
}
// Compute convex hull
exitcode = qh_new_qhull (dim, cloud_transformed.points.size (), points, ismalloc, flags, outfile, errfile);
if (exitcode != 0)
{
PCL_ERROR ("[pcl::%s::performReconstrution] ERROR: qhull was unable to compute a convex hull for the given point cloud (%lu)!\n", getClassName ().c_str (), (unsigned long) input_->points.size ());
//check if it fails because of NaN values...
if (!cloud_transformed.is_dense)
{
bool NaNvalues = false;
for (size_t i = 0; i < cloud_transformed.size (); ++i)
{
if (!pcl_isfinite (cloud_transformed.points[i].x) ||
!pcl_isfinite (cloud_transformed.points[i].y) ||
!pcl_isfinite (cloud_transformed.points[i].z))
{
NaNvalues = true;
break;
}
}
if (NaNvalues)
PCL_ERROR ("[pcl::%s::performReconstruction] ERROR: point cloud contains NaN values, consider running pcl::PassThrough filter first to remove NaNs!\n", getClassName ().c_str ());
}
hull.points.resize (0);
hull.width = hull.height = 0;
polygons.resize (0);
qh_freeqhull (!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
return;
}
qh_triangulate ();
int num_facets = qh num_facets;
int num_vertices = qh num_vertices;
hull.points.resize (num_vertices);
vertexT * vertex;
int i = 0;
// Max vertex id
int max_vertex_id = -1;
FORALLvertices
{
if ((int)vertex->id > max_vertex_id)
max_vertex_id = vertex->id;
}
++max_vertex_id;
std::vector<int> qhid_to_pcidx (max_vertex_id);
FORALLvertices
{
// Add vertices to hull point_cloud
hull.points[i].x = vertex->point[0];
hull.points[i].y = vertex->point[1];
if (dim>2)
hull.points[i].z = vertex->point[2];
else
hull.points[i].z = 0;
qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index
++i;
}
if (compute_area_)
{
total_area_ = qh totarea;
total_volume_ = qh totvol;
}
if (fill_polygon_data)
{
if (dim == 3)
{
polygons.resize (num_facets);
int dd = 0;
facetT * facet;
FORALLfacets
{
polygons[dd].vertices.resize (3);
// Needed by FOREACHvertex_i_
int vertex_n, vertex_i;
FOREACHvertex_i_((*facet).vertices)
//facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]);
polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id];
++dd;
}
}
else
{
// dim=2, we want to return just a polygon with all vertices sorted
// so that they form a non-intersecting polygon...
// this can be moved to the upper loop probably and here just
// the sorting + populate
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
polygons[0].vertices.resize (idx_points.size () + 1);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
// Populate points
for (size_t j = 0; j < idx_points.size (); ++j)
polygons[0].vertices[j] = j;
polygons[0].vertices[idx_points.size ()] = 0;
}
}
else
{
if (dim == 2)
{
// We want to sort the points
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
}
}
// Deallocates memory (also the points)
qh_freeqhull(!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
// Rotate the hull point cloud by transform's inverse
// If the input point cloud has been rotated
if (dim == 2)
{
Eigen::Affine3f transInverse = transform1.inverse ();
pcl::transformPointCloud (hull, hull, transInverse);
//for 2D sets, the qhull library delivers the actual area of the 2d hull in the volume
if(compute_area_)
{
total_area_ = total_volume_;
total_volume_ = 0.0;
}
}
xyz_centroid[0] = -xyz_centroid[0];
xyz_centroid[1] = -xyz_centroid[1];
xyz_centroid[2] = -xyz_centroid[2];
pcl::demeanPointCloud (hull, xyz_centroid, hull);
//if keep_information_
if (keep_information_)
{
//build a tree with the original points
pcl::KdTreeFLANN<PointInT> tree (true);
tree.setInputCloud (input_, indices_);
std::vector<int> neighbor;
std::vector<float> distances;
neighbor.resize (1);
distances.resize (1);
//for each point in the convex hull, search for the nearest neighbor
std::vector<int> indices;
indices.resize (hull.points.size ());
for (size_t i = 0; i < hull.points.size (); i++)
{
tree.nearestKSearch (hull.points[i], 1, neighbor, distances);
indices[i] = (*indices_)[neighbor[0]];
}
//replace point with the closest neighbor in the original point cloud
pcl::copyPointCloud (*input_, indices, hull);
}
hull.width = hull.points.size ();
hull.height = 1;
hull.is_dense = false;
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &output)
{
output.header = input_->header;
if (!initCompute ())
{
output.points.clear ();
return;
}
// Perform the actual surface reconstruction
std::vector<pcl::Vertices> polygons;
performReconstruction (output, polygons, false);
output.width = output.points.size ();
output.height = 1;
output.is_dense = true;
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons)
{
points.header = input_->header;
if (!initCompute ())
{
points.points.clear ();
return;
}
// Perform the actual surface reconstruction
performReconstruction (points, polygons, true);
points.width = points.points.size ();
points.height = 1;
points.is_dense = true;
deinitCompute ();
}
#define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>;
#endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_
#endif
<commit_msg>do not do any processing if the input point cloud is empty<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, 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 Willow Garage, 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.
*
* $Id$
*
*/
#include <pcl/pcl_config.h>
#ifdef HAVE_QHULL
#ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_
#define PCL_SURFACE_IMPL_CONVEX_HULL_H_
#include "pcl/surface/convex_hull.h"
#include <pcl/common/common.h>
#include <pcl/common/eigen.h>
#include <pcl/common/transforms.h>
#include <pcl/common/io.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#ifdef HAVE_QHULL_2011
# include "libqhull/libqhull.h"
# include "libqhull/mem.h"
# include "libqhull/qset.h"
# include "libqhull/geom.h"
# include "libqhull/merge.h"
# include "libqhull/poly.h"
# include "libqhull/io.h"
# include "libqhull/stat.h"
#else
# include "qhull/qhull.h"
# include "qhull/mem.h"
# include "qhull/qset.h"
# include "qhull/geom.h"
# include "qhull/merge.h"
# include "qhull/poly.h"
# include "qhull/io.h"
# include "qhull/stat.h"
#endif
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons,
bool fill_polygon_data)
{
// FInd the principal directions
EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
Eigen::Vector4f xyz_centroid;
compute3DCentroid (*input_, *indices_, xyz_centroid);
computeCovarianceMatrix (*input_, *indices_, xyz_centroid, covariance_matrix);
EIGEN_ALIGN16 Eigen::Vector3f eigen_values;
EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors;
pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values);
Eigen::Affine3f transform1;
transform1.setIdentity ();
int dim = 3;
if (eigen_values[0] / eigen_values[2] < 1.0e-5)
{
// We have points laying on a plane, using 2d convex hull
// Compute transformation bring eigen_vectors.col(i) to z-axis
eigen_vectors.col (2) = eigen_vectors.col (0).cross (eigen_vectors.col (1));
eigen_vectors.col (1) = eigen_vectors.col (2).cross (eigen_vectors.col (0));
transform1 (0, 2) = eigen_vectors (0, 0);
transform1 (1, 2) = eigen_vectors (1, 0);
transform1 (2, 2) = eigen_vectors (2, 0);
transform1 (0, 1) = eigen_vectors (0, 1);
transform1 (1, 1) = eigen_vectors (1, 1);
transform1 (2, 1) = eigen_vectors (2, 1);
transform1 (0, 0) = eigen_vectors (0, 2);
transform1 (1, 0) = eigen_vectors (1, 2);
transform1 (2, 0) = eigen_vectors (2, 2);
transform1 = transform1.inverse ();
dim = 2;
}
else
transform1.setIdentity ();
dim_ = dim;
PointCloud cloud_transformed;
pcl::demeanPointCloud (*input_, *indices_, xyz_centroid, cloud_transformed);
pcl::transformPointCloud (cloud_transformed, cloud_transformed, transform1);
// True if qhull should free points in qh_freeqhull() or reallocation
boolT ismalloc = True;
// output from qh_produce_output(), use NULL to skip qh_produce_output()
FILE *outfile = NULL;
std::string flags_str;
flags_str = "qhull Tc";
if (compute_area_)
{
flags_str.append (" FA");
outfile = stderr;
}
// option flags for qhull, see qh_opt.htm
//char flags[] = "qhull Tc FA";
char * flags = (char *)flags_str.c_str();
// error messages from qhull code
FILE *errfile = stderr;
// 0 if no error from qhull
int exitcode;
// Array of coordinates for each point
coordT *points = (coordT *)calloc (cloud_transformed.points.size () * dim, sizeof(coordT));
for (size_t i = 0; i < cloud_transformed.points.size (); ++i)
{
points[i * dim + 0] = (coordT)cloud_transformed.points[i].x;
points[i * dim + 1] = (coordT)cloud_transformed.points[i].y;
if (dim > 2)
points[i * dim + 2] = (coordT)cloud_transformed.points[i].z;
}
// Compute convex hull
exitcode = qh_new_qhull (dim, cloud_transformed.points.size (), points, ismalloc, flags, outfile, errfile);
if (exitcode != 0)
{
PCL_ERROR ("[pcl::%s::performReconstrution] ERROR: qhull was unable to compute a convex hull for the given point cloud (%lu)!\n", getClassName ().c_str (), (unsigned long) input_->points.size ());
//check if it fails because of NaN values...
if (!cloud_transformed.is_dense)
{
bool NaNvalues = false;
for (size_t i = 0; i < cloud_transformed.size (); ++i)
{
if (!pcl_isfinite (cloud_transformed.points[i].x) ||
!pcl_isfinite (cloud_transformed.points[i].y) ||
!pcl_isfinite (cloud_transformed.points[i].z))
{
NaNvalues = true;
break;
}
}
if (NaNvalues)
PCL_ERROR ("[pcl::%s::performReconstruction] ERROR: point cloud contains NaN values, consider running pcl::PassThrough filter first to remove NaNs!\n", getClassName ().c_str ());
}
hull.points.resize (0);
hull.width = hull.height = 0;
polygons.resize (0);
qh_freeqhull (!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
return;
}
qh_triangulate ();
int num_facets = qh num_facets;
int num_vertices = qh num_vertices;
hull.points.resize (num_vertices);
vertexT * vertex;
int i = 0;
// Max vertex id
int max_vertex_id = -1;
FORALLvertices
{
if ((int)vertex->id > max_vertex_id)
max_vertex_id = vertex->id;
}
++max_vertex_id;
std::vector<int> qhid_to_pcidx (max_vertex_id);
FORALLvertices
{
// Add vertices to hull point_cloud
hull.points[i].x = vertex->point[0];
hull.points[i].y = vertex->point[1];
if (dim>2)
hull.points[i].z = vertex->point[2];
else
hull.points[i].z = 0;
qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index
++i;
}
if (compute_area_)
{
total_area_ = qh totarea;
total_volume_ = qh totvol;
}
if (fill_polygon_data)
{
if (dim == 3)
{
polygons.resize (num_facets);
int dd = 0;
facetT * facet;
FORALLfacets
{
polygons[dd].vertices.resize (3);
// Needed by FOREACHvertex_i_
int vertex_n, vertex_i;
FOREACHvertex_i_((*facet).vertices)
//facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]);
polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id];
++dd;
}
}
else
{
// dim=2, we want to return just a polygon with all vertices sorted
// so that they form a non-intersecting polygon...
// this can be moved to the upper loop probably and here just
// the sorting + populate
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
polygons[0].vertices.resize (idx_points.size () + 1);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
// Populate points
for (size_t j = 0; j < idx_points.size (); ++j)
polygons[0].vertices[j] = j;
polygons[0].vertices[idx_points.size ()] = 0;
}
}
else
{
if (dim == 2)
{
// We want to sort the points
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
}
}
// Deallocates memory (also the points)
qh_freeqhull(!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
// Rotate the hull point cloud by transform's inverse
// If the input point cloud has been rotated
if (dim == 2)
{
Eigen::Affine3f transInverse = transform1.inverse ();
pcl::transformPointCloud (hull, hull, transInverse);
//for 2D sets, the qhull library delivers the actual area of the 2d hull in the volume
if(compute_area_)
{
total_area_ = total_volume_;
total_volume_ = 0.0;
}
}
xyz_centroid[0] = -xyz_centroid[0];
xyz_centroid[1] = -xyz_centroid[1];
xyz_centroid[2] = -xyz_centroid[2];
pcl::demeanPointCloud (hull, xyz_centroid, hull);
//if keep_information_
if (keep_information_)
{
//build a tree with the original points
pcl::KdTreeFLANN<PointInT> tree (true);
tree.setInputCloud (input_, indices_);
std::vector<int> neighbor;
std::vector<float> distances;
neighbor.resize (1);
distances.resize (1);
//for each point in the convex hull, search for the nearest neighbor
std::vector<int> indices;
indices.resize (hull.points.size ());
for (size_t i = 0; i < hull.points.size (); i++)
{
tree.nearestKSearch (hull.points[i], 1, neighbor, distances);
indices[i] = (*indices_)[neighbor[0]];
}
//replace point with the closest neighbor in the original point cloud
pcl::copyPointCloud (*input_, indices, hull);
}
hull.width = hull.points.size ();
hull.height = 1;
hull.is_dense = false;
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &output)
{
output.header = input_->header;
if (!initCompute () || input_->points.empty ())
{
output.points.clear ();
return;
}
// Perform the actual surface reconstruction
std::vector<pcl::Vertices> polygons;
performReconstruction (output, polygons, false);
output.width = output.points.size ();
output.height = 1;
output.is_dense = true;
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons)
{
points.header = input_->header;
if (!initCompute () || input_->points.empty ())
{
points.points.clear ();
return;
}
// Perform the actual surface reconstruction
performReconstruction (points, polygons, true);
points.width = points.points.size ();
points.height = 1;
points.is_dense = true;
deinitCompute ();
}
#define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>;
#endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ForbiddenCharactersEnum.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: mtg $ $Date: 2001-04-02 14:49:56 $
*
* 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): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _FORBIDDEN_CHARACTERS_ENUM_HXX
#define _FORBIDDEN_CHARACTERS_ENUM_HXX
enum ForbiddenCharactersEnum
{
SW_FORBIDDEN_CHARACTER_LANGUAGE,
SW_FORBIDDEN_CHARACTER_COUNTRY,
SW_FORBIDDEN_CHARACTER_VARIANT,
SW_FORBIDDEN_CHARACTER_BEGIN_LINE,
SW_FORBIDDEN_CHARACTER_END_LINE,
SW_FORBIDDEN_CHARACTER_MAX
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1452); FILE MERGED 2005/09/05 13:42:47 rt 1.1.1452.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ForbiddenCharactersEnum.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:17:18 $
*
* 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 _FORBIDDEN_CHARACTERS_ENUM_HXX
#define _FORBIDDEN_CHARACTERS_ENUM_HXX
enum ForbiddenCharactersEnum
{
SW_FORBIDDEN_CHARACTER_LANGUAGE,
SW_FORBIDDEN_CHARACTER_COUNTRY,
SW_FORBIDDEN_CHARACTER_VARIANT,
SW_FORBIDDEN_CHARACTER_BEGIN_LINE,
SW_FORBIDDEN_CHARACTER_END_LINE,
SW_FORBIDDEN_CHARACTER_MAX
};
#endif
<|endoftext|> |
<commit_before>#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "geometry/visualization/put_stl.hh"
#include "planning/jet/jet_dynamics.hh"
#include "planning/jet/jet_planner.hh"
#include "planning/jet/jet_model.hh"
// TODO CLEANUP
#include "viewer/primitives/camera.hh"
#include "viewer/primitives/image.hh"
#include "estimation/vision/calibration.hh"
#include "estimation/vision/fiducial_pose.hh"
#include "util/environment.hh"
#include "eigen.hh"
#include "sophus.hh"
namespace planning {
namespace jet {
constexpr bool SHOW_CAMERA = true;
constexpr bool SHOW_CAMERA_PROJECTION = true;
constexpr bool WRITE_IMAGES = false;
constexpr bool PRINT_STATE = true;
constexpr bool DRAW_VEHICLE = true;
constexpr bool TRACK_VEHICLE = false;
constexpr bool VISUALIZE_TRAJECTORY = true;
namespace {
void setup() {
const auto view = viewer::get_window3d("Mr. Jet, jets");
view->set_target_from_world(
SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
view->set_continue_time_ms(10);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
}
void put_camera_projection(viewer::SimpleGeometry& geo, const viewer::Camera& cam) {
const auto proj = cam.get_projection();
using VPoint = viewer::ViewportPoint;
const auto bottom_left_ray = proj.unproject(VPoint(jcc::Vec2(-1.0, -1.0)));
const auto top_left_ray = proj.unproject(VPoint(jcc::Vec2(1.0, -1.0)));
const auto top_right_ray = proj.unproject(VPoint(jcc::Vec2(1.0, 1.0)));
const auto bottom_right_ray = proj.unproject(VPoint(jcc::Vec2(-1.0, 1.0)));
const jcc::Vec4 red(1.0, 0.1, 0.1, 0.8);
constexpr double length = 5.0;
const jcc::Vec3 origin = bottom_right_ray(0.0);
geo.add_line({origin, bottom_left_ray(length), red});
geo.add_line({origin, top_left_ray(length), red});
geo.add_line({origin, top_right_ray(length), red});
geo.add_line({origin, bottom_right_ray(length), red});
geo.add_line({bottom_left_ray(length), top_left_ray(length), red});
geo.add_line({top_left_ray(length), top_right_ray(length), red});
geo.add_line({top_right_ray(length), bottom_right_ray(length), red});
geo.add_line({bottom_right_ray(length), bottom_left_ray(length), red});
}
void draw_fidudical_detections(const cv::Mat localization_camera_image_rgb,
const SE3 world_from_opengl_camera,
std::shared_ptr<viewer::SimpleGeometry> geo) {
const auto opengl_camera_from_opencv_camera =
SE3(SO3::exp(Eigen::Vector3d(M_PI, 0, 0)), Eigen::Vector3d(0, 0, 0)) *
SE3(SO3::exp(Eigen::Vector3d(0, 0, M_PI / 2 * 0)), Eigen::Vector3d(0, 0, 0));
const auto world_from_camera =
world_from_opengl_camera * opengl_camera_from_opencv_camera;
auto world_from_markers = estimation::vision::get_world_from_marker_centers(
localization_camera_image_rgb, world_from_camera);
for (auto const& marker_detection_world_space : world_from_markers) {
geo->add_line({world_from_opengl_camera.translation(),
marker_detection_world_space.world_from_marker.translation(),
jcc::Vec4(1.0, 0.1, 0.7, 1), 5.0});
}
} // namespace
void go() {
setup();
const auto view = viewer::get_window3d("Mr. Jet, jets");
const std::string jet_path = jcc::Environment::asset_path() + "jetcat_p160.stl";
const auto put_jet = geometry::visualization::create_put_stl(jet_path);
const auto jet_tree = view->add_primitive<viewer::SceneTree>();
const auto jet_geo = view->add_primitive<viewer::SimpleGeometry>();
const auto accum_geo = view->add_primitive<viewer::SimpleGeometry>();
const auto image_tree = view->add_primitive<viewer::SceneTree>();
{
const std::string fiducial_path = jcc::Environment::asset_path() + "fiducial.jpg";
const cv::Mat fiducial_tag = cv::imread(fiducial_path);
const auto board_texture_image = std::make_shared<viewer::Image>(fiducial_tag, 1, 1);
// view->add_primitive(board_texture_image);
// image_tree->add_primitive("root", SE3(), "fiducial_1",
// board_texture_image);
const auto world_from_fiducial =
SE3(SO3::exp(jcc::Vec3(M_PI / 5, 0.5, 0.0)), jcc::Vec3(0.0, 3.0, 0.0));
image_tree->add_primitive("root", world_from_fiducial, "fiducial_2",
board_texture_image);
image_tree->add_primitive(
"root", SE3(SO3::exp(jcc::Vec3(3.14 / 2, 0.0, 0.5)), jcc::Vec3(1.0, 3.0, 1.0)),
"fiducial_3", board_texture_image);
}
const auto camera = std::make_shared<viewer::Camera>();
view->add_camera(camera);
const JetModel model;
if constexpr (DRAW_VEHICLE) {
model.insert(*jet_tree);
}
//
// Add camera projection to the scene tree
//
const SO3 camera_sideways_from_camera_down = SO3::exp(jcc::Vec3(-M_PI / 2, 0.0, 0.0)) *
SO3::exp(jcc::Vec3(0.0, M_PI, 0.0)) *
SO3::exp(jcc::Vec3(0.0, 0, M_PI));
const SE3 jet_from_camera =
SE3(camera_sideways_from_camera_down, jcc::Vec3(0.1, 0.05, 0.1));
if (SHOW_CAMERA_PROJECTION) {
const auto camera_geo = std::make_shared<viewer::SimpleGeometry>();
put_camera_projection(*camera_geo, *camera);
camera_geo->flush();
jet_tree->add_primitive("root", jet_from_camera, "camera", camera_geo);
}
State jet;
jet.x = jcc::Vec3(-2.0, -2.0, 3.0);
jet.w = jcc::Vec3(0.1, -0.1, 0.1);
jet.throttle_pct = 0.0;
const jcc::Vec3 final_target(0.5, 0.5, 0.9);
std::vector<Controls> prev_controls;
int j = 0;
while (!view->should_close()) {
++j;
const jcc::Vec3 prev = jet.x;
//
// Planning state
//
Desires desire;
desire.target = final_target;
if (j > 100) {
desire.target = jcc::Vec3(0, 0, 0);
} else if (j > 300) {
desire.target = jcc::Vec3(0, -2, 0);
} else if (j > 500) {
desire.target = jcc::Vec3(1, 1, -1);
} else if (j > 800) {
desire.target = jcc::Vec3(-2, -6, -1);
} else if (j > 1000) {
desire.target = jcc::Vec3(-2, -6, -1);
} else if (j > 1300) {
desire.target = jcc::Vec3(3, -6, 3);
} else if (j > 1600) {
desire.target = jcc::Vec3(0, 0, 0);
}
//
// Execute planning
//
const auto future_states = plan(jet, desire, prev_controls);
jet = future_states[1].state;
//
// Print out first state
//
const auto ctrl = future_states[1].control;
if constexpr (PRINT_STATE) {
std::cout << j << "..." << std::endl;
std::cout << "\tq : " << ctrl.q.transpose() << std::endl;
std::cout << "\tx : " << jet.x.transpose() << std::endl;
std::cout << "\tw : " << jet.w.transpose() << std::endl;
std::cout << "\tv : " << jet.v.transpose() << std::endl;
std::cout << "\tthrust: " << jet.throttle_pct << std::endl;
}
//
// Visualize
//
const SE3 world_from_jet = SE3(jet.R_world_from_body, jet.x);
// put_jet(*jet_geo, world_from_jet);
// const SO3 camera_sideways_from_camera_down =
// SO3::exp(jcc::Vec3(-M_PI / 2, 0.0, 0.0)) * SO3::exp(jcc::Vec3(0.0, M_PI, 0.0))
// * SO3::exp(jcc::Vec3(0.0, 0, M_PI));
// const SE3 jet_from_camera =
// SE3(camera_sideways_from_camera_down, jcc::Vec3(0.1, 0.05, 0.1));
if constexpr (VISUALIZE_TRAJECTORY) {
for (std::size_t k = 0; k < future_states.size(); ++k) {
const auto& state = future_states.at(k).state;
const SE3 world_from_state = SE3(state.R_world_from_body, state.x);
const double scale =
static_cast<double>(k) / static_cast<double>(future_states.size());
jet_geo->add_axes({world_from_state, 1.0 - scale});
if (k > 1) {
jet_geo->add_line({future_states.at(k).state.x, future_states.at(k - 1).state.x,
jcc::Vec4(0.8, 0.8, 0.1, 0.8), 5.0});
}
}
jet_geo->add_line(
{world_from_jet.translation(),
world_from_jet.translation() +
(world_from_jet.so3() * jcc::Vec3::UnitZ() * jet.throttle_pct * 0.1),
jcc::Vec4(0.1, 0.9, 0.1, 0.8), 9.0});
accum_geo->add_line({prev, jet.x, jcc::Vec4(1.0, 0.7, 0.7, 0.7), 5.0});
}
if constexpr (TRACK_VEHICLE) {
const SO3 world_from_target_rot = SO3::exp(jcc::Vec3::UnitX() * M_PI * 0.5);
const SE3 world_from_target(world_from_target_rot, world_from_jet.translation());
view->set_target_from_world(world_from_target.inverse());
} else {
// view->set_target_from_world(world_from_jet.inverse());
}
jet_tree->set_world_from_root(world_from_jet);
camera->set_world_from_camera(world_from_jet * jet_from_camera);
accum_geo->flush();
const cv::Mat camera_image_rgb = camera->extract_image();
draw_fidudical_detections(camera_image_rgb, world_from_jet * jet_from_camera,
jet_geo);
if (SHOW_CAMERA) {
cv::imshow("Localization Camera", camera_image_rgb);
cv::waitKey(1);
}
estimation::vision::CalibrationManager calibration_manager;
if (j % 10 == 0) {
calibration_manager.add_camera_image(camera_image_rgb);
}
if (calibration_manager.num_images_collected() % (200 / 15) == 0 &&
calibration_manager.num_images_collected() > 0) {
calibration_manager.calibrate();
}
if (WRITE_IMAGES) {
if (j == 0) {
std::cout << "Projection: " << std::endl;
std::cout << camera->get_projection().projection_mat() << std::endl;
}
if (j % 1 == 0) {
std::cout << "-----" << j << std::endl;
std::cout << camera->get_projection().modelview_mat() << std::endl;
cv::imwrite("jet_image_" + std::to_string(j) + ".jpg", camera_image_rgb);
}
}
jet_geo->flip();
}
view->spin_until_step();
cv::destroyAllWindows();
}
} // namespace
} // namespace jet
} // namespace planning
int main() {
planning::jet::go();
}
<commit_msg>Add simualted KF elements to jetsim<commit_after>#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "geometry/visualization/put_stl.hh"
#include "planning/jet/jet_dynamics.hh"
#include "planning/jet/jet_planner.hh"
#include "planning/jet/filter_sim.hh"
#include "planning/jet/jet_model.hh"
// TODO CLEANUP
#include "viewer/primitives/camera.hh"
#include "viewer/primitives/image.hh"
#include "estimation/vision/calibration.hh"
#include "estimation/vision/fiducial_pose.hh"
#include "util/environment.hh"
#include "eigen.hh"
#include "sophus.hh"
namespace planning {
namespace jet {
constexpr bool SHOW_CAMERA = true;
constexpr bool SHOW_CAMERA_PROJECTION = true;
constexpr bool WRITE_IMAGES = false;
constexpr bool PRINT_STATE = true;
constexpr bool DRAW_VEHICLE = true;
constexpr bool TRACK_VEHICLE = false;
constexpr bool VISUALIZE_TRAJECTORY = true;
namespace {
void setup() {
const auto view = viewer::get_window3d("Mr. Jet, jets");
view->set_target_from_world(
SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
view->set_continue_time_ms(10);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
}
void put_camera_projection(viewer::SimpleGeometry& geo, const viewer::Camera& cam) {
const auto proj = cam.get_projection();
using VPoint = viewer::ViewportPoint;
const auto bottom_left_ray = proj.unproject(VPoint(jcc::Vec2(-1.0, -1.0)));
const auto top_left_ray = proj.unproject(VPoint(jcc::Vec2(1.0, -1.0)));
const auto top_right_ray = proj.unproject(VPoint(jcc::Vec2(1.0, 1.0)));
const auto bottom_right_ray = proj.unproject(VPoint(jcc::Vec2(-1.0, 1.0)));
const jcc::Vec4 red(1.0, 0.1, 0.1, 0.8);
constexpr double length = 5.0;
const jcc::Vec3 origin = bottom_right_ray(0.0);
geo.add_line({origin, bottom_left_ray(length), red});
geo.add_line({origin, top_left_ray(length), red});
geo.add_line({origin, top_right_ray(length), red});
geo.add_line({origin, bottom_right_ray(length), red});
geo.add_line({bottom_left_ray(length), top_left_ray(length), red});
geo.add_line({top_left_ray(length), top_right_ray(length), red});
geo.add_line({top_right_ray(length), bottom_right_ray(length), red});
geo.add_line({bottom_right_ray(length), bottom_left_ray(length), red});
}
void draw_fidudical_detections(const cv::Mat localization_camera_image_rgb,
const SE3 world_from_opengl_camera,
std::shared_ptr<viewer::SimpleGeometry> geo) {
const auto opengl_camera_from_opencv_camera =
SE3(SO3::exp(Eigen::Vector3d(M_PI, 0, 0)), Eigen::Vector3d(0, 0, 0)) *
SE3(SO3::exp(Eigen::Vector3d(0, 0, M_PI / 2 * 0)), Eigen::Vector3d(0, 0, 0));
const auto world_from_camera =
world_from_opengl_camera * opengl_camera_from_opencv_camera;
auto world_from_markers = estimation::vision::get_world_from_marker_centers(
localization_camera_image_rgb, world_from_camera);
for (auto const& marker_detection_world_space : world_from_markers) {
geo->add_line({world_from_opengl_camera.translation(),
marker_detection_world_space.world_from_marker.translation(),
jcc::Vec4(1.0, 0.1, 0.7, 1), 5.0});
}
} // namespace
void go() {
setup();
const auto view = viewer::get_window3d("Mr. Jet, jets");
const std::string jet_path = jcc::Environment::asset_path() + "jetcat_p160.stl";
const auto put_jet = geometry::visualization::create_put_stl(jet_path);
const auto jet_tree = view->add_primitive<viewer::SceneTree>();
const auto jet_geo = view->add_primitive<viewer::SimpleGeometry>();
const auto accum_geo = view->add_primitive<viewer::SimpleGeometry>();
const auto image_tree = view->add_primitive<viewer::SceneTree>();
{
const std::string fiducial_path = jcc::Environment::asset_path() + "fiducial.jpg";
const cv::Mat fiducial_tag = cv::imread(fiducial_path);
const auto board_texture_image = std::make_shared<viewer::Image>(fiducial_tag, 1, 1);
// view->add_primitive(board_texture_image);
// image_tree->add_primitive("root", SE3(), "fiducial_1",
// board_texture_image);
const auto world_from_fiducial =
SE3(SO3::exp(jcc::Vec3(M_PI / 5, 0.5, 0.0)), jcc::Vec3(0.0, 3.0, 0.0));
image_tree->add_primitive("root", world_from_fiducial, "fiducial_2",
board_texture_image);
image_tree->add_primitive(
"root", SE3(SO3::exp(jcc::Vec3(3.14 / 2, 0.0, 0.5)), jcc::Vec3(1.0, 3.0, 1.0)),
"fiducial_3", board_texture_image);
}
const auto camera = std::make_shared<viewer::Camera>();
view->add_camera(camera);
const JetModel model;
if constexpr (DRAW_VEHICLE) {
model.insert(*jet_tree);
}
//
// Add camera projection to the scene tree
//
const SO3 camera_sideways_from_camera_down = SO3::exp(jcc::Vec3(-M_PI / 2, 0.0, 0.0)) *
SO3::exp(jcc::Vec3(0.0, M_PI, 0.0)) *
SO3::exp(jcc::Vec3(0.0, 0, M_PI));
const SE3 jet_from_camera =
SE3(camera_sideways_from_camera_down, jcc::Vec3(0.1, 0.05, 0.1));
if (SHOW_CAMERA_PROJECTION) {
const auto camera_geo = std::make_shared<viewer::SimpleGeometry>();
put_camera_projection(*camera_geo, *camera);
camera_geo->flush();
jet_tree->add_primitive("root", jet_from_camera, "camera", camera_geo);
}
State jet;
jet.x = jcc::Vec3(-2.0, -2.0, 3.0);
jet.w = jcc::Vec3(0.1, -0.1, 0.1);
jet.throttle_pct = 0.0;
const jcc::Vec3 final_target(0.5, 0.5, 0.9);
std::vector<Controls> prev_controls;
int j = 0;
while (!view->should_close()) {
++j;
const jcc::Vec3 prev = jet.x;
//
// Planning state
//
Desires desire;
desire.target = final_target;
if (j > 100) {
desire.target = jcc::Vec3(0, 0, 0);
} else if (j > 300) {
desire.target = jcc::Vec3(0, -2, 0);
} else if (j > 500) {
desire.target = jcc::Vec3(1, 1, -1);
} else if (j > 800) {
desire.target = jcc::Vec3(-2, -6, -1);
} else if (j > 1000) {
desire.target = jcc::Vec3(-2, -6, -1);
} else if (j > 1300) {
desire.target = jcc::Vec3(3, -6, 3);
} else if (j > 1600) {
desire.target = jcc::Vec3(0, 0, 0);
}
//
// Execute planning
//
const auto future_states = plan(jet, desire, prev_controls);
jet = future_states[1].state;
//
// Print out first state
//
const auto ctrl = future_states[1].control;
if constexpr (PRINT_STATE) {
std::cout << j << "..." << std::endl;
std::cout << "\tq : " << ctrl.q.transpose() << std::endl;
std::cout << "\tx : " << jet.x.transpose() << std::endl;
std::cout << "\tw : " << jet.w.transpose() << std::endl;
std::cout << "\tv : " << jet.v.transpose() << std::endl;
std::cout << "\tthrust: " << jet.throttle_pct << std::endl;
const Parameters p = get_parameters();
const auto kf_state = kf_state_from_xlqr_state(jet, ctrl, p);
std::cout << "eps_dot : " << kf_state.eps_dot.transpose() << std::endl;
std::cout << "eps_ddot : " << kf_state.eps_ddot.transpose() << std::endl;
std::cout << "accel_bias: " << kf_state.accel_bias.transpose() << std::endl;
std::cout << "gyro_bias : " << kf_state.gyro_bias.transpose() << std::endl;
}
//
// Visualize
//
const SE3 world_from_jet = SE3(jet.R_world_from_body, jet.x);
// put_jet(*jet_geo, world_from_jet);
// const SO3 camera_sideways_from_camera_down =
// SO3::exp(jcc::Vec3(-M_PI / 2, 0.0, 0.0)) * SO3::exp(jcc::Vec3(0.0, M_PI, 0.0))
// * SO3::exp(jcc::Vec3(0.0, 0, M_PI));
// const SE3 jet_from_camera =
// SE3(camera_sideways_from_camera_down, jcc::Vec3(0.1, 0.05, 0.1));
if constexpr (VISUALIZE_TRAJECTORY) {
for (std::size_t k = 0; k < future_states.size(); ++k) {
const auto& state = future_states.at(k).state;
const SE3 world_from_state = SE3(state.R_world_from_body, state.x);
const double scale =
static_cast<double>(k) / static_cast<double>(future_states.size());
jet_geo->add_axes({world_from_state, 1.0 - scale});
if (k > 1) {
jet_geo->add_line({future_states.at(k).state.x, future_states.at(k - 1).state.x,
jcc::Vec4(0.8, 0.8, 0.1, 0.8), 5.0});
}
}
jet_geo->add_line(
{world_from_jet.translation(),
world_from_jet.translation() +
(world_from_jet.so3() * jcc::Vec3::UnitZ() * jet.throttle_pct * 0.1),
jcc::Vec4(0.1, 0.9, 0.1, 0.8), 9.0});
accum_geo->add_line({prev, jet.x, jcc::Vec4(1.0, 0.7, 0.7, 0.7), 5.0});
}
if constexpr (TRACK_VEHICLE) {
const SO3 world_from_target_rot = SO3::exp(jcc::Vec3::UnitX() * M_PI * 0.5);
const SE3 world_from_target(world_from_target_rot, world_from_jet.translation());
view->set_target_from_world(world_from_target.inverse());
} else {
// view->set_target_from_world(world_from_jet.inverse());
}
jet_tree->set_world_from_root(world_from_jet);
camera->set_world_from_camera(world_from_jet * jet_from_camera);
accum_geo->flush();
const cv::Mat camera_image_rgb = camera->extract_image();
draw_fidudical_detections(camera_image_rgb, world_from_jet * jet_from_camera,
jet_geo);
if (SHOW_CAMERA) {
cv::imshow("Localization Camera", camera_image_rgb);
cv::waitKey(1);
}
estimation::vision::CalibrationManager calibration_manager;
if (j % 10 == 0) {
calibration_manager.add_camera_image(camera_image_rgb);
}
if (calibration_manager.num_images_collected() % (200 / 15) == 0 &&
calibration_manager.num_images_collected() > 0) {
calibration_manager.calibrate();
}
if (WRITE_IMAGES) {
if (j == 0) {
std::cout << "Projection: " << std::endl;
std::cout << camera->get_projection().projection_mat() << std::endl;
}
if (j % 1 == 0) {
std::cout << "-----" << j << std::endl;
std::cout << camera->get_projection().modelview_mat() << std::endl;
cv::imwrite("jet_image_" + std::to_string(j) + ".jpg", camera_image_rgb);
}
}
jet_geo->flip();
}
view->spin_until_step();
cv::destroyAllWindows();
}
} // namespace
} // namespace jet
} // namespace planning
int main() {
planning::jet::go();
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*-
kpgpwrapper.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004 Ingo Kloecker <kloecker@kde.org>
Libkleopatra 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.
Libkleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kpgpwrapper.h"
#include "kpgpbackendbase.h"
#include "../../../../libkdenetwork/kpgpbase.h"
#include <backends/kpgp/kpgpkeylistjob.h>
//#include <backends/kpgp/kpgpencryptjob.h>
//#include <backends/kpgp/kpgpdecryptjob.h>
//#include <backends/kpgp/kpgpsignjob.h>
//#include <backends/kpgp/kpgpverifydetachedjob.h>
//#include <backends/kpgp/kpgpverifyopaquejob.h>
//#include <backends/kpgp/kpgpkeygenerationjob.h>
//#include <backends/kpgp/kpgpimportjob.h>
//#include <backends/kpgp/kpgpexportjob.h>
//#include <backends/kpgp/kpgpsecretkeyexportjob.h>
//#include <backends/kpgp/kpgpdownloadjob.h>
//#include <backends/kpgp/kpgpdeletejob.h>
//#include <backends/kpgp/kpgpsignencryptjob.h>
//#include <backends/kpgp/kpgpdecryptverifyjob.h>
//#include <backends/kpgp/kpgpcryptoconfig.h>
KpgpWrapper::KpgpWrapper( const QString & name )
: mName( name ),
mPgpBase( 0 )
{
}
KpgpWrapper::~KpgpWrapper()
{
}
QString KpgpWrapper::name() const
{
return mName;
}
QString KpgpWrapper::displayName() const
{
return mName;
}
Kleo::KeyListJob * KpgpWrapper::keyListJob( bool remote, bool includeSigs,
bool validate ) const
{
return new Kleo::KpgpKeyListJob( pgpBase() );
}
Kleo::EncryptJob * KpgpWrapper::encryptJob( bool armor, bool textmode ) const
{
return 0;
}
Kleo::DecryptJob * KpgpWrapper::decryptJob() const
{
return 0;
}
Kleo::SignJob * KpgpWrapper::signJob( bool armor, bool textMode ) const
{
return 0;
}
Kleo::VerifyDetachedJob * KpgpWrapper::verifyDetachedJob( bool textmode ) const
{
return 0;
}
Kleo::VerifyOpaqueJob * KpgpWrapper::verifyOpaqueJob( bool textmode ) const
{
return 0;
}
Kleo::KeyGenerationJob * KpgpWrapper::keyGenerationJob() const
{
return 0;
}
Kleo::ImportJob * KpgpWrapper::importJob() const
{
return 0;
}
Kleo::ExportJob * KpgpWrapper::publicKeyExportJob( bool armor ) const
{
return 0;
}
Kleo::ExportJob * KpgpWrapper::secretKeyExportJob( bool armor ) const
{
return 0;
}
Kleo::DownloadJob * KpgpWrapper::downloadJob( bool armor ) const
{
return 0;
}
Kleo::DeleteJob * KpgpWrapper::deleteJob() const
{
return 0;
}
Kleo::SignEncryptJob * KpgpWrapper::signEncryptJob( bool armor,
bool textMode ) const
{
return 0;
}
Kleo::DecryptVerifyJob * KpgpWrapper::decryptVerifyJob( bool textmode ) const
{
return 0;
}
Kpgp::Base * KpgpWrapper::pgpBase() const
{
if ( !mPgpBase ) {
if ( name() == GPG1_BACKEND_NAME )
mPgpBase = new Kpgp::BaseG();
else if ( name() == PGP2_BACKEND_NAME )
mPgpBase = new Kpgp::Base2();
else if ( name() == PGP5_BACKEND_NAME )
mPgpBase = new Kpgp::Base5();
else if ( name() == PGP6_BACKEND_NAME )
mPgpBase = new Kpgp::Base6();
}
return mPgpBase;
}
<commit_msg>Avoid 'unused parameter' warnings<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*-
kpgpwrapper.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2004 Ingo Kloecker <kloecker@kde.org>
Libkleopatra 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.
Libkleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kpgpwrapper.h"
#include "kpgpbackendbase.h"
#include "../../../../libkdenetwork/kpgpbase.h"
#include <backends/kpgp/kpgpkeylistjob.h>
//#include <backends/kpgp/kpgpencryptjob.h>
//#include <backends/kpgp/kpgpdecryptjob.h>
//#include <backends/kpgp/kpgpsignjob.h>
//#include <backends/kpgp/kpgpverifydetachedjob.h>
//#include <backends/kpgp/kpgpverifyopaquejob.h>
//#include <backends/kpgp/kpgpkeygenerationjob.h>
//#include <backends/kpgp/kpgpimportjob.h>
//#include <backends/kpgp/kpgpexportjob.h>
//#include <backends/kpgp/kpgpsecretkeyexportjob.h>
//#include <backends/kpgp/kpgpdownloadjob.h>
//#include <backends/kpgp/kpgpdeletejob.h>
//#include <backends/kpgp/kpgpsignencryptjob.h>
//#include <backends/kpgp/kpgpdecryptverifyjob.h>
//#include <backends/kpgp/kpgpcryptoconfig.h>
KpgpWrapper::KpgpWrapper( const QString & name )
: mName( name ),
mPgpBase( 0 )
{
}
KpgpWrapper::~KpgpWrapper()
{
}
QString KpgpWrapper::name() const
{
return mName;
}
QString KpgpWrapper::displayName() const
{
return mName;
}
Kleo::KeyListJob * KpgpWrapper::keyListJob( bool /*remote*/,
bool /*includeSigs*/,
bool /*validate*/ ) const
{
return new Kleo::KpgpKeyListJob( pgpBase() );
}
Kleo::EncryptJob * KpgpWrapper::encryptJob( bool /*armor*/,
bool /*textmode*/ ) const
{
return 0;
}
Kleo::DecryptJob * KpgpWrapper::decryptJob() const
{
return 0;
}
Kleo::SignJob * KpgpWrapper::signJob( bool /*armor*/, bool /*textMode*/ ) const
{
return 0;
}
Kleo::VerifyDetachedJob * KpgpWrapper::verifyDetachedJob( bool /*textmode*/ ) const
{
return 0;
}
Kleo::VerifyOpaqueJob * KpgpWrapper::verifyOpaqueJob( bool /*textmode*/ ) const
{
return 0;
}
Kleo::KeyGenerationJob * KpgpWrapper::keyGenerationJob() const
{
return 0;
}
Kleo::ImportJob * KpgpWrapper::importJob() const
{
return 0;
}
Kleo::ExportJob * KpgpWrapper::publicKeyExportJob( bool /*armor*/ ) const
{
return 0;
}
Kleo::ExportJob * KpgpWrapper::secretKeyExportJob( bool /*armor*/ ) const
{
return 0;
}
Kleo::DownloadJob * KpgpWrapper::downloadJob( bool /*armor*/ ) const
{
return 0;
}
Kleo::DeleteJob * KpgpWrapper::deleteJob() const
{
return 0;
}
Kleo::SignEncryptJob * KpgpWrapper::signEncryptJob( bool /*armor*/,
bool /*textMode*/ ) const
{
return 0;
}
Kleo::DecryptVerifyJob * KpgpWrapper::decryptVerifyJob( bool /*textmode*/ ) const
{
return 0;
}
Kpgp::Base * KpgpWrapper::pgpBase() const
{
if ( !mPgpBase ) {
if ( name() == GPG1_BACKEND_NAME )
mPgpBase = new Kpgp::BaseG();
else if ( name() == PGP2_BACKEND_NAME )
mPgpBase = new Kpgp::Base2();
else if ( name() == PGP5_BACKEND_NAME )
mPgpBase = new Kpgp::Base5();
else if ( name() == PGP6_BACKEND_NAME )
mPgpBase = new Kpgp::Base6();
}
return mPgpBase;
}
<|endoftext|> |
<commit_before>#include <cetty/protobuf/service/builder/ProtobufClientBuilder.h>
#include <cetty/protobuf/service/builder/ProtobufServerBuilder.h>
#include <cetty/zurg/slave/SlaveServiceImpl.h>
#include <cetty/zurg/slave/Heartbeat.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/zurg/master/master.pb.h>
#include <cetty/zurg/slave/ZurgSlave.h>
#include <cetty/config/ConfigCenter.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
namespace cetty {
namespace zurg {
namespace slave {
using namespace cetty::service;
using namespace cetty::protobuf::service::builder;
using namespace cetty::zurg::slave;
using namespace cetty::zurg::master;
using namespace cetty::zurg;
ZurgSlave::ZurgSlave(){
ConfigCenter::instance().configure(&config_);
init();
}
void ZurgSlave::init(){
if (config_.masterAddress_.empty()){
LOG_WARN << "Master address is empty.";
config_.masterAddress_="127.0.0.1";
}
if(config_.masterPort_ <= 0){
LOG_ERROR << "Master listen port is error.";
config_.masterPort_ = 6636;
}
if(config_.listenPort_ <= 0){
LOG_ERROR << "Slave listen port is error.";
config_.listenPort_ = 6637;
}
if(config_.prefix_.empty()){
config_.prefix_ = "/tmp";
LOG_WARN << "Zurg slave profix is not set, set to "
<< config_.prefix_;
}
if(config_.name_.empty()){
LOG_WARN << "Zurg slave name is empty";
}
}
void ZurgSlave::start() {
ProtobufServerBuilder serverBuilder(1, 0);
EventLoopPtr loop = serverBuilder.getParentPool()->getNextLoop();
ProtobufServicePtr service(new SlaveServiceImpl(loop));
serverBuilder.registerService(service);
ProtobufClientBuilder clientBuilder(serverBuilder.getChildPool());
clientBuilder.addConnection(config_.masterAddress_, config_.masterPort_);
// todo what's mean
MasterService_Stub masterClient(clientBuilder.build());
Heartbeat hb(loop, &masterClient);
hb.start();
serverBuilder.buildRpc(config_.listenPort_);
serverBuilder.waitingForExit();
LOG_INFO << "Start zurg_slave";
}
}
}
}
<commit_msg>modiry zurg<commit_after>#include <cetty/protobuf/service/builder/ProtobufClientBuilder.h>
#include <cetty/protobuf/service/builder/ProtobufServerBuilder.h>
#include <cetty/zurg/slave/SlaveServiceImpl.h>
#include <cetty/zurg/slave/Heartbeat.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/zurg/master/master.pb.h>
#include <cetty/zurg/slave/ZurgSlave.h>
#include <cetty/config/ConfigCenter.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
namespace cetty {
namespace zurg {
namespace slave {
using namespace cetty::service;
using namespace cetty::protobuf::service::builder;
using namespace cetty::zurg::slave;
using namespace cetty::zurg::master;
using namespace cetty::zurg;
ZurgSlave::ZurgSlave(){
ConfigCenter::instance().configure(&config_);
init();
}
void ZurgSlave::init(){
if (config_.masterAddress_.empty()){
LOG_WARN << "Master address is empty.";
config_.masterAddress_="127.0.0.1";
}
if(config_.masterPort_ <= 0){
LOG_ERROR << "Master listen port is error.";
config_.masterPort_ = 6636;
}
if(config_.listenPort_ <= 0){
LOG_ERROR << "Slave listen port is error.";
config_.listenPort_ = 6637;
}
if(config_.prefix_.empty()){
config_.prefix_ = "/tmp";
LOG_WARN << "Zurg slave profix is not set, set to "
<< config_.prefix_;
}
if(config_.name_.empty()){
LOG_WARN << "Zurg slave name is empty";
}
}
void ZurgSlave::start() {
ProtobufServerBuilder serverBuilder(1, 0);
EventLoopPtr loop = serverBuilder.getParentPool()->getNextLoop();
ProtobufServicePtr service(new SlaveServiceImpl(loop));
serverBuilder.registerService(service);
ProtobufClientBuilder clientBuilder(serverBuilder.getChildPool());
clientBuilder.addConnection(config_.masterAddress_, config_.masterPort_);
MasterService_Stub masterClient(clientBuilder.build());
Heartbeat hb(loop, &masterClient);
hb.start();
serverBuilder.buildRpc(config_.listenPort_);
serverBuilder.waitingForExit();
LOG_INFO << "Start zurg_slave";
}
}
}
}
<|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* Driver for OTV0p2Base JSON stats output tests.
*/
#include <stdint.h>
#include <gtest/gtest.h>
#include <OTV0p2Base.h>
// Test handling of JSON stats.
//
// Imported 2016/10/29 from Unit_Tests.cpp testJSONStats().
TEST(JSONStats,JSONStats)
{
OTV0P2BASE::SimpleStatsRotation<2> ss1;
ss1.setID(V0p2_SENSOR_TAG_F("1234"));
EXPECT_EQ(0, ss1.size());
EXPECT_EQ(0, ss1.writeJSON(NULL, OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
char buf[OTV0P2BASE::MSG_JSON_MAX_LENGTH + 2]; // Allow for trailing '\0' and spare byte.
// Create minimal JSON message with no data content. just the (supplied) ID.
const uint8_t l1 = ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean());
EXPECT_EQ(12, l1) << buf;
EXPECT_STREQ(buf, "{\"@\":\"1234\"}") << buf;
ss1.enableCount(false);
EXPECT_EQ(12, ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\"}") << buf;
// Check that count works.
ss1.enableCount(true);
EXPECT_EQ(0, ss1.size());
EXPECT_EQ(18, ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
//OTV0P2BASE::serialPrintAndFlush(buf); OTV0P2BASE::serialPrintlnAndFlush();
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"+\":2}");
// Turn count off for rest of tests.
ss1.enableCount(false);
EXPECT_EQ(12, ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
// Check that removal of absent entry does nothing.
EXPECT_FALSE(ss1.remove(V0p2_SENSOR_TAG_F("bogus")));
EXPECT_EQ(0, ss1.size());
// Check that new item can be added/put (with no/default properties).
ss1.put(V0p2_SENSOR_TAG_F("f1"), 0);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(19, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"f1\":0}");
ss1.put(V0p2_SENSOR_TAG_F("f1"), 42);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(20, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"f1\":42}");
ss1.put(V0p2_SENSOR_TAG_F("f1"), -111);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(22, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"f1\":-111}");
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Check that removal of absent entry does nothing.
EXPECT_TRUE(ss1.remove(V0p2_SENSOR_TAG_F("f1")));
EXPECT_EQ(0, ss1.size());
// Check setting direct with Sensor.
OTV0P2BASE::SensorAmbientLightMock alm;
ss1.put(alm);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(18, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"L\":0}");
// Check ID suppression.
ss1.setID(V0p2_SENSOR_TAG_F(""));
EXPECT_EQ(7, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"L\":0}");
}
// Test handling of JSON messages for transmission and reception.
// Includes bit-twiddling, CRC computation, and other error checking.
//
// Imported 2016/10/29 from Unit_Tests.cpp testJSONForTX().
TEST(JSONStats,JSONForTX)
{
char buf[OTV0P2BASE::MSG_JSON_MAX_LENGTH + 2]; // Allow for trailing '\0' or CRC + 0xff terminator.
// Clear the buffer.
memset(buf, 0, sizeof(buf));
// Fail sanity check on a completely empty buffer (zero-length string).
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Fail sanity check on a few initially-plausible length-1 values.
buf[0] = '{';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = '}';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = '[';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = ']';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = ' ';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Fail sanity check with already-adjusted (minimal) nessage.
buf[0] = '{';
buf[1] = char('}' | 0x80);
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Minimal correct messaage should pass.
buf[0] = '{';
buf[1] = '}';
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Try a longer valid trivial message.
strcpy(buf, "{ }");
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Invalidate it with a non-printable char and check that it is rejected.
buf[2] = '\1';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Try a longer valid non-trivial message.
const char * longJSONMsg1 = "{\"@\":\"cdfb\",\"T|C16\":299,\"H|%\":83,\"L\":255,\"B|cV\":256}";
memset(buf, 0, sizeof(buf));
strcpy(buf, longJSONMsg1);
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Invalidate it with a high-bit set and check that it is rejected.
buf[5] |= 0x80;
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// CRC fun!
memset(buf, 0, sizeof(buf));
buf[0] = '{';
buf[1] = '}';
const uint8_t crc1 = OTV0P2BASE::adjustJSONMsgForTXAndComputeCRC(buf);
// Check that top bit is not set (ie CRC was computed OK).
EXPECT_TRUE(!(crc1 & 0x80));
// Check for expected CRC value.
EXPECT_TRUE(0x38 == crc1);
// Check that initial part unaltered.
EXPECT_TRUE('{' == buf[0]);
// Check that top bit has been set in trailing brace.
EXPECT_TRUE((char)('}' | 0x80) == buf[1]);
// Check that trailing '\0' still present.
EXPECT_TRUE(0 == buf[2]);
// Check that TX-format can be converted for RX.
buf[2] = char(crc1);
buf[3] = char(0xff); // As for normal TX...
// FIXME
// const int8_t l1 = adjustJSONMsgForRXAndCheckCRC(buf, sizeof(buf));
// AssertIsTrueWithErr(2 == l1, l1);
// AssertIsTrueWithErr(2 == strlen(buf), strlen(buf));
// AssertIsTrue(quickValidateRawSimpleJSONMessage(buf));
// Now a longer message...
memset(buf, 0, sizeof(buf));
strcpy(buf, longJSONMsg1);
const uint8_t crc2 = OTV0P2BASE::adjustJSONMsgForTXAndComputeCRC(buf);
// Check that top bit is not set (ie CRC was computed OK).
EXPECT_TRUE(!(crc2 & 0x80));
// Check for expected CRC value.
EXPECT_TRUE(0x77 == crc2);
// FIXME
// // Check that TX-format can be converted for RX.
// const int l2o = strlen(buf);
// buf[l2o] = crc2;
// buf[l2o+1] = 0xff;
// FIXME
// const int8_t l2 = adjustJSONMsgForRXAndCheckCRC(buf, sizeof(buf));
// AssertIsTrueWithErr(l2o == l2, l2);
// AssertIsTrue(quickValidateRawSimpleJSONMessage(buf));
}
// This is used to size the stats generator and consistently extract values for it.
// At least one sensor must be supplied.
template<typename T1, typename ... Ts>
class JSONStatsHolder final
{
private:
std::tuple<T1, Ts...> args;
public:
// Number of arguments/stats.
static constexpr size_t argCount = 1 + sizeof...(Ts);
// JSON generator.
typedef OTV0P2BASE::SimpleStatsRotation<OTV0P2BASE::fnmax((size_t)1,argCount)> ss_t;
ss_t ss;
// Construct an instance; though the template helper function is usually easier.
template <typename... Args>
JSONStatsHolder(Args&&... args) : args(std::forward<Args>(args)...)
{
static_assert(sizeof...(Args) > 0, "must take at least one arg");
}
private:
// Big thanks for template wrangling example to David Godfrey:
// http://stackoverflow.com/questions/16868129/how-to-store-variadic-template-arguments
template <int... Ints> struct index {};
template <int N, int... Ints> struct seq : seq<N - 1, N - 1, Ints...> {};
template <int... Ints> struct seq<0, Ints...> : index<Ints...> {};
// Put...
template<typename T> void put(T s) { ss.put(s); }
template <typename... Args, int... Ints>
void putAllJSONArgs(std::tuple<Args...>& tup, index<Ints...>)
{ put(std::get<Ints>(tup)...); }
template <typename... Args>
void putAllJSONArgs(std::tuple<Args...>& tup)
{ putAllJSONArgs(tup, seq<sizeof...(Args)>{}); }
// Read...
template<typename T> void read(T s) { s.read(); }
template <typename... Args, int... Ints>
void readAllSensors(std::tuple<Args...>& tup, index<Ints...>)
{ read(std::get<Ints>(tup)...); }
template <typename... Args>
void readAllSensors(std::tuple<Args...>& tup)
{ readAllSensors(tup, seq<sizeof...(Args)>{}); }
public:
// Call read() on all sensors (usually done once, at initialisation.
void readAll() { readAllSensors(args); }
// Put all the attached sensor values into the stats object.
void putAll() { putAllJSONArgs(args); }
};
// Helper to avoid having to spell out the types explicitly.
template <typename... Args>
constexpr JSONStatsHolder<Args...> makeJSONStatsHolder(Args&&... args)
{ return(JSONStatsHolder<Args...>(std::forward<Args>(args)...)); }
// Testing simplified argument passing and stats object sizing.
TEST(JSONStats,VariadicJSON)
{
static OTV0P2BASE::HumiditySensorMock RelHumidity;
static auto ssh1 = makeJSONStatsHolder(RelHumidity);
auto &ss1 = ssh1.ss;
const uint8_t c1 = ss1.getCapacity();
EXPECT_EQ(1, c1);
// Suppression the ID.
ss1.setID(V0p2_SENSOR_TAG_F(""));
// Disable the counter.
ss1.enableCount(false);
// Set the sensor to a known value.
RelHumidity.set(0);
ssh1.putAll();
char buf[OTV0P2BASE::MSG_JSON_MAX_LENGTH + 2]; // Allow for trailing '\0' and spare byte.
// Create minimal JSON message with no data content. just the (supplied) ID.
const uint8_t l1 = ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8());
EXPECT_EQ(9, l1) << buf;
EXPECT_STREQ(buf, "{\"H|%\":0}") << buf;
}
<commit_msg>TODO-970: having fun<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* Driver for OTV0p2Base JSON stats output tests.
*/
#include <stdint.h>
#include <gtest/gtest.h>
#include <OTV0p2Base.h>
// Test handling of JSON stats.
//
// Imported 2016/10/29 from Unit_Tests.cpp testJSONStats().
TEST(JSONStats,JSONStats)
{
OTV0P2BASE::SimpleStatsRotation<2> ss1;
ss1.setID(V0p2_SENSOR_TAG_F("1234"));
EXPECT_EQ(0, ss1.size());
EXPECT_EQ(0, ss1.writeJSON(NULL, OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
char buf[OTV0P2BASE::MSG_JSON_MAX_LENGTH + 2]; // Allow for trailing '\0' and spare byte.
// Create minimal JSON message with no data content. just the (supplied) ID.
const uint8_t l1 = ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean());
EXPECT_EQ(12, l1) << buf;
EXPECT_STREQ(buf, "{\"@\":\"1234\"}") << buf;
ss1.enableCount(false);
EXPECT_EQ(12, ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\"}") << buf;
// Check that count works.
ss1.enableCount(true);
EXPECT_EQ(0, ss1.size());
EXPECT_EQ(18, ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
//OTV0P2BASE::serialPrintAndFlush(buf); OTV0P2BASE::serialPrintlnAndFlush();
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"+\":2}");
// Turn count off for rest of tests.
ss1.enableCount(false);
EXPECT_EQ(12, ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8(), OTV0P2BASE::randRNG8NextBoolean()));
// Check that removal of absent entry does nothing.
EXPECT_FALSE(ss1.remove(V0p2_SENSOR_TAG_F("bogus")));
EXPECT_EQ(0, ss1.size());
// Check that new item can be added/put (with no/default properties).
ss1.put(V0p2_SENSOR_TAG_F("f1"), 0);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(19, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"f1\":0}");
ss1.put(V0p2_SENSOR_TAG_F("f1"), 42);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(20, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"f1\":42}");
ss1.put(V0p2_SENSOR_TAG_F("f1"), -111);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(22, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"f1\":-111}");
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Check that removal of absent entry does nothing.
EXPECT_TRUE(ss1.remove(V0p2_SENSOR_TAG_F("f1")));
EXPECT_EQ(0, ss1.size());
// Check setting direct with Sensor.
OTV0P2BASE::SensorAmbientLightMock alm;
ss1.put(alm);
EXPECT_EQ(1, ss1.size());
EXPECT_EQ(18, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"@\":\"1234\",\"L\":0}");
// Check ID suppression.
ss1.setID(V0p2_SENSOR_TAG_F(""));
EXPECT_EQ(7, ss1.writeJSON((uint8_t*)buf, sizeof(buf), 0, OTV0P2BASE::randRNG8NextBoolean()));
EXPECT_STREQ(buf, "{\"L\":0}");
}
// Test handling of JSON messages for transmission and reception.
// Includes bit-twiddling, CRC computation, and other error checking.
//
// Imported 2016/10/29 from Unit_Tests.cpp testJSONForTX().
TEST(JSONStats,JSONForTX)
{
char buf[OTV0P2BASE::MSG_JSON_MAX_LENGTH + 2]; // Allow for trailing '\0' or CRC + 0xff terminator.
// Clear the buffer.
memset(buf, 0, sizeof(buf));
// Fail sanity check on a completely empty buffer (zero-length string).
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Fail sanity check on a few initially-plausible length-1 values.
buf[0] = '{';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = '}';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = '[';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = ']';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
buf[0] = ' ';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Fail sanity check with already-adjusted (minimal) nessage.
buf[0] = '{';
buf[1] = char('}' | 0x80);
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Minimal correct messaage should pass.
buf[0] = '{';
buf[1] = '}';
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Try a longer valid trivial message.
strcpy(buf, "{ }");
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Invalidate it with a non-printable char and check that it is rejected.
buf[2] = '\1';
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Try a longer valid non-trivial message.
const char * longJSONMsg1 = "{\"@\":\"cdfb\",\"T|C16\":299,\"H|%\":83,\"L\":255,\"B|cV\":256}";
memset(buf, 0, sizeof(buf));
strcpy(buf, longJSONMsg1);
EXPECT_TRUE(OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// Invalidate it with a high-bit set and check that it is rejected.
buf[5] |= 0x80;
EXPECT_TRUE(!OTV0P2BASE::quickValidateRawSimpleJSONMessage(buf));
// CRC fun!
memset(buf, 0, sizeof(buf));
buf[0] = '{';
buf[1] = '}';
const uint8_t crc1 = OTV0P2BASE::adjustJSONMsgForTXAndComputeCRC(buf);
// Check that top bit is not set (ie CRC was computed OK).
EXPECT_TRUE(!(crc1 & 0x80));
// Check for expected CRC value.
EXPECT_TRUE(0x38 == crc1);
// Check that initial part unaltered.
EXPECT_TRUE('{' == buf[0]);
// Check that top bit has been set in trailing brace.
EXPECT_TRUE((char)('}' | 0x80) == buf[1]);
// Check that trailing '\0' still present.
EXPECT_TRUE(0 == buf[2]);
// Check that TX-format can be converted for RX.
buf[2] = char(crc1);
buf[3] = char(0xff); // As for normal TX...
// FIXME
// const int8_t l1 = adjustJSONMsgForRXAndCheckCRC(buf, sizeof(buf));
// AssertIsTrueWithErr(2 == l1, l1);
// AssertIsTrueWithErr(2 == strlen(buf), strlen(buf));
// AssertIsTrue(quickValidateRawSimpleJSONMessage(buf));
// Now a longer message...
memset(buf, 0, sizeof(buf));
strcpy(buf, longJSONMsg1);
const uint8_t crc2 = OTV0P2BASE::adjustJSONMsgForTXAndComputeCRC(buf);
// Check that top bit is not set (ie CRC was computed OK).
EXPECT_TRUE(!(crc2 & 0x80));
// Check for expected CRC value.
EXPECT_TRUE(0x77 == crc2);
// FIXME
// // Check that TX-format can be converted for RX.
// const int l2o = strlen(buf);
// buf[l2o] = crc2;
// buf[l2o+1] = 0xff;
// FIXME
// const int8_t l2 = adjustJSONMsgForRXAndCheckCRC(buf, sizeof(buf));
// AssertIsTrueWithErr(l2o == l2, l2);
// AssertIsTrue(quickValidateRawSimpleJSONMessage(buf));
}
// This is used to size the stats generator and consistently extract values for it.
// At least one sensor must be provided.
template<typename T1, typename ... Ts>
class JSONStatsHolder final
{
private:
std::tuple<T1, Ts...> args;
public:
// Number of arguments/stats.
static constexpr size_t argCount = 1 + sizeof...(Ts);
// JSON generator.
typedef OTV0P2BASE::SimpleStatsRotation<argCount> ss_t;
ss_t ss;
// Construct an instance; though the template helper function is usually easier.
template <typename... Args>
constexpr JSONStatsHolder(Args&&... args) : args(std::forward<Args>(args)...)
{ static_assert(sizeof...(Args) > 0, "must take at least one arg"); }
private:
// Big thanks for template wrangling example to David Godfrey:
// http://stackoverflow.com/questions/16868129/how-to-store-variadic-template-arguments
template <int... Ints> struct index {};
template <int N, int... Ints> struct seq : seq<N - 1, N - 1, Ints...> {};
template <int... Ints> struct seq<0, Ints...> : index<Ints...> {};
// Put...
template<typename T> void put(T s) { ss.put(s); }
template <typename... Args, int... Ints>
void putAllJSONArgs(std::tuple<Args...>& tup, index<Ints...>)
{ put(std::get<Ints>(tup)...); }
template <typename... Args>
void putAllJSONArgs(std::tuple<Args...>& tup)
{ putAllJSONArgs(tup, seq<sizeof...(Args)>{}); }
// Read...
template<typename T> void read(T s) { s.read(); }
template <typename... Args, int... Ints>
void readAllSensors(std::tuple<Args...>& tup, index<Ints...>)
{ read(std::get<Ints>(tup)...); }
template <typename... Args>
void readAllSensors(std::tuple<Args...>& tup)
{ readAllSensors(tup, seq<sizeof...(Args)>{}); }
public:
// Call read() on all sensors (usually done once, at initialisation.
void readAll() { readAllSensors(args); }
// Put all the attached sensor values into the stats object.
void putAll() { putAllJSONArgs(args); }
};
// Helper to avoid having to spell out the types explicitly.
template <typename... Args>
constexpr JSONStatsHolder<Args...> makeJSONStatsHolder(Args&&... args)
{ return(JSONStatsHolder<Args...>(std::forward<Args>(args)...)); }
// Testing simplified argument passing and stats object sizing.
TEST(JSONStats,VariadicJSON)
{
static OTV0P2BASE::HumiditySensorMock RelHumidity;
static auto ssh1 = makeJSONStatsHolder(RelHumidity);
auto &ss1 = ssh1.ss;
const uint8_t c1 = ss1.getCapacity();
EXPECT_EQ(1, c1);
// Suppression the ID.
ss1.setID(V0p2_SENSOR_TAG_F(""));
// Disable the counter.
ss1.enableCount(false);
// Set the sensor to a known value.
RelHumidity.set(0);
char buf[OTV0P2BASE::MSG_JSON_MAX_LENGTH + 2]; // Allow for trailing '\0' and spare byte.
// No sensor data so stats should be empty.
const uint8_t l0 = ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8());
EXPECT_EQ(2, l0) << buf;
EXPECT_STREQ(buf, "{}") << buf;
// Write sensor values to the stats.
ssh1.putAll();
// Create minimal JSON message with just the sensor data.
const uint8_t l1 = ss1.writeJSON((uint8_t*)buf, sizeof(buf), OTV0P2BASE::randRNG8());
EXPECT_EQ(9, l1) << buf;
EXPECT_STREQ(buf, "{\"H|%\":0}") << buf;
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow 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 "tensorflow/c/experimental/gradients/math_grad.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/gradients.h"
#include "tensorflow/c/experimental/ops/array_ops.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
using std::vector;
using tensorflow::ops::Conj;
using tensorflow::ops::Identity;
using tensorflow::ops::Mul;
namespace tensorflow {
namespace gradients {
namespace {
class AddGradientFunction : public GradientFunction {
public:
Status Compute(Context* ctx, const IncomingGradients& grad_inputs,
vector<AbstractTensorHandle*>* grad_outputs) override {
grad_outputs->resize(2);
vector<AbstractTensorHandle*> identity_outputs(1);
// TODO(b/145674566): Handle name unification in tracing code.
// TODO(b/161805092): Support broadcasting.
TF_RETURN_IF_ERROR(ops::Identity(ctx->ctx, {grad_inputs[0]},
absl::MakeSpan(identity_outputs),
"Identity0"));
(*grad_outputs)[0] = identity_outputs[0];
TF_RETURN_IF_ERROR(ops::Identity(ctx->ctx, {grad_inputs[0]},
absl::MakeSpan(identity_outputs),
"Identity1"));
(*grad_outputs)[1] = identity_outputs[0];
return Status::OK();
}
~AddGradientFunction() override {}
private:
long counter;
};
class ExpGradientFunction : public GradientFunction {
public:
explicit ExpGradientFunction(AbstractTensorHandle* exp) : exp_(exp) {
exp->Ref();
}
Status Compute(Context* ctx, const IncomingGradients& grad_inputs,
vector<AbstractTensorHandle*>* grad_outputs) override {
vector<AbstractTensorHandle*> conj_outputs(1);
TF_RETURN_IF_ERROR(
Conj(ctx->ctx, {exp_.get()}, absl::MakeSpan(conj_outputs), "ExpConj"));
AbstractTensorHandlePtr conj_output_releaser(conj_outputs[0]);
grad_outputs->resize(1);
TF_RETURN_IF_ERROR(Mul(ctx->ctx, {conj_outputs[0], grad_inputs[0]},
absl::MakeSpan(*grad_outputs), "ExpGradMul"));
return Status::OK();
}
~ExpGradientFunction() override {}
private:
AbstractTensorHandlePtr exp_;
};
class MatMulGradientFunction : public GradientFunction {
public:
explicit MatMulGradientFunction(AbstractContext* ctx, std::vector<AbstractTensorHandle*> f_inputs) :
ctx_(ctx), forward_inputs(f_inputs) {}
Status Compute(absl::Span<AbstractTensorHandle* const> grad_inputs,
std::vector<AbstractTensorHandle*>* grad_outputs) override {
/* Given upstream grad U and a matmul op A*B, the gradients are:
*
* dA = U * B.T
* dB = A.T * U
*
* where A.T means `transpose(A)`
*/
AbstractTensorHandle* upstream_grad = grad_inputs[0];
grad_outputs->resize(2);
std::vector<AbstractTensorHandle*> matmul_outputs(1);
// Gradient for A
TF_RETURN_IF_ERROR(MatMul(ctx_, {upstream_grad, forward_inputs[1]},
absl::MakeSpan(matmul_outputs), "mm0",
/*transpose_a = */false, /*transpose_b = */true));
(*grad_outputs)[0] = matmul_outputs[0];
// Gradient for B
TF_RETURN_IF_ERROR(MatMul(ctx_, {forward_inputs[0], upstream_grad},
absl::MakeSpan(matmul_outputs), "mm1",
/*transpose_a = */true, /*transpose_b = */false));
(*grad_outputs)[1] = matmul_outputs[0];
counter += 2; // update counter for names
return Status::OK();
}
~MatMulGradientFunction() override {}
private:
AbstractContext* ctx_;
std::vector<AbstractTensorHandle*> forward_inputs;
long counter;
std::vector<AbstractTensorHandle*> forward_inputs;
};
class ReluGradientFunction : public GradientFunction {
public:
explicit ReluGradientFunction(AbstractContext* ctx, std::vector<AbstractTensorHandle*> f_inputs) :
ctx_(ctx), forward_inputs(f_inputs) {}
Status Compute(absl::Span<AbstractTensorHandle* const> grad_inputs,
std::vector<AbstractTensorHandle*>* grad_outputs) override {
AbstractTensorHandle* upstream_grad = grad_inputs[0];
AbstractTensorHandle* input_features = forward_inputs[0];
grad_outputs->resize(1);
std::vector<AbstractTensorHandle*> relugrad_outputs(1);
// Calculate Grad
TF_RETURN_IF_ERROR(ReluGrad(ctx_, {upstream_grad, input_features},
absl::MakeSpan(relugrad_outputs), "relu_grad"));
(*grad_outputs)[0] = relugrad_outputs[0];
counter += 1;
return Status::OK();
}
~ReluGradientFunction() override {}
private:
AbstractContext* ctx_;
std::vector<AbstractTensorHandle*> forward_inputs;
};
class SparseSoftmaxCrossEntropyLossGradientFunction : public GradientFunction {
public:
explicit SparseSoftmaxCrossEntropyLossGradientFunction(AbstractContext* ctx,
std::vector<AbstractTensorHandle*> f_inputs, std::vector<AbstractTensorHandle*> f_outputs) :
ctx_(ctx), forward_inputs(f_inputs), forward_outputs(f_outputs) {}
Status Compute(absl::Span<AbstractTensorHandle* const> grad_inputs,
std::vector<AbstractTensorHandle*>* grad_outputs) override {
// Forward Inputs : [scores, labels]
grad_outputs->resize(2);
std::vector<AbstractTensorHandle*> sm_outputs(2);
// Calculate Grad
TF_RETURN_IF_ERROR(SparseSoftmaxCrossEntropyLoss(ctx_, {forward_inputs[0], forward_inputs[1]},
absl::MakeSpan(sm_outputs), "softmax_loss"));
// TODO(amturati): fix error where we have to return the softmax loss as the
// 2nd grad for the labels to avoid mangled stack trace
// SparseSoftmaxCrossEntropyLoss returns [loss_vals, grads], so return 2nd output.
(*grad_outputs)[0] = sm_outputs[1]; // return backprop for scores
(*grad_outputs)[1] = sm_outputs[0]; // nullptr; <--- nullptr causes Mangled Stack Trace
counter += 1;
return Status::OK();
}
~SparseSoftmaxCrossEntropyLossGradientFunction() override {}
private:
AbstractContext* ctx_;
std::vector<AbstractTensorHandle*> forward_inputs;
std::vector<AbstractTensorHandle*> forward_outputs;
};
} // namespace
BackwardFunction* AddRegisterer(const ForwardOperation& op) {
auto gradient_function = new AddGradientFunction;
// For ops with a single output, the gradient function is not called if there
// is no incoming gradient. So we do not need to worry about creating zeros
// grads in this case.
auto default_gradients = new PassThroughDefaultGradients(op);
return new BackwardFunction(gradient_function, default_gradients);
}
BackwardFunction* ExpRegisterer(const ForwardOperation& op) {
auto gradient_function = new ExpGradientFunction(op.outputs[0]);
// For ops with a single output, the gradient function is not called if there
// is no incoming gradient. So we do not need to worry about creating zeros
// grads in this case.
auto default_gradients = new PassThroughDefaultGradients(op);
return new BackwardFunction(gradient_function, default_gradients);
}
} // namespace gradients
} // namespace tensorflow
<commit_msg>updating op names to avoid conflict<commit_after>/* Copyright 2020 The TensorFlow 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 "tensorflow/c/experimental/gradients/math_grad.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/gradients.h"
#include "tensorflow/c/experimental/ops/array_ops.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
using std::vector;
using tensorflow::ops::Conj;
using tensorflow::ops::Identity;
using tensorflow::ops::Mul;
namespace tensorflow {
namespace gradients {
namespace {
class AddGradientFunction : public GradientFunction {
public:
Status Compute(Context* ctx, const IncomingGradients& grad_inputs,
vector<AbstractTensorHandle*>* grad_outputs) override {
grad_outputs->resize(2);
vector<AbstractTensorHandle*> identity_outputs(1);
// TODO(b/145674566): Handle name unification in tracing code.
// TODO(b/161805092): Support broadcasting.
std::string name = "Identity_A_" + std::to_string(counter);
TF_RETURN_IF_ERROR(ops::Identity(ctx->ctx, {grad_inputs[0]},
absl::MakeSpan(identity_outputs),
name.c_str()));
(*grad_outputs)[0] = identity_outputs[0];
name = "Identity_B_" + std::to_string(counter);
TF_RETURN_IF_ERROR(ops::Identity(ctx->ctx, {grad_inputs[0]},
absl::MakeSpan(identity_outputs),
name.c_str()));
(*grad_outputs)[1] = identity_outputs[0];
counter += 1;
return Status::OK();
}
~AddGradientFunction() override {}
private:
long counter;
};
class ExpGradientFunction : public GradientFunction {
public:
explicit ExpGradientFunction(AbstractTensorHandle* exp) : exp_(exp) {
exp->Ref();
}
Status Compute(Context* ctx, const IncomingGradients& grad_inputs,
vector<AbstractTensorHandle*>* grad_outputs) override {
vector<AbstractTensorHandle*> conj_outputs(1);
TF_RETURN_IF_ERROR(
Conj(ctx->ctx, {exp_.get()}, absl::MakeSpan(conj_outputs), "ExpConj"));
AbstractTensorHandlePtr conj_output_releaser(conj_outputs[0]);
grad_outputs->resize(1);
TF_RETURN_IF_ERROR(Mul(ctx->ctx, {conj_outputs[0], grad_inputs[0]},
absl::MakeSpan(*grad_outputs), "ExpGradMul"));
return Status::OK();
}
~ExpGradientFunction() override {}
private:
AbstractTensorHandlePtr exp_;
};
class MatMulGradientFunction : public GradientFunction {
public:
explicit MatMulGradientFunction(AbstractContext* ctx, std::vector<AbstractTensorHandle*> f_inputs) :
ctx_(ctx), forward_inputs(f_inputs) {}
Status Compute(absl::Span<AbstractTensorHandle* const> grad_inputs,
std::vector<AbstractTensorHandle*>* grad_outputs) override {
/* Given upstream grad U and a matmul op A*B, the gradients are:
*
* dA = U * B.T
* dB = A.T * U
*
* where A.T means `transpose(A)`
*/
AbstractTensorHandle* upstream_grad = grad_inputs[0];
grad_outputs->resize(2);
std::vector<AbstractTensorHandle*> matmul_outputs(1);
// Gradient for A
TF_RETURN_IF_ERROR(MatMul(ctx_, {upstream_grad, forward_inputs[1]},
absl::MakeSpan(matmul_outputs), "mm0",
/*transpose_a = */false, /*transpose_b = */true));
(*grad_outputs)[0] = matmul_outputs[0];
// Gradient for B
TF_RETURN_IF_ERROR(MatMul(ctx_, {forward_inputs[0], upstream_grad},
absl::MakeSpan(matmul_outputs), "mm1",
/*transpose_a = */true, /*transpose_b = */false));
(*grad_outputs)[1] = matmul_outputs[0];
counter += 1; // update counter for names
return Status::OK();
}
~MatMulGradientFunction() override {}
private:
AbstractContext* ctx_;
std::vector<AbstractTensorHandle*> forward_inputs;
long counter;
std::vector<AbstractTensorHandle*> forward_inputs;
};
class ReluGradientFunction : public GradientFunction {
public:
explicit ReluGradientFunction(AbstractContext* ctx, std::vector<AbstractTensorHandle*> f_inputs) :
ctx_(ctx), forward_inputs(f_inputs) {}
Status Compute(absl::Span<AbstractTensorHandle* const> grad_inputs,
std::vector<AbstractTensorHandle*>* grad_outputs) override {
AbstractTensorHandle* upstream_grad = grad_inputs[0];
AbstractTensorHandle* input_features = forward_inputs[0];
grad_outputs->resize(1);
std::vector<AbstractTensorHandle*> relugrad_outputs(1);
// Calculate Grad
TF_RETURN_IF_ERROR(ReluGrad(ctx_, {upstream_grad, input_features},
absl::MakeSpan(relugrad_outputs), "relu_grad"));
(*grad_outputs)[0] = relugrad_outputs[0];
counter += 1;
return Status::OK();
}
~ReluGradientFunction() override {}
private:
AbstractContext* ctx_;
std::vector<AbstractTensorHandle*> forward_inputs;
};
class SparseSoftmaxCrossEntropyLossGradientFunction : public GradientFunction {
public:
explicit SparseSoftmaxCrossEntropyLossGradientFunction(AbstractContext* ctx,
std::vector<AbstractTensorHandle*> f_inputs, std::vector<AbstractTensorHandle*> f_outputs) :
ctx_(ctx), forward_inputs(f_inputs), forward_outputs(f_outputs) {}
Status Compute(absl::Span<AbstractTensorHandle* const> grad_inputs,
std::vector<AbstractTensorHandle*>* grad_outputs) override {
// Forward Inputs : [scores, labels]
grad_outputs->resize(2);
std::vector<AbstractTensorHandle*> sm_outputs(2);
// Calculate Grad
TF_RETURN_IF_ERROR(SparseSoftmaxCrossEntropyLoss(ctx_, {forward_inputs[0], forward_inputs[1]},
absl::MakeSpan(sm_outputs), "softmax_loss"));
// TODO(amturati): fix error where we have to return the softmax loss as the
// 2nd grad for the labels to avoid mangled stack trace
// SparseSoftmaxCrossEntropyLoss returns [loss_vals, grads], so return 2nd output.
(*grad_outputs)[0] = sm_outputs[1]; // return backprop for scores
(*grad_outputs)[1] = sm_outputs[0]; // nullptr; <--- nullptr causes Mangled Stack Trace
counter += 1;
return Status::OK();
}
~SparseSoftmaxCrossEntropyLossGradientFunction() override {}
private:
AbstractContext* ctx_;
std::vector<AbstractTensorHandle*> forward_inputs;
std::vector<AbstractTensorHandle*> forward_outputs;
};
} // namespace
BackwardFunction* AddRegisterer(const ForwardOperation& op) {
auto gradient_function = new AddGradientFunction;
// For ops with a single output, the gradient function is not called if there
// is no incoming gradient. So we do not need to worry about creating zeros
// grads in this case.
auto default_gradients = new PassThroughDefaultGradients(op);
return new BackwardFunction(gradient_function, default_gradients);
}
BackwardFunction* ExpRegisterer(const ForwardOperation& op) {
auto gradient_function = new ExpGradientFunction(op.outputs[0]);
// For ops with a single output, the gradient function is not called if there
// is no incoming gradient. So we do not need to worry about creating zeros
// grads in this case.
auto default_gradients = new PassThroughDefaultGradients(op);
return new BackwardFunction(gradient_function, default_gradients);
}
} // namespace gradients
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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 "chrome/browser/chromeos/accessibility_util.h"
#include "base/callback.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace accessibility {
// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
public:
// Initialize the ContentScriptLoader with the ID of the extension
// and the RenderViewHost where the scripts should be loaded.
ContentScriptLoader(const std::string& extension_id,
RenderViewHost* render_view_host)
: extension_id_(extension_id),
render_view_host_(render_view_host) {}
// Call this once with the ExtensionResource corresponding to each
// content script to be loaded.
void AppendScript(ExtensionResource resource) {
resources_.push(resource);
}
// Fianlly, call this method once to fetch all of the resources and
// load them. This method will delete this object when done.
void Run() {
if (resources_.empty()) {
delete this;
return;
}
ExtensionResource resource = resources_.front();
resources_.pop();
scoped_refptr<FileReader> reader(new FileReader(resource, NewCallback(
this, &ContentScriptLoader::OnFileLoaded)));
reader->Start();
}
private:
void OnFileLoaded(bool success, const std::string& data) {
if (success) {
ExtensionMsg_ExecuteCode_Params params;
params.request_id = 0;
params.extension_id = extension_id_;
params.is_javascript = true;
params.code = data;
params.all_frames = true;
params.in_main_world = false;
render_view_host_->Send(new ExtensionMsg_ExecuteCode(
render_view_host_->routing_id(), params));
}
Run();
}
std::string extension_id_;
RenderViewHost* render_view_host_;
std::queue<ExtensionResource> resources_;
};
void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
if (accessibility_enabled == enabled) {
LOG(INFO) << "Accessibility is already " <<
(enabled ? "enabled" : "diabled") << ". Going to do nothing.";
return;
}
g_browser_process->local_state()->SetBoolean(
prefs::kAccessibilityEnabled, enabled);
// Explicitly call SavePersistentPrefs instead of ScheduleSavePersistentPrefs
// so that this change gets written immediately, in case the user shuts
// down right now. TODO(dmazzoni) switch this back to
// ScheduleSavePersistentPrefs once http://crosbug.com/19491 is fixed.
g_browser_process->local_state()->SavePersistentPrefs();
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(enabled);
// Load/Unload ChromeVox
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* extension_service =
profile->GetExtensionService();
std::string manifest = ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
ExtensionService::ComponentExtensionInfo info(manifest, path);
if (enabled) { // Load ChromeVox
extension_service->register_component_extension(info);
const Extension* extension =
extension_service->LoadComponentExtension(info);
if (login_web_ui) {
RenderViewHost* render_view_host =
login_web_ui->tab_contents()->render_view_host();
ContentScriptLoader* loader = new ContentScriptLoader(
extension->id(), render_view_host);
for (size_t i = 0; i < extension->content_scripts().size(); i++) {
const UserScript& script = extension->content_scripts()[i];
for (size_t j = 0; j < script.js_scripts().size(); ++j) {
const UserScript::File &file = script.js_scripts()[j];
ExtensionResource resource = extension->GetResource(
file.relative_path());
loader->AppendScript(resource);
}
}
loader->Run(); // It cleans itself up when done.
}
LOG(INFO) << "ChromeVox was Loaded.";
} else { // Unload ChromeVox
extension_service->UnloadComponentExtension(info);
extension_service->UnregisterComponentExtension(info);
LOG(INFO) << "ChromeVox was Unloaded.";
}
}
void ToggleAccessibility(WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
accessibility_enabled = !accessibility_enabled;
EnableAccessibility(accessibility_enabled, login_web_ui);
};
} // namespace accessibility
} // namespace chromeos
<commit_msg>Fix typo in log message.<commit_after>// Copyright (c) 2011 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 "chrome/browser/chromeos/accessibility_util.h"
#include "base/callback.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/file_reader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/pref_names.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/webui/web_ui.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace accessibility {
// Helper class that directly loads an extension's content scripts into
// all of the frames corresponding to a given RenderViewHost.
class ContentScriptLoader {
public:
// Initialize the ContentScriptLoader with the ID of the extension
// and the RenderViewHost where the scripts should be loaded.
ContentScriptLoader(const std::string& extension_id,
RenderViewHost* render_view_host)
: extension_id_(extension_id),
render_view_host_(render_view_host) {}
// Call this once with the ExtensionResource corresponding to each
// content script to be loaded.
void AppendScript(ExtensionResource resource) {
resources_.push(resource);
}
// Fianlly, call this method once to fetch all of the resources and
// load them. This method will delete this object when done.
void Run() {
if (resources_.empty()) {
delete this;
return;
}
ExtensionResource resource = resources_.front();
resources_.pop();
scoped_refptr<FileReader> reader(new FileReader(resource, NewCallback(
this, &ContentScriptLoader::OnFileLoaded)));
reader->Start();
}
private:
void OnFileLoaded(bool success, const std::string& data) {
if (success) {
ExtensionMsg_ExecuteCode_Params params;
params.request_id = 0;
params.extension_id = extension_id_;
params.is_javascript = true;
params.code = data;
params.all_frames = true;
params.in_main_world = false;
render_view_host_->Send(new ExtensionMsg_ExecuteCode(
render_view_host_->routing_id(), params));
}
Run();
}
std::string extension_id_;
RenderViewHost* render_view_host_;
std::queue<ExtensionResource> resources_;
};
void EnableAccessibility(bool enabled, WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
if (accessibility_enabled == enabled) {
LOG(INFO) << "Accessibility is already " <<
(enabled ? "enabled" : "disabled") << ". Going to do nothing.";
return;
}
g_browser_process->local_state()->SetBoolean(
prefs::kAccessibilityEnabled, enabled);
// Explicitly call SavePersistentPrefs instead of ScheduleSavePersistentPrefs
// so that this change gets written immediately, in case the user shuts
// down right now. TODO(dmazzoni) switch this back to
// ScheduleSavePersistentPrefs once http://crosbug.com/19491 is fixed.
g_browser_process->local_state()->SavePersistentPrefs();
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(enabled);
// Load/Unload ChromeVox
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* extension_service =
profile->GetExtensionService();
std::string manifest = ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_CHROMEVOX_MANIFEST).as_string();
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
ExtensionService::ComponentExtensionInfo info(manifest, path);
if (enabled) { // Load ChromeVox
extension_service->register_component_extension(info);
const Extension* extension =
extension_service->LoadComponentExtension(info);
if (login_web_ui) {
RenderViewHost* render_view_host =
login_web_ui->tab_contents()->render_view_host();
ContentScriptLoader* loader = new ContentScriptLoader(
extension->id(), render_view_host);
for (size_t i = 0; i < extension->content_scripts().size(); i++) {
const UserScript& script = extension->content_scripts()[i];
for (size_t j = 0; j < script.js_scripts().size(); ++j) {
const UserScript::File &file = script.js_scripts()[j];
ExtensionResource resource = extension->GetResource(
file.relative_path());
loader->AppendScript(resource);
}
}
loader->Run(); // It cleans itself up when done.
}
LOG(INFO) << "ChromeVox was Loaded.";
} else { // Unload ChromeVox
extension_service->UnloadComponentExtension(info);
extension_service->UnregisterComponentExtension(info);
LOG(INFO) << "ChromeVox was Unloaded.";
}
}
void ToggleAccessibility(WebUI* login_web_ui) {
bool accessibility_enabled = g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled);
accessibility_enabled = !accessibility_enabled;
EnableAccessibility(accessibility_enabled, login_web_ui);
};
} // namespace accessibility
} // namespace chromeos
<|endoftext|> |
<commit_before><commit_msg>[cros] migrate to safe ownership API<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 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 "chrome/browser/extensions/component_loader.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/json/json_value_serializer.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/pref_names.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
typedef std::list<std::pair<FilePath::StringType, int> >
ComponentExtensionList;
#if defined(FILE_MANAGER_EXTENSION)
void AddFileManagerExtension(ComponentExtensionList* component_extensions) {
#ifndef NDEBUG
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kFileManagerExtensionPath)) {
FilePath filemgr_extension_path =
command_line->GetSwitchValuePath(switches::kFileManagerExtensionPath);
component_extensions->push_back(std::make_pair(
filemgr_extension_path.value(),
IDR_FILEMANAGER_MANIFEST));
return;
}
#endif // NDEBUG
component_extensions->push_back(std::make_pair(
FILE_PATH_LITERAL("file_manager"),
IDR_FILEMANAGER_MANIFEST));
}
#endif // defined(FILE_MANAGER_EXTENSION)
} // namespace
namespace extensions {
bool ComponentLoader::ComponentExtensionInfo::Equals(
const ComponentExtensionInfo& other) const {
return other.manifest == manifest && other.root_directory == root_directory;
}
ComponentLoader::ComponentLoader(ExtensionService* extension_service)
: extension_service_(extension_service) {
}
ComponentLoader::~ComponentLoader() {
}
void ComponentLoader::LoadAll() {
for (RegisteredComponentExtensions::iterator it =
component_extensions_.begin();
it != component_extensions_.end(); ++it) {
Load(*it);
}
}
const Extension* ComponentLoader::Add(
const std::string& manifest, const FilePath& root_directory) {
ComponentExtensionInfo info(manifest, root_directory);
Register(info);
if (extension_service_->is_ready())
return Load(info);
return NULL;
}
const Extension* ComponentLoader::Load(const ComponentExtensionInfo& info) {
JSONStringValueSerializer serializer(info.manifest);
scoped_ptr<Value> manifest(serializer.Deserialize(NULL, NULL));
if (!manifest.get()) {
LOG(ERROR) << "Failed to parse manifest for extension";
return NULL;
}
int flags = Extension::REQUIRE_KEY;
if (Extension::ShouldDoStrictErrorChecking(Extension::COMPONENT))
flags |= Extension::STRICT_ERROR_CHECKS;
std::string error;
scoped_refptr<const Extension> extension(Extension::Create(
info.root_directory,
Extension::COMPONENT,
*static_cast<DictionaryValue*>(manifest.get()),
flags,
&error));
if (!extension.get()) {
LOG(ERROR) << error;
return NULL;
}
extension_service_->AddExtension(extension);
return extension;
}
void ComponentLoader::Remove(const std::string& manifest_str) {
// Unload the extension.
JSONStringValueSerializer serializer(manifest_str);
scoped_ptr<Value> manifest(serializer.Deserialize(NULL, NULL));
if (!manifest.get()) {
LOG(ERROR) << "Failed to parse manifest for extension";
return;
}
std::string public_key;
std::string public_key_bytes;
std::string id;
if (!static_cast<DictionaryValue*>(manifest.get())->
GetString(extension_manifest_keys::kPublicKey, &public_key) ||
!Extension::ParsePEMKeyBytes(public_key, &public_key_bytes) ||
!Extension::GenerateId(public_key_bytes, &id)) {
LOG(ERROR) << "Failed to get extension id";
return;
}
extension_service_->
UnloadExtension(id, extension_misc::UNLOAD_REASON_DISABLE);
// Unregister the extension.
RegisteredComponentExtensions new_component_extensions;
for (RegisteredComponentExtensions::iterator it =
component_extensions_.begin();
it != component_extensions_.end(); ++it) {
if (it->manifest != manifest_str)
new_component_extensions.push_back(*it);
}
component_extensions_.swap(new_component_extensions);
}
// We take ComponentExtensionList:
// path, manifest ID => full manifest, absolute path
void ComponentLoader::AddDefaultComponentExtensions() {
ComponentExtensionList component_extensions;
// Bookmark manager.
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("bookmark_manager"),
IDR_BOOKMARKS_MANIFEST));
#if defined(FILE_MANAGER_EXTENSION)
AddFileManagerExtension(&component_extensions);
#endif
#if defined(TOUCH_UI)
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("keyboard"),
IDR_KEYBOARD_MANIFEST));
#endif
#if defined(OS_CHROMEOS)
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("/usr/share/chromeos-assets/mobile"),
IDR_MOBILE_MANIFEST));
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kAuthExtensionPath)) {
FilePath auth_extension_path =
command_line->GetSwitchValuePath(switches::kAuthExtensionPath);
component_extensions.push_back(std::make_pair(
auth_extension_path.value(),
IDR_GAIA_TEST_AUTH_MANIFEST));
} else {
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("/usr/share/chromeos-assets/gaia_auth"),
IDR_GAIA_AUTH_MANIFEST));
}
#if defined(OFFICIAL_BUILD)
if (browser_defaults::enable_help_app) {
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("/usr/share/chromeos-assets/helpapp"),
IDR_HELP_MANIFEST));
}
#endif
#endif
// Web Store.
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("web_store"),
IDR_WEBSTORE_MANIFEST));
#if !defined(OS_CHROMEOS)
// Cloud Print component app. Not required on Chrome OS.
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("cloud_print"),
IDR_CLOUDPRINT_MANIFEST));
#endif // !defined(OS_CHROMEOS)
for (ComponentExtensionList::iterator iter = component_extensions.begin();
iter != component_extensions.end(); ++iter) {
FilePath path(iter->first);
if (!path.IsAbsolute()) {
if (PathService::Get(chrome::DIR_RESOURCES, &path)) {
path = path.Append(iter->first);
} else {
NOTREACHED();
}
}
std::string manifest =
ResourceBundle::GetSharedInstance().GetRawDataResource(
iter->second).as_string();
Add(manifest, path);
}
#if defined(OS_CHROMEOS)
// Register access extensions only if accessibility is enabled.
if (g_browser_process->local_state()->
GetBoolean(prefs::kAccessibilityEnabled)) {
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
std::string manifest =
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_CHROMEVOX_MANIFEST).as_string();
Add(manifest, path);
}
#endif
}
} // namespace extensions
<commit_msg>Add a missing header for official build to fix compile error.<commit_after>// Copyright (c) 2011 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 "chrome/browser/extensions/component_loader.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/json/json_value_serializer.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/pref_names.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OFFICIAL_BUILD)
#include "chrome/browser/defaults.h"
#endif
namespace {
typedef std::list<std::pair<FilePath::StringType, int> >
ComponentExtensionList;
#if defined(FILE_MANAGER_EXTENSION)
void AddFileManagerExtension(ComponentExtensionList* component_extensions) {
#ifndef NDEBUG
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kFileManagerExtensionPath)) {
FilePath filemgr_extension_path =
command_line->GetSwitchValuePath(switches::kFileManagerExtensionPath);
component_extensions->push_back(std::make_pair(
filemgr_extension_path.value(),
IDR_FILEMANAGER_MANIFEST));
return;
}
#endif // NDEBUG
component_extensions->push_back(std::make_pair(
FILE_PATH_LITERAL("file_manager"),
IDR_FILEMANAGER_MANIFEST));
}
#endif // defined(FILE_MANAGER_EXTENSION)
} // namespace
namespace extensions {
bool ComponentLoader::ComponentExtensionInfo::Equals(
const ComponentExtensionInfo& other) const {
return other.manifest == manifest && other.root_directory == root_directory;
}
ComponentLoader::ComponentLoader(ExtensionService* extension_service)
: extension_service_(extension_service) {
}
ComponentLoader::~ComponentLoader() {
}
void ComponentLoader::LoadAll() {
for (RegisteredComponentExtensions::iterator it =
component_extensions_.begin();
it != component_extensions_.end(); ++it) {
Load(*it);
}
}
const Extension* ComponentLoader::Add(
const std::string& manifest, const FilePath& root_directory) {
ComponentExtensionInfo info(manifest, root_directory);
Register(info);
if (extension_service_->is_ready())
return Load(info);
return NULL;
}
const Extension* ComponentLoader::Load(const ComponentExtensionInfo& info) {
JSONStringValueSerializer serializer(info.manifest);
scoped_ptr<Value> manifest(serializer.Deserialize(NULL, NULL));
if (!manifest.get()) {
LOG(ERROR) << "Failed to parse manifest for extension";
return NULL;
}
int flags = Extension::REQUIRE_KEY;
if (Extension::ShouldDoStrictErrorChecking(Extension::COMPONENT))
flags |= Extension::STRICT_ERROR_CHECKS;
std::string error;
scoped_refptr<const Extension> extension(Extension::Create(
info.root_directory,
Extension::COMPONENT,
*static_cast<DictionaryValue*>(manifest.get()),
flags,
&error));
if (!extension.get()) {
LOG(ERROR) << error;
return NULL;
}
extension_service_->AddExtension(extension);
return extension;
}
void ComponentLoader::Remove(const std::string& manifest_str) {
// Unload the extension.
JSONStringValueSerializer serializer(manifest_str);
scoped_ptr<Value> manifest(serializer.Deserialize(NULL, NULL));
if (!manifest.get()) {
LOG(ERROR) << "Failed to parse manifest for extension";
return;
}
std::string public_key;
std::string public_key_bytes;
std::string id;
if (!static_cast<DictionaryValue*>(manifest.get())->
GetString(extension_manifest_keys::kPublicKey, &public_key) ||
!Extension::ParsePEMKeyBytes(public_key, &public_key_bytes) ||
!Extension::GenerateId(public_key_bytes, &id)) {
LOG(ERROR) << "Failed to get extension id";
return;
}
extension_service_->
UnloadExtension(id, extension_misc::UNLOAD_REASON_DISABLE);
// Unregister the extension.
RegisteredComponentExtensions new_component_extensions;
for (RegisteredComponentExtensions::iterator it =
component_extensions_.begin();
it != component_extensions_.end(); ++it) {
if (it->manifest != manifest_str)
new_component_extensions.push_back(*it);
}
component_extensions_.swap(new_component_extensions);
}
// We take ComponentExtensionList:
// path, manifest ID => full manifest, absolute path
void ComponentLoader::AddDefaultComponentExtensions() {
ComponentExtensionList component_extensions;
// Bookmark manager.
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("bookmark_manager"),
IDR_BOOKMARKS_MANIFEST));
#if defined(FILE_MANAGER_EXTENSION)
AddFileManagerExtension(&component_extensions);
#endif
#if defined(TOUCH_UI)
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("keyboard"),
IDR_KEYBOARD_MANIFEST));
#endif
#if defined(OS_CHROMEOS)
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("/usr/share/chromeos-assets/mobile"),
IDR_MOBILE_MANIFEST));
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kAuthExtensionPath)) {
FilePath auth_extension_path =
command_line->GetSwitchValuePath(switches::kAuthExtensionPath);
component_extensions.push_back(std::make_pair(
auth_extension_path.value(),
IDR_GAIA_TEST_AUTH_MANIFEST));
} else {
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("/usr/share/chromeos-assets/gaia_auth"),
IDR_GAIA_AUTH_MANIFEST));
}
#if defined(OFFICIAL_BUILD)
if (browser_defaults::enable_help_app) {
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("/usr/share/chromeos-assets/helpapp"),
IDR_HELP_MANIFEST));
}
#endif
#endif
// Web Store.
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("web_store"),
IDR_WEBSTORE_MANIFEST));
#if !defined(OS_CHROMEOS)
// Cloud Print component app. Not required on Chrome OS.
component_extensions.push_back(std::make_pair(
FILE_PATH_LITERAL("cloud_print"),
IDR_CLOUDPRINT_MANIFEST));
#endif // !defined(OS_CHROMEOS)
for (ComponentExtensionList::iterator iter = component_extensions.begin();
iter != component_extensions.end(); ++iter) {
FilePath path(iter->first);
if (!path.IsAbsolute()) {
if (PathService::Get(chrome::DIR_RESOURCES, &path)) {
path = path.Append(iter->first);
} else {
NOTREACHED();
}
}
std::string manifest =
ResourceBundle::GetSharedInstance().GetRawDataResource(
iter->second).as_string();
Add(manifest, path);
}
#if defined(OS_CHROMEOS)
// Register access extensions only if accessibility is enabled.
if (g_browser_process->local_state()->
GetBoolean(prefs::kAccessibilityEnabled)) {
FilePath path = FilePath(extension_misc::kAccessExtensionPath)
.AppendASCII(extension_misc::kChromeVoxDirectoryName);
std::string manifest =
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_CHROMEVOX_MANIFEST).as_string();
Add(manifest, path);
}
#endif
}
} // namespace extensions
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/instant/instant_field_trial.h"
#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
namespace {
// Field trial IDs of the control and experiment groups. Though they are not
// literally "const", they are set only once, in Activate() below. See the .h
// file for what these groups represent.
int g_inactive = -1;
int g_instant = 0;
int g_suggest = 0;
int g_hidden = 0;
int g_silent = 0;
int g_control = 0;
}
// static
void InstantFieldTrial::Activate() {
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
"Instant", 1000, "Inactive", 2013, 7, 1, &g_inactive));
// Try to give the user a consistent experience, if possible.
if (base::FieldTrialList::IsOneTimeRandomizationEnabled())
trial->UseOneTimeRandomization();
g_instant = trial->AppendGroup("Instant", 10); // 1%
g_suggest = trial->AppendGroup("Suggest", 10); // 1%
g_hidden = trial->AppendGroup("Hidden", 960); // 96%
g_silent = trial->AppendGroup("Silent", 10); // 1%
g_control = trial->AppendGroup("Control", 10); // 1%
int group = 0;
if (trial->group() == g_instant)
group = 1;
else if (trial->group() == g_suggest)
group = 2;
else if (trial->group() == g_hidden)
group = 3;
else if (trial->group() == g_silent)
group = 4;
else if (trial->group() == g_control)
group = 5;
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Size", group, 6);
}
// static
InstantFieldTrial::Group InstantFieldTrial::GetGroup(Profile* profile) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kInstantFieldTrial)) {
std::string switch_value =
command_line->GetSwitchValueASCII(switches::kInstantFieldTrial);
Group group = INACTIVE;
if (switch_value == switches::kInstantFieldTrialInstant)
group = INSTANT;
else if (switch_value == switches::kInstantFieldTrialSuggest)
group = SUGGEST;
else if (switch_value == switches::kInstantFieldTrialHidden)
group = HIDDEN;
else if (switch_value == switches::kInstantFieldTrialSilent)
group = SILENT;
else if (switch_value == switches::kInstantFieldTrialControl)
group = CONTROL;
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 1, 10);
return group;
}
const int group = base::FieldTrialList::FindValue("Instant");
if (group == base::FieldTrial::kNotFinalized || group == g_inactive) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 2, 10);
return INACTIVE;
}
const PrefService* prefs = profile ? profile->GetPrefs() : NULL;
if (!prefs) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 3, 10);
return INACTIVE;
}
if (profile->IsOffTheRecord()) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 4, 10);
return INACTIVE;
}
if (prefs->GetBoolean(prefs::kInstantEnabledOnce)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 5, 10);
return INACTIVE;
}
if (!prefs->GetBoolean(prefs::kSearchSuggestEnabled)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 6, 10);
return INACTIVE;
}
if (prefs->IsManagedPreference(prefs::kInstantEnabled)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 7, 10);
return INACTIVE;
}
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 0, 10);
if (group == g_instant)
return INSTANT;
if (group == g_suggest)
return SUGGEST;
if (group == g_hidden)
return HIDDEN;
if (group == g_silent)
return SILENT;
if (group == g_control)
return CONTROL;
NOTREACHED();
return INACTIVE;
}
// static
bool InstantFieldTrial::IsInstantExperiment(Profile* profile) {
Group group = GetGroup(profile);
return group == INSTANT || group == SUGGEST || group == HIDDEN ||
group == SILENT;
}
// static
bool InstantFieldTrial::IsHiddenExperiment(Profile* profile) {
Group group = GetGroup(profile);
return group == SUGGEST || group == HIDDEN || group == SILENT;
}
// static
bool InstantFieldTrial::IsSilentExperiment(Profile* profile) {
Group group = GetGroup(profile);
return group == SILENT;
}
// static
std::string InstantFieldTrial::GetGroupName(Profile* profile) {
switch (GetGroup(profile)) {
case INACTIVE: return std::string();
case INSTANT: return "_Instant";
case SUGGEST: return "_Suggest";
case HIDDEN: return "_Hidden";
case SILENT: return "_Silent";
case CONTROL: return "_Control";
}
NOTREACHED();
return std::string();
}
// static
std::string InstantFieldTrial::GetGroupAsUrlParam(Profile* profile) {
bool uma = MetricsServiceHelper::IsMetricsReportingEnabled();
switch (GetGroup(profile)) {
case INACTIVE: return std::string();
case INSTANT: if (uma) return "ix=ui&";
return "ix=ni&";
case SUGGEST: if (uma) return "ix=ut&";
return "ix=nt&";
case HIDDEN: if (uma) return "ix=uh&";
return "ix=nh&";
case SILENT: if (uma) return "ix=us&";
return "ix=ns&";
case CONTROL: if (uma) return "ix=uc&";
return "ix=nc&";
}
NOTREACHED();
return std::string();
}
// static
bool InstantFieldTrial::ShouldSetSuggestedText(Profile* profile) {
Group group = GetGroup(profile);
return group != HIDDEN && group != SILENT;
}
<commit_msg>Don't leak UMA opt-in state.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/instant/instant_field_trial.h"
#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
namespace {
// Field trial IDs of the control and experiment groups. Though they are not
// literally "const", they are set only once, in Activate() below. See the .h
// file for what these groups represent.
int g_inactive = -1;
int g_instant = 0;
int g_suggest = 0;
int g_hidden = 0;
int g_silent = 0;
int g_control = 0;
}
// static
void InstantFieldTrial::Activate() {
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
"Instant", 1000, "Inactive", 2013, 7, 1, &g_inactive));
// Try to give the user a consistent experience, if possible.
if (base::FieldTrialList::IsOneTimeRandomizationEnabled())
trial->UseOneTimeRandomization();
g_instant = trial->AppendGroup("Instant", 10); // 1%
g_suggest = trial->AppendGroup("Suggest", 10); // 1%
g_hidden = trial->AppendGroup("Hidden", 960); // 96%
g_silent = trial->AppendGroup("Silent", 10); // 1%
g_control = trial->AppendGroup("Control", 10); // 1%
int group = 0;
if (trial->group() == g_instant)
group = 1;
else if (trial->group() == g_suggest)
group = 2;
else if (trial->group() == g_hidden)
group = 3;
else if (trial->group() == g_silent)
group = 4;
else if (trial->group() == g_control)
group = 5;
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Size", group, 6);
}
// static
InstantFieldTrial::Group InstantFieldTrial::GetGroup(Profile* profile) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kInstantFieldTrial)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 1, 10);
std::string switch_value =
command_line->GetSwitchValueASCII(switches::kInstantFieldTrial);
if (switch_value == switches::kInstantFieldTrialInstant)
return INSTANT;
if (switch_value == switches::kInstantFieldTrialSuggest)
return SUGGEST;
if (switch_value == switches::kInstantFieldTrialHidden)
return HIDDEN;
if (switch_value == switches::kInstantFieldTrialSilent)
return SILENT;
if (switch_value == switches::kInstantFieldTrialControl)
return CONTROL;
return INACTIVE;
}
const int group = base::FieldTrialList::FindValue("Instant");
if (group == base::FieldTrial::kNotFinalized || group == g_inactive) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 2, 10);
return INACTIVE;
}
const PrefService* prefs = profile ? profile->GetPrefs() : NULL;
if (!prefs) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 3, 10);
return INACTIVE;
}
if (profile->IsOffTheRecord()) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 4, 10);
return INACTIVE;
}
if (prefs->GetBoolean(prefs::kInstantEnabledOnce)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 5, 10);
return INACTIVE;
}
if (!prefs->GetBoolean(prefs::kSearchSuggestEnabled)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 6, 10);
return INACTIVE;
}
if (prefs->IsManagedPreference(prefs::kInstantEnabled)) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 7, 10);
return INACTIVE;
}
if (!MetricsServiceHelper::IsMetricsReportingEnabled()) {
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 8, 10);
return INACTIVE;
}
UMA_HISTOGRAM_ENUMERATION("Instant.FieldTrial.Reason", 0, 10);
if (group == g_instant)
return INSTANT;
if (group == g_suggest)
return SUGGEST;
if (group == g_hidden)
return HIDDEN;
if (group == g_silent)
return SILENT;
if (group == g_control)
return CONTROL;
NOTREACHED();
return INACTIVE;
}
// static
bool InstantFieldTrial::IsInstantExperiment(Profile* profile) {
Group group = GetGroup(profile);
return group == INSTANT || group == SUGGEST || group == HIDDEN ||
group == SILENT;
}
// static
bool InstantFieldTrial::IsHiddenExperiment(Profile* profile) {
Group group = GetGroup(profile);
return group == SUGGEST || group == HIDDEN || group == SILENT;
}
// static
bool InstantFieldTrial::IsSilentExperiment(Profile* profile) {
Group group = GetGroup(profile);
return group == SILENT;
}
// static
std::string InstantFieldTrial::GetGroupName(Profile* profile) {
switch (GetGroup(profile)) {
case INACTIVE: return std::string();
case INSTANT: return "_Instant";
case SUGGEST: return "_Suggest";
case HIDDEN: return "_Hidden";
case SILENT: return "_Silent";
case CONTROL: return "_Control";
}
NOTREACHED();
return std::string();
}
// static
std::string InstantFieldTrial::GetGroupAsUrlParam(Profile* profile) {
switch (GetGroup(profile)) {
case INACTIVE: return std::string();
case INSTANT: return "ix=i9&";
case SUGGEST: return "ix=t9&";
case HIDDEN: return "ix=h9&";
case SILENT: return "ix=s9&";
case CONTROL: return "ix=c9&";
}
NOTREACHED();
return std::string();
}
// static
bool InstantFieldTrial::ShouldSetSuggestedText(Profile* profile) {
Group group = GetGroup(profile);
return group != HIDDEN && group != SILENT;
}
<|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 "chrome/browser/views/page_info_bubble_view.h"
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/toolbar_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/separator.h"
#include "views/grid_layout.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
namespace {
// Layout constants.
const int kHGapToBorder = 11;
const int kVGapToImage = 10;
const int kVGapToHeadline = 7;
const int kHGapImageToDescription = 6;
const int kTextPaddingRight = 10;
const int kPaddingBelowSeparator = 4;
const int kPaddingAboveSeparator = 13;
const int kIconOffset = 28;
// A section contains an image that shows a status (good or bad), a title, an
// optional head-line (in bold) and a description.
class Section : public views::View,
public views::LinkController {
public:
Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info,
const SkBitmap* status_icon,
bool show_cert);
virtual ~Section();
// views::View methods:
virtual int GetHeightForWidth(int w);
virtual void Layout();
// views::LinkController methods:
virtual void LinkActivated(views::Link* source, int event_flags);
private:
// Calculate the layout if |compute_bounds_only|, otherwise does Layout also.
gfx::Size LayoutItems(bool compute_bounds_only, int width);
// The view that owns this Section object.
PageInfoBubbleView* owner_;
// The information this view represents.
PageInfoModel::SectionInfo info_;
views::ImageView* status_image_;
views::Label* headline_label_;
views::Label* description_label_;
views::Link* link_;
DISALLOW_COPY_AND_ASSIGN(Section);
};
} // namespace
////////////////////////////////////////////////////////////////////////////////
// PageInfoBubbleView
PageInfoBubbleView::PageInfoBubbleView(gfx::NativeWindow parent_window,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
parent_window_(parent_window),
cert_id_(ssl.cert_id()),
info_bubble_(NULL),
help_center_link_(NULL) {
LayoutSections();
}
PageInfoBubbleView::~PageInfoBubbleView() {
}
void PageInfoBubbleView::ShowCertDialog() {
ShowCertificateViewerByID(parent_window_, cert_id_);
}
void PageInfoBubbleView::LayoutSections() {
// Remove all the existing sections.
RemoveAllChildViews(true);
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
views::ColumnSet* columns = layout->AddColumnSet(0);
columns->AddColumn(views::GridLayout::FILL, // Horizontal resize.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
layout->StartRow(0, 0);
// TODO(finnur): Remove title from the info struct, since it is
// not used anymore.
const SkBitmap* icon = model_.GetIconImage(info.icon_id);
layout->AddView(new Section(this, info, icon, cert_id_ > 0));
// Add separator after all sections.
layout->AddPaddingRow(0, kPaddingAboveSeparator);
layout->StartRow(0, 0);
layout->AddView(new views::Separator());
layout->AddPaddingRow(0, kPaddingBelowSeparator);
}
// Then add the help center link at the bottom.
layout->StartRow(0, 0);
help_center_link_ =
new views::Link(l10n_util::GetString(IDS_PAGE_INFO_HELP_CENTER_LINK));
help_center_link_->SetController(this);
layout->AddView(help_center_link_);
}
gfx::Size PageInfoBubbleView::GetPreferredSize() {
gfx::Size size(views::Window::GetLocalizedContentsSize(
IDS_PAGEINFOBUBBLE_WIDTH_CHARS, IDS_PAGEINFOBUBBLE_HEIGHT_LINES));
size.set_height(0);
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
const SkBitmap* icon = model_.GetIconImage(info.icon_id);
Section section(this, info, icon, cert_id_ > 0);
size.Enlarge(0, section.GetHeightForWidth(size.width()));
}
// Calculate how much space the separators take up (with padding).
views::Separator separator;
gfx::Size separator_size = separator.GetPreferredSize();
gfx::Size separator_plus_padding(0, separator_size.height() +
kPaddingAboveSeparator +
kPaddingBelowSeparator);
// Account for the separators and padding within sections.
size.Enlarge(0, (count - 1) * separator_plus_padding.height());
// Account for the Help Center link and the separator above it.
gfx::Size link_size = help_center_link_->GetPreferredSize();
size.Enlarge(0, separator_plus_padding.height() +
link_size.height());
return size;
}
void PageInfoBubbleView::ModelChanged() {
LayoutSections();
info_bubble_->SizeToContents();
}
void PageInfoBubbleView::LinkActivated(views::Link* source, int event_flags) {
GURL url = GURL(l10n_util::GetStringUTF16(IDS_PAGE_INFO_HELP_CENTER));
Browser* browser = BrowserList::GetLastActive();
browser->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
}
////////////////////////////////////////////////////////////////////////////////
// Section
Section::Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info,
const SkBitmap* state_icon,
bool show_cert)
: owner_(owner),
info_(section_info),
status_image_(NULL),
link_(NULL) {
if (state_icon) {
status_image_ = new views::ImageView();
status_image_->SetImage(*state_icon);
AddChildView(status_image_);
}
headline_label_ = new views::Label(UTF16ToWideHack(info_.headline));
headline_label_->SetFont(
headline_label_->font().DeriveFont(0, gfx::Font::BOLD));
headline_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(headline_label_);
description_label_ = new views::Label(UTF16ToWideHack(info_.description));
description_label_->SetMultiLine(true);
description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
description_label_->SetAllowCharacterBreak(true);
AddChildView(description_label_);
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY && show_cert) {
link_ = new views::Link(
l10n_util::GetString(IDS_PAGEINFO_CERT_INFO_BUTTON));
link_->SetController(this);
AddChildView(link_);
}
}
Section::~Section() {
}
int Section::GetHeightForWidth(int width) {
return LayoutItems(true, width).height();
}
void Section::Layout() {
LayoutItems(false, width());
}
void Section::LinkActivated(views::Link* source, int event_flags) {
owner_->ShowCertDialog();
}
gfx::Size Section::LayoutItems(bool compute_bounds_only, int width) {
int x = kHGapToBorder;
int y = kVGapToImage;
// Layout the image, head-line and description.
gfx::Size size;
if (status_image_) {
size = status_image_->GetPreferredSize();
if (!compute_bounds_only)
status_image_->SetBounds(x, y, size.width(), size.height());
}
int image_height = y + size.height();
x += size.width() + kHGapImageToDescription;
int w = width - x - kTextPaddingRight;
y = kVGapToHeadline;
if (!headline_label_->GetText().empty()) {
size = headline_label_->GetPreferredSize();
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, w > 0 ? w : 0, size.height());
y += size.height();
} else {
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, 0, 0);
}
if (w > 0) {
int height = description_label_->GetHeightForWidth(w);
if (!compute_bounds_only)
description_label_->SetBounds(x, y, w, height);
y += height;
} else {
if (!compute_bounds_only)
description_label_->SetBounds(x, y, 0, 0);
}
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY && link_) {
size = link_->GetPreferredSize();
if (!compute_bounds_only)
link_->SetBounds(x, y, size.width(), size.height());
y += size.height();
}
// Make sure the image is not truncated if the text doesn't contain much.
y = std::max(y, image_height);
return gfx::Size(width, y);
}
namespace browser {
void ShowPageInfoBubble(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
// Find where to point the bubble at.
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(parent);
gfx::Point point;
if (base::i18n::IsRTL()) {
int width = browser_view->toolbar()->location_bar()->width();
point = gfx::Point(width - kIconOffset, 0);
}
views::View::ConvertPointToScreen(browser_view->toolbar()->location_bar(),
&point);
gfx::Rect bounds = browser_view->toolbar()->location_bar()->bounds();
bounds.set_origin(point);
bounds.set_width(kIconOffset);
// Show the bubble.
PageInfoBubbleView* page_info_bubble =
new PageInfoBubbleView(parent, profile, url, ssl, show_history);
InfoBubble* info_bubble =
InfoBubble::Show(browser_view->GetWidget(), bounds,
BubbleBorder::TOP_LEFT,
page_info_bubble, page_info_bubble);
page_info_bubble->set_info_bubble(info_bubble);
}
}
<commit_msg>SSL page info bubble quick polish issues.<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 "chrome/browser/views/page_info_bubble_view.h"
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/toolbar_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/separator.h"
#include "views/grid_layout.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
namespace {
// Layout constants.
const int kHGapToBorder = 11;
const int kVGapToImage = 10;
const int kVGapToHeadline = 7;
const int kHGapImageToDescription = 6;
const int kTextPaddingRight = 10;
const int kPaddingBelowSeparator = 4;
const int kPaddingAboveSeparator = 13;
const int kIconHorizontalOffset = 27;
const int kIconVerticalOffset = -7;
// A section contains an image that shows a status (good or bad), a title, an
// optional head-line (in bold) and a description.
class Section : public views::View,
public views::LinkController {
public:
Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info,
const SkBitmap* status_icon,
bool show_cert);
virtual ~Section();
// views::View methods:
virtual int GetHeightForWidth(int w);
virtual void Layout();
// views::LinkController methods:
virtual void LinkActivated(views::Link* source, int event_flags);
private:
// Calculate the layout if |compute_bounds_only|, otherwise does Layout also.
gfx::Size LayoutItems(bool compute_bounds_only, int width);
// The view that owns this Section object.
PageInfoBubbleView* owner_;
// The information this view represents.
PageInfoModel::SectionInfo info_;
views::ImageView* status_image_;
views::Label* headline_label_;
views::Label* description_label_;
views::Link* link_;
DISALLOW_COPY_AND_ASSIGN(Section);
};
} // namespace
////////////////////////////////////////////////////////////////////////////////
// PageInfoBubbleView
PageInfoBubbleView::PageInfoBubbleView(gfx::NativeWindow parent_window,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
parent_window_(parent_window),
cert_id_(ssl.cert_id()),
info_bubble_(NULL),
help_center_link_(NULL) {
LayoutSections();
}
PageInfoBubbleView::~PageInfoBubbleView() {
}
void PageInfoBubbleView::ShowCertDialog() {
ShowCertificateViewerByID(parent_window_, cert_id_);
}
void PageInfoBubbleView::LayoutSections() {
// Remove all the existing sections.
RemoveAllChildViews(true);
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
views::ColumnSet* columns = layout->AddColumnSet(0);
columns->AddColumn(views::GridLayout::FILL, // Horizontal resize.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
// Add a column set for aligning the text when it has no icons (such as the
// help center link).
columns = layout->AddColumnSet(1);
columns->AddPaddingColumn(
0, kHGapToBorder + kIconHorizontalOffset + kHGapImageToDescription);
columns->AddColumn(views::GridLayout::LEADING, // Horizontal resize.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
layout->StartRow(0, 0);
// TODO(finnur): Remove title from the info struct, since it is
// not used anymore.
const SkBitmap* icon = model_.GetIconImage(info.icon_id);
layout->AddView(new Section(this, info, icon, cert_id_ > 0));
// Add separator after all sections.
layout->AddPaddingRow(0, kPaddingAboveSeparator);
layout->StartRow(0, 0);
layout->AddView(new views::Separator());
layout->AddPaddingRow(0, kPaddingBelowSeparator);
}
// Then add the help center link at the bottom.
layout->StartRow(0, 1);
help_center_link_ =
new views::Link(l10n_util::GetString(IDS_PAGE_INFO_HELP_CENTER_LINK));
help_center_link_->SetController(this);
layout->AddView(help_center_link_);
}
gfx::Size PageInfoBubbleView::GetPreferredSize() {
gfx::Size size(views::Window::GetLocalizedContentsSize(
IDS_PAGEINFOBUBBLE_WIDTH_CHARS, IDS_PAGEINFOBUBBLE_HEIGHT_LINES));
size.set_height(0);
int count = model_.GetSectionCount();
for (int i = 0; i < count; ++i) {
PageInfoModel::SectionInfo info = model_.GetSectionInfo(i);
const SkBitmap* icon = model_.GetIconImage(info.icon_id);
Section section(this, info, icon, cert_id_ > 0);
size.Enlarge(0, section.GetHeightForWidth(size.width()));
}
// Calculate how much space the separators take up (with padding).
views::Separator separator;
gfx::Size separator_size = separator.GetPreferredSize();
gfx::Size separator_plus_padding(0, separator_size.height() +
kPaddingAboveSeparator +
kPaddingBelowSeparator);
// Account for the separators and padding within sections.
size.Enlarge(0, (count - 1) * separator_plus_padding.height());
// Account for the Help Center link and the separator above it.
gfx::Size link_size = help_center_link_->GetPreferredSize();
size.Enlarge(0, separator_plus_padding.height() +
link_size.height());
return size;
}
void PageInfoBubbleView::ModelChanged() {
LayoutSections();
info_bubble_->SizeToContents();
}
void PageInfoBubbleView::LinkActivated(views::Link* source, int event_flags) {
GURL url = GURL(l10n_util::GetStringUTF16(IDS_PAGE_INFO_HELP_CENTER));
Browser* browser = BrowserList::GetLastActive();
browser->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
}
////////////////////////////////////////////////////////////////////////////////
// Section
Section::Section(PageInfoBubbleView* owner,
const PageInfoModel::SectionInfo& section_info,
const SkBitmap* state_icon,
bool show_cert)
: owner_(owner),
info_(section_info),
status_image_(NULL),
link_(NULL) {
if (state_icon) {
status_image_ = new views::ImageView();
status_image_->SetImage(*state_icon);
AddChildView(status_image_);
}
headline_label_ = new views::Label(UTF16ToWideHack(info_.headline));
headline_label_->SetFont(
headline_label_->font().DeriveFont(0, gfx::Font::BOLD));
headline_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(headline_label_);
description_label_ = new views::Label(UTF16ToWideHack(info_.description));
description_label_->SetMultiLine(true);
description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
description_label_->SetAllowCharacterBreak(true);
AddChildView(description_label_);
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY && show_cert) {
link_ = new views::Link(
l10n_util::GetString(IDS_PAGEINFO_CERT_INFO_BUTTON));
link_->SetController(this);
AddChildView(link_);
}
}
Section::~Section() {
}
int Section::GetHeightForWidth(int width) {
return LayoutItems(true, width).height();
}
void Section::Layout() {
LayoutItems(false, width());
}
void Section::LinkActivated(views::Link* source, int event_flags) {
owner_->ShowCertDialog();
}
gfx::Size Section::LayoutItems(bool compute_bounds_only, int width) {
int x = kHGapToBorder;
int y = kVGapToImage;
// Layout the image, head-line and description.
gfx::Size size;
if (status_image_) {
size = status_image_->GetPreferredSize();
if (!compute_bounds_only)
status_image_->SetBounds(x, y, size.width(), size.height());
}
int image_height = y + size.height();
x += size.width() + kHGapImageToDescription;
int w = width - x - kTextPaddingRight;
y = kVGapToHeadline;
if (!headline_label_->GetText().empty()) {
size = headline_label_->GetPreferredSize();
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, w > 0 ? w : 0, size.height());
y += size.height();
} else {
if (!compute_bounds_only)
headline_label_->SetBounds(x, y, 0, 0);
}
if (w > 0) {
int height = description_label_->GetHeightForWidth(w);
if (!compute_bounds_only)
description_label_->SetBounds(x, y, w, height);
y += height;
} else {
if (!compute_bounds_only)
description_label_->SetBounds(x, y, 0, 0);
}
if (info_.type == PageInfoModel::SECTION_INFO_IDENTITY && link_) {
size = link_->GetPreferredSize();
if (!compute_bounds_only)
link_->SetBounds(x, y, size.width(), size.height());
y += size.height();
}
// Make sure the image is not truncated if the text doesn't contain much.
y = std::max(y, image_height);
return gfx::Size(width, y);
}
namespace browser {
void ShowPageInfoBubble(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
// Find where to point the bubble at.
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(parent);
gfx::Point point;
if (base::i18n::IsRTL()) {
int width = browser_view->toolbar()->location_bar()->width();
point = gfx::Point(width - kIconHorizontalOffset, 0);
}
point.Offset(0, kIconVerticalOffset);
views::View::ConvertPointToScreen(browser_view->toolbar()->location_bar(),
&point);
gfx::Rect bounds = browser_view->toolbar()->location_bar()->bounds();
bounds.set_origin(point);
bounds.set_width(kIconHorizontalOffset);
// Show the bubble.
PageInfoBubbleView* page_info_bubble =
new PageInfoBubbleView(parent, profile, url, ssl, show_history);
InfoBubble* info_bubble =
InfoBubble::Show(browser_view->GetWidget(), bounds,
BubbleBorder::TOP_LEFT,
page_info_bubble, page_info_bubble);
page_info_bubble->set_info_bubble(info_bubble);
}
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow 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 <cstdint>
#include <cstdlib>
#include "tensorflow/core/platform/status.h"
#include <fuzzer/FuzzedDataProvider.h>
// This is a fuzzer for `tensorflow::StatusGroup`. Since `Status` is used almost
// everywhere, we need to ensure that the common functionality is safe. We don't
// expect many crashes from this fuzzer
namespace {
tensorflow::error::Code BuildRandomErrorCode(uint32_t code){
// We cannot build a `Status` with error_code of 0 and a message, so force
// error code to be non-zero.
if (code == 0) {
return tensorflow::error::UNKNOWN;
}
return static_cast<tensorflow::error::Code>(code);
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
const std::string error_message = "ERROR";
tensorflow::StatusGroup sg;
FuzzedDataProvider fuzzed_data(data, size);
while(fuzzed_data.remaining_bytes() > 0) {
uint32_t code = fuzzed_data.ConsumeIntegral<uint32_t>();
tensorflow::error::Code error_code = BuildRandomErrorCode(code);
bool is_derived = fuzzed_data.ConsumeBool();
tensorflow::Status s = tensorflow::Status(error_code, error_message);
if(is_derived) {
tensorflow::Status derived_s = tensorflow::StatusGroup::MakeDerived(s);
sg.Update(derived_s);
} else {
sg.Update(s);
}
}
sg.as_summary_status();
sg.as_concatenated_status();
sg.AttachLogMessages();
return 0;
}
} // namespace
<commit_msg>Moved final StatusGroup method calls<commit_after>/* Copyright 2020 The TensorFlow 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 <cstdint>
#include <cstdlib>
#include "tensorflow/core/platform/status.h"
#include <fuzzer/FuzzedDataProvider.h>
// This is a fuzzer for `tensorflow::StatusGroup`. Since `Status` is used almost
// everywhere, we need to ensure that the common functionality is safe. We don't
// expect many crashes from this fuzzer
namespace {
tensorflow::error::Code BuildRandomErrorCode(uint32_t code){
// We cannot build a `Status` with error_code of 0 and a message, so force
// error code to be non-zero.
if (code == 0) {
return tensorflow::error::UNKNOWN;
}
return static_cast<tensorflow::error::Code>(code);
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
const std::string error_message = "ERROR";
tensorflow::StatusGroup sg;
FuzzedDataProvider fuzzed_data(data, size);
while(fuzzed_data.remaining_bytes() > 0) {
uint32_t code = fuzzed_data.ConsumeIntegral<uint32_t>();
tensorflow::error::Code error_code = BuildRandomErrorCode(code);
bool is_derived = fuzzed_data.ConsumeBool();
tensorflow::Status s = tensorflow::Status(error_code, error_message);
if(is_derived) {
tensorflow::Status derived_s = tensorflow::StatusGroup::MakeDerived(s);
sg.Update(derived_s);
} else {
sg.Update(s);
}
}
sg.as_summary_status();
sg.as_concatenated_status();
sg.AttachLogMessages();
return 0;
}
} // namespace
<|endoftext|> |
<commit_before>// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -DSHARED %s -shared -o %T/stack_trace_dlclose.so -fPIC
// RUN: %clangxx_asan -DSO_DIR=\"%T\" %s %libdl -o %t
// RUN: env ASAN_OPTIONS=$ASAN_OPTIONS:exitcode=0 %run %t 2>&1 | FileCheck %s
// XFAIL: arm-linux-gnueabi
// XFAIL: armv7l-unknown-linux-gnueabihf
#include <assert.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sanitizer/common_interface_defs.h>
#ifdef SHARED
extern "C" {
void *foo() {
return malloc(1);
}
}
#else
void *handle;
int main(int argc, char **argv) {
void *handle = dlopen(SO_DIR "/stack_trace_dlclose.so", RTLD_LAZY);
assert(handle);
void *(*foo)() = (void *(*)())dlsym(handle, "foo");
assert(foo);
void *p = foo();
assert(p);
dlclose(handle);
free(p);
free(p); // double-free
return 0;
}
#endif
// CHECK: {{ #0 0x.* in malloc}}
// CHECK: {{ #1 0x.* \(<unknown module>\)}}
// CHECK: {{ #2 0x.* in main}}
<commit_msg>[asan] relax the test case to allow either 'malloc' or '__interceptor_malloc' ; PR22681<commit_after>// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -DSHARED %s -shared -o %T/stack_trace_dlclose.so -fPIC
// RUN: %clangxx_asan -DSO_DIR=\"%T\" %s %libdl -o %t
// RUN: env ASAN_OPTIONS=$ASAN_OPTIONS:exitcode=0 %run %t 2>&1 | FileCheck %s
// XFAIL: arm-linux-gnueabi
// XFAIL: armv7l-unknown-linux-gnueabihf
#include <assert.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sanitizer/common_interface_defs.h>
#ifdef SHARED
extern "C" {
void *foo() {
return malloc(1);
}
}
#else
void *handle;
int main(int argc, char **argv) {
void *handle = dlopen(SO_DIR "/stack_trace_dlclose.so", RTLD_LAZY);
assert(handle);
void *(*foo)() = (void *(*)())dlsym(handle, "foo");
assert(foo);
void *p = foo();
assert(p);
dlclose(handle);
free(p);
free(p); // double-free
return 0;
}
#endif
// CHECK: {{ #0 0x.* in (__interceptor_)?malloc}}
// CHECK: {{ #1 0x.* \(<unknown module>\)}}
// CHECK: {{ #2 0x.* in main}}
<|endoftext|> |
<commit_before>// Copyright 2014 the V8 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.
#include <limits>
#include "src/compiler/control-builders.h"
#include "src/compiler/generic-node-inl.h"
#include "src/compiler/node-properties-inl.h"
#include "src/compiler/pipeline.h"
#include "src/compiler/simplified-lowering.h"
#include "src/compiler/simplified-node-factory.h"
#include "src/compiler/typer.h"
#include "src/compiler/verifier.h"
#include "src/execution.h"
#include "src/parser.h"
#include "src/rewriter.h"
#include "src/scopes.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/codegen-tester.h"
#include "test/cctest/compiler/graph-builder-tester.h"
#include "test/cctest/compiler/value-helper.h"
using namespace v8::internal;
using namespace v8::internal::compiler;
// TODO(titzer): rename this to VMLoweringTester
template <typename ReturnType>
class SimplifiedGraphBuilderTester : public GraphBuilderTester<ReturnType> {
public:
SimplifiedGraphBuilderTester(MachineRepresentation p0 = kMachineLast,
MachineRepresentation p1 = kMachineLast,
MachineRepresentation p2 = kMachineLast,
MachineRepresentation p3 = kMachineLast,
MachineRepresentation p4 = kMachineLast)
: GraphBuilderTester<ReturnType>(p0, p1, p2, p3, p4),
typer(this->zone()),
source_positions(this->graph()),
jsgraph(this->graph(), this->common(), &typer),
lowering(&jsgraph, &source_positions) {}
Typer typer;
SourcePositionTable source_positions;
JSGraph jsgraph;
SimplifiedLowering lowering;
// Close graph and lower one node.
void Lower(Node* node) {
this->End();
if (node == NULL) {
lowering.LowerAllNodes();
} else {
lowering.Lower(node);
}
}
// Close graph and lower all nodes.
void LowerAllNodes() { Lower(NULL); }
void StoreFloat64(Node* node, double* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
this->Store(kMachineFloat64, ptr_node, node);
}
Node* LoadInt32(int32_t* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
return this->Load(kMachineWord32, ptr_node);
}
Node* LoadUint32(uint32_t* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
return this->Load(kMachineWord32, ptr_node);
}
Node* LoadFloat64(double* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
return this->Load(kMachineFloat64, ptr_node);
}
Factory* factory() { return this->isolate()->factory(); }
Heap* heap() { return this->isolate()->heap(); }
};
// TODO(dcarney): find a home for these functions.
namespace {
FieldAccess ForJSObjectMap() {
FieldAccess access = {kTaggedBase, JSObject::kMapOffset, Handle<Name>(),
Type::Any(), kMachineTagged};
return access;
}
FieldAccess ForJSObjectProperties() {
FieldAccess access = {kTaggedBase, JSObject::kPropertiesOffset,
Handle<Name>(), Type::Any(), kMachineTagged};
return access;
}
FieldAccess ForArrayBufferBackingStore() {
FieldAccess access = {
kTaggedBase, JSArrayBuffer::kBackingStoreOffset,
Handle<Name>(), Type::UntaggedPtr(),
MachineOperatorBuilder::pointer_rep(),
};
return access;
}
ElementAccess ForFixedArrayElement() {
ElementAccess access = {kTaggedBase, FixedArray::kHeaderSize, Type::Any(),
kMachineTagged};
return access;
}
ElementAccess ForBackingStoreElement(MachineRepresentation rep) {
ElementAccess access = {kUntaggedBase,
kNonHeapObjectHeaderSize - kHeapObjectTag,
Type::Any(), rep};
return access;
}
}
// Create a simple JSObject with a unique map.
static Handle<JSObject> TestObject() {
static int index = 0;
char buffer[50];
v8::base::OS::SNPrintF(buffer, 50, "({'a_%d':1})", index++);
return Handle<JSObject>::cast(v8::Utils::OpenHandle(*CompileRun(buffer)));
}
TEST(RunLoadMap) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
FieldAccess access = ForJSObjectMap();
Node* load = t.LoadField(access, t.Parameter(0));
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<Map> src_map(src->map());
Object* result = t.Call(*src);
CHECK_EQ(*src_map, result);
}
TEST(RunStoreMap) {
SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);
FieldAccess access = ForJSObjectMap();
t.StoreField(access, t.Parameter(1), t.Parameter(0));
t.Return(t.Int32Constant(0));
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<Map> src_map(src->map());
Handle<JSObject> dst = TestObject();
CHECK(src->map() != dst->map());
t.Call(*src_map, *dst);
CHECK(*src_map == dst->map());
}
TEST(RunLoadProperties) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
FieldAccess access = ForJSObjectProperties();
Node* load = t.LoadField(access, t.Parameter(0));
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<FixedArray> src_props(src->properties());
Object* result = t.Call(*src);
CHECK_EQ(*src_props, result);
}
TEST(RunLoadStoreMap) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged, kMachineTagged);
FieldAccess access = ForJSObjectMap();
Node* load = t.LoadField(access, t.Parameter(0));
t.StoreField(access, t.Parameter(1), load);
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<Map> src_map(src->map());
Handle<JSObject> dst = TestObject();
CHECK(src->map() != dst->map());
Object* result = t.Call(*src, *dst);
CHECK(result->IsMap());
CHECK_EQ(*src_map, result);
CHECK(*src_map == dst->map());
}
TEST(RunLoadStoreFixedArrayIndex) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
ElementAccess access = ForFixedArrayElement();
Node* load = t.LoadElement(access, t.Parameter(0), t.Int32Constant(0));
t.StoreElement(access, t.Parameter(0), t.Int32Constant(1), load);
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<FixedArray> array = t.factory()->NewFixedArray(2);
Handle<JSObject> src = TestObject();
Handle<JSObject> dst = TestObject();
array->set(0, *src);
array->set(1, *dst);
Object* result = t.Call(*array);
CHECK_EQ(*src, result);
CHECK_EQ(*src, array->get(0));
CHECK_EQ(*src, array->get(1));
}
TEST(RunLoadStoreArrayBuffer) {
SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged);
const int index = 12;
FieldAccess access = ForArrayBufferBackingStore();
Node* backing_store = t.LoadField(access, t.Parameter(0));
ElementAccess buffer_access = ForBackingStoreElement(kMachineWord8);
Node* load =
t.LoadElement(buffer_access, backing_store, t.Int32Constant(index));
t.StoreElement(buffer_access, backing_store, t.Int32Constant(index + 1),
load);
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSArrayBuffer> array = t.factory()->NewJSArrayBuffer();
const int array_length = 2 * index;
Runtime::SetupArrayBufferAllocatingData(t.isolate(), array, array_length);
uint8_t* data = reinterpret_cast<uint8_t*>(array->backing_store());
for (int i = 0; i < array_length; i++) {
data[i] = i;
}
int32_t result = t.Call(*array);
CHECK_EQ(index, result);
for (int i = 0; i < array_length; i++) {
uint8_t expected = i;
if (i == (index + 1)) expected = result;
CHECK_EQ(data[i], expected);
}
}
TEST(RunCopyFixedArray) {
SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);
const int kArraySize = 15;
Node* one = t.Int32Constant(1);
Node* index = t.Int32Constant(0);
Node* limit = t.Int32Constant(kArraySize);
t.environment()->Push(index);
{
LoopBuilder loop(&t);
loop.BeginLoop();
// Loop exit condition.
index = t.environment()->Top();
Node* condition = t.Int32LessThan(index, limit);
loop.BreakUnless(condition);
// src[index] = dst[index].
index = t.environment()->Pop();
ElementAccess access = ForFixedArrayElement();
Node* src = t.Parameter(0);
Node* load = t.LoadElement(access, src, index);
Node* dst = t.Parameter(1);
t.StoreElement(access, dst, index, load);
// index++
index = t.Int32Add(index, one);
t.environment()->Push(index);
// continue.
loop.EndBody();
loop.EndLoop();
}
index = t.environment()->Pop();
t.Return(index);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<FixedArray> src = t.factory()->NewFixedArray(kArraySize);
Handle<FixedArray> src_copy = t.factory()->NewFixedArray(kArraySize);
Handle<FixedArray> dst = t.factory()->NewFixedArray(kArraySize);
for (int i = 0; i < kArraySize; i++) {
src->set(i, *TestObject());
src_copy->set(i, src->get(i));
dst->set(i, *TestObject());
CHECK_NE(src_copy->get(i), dst->get(i));
}
CHECK_EQ(kArraySize, t.Call(*src, *dst));
for (int i = 0; i < kArraySize; i++) {
CHECK_EQ(src_copy->get(i), dst->get(i));
}
}
TEST(RunLoadFieldFromUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
FieldAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // offset
Handle<Name>(), Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t;
Node* load = t.LoadField(access, t.PointerConstant(smis));
t.Return(load);
t.LowerAllNodes();
for (int j = -5; j <= 5; j++) {
Smi* expected = Smi::FromInt(j);
smis[i] = expected;
CHECK_EQ(expected, t.Call());
}
}
}
TEST(RunStoreFieldToUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
FieldAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // offset
Handle<Name>(), Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
Node* p0 = t.Parameter(0);
t.StoreField(access, t.PointerConstant(smis), p0);
t.Return(p0);
t.LowerAllNodes();
for (int j = -5; j <= 5; j++) {
Smi* expected = Smi::FromInt(j);
smis[i] = Smi::FromInt(-100);
CHECK_EQ(expected, t.Call(expected));
CHECK_EQ(expected, smis[i]);
}
}
}
TEST(RunLoadElementFromUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
Smi::FromInt(4), Smi::FromInt(5)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) { // for header sizes
for (size_t j = i; j < ARRAY_SIZE(smis); j++) { // for element index
ElementAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // header size
Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t;
Node* load =
t.LoadElement(access, t.PointerConstant(smis), t.Int32Constant(j));
t.Return(load);
t.LowerAllNodes();
for (int k = -5; k <= 5; k++) {
Smi* expected = Smi::FromInt(k);
smis[i + j] = expected;
CHECK_EQ(expected, t.Call());
}
}
}
}
TEST(RunStoreElementFromUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
Smi::FromInt(4), Smi::FromInt(5)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) { // for header sizes
for (size_t j = i; j < ARRAY_SIZE(smis); j++) { // for element index
ElementAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // header size
Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
Node* p0 = t.Parameter(0);
t.StoreElement(access, t.PointerConstant(smis), t.Int32Constant(j), p0);
t.Return(p0);
t.LowerAllNodes();
for (int k = -5; k <= 5; k++) {
Smi* expected = Smi::FromInt(k);
smis[i + j] = Smi::FromInt(-100);
CHECK_EQ(expected, t.Call(expected));
CHECK_EQ(expected, smis[i + j]);
}
}
}
}
<commit_msg>TF: simplified-lowering tests accidentally ran on unsupported platforms.<commit_after>// Copyright 2014 the V8 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.
#include <limits>
#include "src/compiler/control-builders.h"
#include "src/compiler/generic-node-inl.h"
#include "src/compiler/node-properties-inl.h"
#include "src/compiler/pipeline.h"
#include "src/compiler/simplified-lowering.h"
#include "src/compiler/simplified-node-factory.h"
#include "src/compiler/typer.h"
#include "src/compiler/verifier.h"
#include "src/execution.h"
#include "src/parser.h"
#include "src/rewriter.h"
#include "src/scopes.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/codegen-tester.h"
#include "test/cctest/compiler/graph-builder-tester.h"
#include "test/cctest/compiler/value-helper.h"
using namespace v8::internal;
using namespace v8::internal::compiler;
// TODO(titzer): rename this to VMLoweringTester
template <typename ReturnType>
class SimplifiedGraphBuilderTester : public GraphBuilderTester<ReturnType> {
public:
SimplifiedGraphBuilderTester(MachineRepresentation p0 = kMachineLast,
MachineRepresentation p1 = kMachineLast,
MachineRepresentation p2 = kMachineLast,
MachineRepresentation p3 = kMachineLast,
MachineRepresentation p4 = kMachineLast)
: GraphBuilderTester<ReturnType>(p0, p1, p2, p3, p4),
typer(this->zone()),
source_positions(this->graph()),
jsgraph(this->graph(), this->common(), &typer),
lowering(&jsgraph, &source_positions) {}
Typer typer;
SourcePositionTable source_positions;
JSGraph jsgraph;
SimplifiedLowering lowering;
// Close graph and lower one node.
void Lower(Node* node) {
this->End();
if (node == NULL) {
lowering.LowerAllNodes();
} else {
lowering.Lower(node);
}
}
// Close graph and lower all nodes.
void LowerAllNodes() { Lower(NULL); }
void StoreFloat64(Node* node, double* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
this->Store(kMachineFloat64, ptr_node, node);
}
Node* LoadInt32(int32_t* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
return this->Load(kMachineWord32, ptr_node);
}
Node* LoadUint32(uint32_t* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
return this->Load(kMachineWord32, ptr_node);
}
Node* LoadFloat64(double* ptr) {
Node* ptr_node = this->PointerConstant(ptr);
return this->Load(kMachineFloat64, ptr_node);
}
Factory* factory() { return this->isolate()->factory(); }
Heap* heap() { return this->isolate()->heap(); }
};
// TODO(dcarney): find a home for these functions.
namespace {
FieldAccess ForJSObjectMap() {
FieldAccess access = {kTaggedBase, JSObject::kMapOffset, Handle<Name>(),
Type::Any(), kMachineTagged};
return access;
}
FieldAccess ForJSObjectProperties() {
FieldAccess access = {kTaggedBase, JSObject::kPropertiesOffset,
Handle<Name>(), Type::Any(), kMachineTagged};
return access;
}
FieldAccess ForArrayBufferBackingStore() {
FieldAccess access = {
kTaggedBase, JSArrayBuffer::kBackingStoreOffset,
Handle<Name>(), Type::UntaggedPtr(),
MachineOperatorBuilder::pointer_rep(),
};
return access;
}
ElementAccess ForFixedArrayElement() {
ElementAccess access = {kTaggedBase, FixedArray::kHeaderSize, Type::Any(),
kMachineTagged};
return access;
}
ElementAccess ForBackingStoreElement(MachineRepresentation rep) {
ElementAccess access = {kUntaggedBase,
kNonHeapObjectHeaderSize - kHeapObjectTag,
Type::Any(), rep};
return access;
}
}
// Create a simple JSObject with a unique map.
static Handle<JSObject> TestObject() {
static int index = 0;
char buffer[50];
v8::base::OS::SNPrintF(buffer, 50, "({'a_%d':1})", index++);
return Handle<JSObject>::cast(v8::Utils::OpenHandle(*CompileRun(buffer)));
}
TEST(RunLoadMap) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
FieldAccess access = ForJSObjectMap();
Node* load = t.LoadField(access, t.Parameter(0));
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<Map> src_map(src->map());
Object* result = t.Call(*src);
CHECK_EQ(*src_map, result);
}
TEST(RunStoreMap) {
SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);
FieldAccess access = ForJSObjectMap();
t.StoreField(access, t.Parameter(1), t.Parameter(0));
t.Return(t.Int32Constant(0));
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<Map> src_map(src->map());
Handle<JSObject> dst = TestObject();
CHECK(src->map() != dst->map());
t.Call(*src_map, *dst);
CHECK(*src_map == dst->map());
}
TEST(RunLoadProperties) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
FieldAccess access = ForJSObjectProperties();
Node* load = t.LoadField(access, t.Parameter(0));
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<FixedArray> src_props(src->properties());
Object* result = t.Call(*src);
CHECK_EQ(*src_props, result);
}
TEST(RunLoadStoreMap) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged, kMachineTagged);
FieldAccess access = ForJSObjectMap();
Node* load = t.LoadField(access, t.Parameter(0));
t.StoreField(access, t.Parameter(1), load);
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSObject> src = TestObject();
Handle<Map> src_map(src->map());
Handle<JSObject> dst = TestObject();
CHECK(src->map() != dst->map());
Object* result = t.Call(*src, *dst);
CHECK(result->IsMap());
CHECK_EQ(*src_map, result);
CHECK(*src_map == dst->map());
}
TEST(RunLoadStoreFixedArrayIndex) {
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
ElementAccess access = ForFixedArrayElement();
Node* load = t.LoadElement(access, t.Parameter(0), t.Int32Constant(0));
t.StoreElement(access, t.Parameter(0), t.Int32Constant(1), load);
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<FixedArray> array = t.factory()->NewFixedArray(2);
Handle<JSObject> src = TestObject();
Handle<JSObject> dst = TestObject();
array->set(0, *src);
array->set(1, *dst);
Object* result = t.Call(*array);
CHECK_EQ(*src, result);
CHECK_EQ(*src, array->get(0));
CHECK_EQ(*src, array->get(1));
}
TEST(RunLoadStoreArrayBuffer) {
SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged);
const int index = 12;
FieldAccess access = ForArrayBufferBackingStore();
Node* backing_store = t.LoadField(access, t.Parameter(0));
ElementAccess buffer_access = ForBackingStoreElement(kMachineWord8);
Node* load =
t.LoadElement(buffer_access, backing_store, t.Int32Constant(index));
t.StoreElement(buffer_access, backing_store, t.Int32Constant(index + 1),
load);
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<JSArrayBuffer> array = t.factory()->NewJSArrayBuffer();
const int array_length = 2 * index;
Runtime::SetupArrayBufferAllocatingData(t.isolate(), array, array_length);
uint8_t* data = reinterpret_cast<uint8_t*>(array->backing_store());
for (int i = 0; i < array_length; i++) {
data[i] = i;
}
int32_t result = t.Call(*array);
CHECK_EQ(index, result);
for (int i = 0; i < array_length; i++) {
uint8_t expected = i;
if (i == (index + 1)) expected = result;
CHECK_EQ(data[i], expected);
}
}
TEST(RunCopyFixedArray) {
SimplifiedGraphBuilderTester<int32_t> t(kMachineTagged, kMachineTagged);
const int kArraySize = 15;
Node* one = t.Int32Constant(1);
Node* index = t.Int32Constant(0);
Node* limit = t.Int32Constant(kArraySize);
t.environment()->Push(index);
{
LoopBuilder loop(&t);
loop.BeginLoop();
// Loop exit condition.
index = t.environment()->Top();
Node* condition = t.Int32LessThan(index, limit);
loop.BreakUnless(condition);
// src[index] = dst[index].
index = t.environment()->Pop();
ElementAccess access = ForFixedArrayElement();
Node* src = t.Parameter(0);
Node* load = t.LoadElement(access, src, index);
Node* dst = t.Parameter(1);
t.StoreElement(access, dst, index, load);
// index++
index = t.Int32Add(index, one);
t.environment()->Push(index);
// continue.
loop.EndBody();
loop.EndLoop();
}
index = t.environment()->Pop();
t.Return(index);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) return;
Handle<FixedArray> src = t.factory()->NewFixedArray(kArraySize);
Handle<FixedArray> src_copy = t.factory()->NewFixedArray(kArraySize);
Handle<FixedArray> dst = t.factory()->NewFixedArray(kArraySize);
for (int i = 0; i < kArraySize; i++) {
src->set(i, *TestObject());
src_copy->set(i, src->get(i));
dst->set(i, *TestObject());
CHECK_NE(src_copy->get(i), dst->get(i));
}
CHECK_EQ(kArraySize, t.Call(*src, *dst));
for (int i = 0; i < kArraySize; i++) {
CHECK_EQ(src_copy->get(i), dst->get(i));
}
}
TEST(RunLoadFieldFromUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
FieldAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // offset
Handle<Name>(), Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t;
Node* load = t.LoadField(access, t.PointerConstant(smis));
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) continue;
for (int j = -5; j <= 5; j++) {
Smi* expected = Smi::FromInt(j);
smis[i] = expected;
CHECK_EQ(expected, t.Call());
}
}
}
TEST(RunStoreFieldToUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) {
FieldAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // offset
Handle<Name>(), Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
Node* p0 = t.Parameter(0);
t.StoreField(access, t.PointerConstant(smis), p0);
t.Return(p0);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) continue;
for (int j = -5; j <= 5; j++) {
Smi* expected = Smi::FromInt(j);
smis[i] = Smi::FromInt(-100);
CHECK_EQ(expected, t.Call(expected));
CHECK_EQ(expected, smis[i]);
}
}
}
TEST(RunLoadElementFromUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
Smi::FromInt(4), Smi::FromInt(5)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) { // for header sizes
for (size_t j = i; j < ARRAY_SIZE(smis); j++) { // for element index
ElementAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // header size
Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t;
Node* load =
t.LoadElement(access, t.PointerConstant(smis), t.Int32Constant(j));
t.Return(load);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) continue;
for (int k = -5; k <= 5; k++) {
Smi* expected = Smi::FromInt(k);
smis[i + j] = expected;
CHECK_EQ(expected, t.Call());
}
}
}
}
TEST(RunStoreElementFromUntaggedBase) {
Smi* smis[] = {Smi::FromInt(1), Smi::FromInt(2), Smi::FromInt(3),
Smi::FromInt(4), Smi::FromInt(5)};
for (size_t i = 0; i < ARRAY_SIZE(smis); i++) { // for header sizes
for (size_t j = i; j < ARRAY_SIZE(smis); j++) { // for element index
ElementAccess access = {kUntaggedBase, // untagged base
i * sizeof(Smi*), // header size
Type::Integral32(), kMachineTagged};
SimplifiedGraphBuilderTester<Object*> t(kMachineTagged);
Node* p0 = t.Parameter(0);
t.StoreElement(access, t.PointerConstant(smis), t.Int32Constant(j), p0);
t.Return(p0);
t.LowerAllNodes();
if (!Pipeline::SupportedTarget()) continue;
for (int k = -5; k <= 5; k++) {
Smi* expected = Smi::FromInt(k);
smis[i + j] = Smi::FromInt(-100);
CHECK_EQ(expected, t.Call(expected));
CHECK_EQ(expected, smis[i + j]);
}
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkEllipsoidInteriorExteriorSpatialFunctionExample.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 "itkEllipsoidInteriorExteriorSpatialFunction.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
#include "itkEllipsoidInteriorExteriorSpatialFunction.h"
#include "itkVTKImageWriter.h"
#include "vnl/vnl_matrix.h"
int main()
{
std::cout << "itkEllipsoidInteriorExteriorSpatialFunction example start" << std::endl;
// This example will create an ellipsoid (3-D) in an image
const unsigned int dimension = 3;
// Image size and spacing parameters
unsigned long xExtent = 50;
unsigned long yExtent = 50;
unsigned long zExtent = 50;
unsigned long sourceImageSize[] = { xExtent, yExtent, zExtent };
double sourceImageSpacing[] = { 1.0,1.0,1.0 };
double sourceImageOrigin[] = { 0,0,0 };
// Calculate image volume
unsigned long imageVolume = xExtent * yExtent * zExtent;
// Image typedef
typedef itk::Image< unsigned char, dimension> TImageType;
// Creates the sourceImage (but doesn't set the size or allocate memory)
TImageType::Pointer sourceImage = TImageType::New();
sourceImage->SetOrigin(sourceImageOrigin);
sourceImage->SetSpacing(sourceImageSpacing);
std::cout << "New physical sourceImage created\n";
//-----The following block allocates the sourceImage-----
// Create a size object native to the sourceImage type
TImageType::SizeType sourceImageSizeObject;
// Set the size object to the array defined earlier
sourceImageSizeObject.SetSize( sourceImageSize );
// Create a region object native to the sourceImage type
TImageType::RegionType largestPossibleRegion;
// Resize the region
largestPossibleRegion.SetSize( sourceImageSizeObject );
// Set the largest legal region size (i.e. the size of the whole sourceImage) to what we just defined
sourceImage->SetLargestPossibleRegion( largestPossibleRegion );
// Set the buffered region
sourceImage->SetBufferedRegion( largestPossibleRegion );
// Set the requested region
sourceImage->SetRequestedRegion( largestPossibleRegion );
// Now allocate memory for the sourceImage
sourceImage->Allocate();
std::cout << "New physical sourceImage allocated\n";
// Initialize the image to hold all 128
itk::ImageRegionIterator<TImageType> it =
itk::ImageRegionIterator<TImageType>(sourceImage, largestPossibleRegion);
int numImagePixels = 0;
unsigned char exteriorPixelValue = 128;
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
it.Set(exteriorPixelValue);
++numImagePixels;
}
//-----Create ellipsoid in sourceImage-----------------
// Ellipsoid spatial function typedef
typedef itk::EllipsoidInteriorExteriorSpatialFunction<double, dimension> TEllipsoidFunctionType;
// Point position typedef
typedef TEllipsoidFunctionType::TPositionType TEllipsoidFunctionVectorType;
// Create an ellipsoid spatial function for the source image
TEllipsoidFunctionType::Pointer spatialFunc = TEllipsoidFunctionType::New();
// Define and set the axes lengths for the ellipsoid
TEllipsoidFunctionVectorType axes;
axes[0] = 40;
axes[1] = 30;
axes[2] = 20;
spatialFunc->SetAxes(axes);
// Define and set the center of the ellipsoid in physical space
TEllipsoidFunctionVectorType center;
center[0] = xExtent/2;
center[1] = yExtent/2;
center[2] = zExtent/2;
spatialFunc->SetCenter(center);
// Define the orientations of the ellipsoid axes
// (0,1,0) corresponds to the axes of length axes[0]
// (1,0,0) corresponds to the axes of length axes[1]
// (0,0,1) corresponds to the axes of lenght axes[2]
double data[] = {0, 1, 0, 1, 0, 0, 0, 0, 1};
vnl_matrix<double> orientations (data, 3, 3);
// Set the orientations of the ellipsoids
spatialFunc->SetOrientations(orientations);
TImageType::IndexType seedPos;
const unsigned long pos[] = {center[0], center[1], center[2]};
seedPos.SetIndex(pos);
itk::FloodFilledSpatialFunctionConditionalIterator<TImageType, TEllipsoidFunctionType>
sfi = itk::FloodFilledSpatialFunctionConditionalIterator<TImageType,
TEllipsoidFunctionType>(sourceImage, spatialFunc, seedPos);
// Iterate through the entire image and set interior pixels to 255
int numInteriorPixels1 = 0;
unsigned char interiorPixelValue = 255;
for(; !sfi.IsAtEnd(); ++sfi)
{
sfi.Set(interiorPixelValue);
++numInteriorPixels1;
}
TImageType::PixelType apixel;
int numExteriorPixels = 0; // Number of pixels not filled by spatial function
int numInteriorPixels2 = 0; // Number of pixels filled by spatial function
int numErrorPixels = 0; // Number of pixels not set by spatial function
unsigned long indexarray[3] = {0,0,0};
// Iterate through source image and get pixel values and count pixels
// iterated through, not filled by spatial function, filled by spatial
// function, and not set by the spatial function.
for(int x = 0; x < xExtent; x++)
{
for(int y = 0; y < yExtent; y++)
{
for(int z = 0; z < zExtent; z++)
{
indexarray[0] = x;
indexarray[1] = y;
indexarray[2] = z;
TImageType::IndexType index;
index.SetIndex(indexarray);
apixel = sourceImage->GetPixel(index);
if(apixel == exteriorPixelValue)
++numExteriorPixels;
else if(apixel == interiorPixelValue)
++numInteriorPixels2;
else if(apixel != interiorPixelValue || apixel != exteriorPixelValue)
++numErrorPixels;
}
}
}
// Check to see that number of pixels within ellipsoid are equal
// for different iteration loops.
int numInteriorPixels = 0;
if(numInteriorPixels1 == numInteriorPixels2)
{
std::cerr << "numInteriorPixels1 != numInteriorPixels2" << std::endl;
return EXIT_FAILURE;
}
else
{
numInteriorPixels = numInteriorPixels1;
}
// Volume of ellipsoid using V=(4/3)*pi*(a/2)*(b/2)*(c/2)
double volume = 4.18879013333*(axes[0]/2)*(axes[1]/2)*(axes[2]/2);
// Percent difference in volume measurement and calculation.
double volumeError = (fabs(volume - numInteriorPixels2)/volume)*100;
// Test the center of the ellipsoid which should be within the sphere
// and return 1.
double testPosition[dimension];
bool functionValue;
testPosition[0] = center[0];
testPosition[1] = center[1];
testPosition[2] = center[2];
functionValue = spatialFunc->Evaluate(testPosition);
// 5% error was randomly chosen as a successful ellipsoid fill.
// This should actually be some function of the image/ellipsoid size.
if(volumeError > 5 || functionValue == 0)
{
std::cerr << std::endl << "calculated ellipsoid volume = " << volume << std::endl
<< "measured ellipsoid volume = " << numInteriorPixels << std::endl
<< "volume error = " << volumeError << "%" << std::endl
<< "function value = " << functionValue << std::endl
<< "itkEllipsoidInteriorExteriorSpatialFunction failed :(" << std::endl;
return EXIT_FAILURE;
}
else if(numImagePixels != (imageVolume))
{
// Make sure that the number of pixels iterated through from source image
// is equal to the pre-defined image size.
std::cerr << "Number of pixels iterated through in sourceimage = "
<< numImagePixels << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << std::endl << "calculated ellipsoid volume = " << volume << std::endl
<< "measured ellipsoid volume = " << numInteriorPixels << std::endl
<< "volume error = " << volumeError << "%" << std::endl
<< "function value = " << functionValue << std::endl
<< "itkEllipsoidInteriorExteriorSpatialFunction ended succesfully!" << std::endl;
// Write the ellipsoid image to a vtk image file
itk::VTKImageWriter< TImageType >::Pointer vtkWriter;
vtkWriter = itk::VTKImageWriter< TImageType >::New();
vtkWriter->SetInput(sourceImage);
vtkWriter->SetFileName("ellipsoid.vtk");
vtkWriter->SetFileTypeToBinary();
vtkWriter->Write();
return EXIT_SUCCESS;
}
}
<commit_msg>ADD: Comments<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkEllipsoidInteriorExteriorSpatialFunctionExample.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 "itkEllipsoidInteriorExteriorSpatialFunction.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkFloodFilledSpatialFunctionConditionalIterator.h"
#include "itkEllipsoidInteriorExteriorSpatialFunction.h"
#include "itkVTKImageWriter.h"
#include "vnl/vnl_matrix.h"
int main()
{
std::cout << "itkEllipsoidInteriorExteriorSpatialFunction example start" << std::endl;
// This example will create an ellipsoid (3-D) in an image
const unsigned int dimension = 3;
// Image size and spacing parameters
unsigned long xExtent = 50;
unsigned long yExtent = 50;
unsigned long zExtent = 50;
unsigned long sourceImageSize[] = { xExtent, yExtent, zExtent };
double sourceImageSpacing[] = { 1.0,1.0,1.0 };
double sourceImageOrigin[] = { 0,0,0 };
// Calculate image volume
unsigned long imageVolume = xExtent * yExtent * zExtent;
// Image typedef
typedef itk::Image< unsigned char, dimension> TImageType;
// Creates the sourceImage (but doesn't set the size or allocate memory)
TImageType::Pointer sourceImage = TImageType::New();
sourceImage->SetOrigin(sourceImageOrigin);
sourceImage->SetSpacing(sourceImageSpacing);
std::cout << "New physical sourceImage created\n";
//-----The following block allocates the sourceImage-----
// Create a size object native to the sourceImage type
TImageType::SizeType sourceImageSizeObject;
// Set the size object to the array defined earlier
sourceImageSizeObject.SetSize( sourceImageSize );
// Create a region object native to the sourceImage type
TImageType::RegionType largestPossibleRegion;
// Resize the region
largestPossibleRegion.SetSize( sourceImageSizeObject );
// Set the largest legal region size (i.e. the size of the whole sourceImage) to what we just defined
sourceImage->SetLargestPossibleRegion( largestPossibleRegion );
// Set the buffered region
sourceImage->SetBufferedRegion( largestPossibleRegion );
// Set the requested region
sourceImage->SetRequestedRegion( largestPossibleRegion );
// Now allocate memory for the sourceImage
sourceImage->Allocate();
std::cout << "New physical sourceImage allocated\n";
// Initialize the image to hold all 128
itk::ImageRegionIterator<TImageType> it =
itk::ImageRegionIterator<TImageType>(sourceImage, largestPossibleRegion);
int numImagePixels = 0;
unsigned char exteriorPixelValue = 128;
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
it.Set(exteriorPixelValue);
++numImagePixels;
}
//-----Create ellipsoid in sourceImage-----------------
// Ellipsoid spatial function typedef
typedef itk::EllipsoidInteriorExteriorSpatialFunction<double, dimension> TEllipsoidFunctionType;
// Point position typedef
typedef TEllipsoidFunctionType::TPositionType TEllipsoidFunctionVectorType;
// Create an ellipsoid spatial function for the source image
TEllipsoidFunctionType::Pointer spatialFunc = TEllipsoidFunctionType::New();
// Define and set the axes lengths for the ellipsoid
TEllipsoidFunctionVectorType axes;
axes[0] = 40;
axes[1] = 30;
axes[2] = 20;
spatialFunc->SetAxes(axes);
// Define and set the center of the ellipsoid in physical space
TEllipsoidFunctionVectorType center;
center[0] = xExtent/2;
center[1] = yExtent/2;
center[2] = zExtent/2;
spatialFunc->SetCenter(center);
// Define the orientations of the ellipsoid axes, vectors must be normalized
// (0,1,0) corresponds to the axes of length axes[0]
// (1,0,0) corresponds to the axes of length axes[1]
// (0,0,1) corresponds to the axes of lenght axes[2]
double data[] = {0, 1, 0, 1, 0, 0, 0, 0, 1};
vnl_matrix<double> orientations (data, 3, 3);
// Set the orientations of the ellipsoids
spatialFunc->SetOrientations(orientations);
TImageType::IndexType seedPos;
const unsigned long pos[] = {center[0], center[1], center[2]};
seedPos.SetIndex(pos);
itk::FloodFilledSpatialFunctionConditionalIterator<TImageType, TEllipsoidFunctionType>
sfi = itk::FloodFilledSpatialFunctionConditionalIterator<TImageType,
TEllipsoidFunctionType>(sourceImage, spatialFunc, seedPos);
// Iterate through the entire image and set interior pixels to 255
int numInteriorPixels1 = 0;
unsigned char interiorPixelValue = 255;
for(; !sfi.IsAtEnd(); ++sfi)
{
sfi.Set(interiorPixelValue);
++numInteriorPixels1;
}
TImageType::PixelType apixel;
int numExteriorPixels = 0; // Number of pixels not filled by spatial function
int numInteriorPixels2 = 0; // Number of pixels filled by spatial function
int numErrorPixels = 0; // Number of pixels not set by spatial function
unsigned long indexarray[3] = {0,0,0};
// Iterate through source image and get pixel values and count pixels
// iterated through, not filled by spatial function, filled by spatial
// function, and not set by the spatial function.
for(int x = 0; x < xExtent; x++)
{
for(int y = 0; y < yExtent; y++)
{
for(int z = 0; z < zExtent; z++)
{
indexarray[0] = x;
indexarray[1] = y;
indexarray[2] = z;
TImageType::IndexType index;
index.SetIndex(indexarray);
apixel = sourceImage->GetPixel(index);
if(apixel == exteriorPixelValue)
++numExteriorPixels;
else if(apixel == interiorPixelValue)
++numInteriorPixels2;
else if(apixel != interiorPixelValue || apixel != exteriorPixelValue)
++numErrorPixels;
}
}
}
// Check to see that number of pixels within ellipsoid are equal
// for different iteration loops.
int numInteriorPixels = 0;
if(numInteriorPixels1 == numInteriorPixels2)
{
std::cerr << "numInteriorPixels1 != numInteriorPixels2" << std::endl;
return EXIT_FAILURE;
}
else
{
numInteriorPixels = numInteriorPixels1;
}
// Volume of ellipsoid using V=(4/3)*pi*(a/2)*(b/2)*(c/2)
double volume = 4.18879013333*(axes[0]/2)*(axes[1]/2)*(axes[2]/2);
// Percent difference in volume measurement and calculation.
double volumeError = (fabs(volume - numInteriorPixels2)/volume)*100;
// Test the center of the ellipsoid which should be within the sphere
// and return 1.
double testPosition[dimension];
bool functionValue;
testPosition[0] = center[0];
testPosition[1] = center[1];
testPosition[2] = center[2];
functionValue = spatialFunc->Evaluate(testPosition);
// 5% error was randomly chosen as a successful ellipsoid fill.
// This should actually be some function of the image/ellipsoid size.
if(volumeError > 5 || functionValue == 0)
{
std::cerr << std::endl << "calculated ellipsoid volume = " << volume << std::endl
<< "measured ellipsoid volume = " << numInteriorPixels << std::endl
<< "volume error = " << volumeError << "%" << std::endl
<< "function value = " << functionValue << std::endl
<< "itkEllipsoidInteriorExteriorSpatialFunction failed :(" << std::endl;
return EXIT_FAILURE;
}
else if(numImagePixels != (imageVolume))
{
// Make sure that the number of pixels iterated through from source image
// is equal to the pre-defined image size.
std::cerr << "Number of pixels iterated through in sourceimage = "
<< numImagePixels << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << std::endl << "calculated ellipsoid volume = " << volume << std::endl
<< "measured ellipsoid volume = " << numInteriorPixels << std::endl
<< "volume error = " << volumeError << "%" << std::endl
<< "function value = " << functionValue << std::endl
<< "itkEllipsoidInteriorExteriorSpatialFunction ended succesfully!" << std::endl;
// Write the ellipsoid image to a vtk image file
itk::VTKImageWriter< TImageType >::Pointer vtkWriter;
vtkWriter = itk::VTKImageWriter< TImageType >::New();
vtkWriter->SetInput(sourceImage);
vtkWriter->SetFileName("ellipsoid.vtk");
vtkWriter->SetFileTypeToBinary();
vtkWriter->Write();
return EXIT_SUCCESS;
}
}
<|endoftext|> |
<commit_before>/**
* @file filelocation_messages_test.cc
* @author Bartek Kryza
* @copyright (C) 2018 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "messages/fuse/fileBlock.h"
#include "messages/fuse/fileLocation.h"
#include <gtest/gtest.h>
using namespace one::messages::fuse;
/**
* The purpose of this test suite is to test the file location message
* and in particular the file blocks map rendering.
*/
struct FuseFileLocationMessagesTest : public ::testing::Test {
};
TEST_F(FuseFileLocationMessagesTest, replicationProgressShouldWork)
{
auto fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.replicationProgress(1024), 0.0);
fileLocation.putBlock(0, 1024, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(1024), 1.0);
}
TEST_F(FuseFileLocationMessagesTest, blocksInRangeCounterShouldWork)
{
auto fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 0);
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(1024, 1500), 0);
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 1);
fileLocation.putBlock(515, 5, FileBlock{"", ""});
fileLocation.putBlock(600, 10, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(256, 530), 2);
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 3);
fileLocation.putBlock(1000, 200, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(515, 650), 2);
EXPECT_EQ(fileLocation.blocksInRange(0, 650), 3);
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 4);
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldAddNewBlocks)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
fileLocationChange.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.updateInRange(40, 70, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(50, 10, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldRemoveNewBlocks)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
oldFileLocation.updateInRange(40, 70, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldReplaceBlocks)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.putBlock(65, 2, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
fileLocationChange.putBlock(40, 25, FileBlock{"", ""});
oldFileLocation.updateInRange(40, 70, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(40, 25, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldIgnoreEmptyChange)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.putBlock(65, 2, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
fileLocationChange.putBlock(40, 25, FileBlock{"", ""});
oldFileLocation.updateInRange(0, 0, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(50, 10, FileBlock{"", ""});
targetFileLocation.putBlock(65, 2, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, linearReadPrefetchThresholdReachedMustWork)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_TRUE(fileLocation.linearReadPrefetchThresholdReached(0.4, 1024));
EXPECT_FALSE(fileLocation.linearReadPrefetchThresholdReached(0.6, 1024));
}
TEST_F(FuseFileLocationMessagesTest, randomReadPrefetchThresholdReachedMustWork)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 50, FileBlock{"", ""});
fileLocation.putBlock(100, 50, FileBlock{"", ""});
fileLocation.putBlock(500, 50, FileBlock{"", ""});
fileLocation.putBlock(600, 50, FileBlock{"", ""});
EXPECT_FALSE(fileLocation.randomReadPrefetchThresholdReached(0.2, 1024));
fileLocation.putBlock(700, 50, FileBlock{"", ""});
fileLocation.putBlock(800, 50, FileBlock{"", ""});
EXPECT_TRUE(fileLocation.randomReadPrefetchThresholdReached(0.2, 1024));
}
TEST_F(FuseFileLocationMessagesTest, emptyFileLocationShouldRenderEmptyProgress)
{
auto fileLocation = FileLocation{};
std::string expected(10, ' ');
EXPECT_EQ(fileLocation.progressString(1024, 10), expected);
EXPECT_EQ(fileLocation.progressString(10, 10), expected);
EXPECT_EQ(fileLocation.progressString(5, 10), expected);
EXPECT_EQ(fileLocation.progressString(1, 10), expected);
EXPECT_EQ(fileLocation.progressString(0, 10), expected);
}
TEST_F(FuseFileLocationMessagesTest,
completeFileLocationShouldRenderCompleteProgress)
{
std::string expected(10, '#');
auto fileLocationLarge = FileLocation{};
fileLocationLarge.putBlock(0, 1024, FileBlock{"", ""});
EXPECT_EQ(fileLocationLarge.progressString(1024, 10), expected);
auto fileLocationEqual = FileLocation{};
fileLocationEqual.putBlock(0, 10, FileBlock{"", ""});
EXPECT_EQ(fileLocationEqual.progressString(10, 10), expected);
auto fileLocationSmall = FileLocation{};
fileLocationSmall.putBlock(0, 2, FileBlock{"", ""});
EXPECT_EQ(fileLocationSmall.progressString(2, 10), expected);
}
TEST_F(FuseFileLocationMessagesTest,
partialFileLocationShouldRenderPartialProgress)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(100, 10), ". ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 511 - 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(1024, 10), "##### ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(1024, 10), "#####. ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 600, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(1024, 10), "#####o ");
fileLocation = FileLocation{};
fileLocation.putBlock(511 - 1, 1024, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(1024, 10), " #####");
fileLocation = FileLocation{};
fileLocation.putBlock(950, 1024, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(1024, 10), " o");
}
TEST_F(FuseFileLocationMessagesTest,
partialFileLocationShouldRenderPartialProgressForSmallFiles)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(15, 10), "..........");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 10, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(15, 10), "oooooooooo");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 15, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(15, 10), "##########");
}
TEST_F(
FuseFileLocationMessagesTest, replicationProgressShouldReportProperValues)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(100), 0.01);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(1024), 0.5);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 100, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(0), 0);
fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.replicationProgress(1024), 0);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 100, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(100), 1.0);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 100, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(50), 1.0);
}
<commit_msg>VFS-4563 Improved FileLocation unit tests<commit_after>/**
* @file filelocation_messages_test.cc
* @author Bartek Kryza
* @copyright (C) 2018 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in
* 'LICENSE.txt'
*/
#include "messages/fuse/fileBlock.h"
#include "messages/fuse/fileLocation.h"
#include <gtest/gtest.h>
using namespace one::messages::fuse;
/**
* The purpose of this test suite is to test the file location message
* and in particular the file blocks map rendering.
*/
struct FuseFileLocationMessagesTest : public ::testing::Test {
};
TEST_F(FuseFileLocationMessagesTest, replicationProgressShouldWork)
{
auto fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.replicationProgress(1024), 0.0);
fileLocation.putBlock(0, 1024, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(1024), 1.0);
}
TEST_F(FuseFileLocationMessagesTest, blocksInRangeCounterShouldWork)
{
auto fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 0);
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(1024, 1500), 0);
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 1);
fileLocation.putBlock(515, 5, FileBlock{"", ""});
fileLocation.putBlock(600, 10, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(256, 530), 2);
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 3);
fileLocation.putBlock(1000, 200, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(515, 650), 2);
EXPECT_EQ(fileLocation.blocksInRange(0, 650), 3);
EXPECT_EQ(fileLocation.blocksInRange(256, 1024), 4);
}
TEST_F(FuseFileLocationMessagesTest, blocksLengthInRangeShouldWork)
{
auto fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.blocksLengthInRange(250, 1000), 0);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 500, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksLengthInRange(0, 1000), 500);
fileLocation.putBlock(500, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksInRange(0, 1000), 1);
EXPECT_EQ(fileLocation.blocksLengthInRange(0, 1000), 501);
EXPECT_EQ(fileLocation.blocksLengthInRange(500, 1000), 1);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 25, FileBlock{"", ""});
fileLocation.putBlock(100, 25, FileBlock{"", ""});
fileLocation.putBlock(200, 25, FileBlock{"", ""});
fileLocation.putBlock(300, 25, FileBlock{"", ""});
EXPECT_EQ(fileLocation.blocksLengthInRange(0, 1000), 100);
EXPECT_EQ(fileLocation.blocksLengthInRange(0, 320), 95);
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldAddNewBlocks)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
fileLocationChange.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.updateInRange(40, 70, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(50, 10, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldRemoveNewBlocks)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
oldFileLocation.updateInRange(40, 70, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldReplaceBlocks)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.putBlock(65, 2, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
fileLocationChange.putBlock(40, 25, FileBlock{"", ""});
oldFileLocation.updateInRange(40, 70, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(40, 25, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, updateInRangeShouldIgnoreEmptyChange)
{
auto oldFileLocation = FileLocation{};
oldFileLocation.putBlock(0, 10, FileBlock{"", ""});
oldFileLocation.putBlock(50, 10, FileBlock{"", ""});
oldFileLocation.putBlock(65, 2, FileBlock{"", ""});
oldFileLocation.putBlock(100, 10, FileBlock{"", ""});
auto fileLocationChange = FileLocation{};
fileLocationChange.putBlock(40, 25, FileBlock{"", ""});
oldFileLocation.updateInRange(0, 0, fileLocationChange);
auto targetFileLocation = FileLocation{};
targetFileLocation.putBlock(0, 10, FileBlock{"", ""});
targetFileLocation.putBlock(50, 10, FileBlock{"", ""});
targetFileLocation.putBlock(65, 2, FileBlock{"", ""});
targetFileLocation.putBlock(100, 10, FileBlock{"", ""});
EXPECT_TRUE(oldFileLocation.blocks() == targetFileLocation.blocks());
EXPECT_EQ(oldFileLocation.toString(), targetFileLocation.toString());
}
TEST_F(FuseFileLocationMessagesTest, linearReadPrefetchThresholdReachedMustWork)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_TRUE(fileLocation.linearReadPrefetchThresholdReached(0.4, 1024));
EXPECT_FALSE(fileLocation.linearReadPrefetchThresholdReached(0.6, 1024));
}
TEST_F(FuseFileLocationMessagesTest, randomReadPrefetchThresholdReachedMustWork)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 50, FileBlock{"", ""});
fileLocation.putBlock(100, 50, FileBlock{"", ""});
fileLocation.putBlock(500, 50, FileBlock{"", ""});
fileLocation.putBlock(600, 50, FileBlock{"", ""});
EXPECT_FALSE(fileLocation.randomReadPrefetchThresholdReached(0.2, 1024));
fileLocation.putBlock(700, 50, FileBlock{"", ""});
fileLocation.putBlock(800, 50, FileBlock{"", ""});
EXPECT_TRUE(fileLocation.randomReadPrefetchThresholdReached(0.2, 1024));
}
TEST_F(FuseFileLocationMessagesTest, emptyFileLocationShouldRenderEmptyProgress)
{
auto fileLocation = FileLocation{};
std::string expected(10, ' ');
EXPECT_EQ(fileLocation.progressString(1024, 10), expected);
EXPECT_EQ(fileLocation.progressString(10, 10), expected);
EXPECT_EQ(fileLocation.progressString(5, 10), expected);
EXPECT_EQ(fileLocation.progressString(1, 10), expected);
EXPECT_EQ(fileLocation.progressString(0, 10), expected);
}
TEST_F(FuseFileLocationMessagesTest,
completeFileLocationShouldRenderCompleteProgress)
{
std::string expected(10, '#');
auto fileLocationLarge = FileLocation{};
fileLocationLarge.putBlock(0, 1024, FileBlock{"", ""});
EXPECT_EQ(fileLocationLarge.progressString(1024, 10), expected);
auto fileLocationEqual = FileLocation{};
fileLocationEqual.putBlock(0, 10, FileBlock{"", ""});
EXPECT_EQ(fileLocationEqual.progressString(10, 10), expected);
auto fileLocationSmall = FileLocation{};
fileLocationSmall.putBlock(0, 2, FileBlock{"", ""});
EXPECT_EQ(fileLocationSmall.progressString(2, 10), expected);
}
TEST_F(FuseFileLocationMessagesTest,
partialFileLocationShouldRenderPartialProgress)
{
auto fileLocation = FileLocation{};
const auto fileSize = 1000;
fileLocation.putBlock(0, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), ". ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, fileSize * 0.1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), "# ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, fileSize * 0.9, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), "######### ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, fileSize / 2, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), "##### ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, fileSize / 2 + 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), "#####. ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, fileSize / 2 - 25, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), "####o ");
fileLocation = FileLocation{};
fileLocation.putBlock(0, fileSize / 2 + 75, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), "#####o ");
fileLocation = FileLocation{};
fileLocation.putBlock(fileSize / 2, fileSize / 2, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), " #####");
fileLocation = FileLocation{};
fileLocation.putBlock(
fileSize * 0.93, fileSize - fileSize * 0.93, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(fileSize, 10), " o");
}
TEST_F(FuseFileLocationMessagesTest,
partialFileLocationShouldRenderPartialProgressForSmallFiles)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(15, 10), "..........");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 10, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(15, 10), "oooooooooo");
fileLocation = FileLocation{};
fileLocation.putBlock(0, 15, FileBlock{"", ""});
EXPECT_EQ(fileLocation.progressString(15, 10), "##########");
}
TEST_F(
FuseFileLocationMessagesTest, replicationProgressShouldReportProperValues)
{
auto fileLocation = FileLocation{};
fileLocation.putBlock(0, 1, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(100), 0.01);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 512, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(1024), 0.5);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 100, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(0), 0);
fileLocation = FileLocation{};
EXPECT_EQ(fileLocation.replicationProgress(1024), 0);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 100, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(100), 1.0);
fileLocation = FileLocation{};
fileLocation.putBlock(0, 100, FileBlock{"", ""});
EXPECT_EQ(fileLocation.replicationProgress(50), 1.0);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QLibraryInfo>
#include <QDir>
#include <QProcess>
#include <QDebug>
class tst_examples : public QObject
{
Q_OBJECT
public:
tst_examples();
private slots:
void examples_data();
void examples();
void namingConvention();
private:
QString qmlviewer;
QStringList excludedDirs;
void namingConvention(const QDir &);
QStringList findQmlFiles(const QDir &);
};
tst_examples::tst_examples()
{
QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath);
#if defined(Q_WS_MAC)
qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.app/Contents/MacOS/qmlviewer");
#elif defined(Q_WS_WIN)
qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.exe");
#else
qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer");
#endif
// Add directories you want excluded here
excludedDirs << "examples/declarative/extending";
}
/*
This tests that the demos and examples follow the naming convention required
to have them tested by the examples() test.
*/
void tst_examples::namingConvention(const QDir &d)
{
for (int ii = 0; ii < excludedDirs.count(); ++ii) {
QString s = QDir::toNativeSeparators(excludedDirs.at(ii));
if (d.absolutePath().endsWith(s))
return;
}
QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
QDir::Files);
bool seenQml = !files.isEmpty();
bool seenLowercase = false;
foreach (const QString &file, files) {
if (file.at(0).isLower())
seenLowercase = true;
}
if (!seenQml) {
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QString &dir, dirs) {
QDir sub = d;
sub.cd(dir);
namingConvention(sub);
}
} else if(!seenLowercase) {
QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__);
}
}
void tst_examples::namingConvention()
{
QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath);
QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath);
namingConvention(QDir(examples));
namingConvention(QDir(demos));
}
QStringList tst_examples::findQmlFiles(const QDir &d)
{
for (int ii = 0; ii < excludedDirs.count(); ++ii) {
QString s = QDir::toNativeSeparators(excludedDirs.at(ii));
if (d.absolutePath().endsWith(s))
return QStringList();
}
QStringList rv;
QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
QDir::Files);
foreach (const QString &file, files) {
if (file.at(0).isLower()) {
rv << d.absoluteFilePath(file);
}
}
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QString &dir, dirs) {
QDir sub = d;
sub.cd(dir);
rv << findQmlFiles(sub);
}
return rv;
}
/*
This test runs all the examples in the declarative UI source tree and ensures
that they start and exit cleanly.
Examples are any .qml files under the examples/ or demos/ directory that start
with a lower case letter.
*/
void tst_examples::examples_data()
{
QTest::addColumn<QString>("file");
QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath);
QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath);
QStringList files;
files << findQmlFiles(QDir(examples));
files << findQmlFiles(QDir(demos));
foreach (const QString &file, files)
QTest::newRow(file.toLatin1().constData()) << file;
}
void tst_examples::examples()
{
QFETCH(QString, file);
QFileInfo fi(file);
QFileInfo dir(fi.path());
QString script = "data/"+dir.baseName()+"/"+fi.baseName();
QFileInfo testdata(script+".qml");
QStringList arguments;
arguments << "-script" << (testdata.exists() ? script : QLatin1String("data/dummytest"))
<< "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure"
<< file;
QProcess p;
p.start(qmlviewer, arguments);
QVERIFY(p.waitForFinished());
QCOMPARE(p.exitStatus(), QProcess::NormalExit);
QCOMPARE(p.exitCode(), 0);
}
QTEST_MAIN(tst_examples)
#include "tst_examples.moc"
<commit_msg>Exclude plugins example in test.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QLibraryInfo>
#include <QDir>
#include <QProcess>
#include <QDebug>
class tst_examples : public QObject
{
Q_OBJECT
public:
tst_examples();
private slots:
void examples_data();
void examples();
void namingConvention();
private:
QString qmlviewer;
QStringList excludedDirs;
void namingConvention(const QDir &);
QStringList findQmlFiles(const QDir &);
};
tst_examples::tst_examples()
{
QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath);
#if defined(Q_WS_MAC)
qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.app/Contents/MacOS/qmlviewer");
#elif defined(Q_WS_WIN)
qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer.exe");
#else
qmlviewer = QDir(binaries).absoluteFilePath("qmlviewer");
#endif
// Add directories you want excluded here
excludedDirs << "examples/declarative/extending";
excludedDirs << "examples/declarative/plugins";
}
/*
This tests that the demos and examples follow the naming convention required
to have them tested by the examples() test.
*/
void tst_examples::namingConvention(const QDir &d)
{
for (int ii = 0; ii < excludedDirs.count(); ++ii) {
QString s = QDir::toNativeSeparators(excludedDirs.at(ii));
if (d.absolutePath().endsWith(s))
return;
}
QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
QDir::Files);
bool seenQml = !files.isEmpty();
bool seenLowercase = false;
foreach (const QString &file, files) {
if (file.at(0).isLower())
seenLowercase = true;
}
if (!seenQml) {
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QString &dir, dirs) {
QDir sub = d;
sub.cd(dir);
namingConvention(sub);
}
} else if(!seenLowercase) {
QTest::qFail(QString("Directory " + d.absolutePath() + " violates naming convention").toLatin1().constData(), __FILE__, __LINE__);
}
}
void tst_examples::namingConvention()
{
QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath);
QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath);
namingConvention(QDir(examples));
namingConvention(QDir(demos));
}
QStringList tst_examples::findQmlFiles(const QDir &d)
{
for (int ii = 0; ii < excludedDirs.count(); ++ii) {
QString s = QDir::toNativeSeparators(excludedDirs.at(ii));
if (d.absolutePath().endsWith(s))
return QStringList();
}
QStringList rv;
QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
QDir::Files);
foreach (const QString &file, files) {
if (file.at(0).isLower()) {
rv << d.absoluteFilePath(file);
}
}
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QString &dir, dirs) {
QDir sub = d;
sub.cd(dir);
rv << findQmlFiles(sub);
}
return rv;
}
/*
This test runs all the examples in the declarative UI source tree and ensures
that they start and exit cleanly.
Examples are any .qml files under the examples/ or demos/ directory that start
with a lower case letter.
*/
void tst_examples::examples_data()
{
QTest::addColumn<QString>("file");
QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath);
QString demos = QLibraryInfo::location(QLibraryInfo::DemosPath);
QStringList files;
files << findQmlFiles(QDir(examples));
files << findQmlFiles(QDir(demos));
foreach (const QString &file, files)
QTest::newRow(file.toLatin1().constData()) << file;
}
void tst_examples::examples()
{
QFETCH(QString, file);
QFileInfo fi(file);
QFileInfo dir(fi.path());
QString script = "data/"+dir.baseName()+"/"+fi.baseName();
QFileInfo testdata(script+".qml");
QStringList arguments;
arguments << "-script" << (testdata.exists() ? script : QLatin1String("data/dummytest"))
<< "-scriptopts" << "play,testerror,exitoncomplete,exitonfailure"
<< file;
QProcess p;
p.start(qmlviewer, arguments);
QVERIFY(p.waitForFinished());
QCOMPARE(p.exitStatus(), QProcess::NormalExit);
QCOMPARE(p.exitCode(), 0);
}
QTEST_MAIN(tst_examples)
#include "tst_examples.moc"
<|endoftext|> |
<commit_before>#include "TestClass.hpp"
static int magic = 0x11223344;
int TestClass::testOutlineFunction()
{
return someData_ * reinterpret_cast<int>(&magic);
}
int TestClass::testOutlineFunctionWithStaticVariable()
{
static int staticVar = -1;
staticVar += testOutlineFunction();
return staticVar;
}
void getTestData1(TestDataArray * d)
{
GET_TEST_DATA_IMPL();
}
<commit_msg>-: Warning fixed<commit_after>#include "TestClass.hpp"
static int magic = 0x11223344;
int TestClass::testOutlineFunction()
{
return someData_ * (int)reinterpret_cast<size_t>(&magic);
}
int TestClass::testOutlineFunctionWithStaticVariable()
{
static int staticVar = -1;
staticVar += testOutlineFunction();
return staticVar;
}
void getTestData1(TestDataArray * d)
{
GET_TEST_DATA_IMPL();
}
<|endoftext|> |
<commit_before>#ifndef PCL_TRACKING_IMPL_COHERENCE_H_
#define PCL_TRACKING_IMPL_COHERENCE_H_
namespace pcl
{
namespace tracking
{
template <typename PointInT> double
PointCoherence<PointInT>::compute (PointInT &source, PointInT &target)
{
return computeCoherence (source, target);
}
template <typename PointInT> double
PointCloudCoherence<PointInT>::calcPointCoherence (PointInT &source, PointInT &target)
{
double val = 1.0;
for (size_t i = 0; i < point_coherences_.size (); i++)\
{
PointCoherencePtr coherence = point_coherences_[i];
val *= coherence->comput (source, target);
}
return val;
}
template <typename PointInT> bool
PointCloudCoherence<PointInT>::initCompute ()
{
if (PCLBase<PointInT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] PCLBase::Init failed.\n", getClassName ().c_str ());
deinitCompute ();
return (false);
}
if (!target_input_ || target_input_->points.empty ())
{
PCL_ERROR ("[pcl::%s::compute] target_input_ is empty!\n", getClassName ().c_str ());
deinitCompute ();
return false;
}
return true;
}
template <typename PointInT> double
PointCloudCoherence<PointInT>::compute ()
{
if (initCompute ())
{
PCL_ERROR ("[pcl::%s::compute] Init failed.\n", getClassName ().c_str ());
return (false);
}
return computeCoherence ();
}
}
}
#endif
<commit_msg>fix typo<commit_after>#ifndef PCL_TRACKING_IMPL_COHERENCE_H_
#define PCL_TRACKING_IMPL_COHERENCE_H_
namespace pcl
{
namespace tracking
{
template <typename PointInT> double
PointCoherence<PointInT>::compute (PointInT &source, PointInT &target)
{
return computeCoherence (source, target);
}
template <typename PointInT> double
PointCloudCoherence<PointInT>::calcPointCoherence (PointInT &source, PointInT &target)
{
double val = 1.0;
for (size_t i = 0; i < point_coherences_.size (); i++)\
{
PointCoherencePtr coherence = point_coherences_[i];
val *= coherence->compute (source, target);
}
return val;
}
template <typename PointInT> bool
PointCloudCoherence<PointInT>::initCompute ()
{
if (PCLBase<PointInT>::initCompute ())
{
PCL_ERROR ("[pcl::%s::initCompute] PCLBase::Init failed.\n", getClassName ().c_str ());
deinitCompute ();
return (false);
}
if (!target_input_ || target_input_->points.empty ())
{
PCL_ERROR ("[pcl::%s::compute] target_input_ is empty!\n", getClassName ().c_str ());
deinitCompute ();
return false;
}
return true;
}
template <typename PointInT> double
PointCloudCoherence<PointInT>::compute ()
{
if (initCompute ())
{
PCL_ERROR ("[pcl::%s::compute] Init failed.\n", getClassName ().c_str ());
return (false);
}
return computeCoherence ();
}
}
}
#endif
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : A.cpp
* Author : Kazune Takahashi
* Created : 2020/6/28 20:51:38
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
void TLE()
{
sleep(10);
}
void RE()
{
assert(false);
}
std::random_device seed_gen;
std::mt19937 engine(seed_gen());
// ----- Solve -----
#if DEBUG == 1
constexpr int D = 5;
#else
constexpr int D = 365;
#endif
constexpr int C = 26;
constexpr int K = 10;
constexpr int M = 5000;
class Solve
{
vector<ll> c;
vector<vector<ll>> s;
vector<int> t;
vector<set<int>> contestDays;
ll totalScore;
public:
Solve() : c(C), s(D, vector<ll>(C, 0)), t(D), contestDays(C), totalScore{0}
{
for (auto i{0}; i < C; ++i)
{
cin >> c[i];
}
for (auto i{0}; i < D; ++i)
{
for (auto j{0}; j < C; ++j)
{
cin >> s[i][j];
}
}
for (auto i{0}; i < C; ++i)
{
contestDays[i].insert(0);
contestDays[i].insert(D + 1);
}
}
void flush()
{
for (auto i{0}; i < D; ++i)
{
t[i] = engine() % C;
}
calc_score();
for (auto i{0}; i < M; ++i)
{
auto pScore{totalScore};
vector<int> d(K), q(K), p(K);
for (auto j{0}; j < K; ++j)
{
d[j] = engine() % D;
q[j] = engine() % C;
p[j] = t[d[j]];
change_score(d[j] + 1, q[j]);
}
auto qScore{totalScore};
#if DEBUG == 1
cerr << "pScore = " << pScore << ", qScore = " << qScore << endl;
#endif
if (pScore > qScore)
{
for (auto j{K - 1}; j >= 0; --j)
{
change_score(d[j] + 1, p[j]);
}
}
}
for (auto e : t)
{
cout << e + 1 << endl;
}
}
private:
ll change_score(int d, int q)
{
int p{t[d - 1]};
if (p == q)
{
return totalScore;
}
ll newScore{totalScore};
t[d - 1] = q;
newScore -= s[d - 1][p];
newScore += s[d - 1][q];
{
auto it{contestDays[p].find(d)};
--it;
auto x{*it};
++it;
++it;
auto y{*it};
auto dif{(y - d) * (d - x)};
newScore -= c[p] * dif;
--it;
contestDays[p].erase(it);
}
{
contestDays[q].insert(d);
auto it{contestDays[q].find(d)};
--it;
auto x{*it};
++it;
++it;
auto y{*it};
auto dif{(y - d) * (d - x)};
newScore += c[q] * dif;
}
return totalScore = newScore;
}
vector<ll> calc_score()
{
vector<ll> ans(D);
vector<vector<int>> last(D + 1, vector<int>(C, 0));
ll now{0};
for (auto d{0}; d < D; ++d)
{
now += s[d][t[d]];
contestDays[t[d]].insert(d + 1);
last[d + 1] = last[d];
last[d + 1][t[d]] = d + 1;
ll penalty{0};
for (auto i{0}; i < C; ++i)
{
penalty += c[i] * (d + 1 - last[d + 1][i]);
}
now -= penalty;
ans[d] = now;
}
totalScore = now;
return ans;
}
};
// ----- main() -----
int main()
{
ll d;
cin >> d;
Solve solve;
solve.flush();
}
<commit_msg>tried A.cpp to 'A'<commit_after>#define DEBUG 1
/**
* File : A.cpp
* Author : Kazune Takahashi
* Created : 2020/6/28 20:51:38
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
bool ch_max(T &left, T right)
{
if (left < right)
{
left = right;
return true;
}
return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
if (left > right)
{
left = right;
return true;
}
return false;
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
void TLE()
{
sleep(10);
}
void RE()
{
assert(false);
}
std::random_device seed_gen;
std::mt19937 engine(seed_gen());
// ----- Solve -----
#if DEBUG == 1
constexpr int D = 5;
#else
constexpr int D = 365;
#endif
constexpr int C = 26;
constexpr int K = 100;
constexpr int M = 5000;
class Solve
{
vector<ll> c;
vector<vector<ll>> s;
vector<int> t;
vector<set<int>> contestDays;
ll totalScore;
public:
Solve() : c(C), s(D, vector<ll>(C, 0)), t(D), contestDays(C), totalScore{0}
{
for (auto i{0}; i < C; ++i)
{
cin >> c[i];
}
for (auto i{0}; i < D; ++i)
{
for (auto j{0}; j < C; ++j)
{
cin >> s[i][j];
}
}
for (auto i{0}; i < C; ++i)
{
contestDays[i].insert(0);
contestDays[i].insert(D + 1);
}
}
void flush()
{
for (auto i{0}; i < D; ++i)
{
t[i] = engine() % C;
}
calc_score();
for (auto i{0}; i < M; ++i)
{
auto pScore{totalScore};
vector<int> d(K), q(K), p(K);
for (auto j{0}; j < K; ++j)
{
d[j] = engine() % D;
q[j] = engine() % C;
p[j] = t[d[j]];
change_score(d[j] + 1, q[j]);
}
auto qScore{totalScore};
#if DEBUG == 1
cerr << "pScore = " << pScore << ", qScore = " << qScore << endl;
#endif
if (pScore > qScore)
{
for (auto j{K - 1}; j >= 0; --j)
{
change_score(d[j] + 1, p[j]);
}
}
}
for (auto e : t)
{
cout << e + 1 << endl;
}
}
private:
ll change_score(int d, int q)
{
int p{t[d - 1]};
if (p == q)
{
return totalScore;
}
ll newScore{totalScore};
t[d - 1] = q;
newScore -= s[d - 1][p];
newScore += s[d - 1][q];
{
auto it{contestDays[p].find(d)};
--it;
auto x{*it};
++it;
++it;
auto y{*it};
auto dif{(y - d) * (d - x)};
newScore -= c[p] * dif;
--it;
contestDays[p].erase(it);
}
{
contestDays[q].insert(d);
auto it{contestDays[q].find(d)};
--it;
auto x{*it};
++it;
++it;
auto y{*it};
auto dif{(y - d) * (d - x)};
newScore += c[q] * dif;
}
return totalScore = newScore;
}
vector<ll> calc_score()
{
vector<ll> ans(D);
vector<vector<int>> last(D + 1, vector<int>(C, 0));
ll now{0};
for (auto d{0}; d < D; ++d)
{
now += s[d][t[d]];
contestDays[t[d]].insert(d + 1);
last[d + 1] = last[d];
last[d + 1][t[d]] = d + 1;
ll penalty{0};
for (auto i{0}; i < C; ++i)
{
penalty += c[i] * (d + 1 - last[d + 1][i]);
}
now -= penalty;
ans[d] = now;
}
totalScore = now;
return ans;
}
};
// ----- main() -----
int main()
{
ll d;
cin >> d;
Solve solve;
solve.flush();
}
<|endoftext|> |
<commit_before>/**-------------------------------------------------------------------------
@file uart_bleintrf.cpp
@brief Implementation of UART BLE Interface object
The interface can be either Nordic NUS or BlueIO UART based
@author Hoang Nguyen Hoan
@date Feb. 18, 2019
@license
Copyright (c) 2019, I-SYST inc., all rights reserved
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "app_util_platform.h"
#include "coredev/uart.h"
#include "bluetooth/blueio_blesrvc.h"
#include "ble_intrf.h"
#include "blueio_board.h"
int BleIntrfEvtCallback(DEVINTRF *pDev, DEVINTRF_EVT EvtId, uint8_t *pBuffer, int BufferLen);
void UartTxSrvcCallback(BLESRVC *pBlueIOSvc, uint8_t *pData, int Offset, int Len);
int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen);
// NUS BLE
static const char s_NUSRxCharDescString[] = {
"NUS Rx characteristic",
};
static const char s_NUSTxCharDescString[] = {
"NUS Tx characteristic",
};
/// Characteristic definitions
static BLESRVC_CHAR s_NUSChars[] = {
{
// Read characteristic
.Uuid = BLE_UUID_NUS_TX_CHARACTERISTIC,
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN,
.Property = BLE_UUID_NUS_TX_CHAR_PROP,
.pDesc = s_NUSTxCharDescString, // char UTF-8 description string
.WrCB = NULL, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0, // Default value length in bytes
},
{
// Write characteristic
.Uuid = BLE_UUID_NUS_RX_CHARACTERISTIC, // char UUID
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN, // char max data length
.Property = BLE_UUID_NUS_RX_CHAR_PROP,// char properties define by BLUEIOSVC_CHAR_PROP_...
.pDesc = s_NUSRxCharDescString, // char UTF-8 description string
.WrCB = UartTxSrvcCallback, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0 // Default value length in bytes
},
};
static const int s_NbNUSChar = sizeof(s_NUSChars) / sizeof(BLESRVC_CHAR);
//uint8_t g_LWrBuffer[512];
/// Service definition
const BLESRVC_CFG s_NUSBleSrvcCfg = {
.SecType = BLESRVC_SECTYPE_NONE, // Secure or Open service/char
.UuidBase = NUS_BASE_UUID, // Base UUID
.UuidSvc = BLE_UUID_NUS_SERVICE, // Service UUID
.NbChar = s_NbNUSChar, // Total number of characteristics for the service
.pCharArray = s_NUSChars, // Pointer a an array of characteristic
.pLongWrBuff = NULL,//g_LWrBuffer, // pointer to user long write buffer
.LongWrBuffSize = 0,//sizeof(g_LWrBuffer), // long write buffer size
};
static BLESRVC s_NUSBleSrvc;
#define NUS_INTRF_CFIFO_MEMSIZE CFIFO_MEMSIZE(10 * BLE_NUSUART_MAX_DATA_LEN)
alignas(4) static uint8_t s_NUSIntrfRxBuff[NUS_INTRF_CFIFO_MEMSIZE];
alignas(4) static uint8_t s_NUSIntrfTxBuff[NUS_INTRF_CFIFO_MEMSIZE];
static BLEINTRF_CFG s_NUSBleIntrfCfg = {
.pBleSrv = &s_NUSBleSrvc,
.RxCharIdx = 1,
.TxCharIdx = 0,
.PacketSize = 0,
.RxFifoMemSize = NUS_INTRF_CFIFO_MEMSIZE,
.pRxFifoMem = s_NUSIntrfRxBuff,
.TxFifoMemSize = NUS_INTRF_CFIFO_MEMSIZE,
.pTxFifoMem = s_NUSIntrfTxBuff,
.EvtCB = BleIntrfEvtCallback
};
static BleIntrf s_NUSBleIntrf;
// -----------------------
// UART BLE
static const char s_RxCharDescString[] = {
"UART Rx characteristic",
};
static const char s_TxCharDescString[] = {
"UART Tx characteristic",
};
/// Characteristic definitions
static BLESRVC_CHAR s_UartChars[] = {
{
// Read characteristic
.Uuid = BLUEIO_UUID_UART_RX_CHAR,
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN,
.Property = BLUEIO_UUID_UART_RX_CHAR_PROP,
.pDesc = s_RxCharDescString, // char UTF-8 description string
.WrCB = NULL, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0, // Default value length in bytes
},
{
// Write characteristic
.Uuid = BLUEIO_UUID_UART_TX_CHAR, // char UUID
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN, // char max data length
.Property = BLUEIO_UUID_UART_TX_CHAR_PROP,// char properties define by BLUEIOSVC_CHAR_PROP_...
.pDesc = s_TxCharDescString, // char UTF-8 description string
.WrCB = UartTxSrvcCallback, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0 // Default value length in bytes
},
};
static const int s_NbUartChar = sizeof(s_UartChars) / sizeof(BLESRVC_CHAR);
//uint8_t g_LWrBuffer[512];
/// Service definition
const BLESRVC_CFG s_UartSrvcCfg = {
.SecType = BLESRVC_SECTYPE_NONE, // Secure or Open service/char
.UuidBase = BLUEIO_UUID_BASE, // Base UUID
.UuidSvc = BLUEIO_UUID_UART_SERVICE, // Service UUID
.NbChar = s_NbUartChar, // Total number of characteristics for the service
.pCharArray = s_UartChars, // Pointer a an array of characteristic
.pLongWrBuff = NULL,//g_LWrBuffer, // pointer to user long write buffer
.LongWrBuffSize = 0,//sizeof(g_LWrBuffer), // long write buffer size
};
static BLESRVC s_UartBleSrvc;
#define BLUEIO_INTRF_CFIFO_MEMSIZE CFIFO_MEMSIZE(10 * BLE_NUSUART_MAX_DATA_LEN)
alignas(4) static uint8_t s_BlueIOIntrfRxBuff[BLUEIO_INTRF_CFIFO_MEMSIZE];
alignas(4) static uint8_t s_BlueIOIntrfTxBuff[BLUEIO_INTRF_CFIFO_MEMSIZE];
static BLEINTRF_CFG s_BlueIOBleIntrfCfg = {
.pBleSrv = &s_UartBleSrvc,
.RxCharIdx = 0,
.TxCharIdx = 1,
.PacketSize = sizeof(BLUEIO_PACKET),
.RxFifoMemSize = BLUEIO_INTRF_CFIFO_MEMSIZE,
.pRxFifoMem = s_BlueIOIntrfRxBuff,
.TxFifoMemSize = BLUEIO_INTRF_CFIFO_MEMSIZE,
.pTxFifoMem = s_BlueIOIntrfTxBuff,
.EvtCB = BleIntrfEvtCallback
};
static BleIntrf s_BlueIOBleIntrf;
/*
static const IOPINCFG s_UartPins[] = {
{BLUEIO_UART_RX_PORT, BLUEIO_UART_RX_PIN, BLUEIO_UART_RX_PINOP, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // RX
{BLUEIO_UART_TX_PORT, BLUEIO_UART_TX_PIN, BLUEIO_UART_TX_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // TX
{-1, -1, -1, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // CTS
{-1, -1, -1, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // RTS
};
static UARTCFG s_UartCfg = {
.DevNo = 0, // Device number zero based
.pIoMap = s_UartPins, // UART assigned pins
.IoMapLen = sizeof(s_UartPins) / sizeof(IOPINCFG), // Total number of UART pins used
.Rate = 1000000, // Baudrate
.DataBits = 8, // Data bits
.Parity = UART_PARITY_NONE, // Parity
.StopBits = 1, // Stop bit
.FlowControl = UART_FLWCTRL_NONE, // Flow control
.bIntMode = true, // Interrupt mode
.IntPrio = APP_IRQ_PRIORITY_LOW, // Interrupt priority
.EvtCallback = nRFUartEvthandler, // UART event handler
.bFifoBlocking = true, // Blocking FIFO
};
static UART s_Uart;
*/
int BleIntrfEvtCallback(DEVINTRF *pDev, DEVINTRF_EVT EvtId, uint8_t *pBuffer, int BufferLen)
{
int cnt = 0;
if (EvtId == DEVINTRF_EVT_RX_DATA)
{
uint8_t buff[128];
int l = s_BlueIOBleIntrf.Rx(0, buff, 128);
/* if (l > 0)
{
s_Uart.Tx(buff, l);
}*/
cnt += l;
}
return cnt;
}
/*
void UartTxSrvcCallback(BLESRVC *pBlueIOSvc, uint8_t *pData, int Offset, int Len)
{
s_Uart.Tx(pData, Len);
}
void UartRxChedHandler(void * p_event_data, uint16_t event_size)
{
uint8_t buff[128];
int l = s_Uart.Rx(buff, 128);
if (l > 0)
{
BleSrvcCharNotify(&g_UartBleSrvc, 0, buff, l);
}
}
bool BlueIOUartSrvcInit(IOPINCFG *pPins, int NbPins, uint32_t Rate)
{
uint32_t err_code;
if (pPins == NULL)
return false;
s_UartCfg.pIoMap = pPins;
s_UartCfg.IoMapLen = NbPins;
s_UartCfg.Rate = Rate;
s_Uart.Init(s_UartCfg);
err_code = BleSrvcInit(&g_UartBleSrvc, &s_UartSrvcCfg);
APP_ERROR_CHECK(err_code);
s_BlueIOBleIntrf.Init(s_BlueIOBleIntrfCfg);
return err_code;
}
int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen)
{
int cnt = 0;
uint8_t buff[20];
switch (EvtId)
{
case UART_EVT_RXTIMEOUT:
case UART_EVT_RXDATA:
//app_sched_event_put(NULL, 0, UartRxChedHandler);
break;
case UART_EVT_TXREADY:
break;
case UART_EVT_LINESTATE:
break;
}
return cnt;
}*/
BleIntrf * const NusBleIntrfInit(DEVINTRF_EVTCB EvtCB)
{
uint32_t err_code = BleSrvcInit(&s_NUSBleSrvc, &s_NUSBleSrvcCfg);
APP_ERROR_CHECK(err_code);
s_NUSBleIntrfCfg.EvtCB = EvtCB;
if (s_NUSBleIntrf.Init(s_NUSBleIntrfCfg))
{
return &s_NUSBleIntrf;
}
return NULL;
}
BleIntrf * const UartBleIntrfInit(DEVINTRF_EVTCB EvtCB)
{
uint32_t err_code = BleSrvcInit(&s_UartBleSrvc, &s_UartSrvcCfg);
APP_ERROR_CHECK(err_code);
s_BlueIOBleIntrfCfg.EvtCB = EvtCB;
if (s_BlueIOBleIntrf.Init(s_BlueIOBleIntrfCfg))
{
return &s_BlueIOBleIntrf;
}
return NULL;
}
<commit_msg>change fifo size<commit_after>/**-------------------------------------------------------------------------
@file uart_bleintrf.cpp
@brief Implementation of UART BLE Interface object
The interface can be either Nordic NUS or BlueIO UART based
@author Hoang Nguyen Hoan
@date Feb. 18, 2019
@license
Copyright (c) 2019, I-SYST inc., all rights reserved
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 "app_util_platform.h"
#include "coredev/uart.h"
#include "bluetooth/blueio_blesrvc.h"
#include "ble_intrf.h"
#include "blueio_board.h"
int BleIntrfEvtCallback(DEVINTRF *pDev, DEVINTRF_EVT EvtId, uint8_t *pBuffer, int BufferLen);
void UartTxSrvcCallback(BLESRVC *pBlueIOSvc, uint8_t *pData, int Offset, int Len);
int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen);
// NUS BLE
static const char s_NUSRxCharDescString[] = {
"NUS Rx characteristic",
};
static const char s_NUSTxCharDescString[] = {
"NUS Tx characteristic",
};
/// Characteristic definitions
static BLESRVC_CHAR s_NUSChars[] = {
{
// Read characteristic
.Uuid = BLE_UUID_NUS_TX_CHARACTERISTIC,
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN,
.Property = BLE_UUID_NUS_TX_CHAR_PROP,
.pDesc = s_NUSTxCharDescString, // char UTF-8 description string
.WrCB = NULL, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0, // Default value length in bytes
},
{
// Write characteristic
.Uuid = BLE_UUID_NUS_RX_CHARACTERISTIC, // char UUID
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN, // char max data length
.Property = BLE_UUID_NUS_RX_CHAR_PROP,// char properties define by BLUEIOSVC_CHAR_PROP_...
.pDesc = s_NUSRxCharDescString, // char UTF-8 description string
.WrCB = UartTxSrvcCallback, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0 // Default value length in bytes
},
};
static const int s_NbNUSChar = sizeof(s_NUSChars) / sizeof(BLESRVC_CHAR);
//uint8_t g_LWrBuffer[512];
/// Service definition
const BLESRVC_CFG s_NUSBleSrvcCfg = {
.SecType = BLESRVC_SECTYPE_NONE, // Secure or Open service/char
.UuidBase = NUS_BASE_UUID, // Base UUID
.UuidSvc = BLE_UUID_NUS_SERVICE, // Service UUID
.NbChar = s_NbNUSChar, // Total number of characteristics for the service
.pCharArray = s_NUSChars, // Pointer a an array of characteristic
.pLongWrBuff = NULL,//g_LWrBuffer, // pointer to user long write buffer
.LongWrBuffSize = 0,//sizeof(g_LWrBuffer), // long write buffer size
};
static BLESRVC s_NUSBleSrvc;
#define NUS_INTRF_CFIFO_MEMSIZE CFIFO_TOTAL_MEMSIZE(20, BLE_NUSUART_MAX_DATA_LEN + sizeof(BLEINTRF_PKT) - 1)
alignas(4) static uint8_t s_NUSIntrfRxBuff[NUS_INTRF_CFIFO_MEMSIZE];
alignas(4) static uint8_t s_NUSIntrfTxBuff[NUS_INTRF_CFIFO_MEMSIZE];
static BLEINTRF_CFG s_NUSBleIntrfCfg = {
.pBleSrv = &s_NUSBleSrvc,
.RxCharIdx = 1,
.TxCharIdx = 0,
.PacketSize = 0,
.RxFifoMemSize = NUS_INTRF_CFIFO_MEMSIZE,
.pRxFifoMem = s_NUSIntrfRxBuff,
.TxFifoMemSize = NUS_INTRF_CFIFO_MEMSIZE,
.pTxFifoMem = s_NUSIntrfTxBuff,
.EvtCB = BleIntrfEvtCallback
};
static BleIntrf s_NUSBleIntrf;
// -----------------------
// UART BLE
static const char s_RxCharDescString[] = {
"UART Rx characteristic",
};
static const char s_TxCharDescString[] = {
"UART Tx characteristic",
};
/// Characteristic definitions
static BLESRVC_CHAR s_UartChars[] = {
{
// Read characteristic
.Uuid = BLUEIO_UUID_UART_RX_CHAR,
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN,
.Property = BLUEIO_UUID_UART_RX_CHAR_PROP,
.pDesc = s_RxCharDescString, // char UTF-8 description string
.WrCB = NULL, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0, // Default value length in bytes
},
{
// Write characteristic
.Uuid = BLUEIO_UUID_UART_TX_CHAR, // char UUID
.MaxDataLen = BLE_NUSUART_MAX_DATA_LEN, // char max data length
.Property = BLUEIO_UUID_UART_TX_CHAR_PROP,// char properties define by BLUEIOSVC_CHAR_PROP_...
.pDesc = s_TxCharDescString, // char UTF-8 description string
.WrCB = UartTxSrvcCallback, // Callback for write char, set to NULL for read char
.SetNotifCB = NULL, // Callback on set notification
.TxCompleteCB = NULL, // Tx completed callback
.pDefValue = NULL, // pointer to char default values
.ValueLen = 0 // Default value length in bytes
},
};
static const int s_NbUartChar = sizeof(s_UartChars) / sizeof(BLESRVC_CHAR);
//uint8_t g_LWrBuffer[512];
/// Service definition
const BLESRVC_CFG s_UartSrvcCfg = {
.SecType = BLESRVC_SECTYPE_NONE, // Secure or Open service/char
.UuidBase = BLUEIO_UUID_BASE, // Base UUID
.UuidSvc = BLUEIO_UUID_UART_SERVICE, // Service UUID
.NbChar = s_NbUartChar, // Total number of characteristics for the service
.pCharArray = s_UartChars, // Pointer a an array of characteristic
.pLongWrBuff = NULL,//g_LWrBuffer, // pointer to user long write buffer
.LongWrBuffSize = 0,//sizeof(g_LWrBuffer), // long write buffer size
};
static BLESRVC s_UartBleSrvc;
#define BLUEIO_INTRF_CFIFO_MEMSIZE CFIFO_TOTAL_MEMSIZE(20, BLE_NUSUART_MAX_DATA_LEN + sizeof(BLEINTRF_PKT) - 1)
alignas(4) static uint8_t s_BlueIOIntrfRxBuff[BLUEIO_INTRF_CFIFO_MEMSIZE];
alignas(4) static uint8_t s_BlueIOIntrfTxBuff[BLUEIO_INTRF_CFIFO_MEMSIZE];
static BLEINTRF_CFG s_BlueIOBleIntrfCfg = {
.pBleSrv = &s_UartBleSrvc,
.RxCharIdx = 0,
.TxCharIdx = 1,
.PacketSize = sizeof(BLUEIO_PACKET),
.RxFifoMemSize = BLUEIO_INTRF_CFIFO_MEMSIZE,
.pRxFifoMem = s_BlueIOIntrfRxBuff,
.TxFifoMemSize = BLUEIO_INTRF_CFIFO_MEMSIZE,
.pTxFifoMem = s_BlueIOIntrfTxBuff,
.EvtCB = BleIntrfEvtCallback
};
static BleIntrf s_BlueIOBleIntrf;
/*
static const IOPINCFG s_UartPins[] = {
{BLUEIO_UART_RX_PORT, BLUEIO_UART_RX_PIN, BLUEIO_UART_RX_PINOP, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // RX
{BLUEIO_UART_TX_PORT, BLUEIO_UART_TX_PIN, BLUEIO_UART_TX_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // TX
{-1, -1, -1, IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // CTS
{-1, -1, -1, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL}, // RTS
};
static UARTCFG s_UartCfg = {
.DevNo = 0, // Device number zero based
.pIoMap = s_UartPins, // UART assigned pins
.IoMapLen = sizeof(s_UartPins) / sizeof(IOPINCFG), // Total number of UART pins used
.Rate = 1000000, // Baudrate
.DataBits = 8, // Data bits
.Parity = UART_PARITY_NONE, // Parity
.StopBits = 1, // Stop bit
.FlowControl = UART_FLWCTRL_NONE, // Flow control
.bIntMode = true, // Interrupt mode
.IntPrio = APP_IRQ_PRIORITY_LOW, // Interrupt priority
.EvtCallback = nRFUartEvthandler, // UART event handler
.bFifoBlocking = true, // Blocking FIFO
};
static UART s_Uart;
*/
int BleIntrfEvtCallback(DEVINTRF *pDev, DEVINTRF_EVT EvtId, uint8_t *pBuffer, int BufferLen)
{
int cnt = 0;
if (EvtId == DEVINTRF_EVT_RX_DATA)
{
uint8_t buff[128];
int l = s_BlueIOBleIntrf.Rx(0, buff, 128);
/* if (l > 0)
{
s_Uart.Tx(buff, l);
}*/
cnt += l;
}
return cnt;
}
/*
void UartTxSrvcCallback(BLESRVC *pBlueIOSvc, uint8_t *pData, int Offset, int Len)
{
s_Uart.Tx(pData, Len);
}
void UartRxChedHandler(void * p_event_data, uint16_t event_size)
{
uint8_t buff[128];
int l = s_Uart.Rx(buff, 128);
if (l > 0)
{
BleSrvcCharNotify(&g_UartBleSrvc, 0, buff, l);
}
}
bool BlueIOUartSrvcInit(IOPINCFG *pPins, int NbPins, uint32_t Rate)
{
uint32_t err_code;
if (pPins == NULL)
return false;
s_UartCfg.pIoMap = pPins;
s_UartCfg.IoMapLen = NbPins;
s_UartCfg.Rate = Rate;
s_Uart.Init(s_UartCfg);
err_code = BleSrvcInit(&g_UartBleSrvc, &s_UartSrvcCfg);
APP_ERROR_CHECK(err_code);
s_BlueIOBleIntrf.Init(s_BlueIOBleIntrfCfg);
return err_code;
}
int nRFUartEvthandler(UARTDEV *pDev, UART_EVT EvtId, uint8_t *pBuffer, int BufferLen)
{
int cnt = 0;
uint8_t buff[20];
switch (EvtId)
{
case UART_EVT_RXTIMEOUT:
case UART_EVT_RXDATA:
//app_sched_event_put(NULL, 0, UartRxChedHandler);
break;
case UART_EVT_TXREADY:
break;
case UART_EVT_LINESTATE:
break;
}
return cnt;
}*/
BleIntrf * const NusBleIntrfInit(DEVINTRF_EVTCB EvtCB)
{
uint32_t err_code = BleSrvcInit(&s_NUSBleSrvc, &s_NUSBleSrvcCfg);
APP_ERROR_CHECK(err_code);
s_NUSBleIntrfCfg.EvtCB = EvtCB;
if (s_NUSBleIntrf.Init(s_NUSBleIntrfCfg))
{
return &s_NUSBleIntrf;
}
return NULL;
}
BleIntrf * const UartBleIntrfInit(DEVINTRF_EVTCB EvtCB)
{
uint32_t err_code = BleSrvcInit(&s_UartBleSrvc, &s_UartSrvcCfg);
APP_ERROR_CHECK(err_code);
s_BlueIOBleIntrfCfg.EvtCB = EvtCB;
if (s_BlueIOBleIntrf.Init(s_BlueIOBleIntrfCfg))
{
return &s_BlueIOBleIntrf;
}
return NULL;
}
<|endoftext|> |
<commit_before>//==- UninitializedValues.cpp - Find Unintialized Values --------*- C++ --*-==//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements Uninitialized Values analysis for source-level CFGs.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/UninitializedValues.h"
#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
#include "clang/Analysis/LocalCheckers.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/ASTContext.h"
#include "clang/Analysis/FlowSensitive/DataflowSolver.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// Dataflow initialization logic.
//===----------------------------------------------------------------------===//
namespace {
class RegisterDecls : public CFGRecStmtDeclVisitor<RegisterDecls> {
UninitializedValues::AnalysisDataTy& AD;
public:
RegisterDecls(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {}
void VisitBlockVarDecl(BlockVarDecl* VD) { AD.Register(VD); }
CFG& getCFG() { return AD.getCFG(); }
};
} // end anonymous namespace
void UninitializedValues::InitializeValues(const CFG& cfg) {
RegisterDecls R(getAnalysisData());
cfg.VisitBlockStmts(R);
}
//===----------------------------------------------------------------------===//
// Transfer functions.
//===----------------------------------------------------------------------===//
namespace {
class TransferFuncs : public CFGStmtVisitor<TransferFuncs,bool> {
UninitializedValues::ValTy V;
UninitializedValues::AnalysisDataTy& AD;
public:
TransferFuncs(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {
V.resetValues(AD);
}
UninitializedValues::ValTy& getVal() { return V; }
CFG& getCFG() { return AD.getCFG(); }
bool VisitDeclRefExpr(DeclRefExpr* DR);
bool VisitBinaryOperator(BinaryOperator* B);
bool VisitUnaryOperator(UnaryOperator* U);
bool VisitStmt(Stmt* S);
bool VisitCallExpr(CallExpr* C);
bool VisitDeclStmt(DeclStmt* D);
bool VisitConditionalOperator(ConditionalOperator* C);
bool Visit(Stmt *S);
bool BlockStmt_VisitExpr(Expr* E);
BlockVarDecl* FindBlockVarDecl(Stmt* S);
};
static const bool Initialized = true;
static const bool Uninitialized = false;
bool TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {
if (BlockVarDecl* VD = dyn_cast<BlockVarDecl>(DR->getDecl())) {
if (AD.Observer) AD.Observer->ObserveDeclRefExpr(V,AD,DR,VD);
// Pseudo-hack to prevent cascade of warnings. If an accessed variable
// is uninitialized, then we are already going to flag a warning for
// this variable, which a "source" of uninitialized values.
// We can otherwise do a full "taint" of uninitialized values. The
// client has both options by toggling AD.FullUninitTaint.
return AD.FullUninitTaint ? V(VD,AD) : Initialized;
}
else return Initialized;
}
BlockVarDecl* TransferFuncs::FindBlockVarDecl(Stmt *S) {
for (;;)
if (ParenExpr* P = dyn_cast<ParenExpr>(S)) {
S = P->getSubExpr(); continue;
}
else if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(S)) {
if (BlockVarDecl* VD = dyn_cast<BlockVarDecl>(DR->getDecl()))
return VD;
else
return NULL;
}
else return NULL;
}
bool TransferFuncs::VisitBinaryOperator(BinaryOperator* B) {
if (BlockVarDecl* VD = FindBlockVarDecl(B->getLHS()))
if (B->isAssignmentOp()) {
if (B->getOpcode() == BinaryOperator::Assign)
return V(VD,AD) = Visit(B->getRHS());
else // Handle +=, -=, *=, etc. We do want '&', not '&&'.
return V(VD,AD) = Visit(B->getLHS()) & Visit(B->getRHS());
}
return VisitStmt(B);
}
bool TransferFuncs::VisitDeclStmt(DeclStmt* S) {
for (ScopedDecl* D = S->getDecl(); D != NULL; D = D->getNextDeclarator())
if (BlockVarDecl* VD = dyn_cast<BlockVarDecl>(D)) {
if (Stmt* I = VD->getInit())
V(VD,AD) = AD.FullUninitTaint ? V(cast<Expr>(I),AD) : Initialized;
else V(VD,AD) = Uninitialized;
}
return Uninitialized; // Value is never consumed.
}
bool TransferFuncs::VisitCallExpr(CallExpr* C) {
VisitChildren(C);
return Initialized;
}
bool TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {
switch (U->getOpcode()) {
case UnaryOperator::AddrOf:
if (BlockVarDecl* VD = FindBlockVarDecl(U->getSubExpr()))
return V(VD,AD) = Initialized;
break;
case UnaryOperator::SizeOf:
return Initialized;
default:
break;
}
return Visit(U->getSubExpr());
}
bool TransferFuncs::VisitConditionalOperator(ConditionalOperator* C) {
Visit(C->getCond());
bool rhsResult = Visit(C->getRHS());
// Handle the GNU extension for missing LHS.
if (Expr *lhs = C->getLHS())
return Visit(lhs) & rhsResult; // Yes: we want &, not &&.
else
return rhsResult;
}
bool TransferFuncs::VisitStmt(Stmt* S) {
bool x = Initialized;
// We don't stop at the first subexpression that is Uninitialized because
// evaluating some subexpressions may result in propogating "Uninitialized"
// or "Initialized" to variables referenced in the other subexpressions.
for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
if (*I && Visit(*I) == Uninitialized) x = Uninitialized;
return x;
}
bool TransferFuncs::Visit(Stmt *S) {
if (AD.isTracked(static_cast<Expr*>(S))) return V(static_cast<Expr*>(S),AD);
else return static_cast<CFGStmtVisitor<TransferFuncs,bool>*>(this)->Visit(S);
}
bool TransferFuncs::BlockStmt_VisitExpr(Expr* E) {
assert (AD.isTracked(E));
return V(E,AD) =
static_cast<CFGStmtVisitor<TransferFuncs,bool>*>(this)->Visit(E);
}
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Merge operator.
//
// In our transfer functions we take the approach that any
// combination of unintialized values, e.g. Unitialized + ___ = Unitialized.
//
// Merges take the opposite approach.
//
// In the merge of dataflow values we prefer unsoundness, and
// prefer false negatives to false positives. At merges, if a value for a
// tracked Decl is EVER initialized in any of the predecessors we treat it as
// initialized at the confluence point.
//===----------------------------------------------------------------------===//
namespace {
typedef ExprDeclBitVector_Types::Union Merge;
typedef DataflowSolver<UninitializedValues,TransferFuncs,Merge> Solver;
}
//===----------------------------------------------------------------------===//
// Unitialized values checker. Scan an AST and flag variable uses
//===----------------------------------------------------------------------===//
UninitializedValues_ValueTypes::ObserverTy::~ObserverTy() {}
namespace {
class UninitializedValuesChecker : public UninitializedValues::ObserverTy {
ASTContext &Ctx;
Diagnostic &Diags;
llvm::SmallPtrSet<BlockVarDecl*,10> AlreadyWarned;
public:
UninitializedValuesChecker(ASTContext &ctx, Diagnostic &diags)
: Ctx(ctx), Diags(diags) {}
virtual void ObserveDeclRefExpr(UninitializedValues::ValTy& V,
UninitializedValues::AnalysisDataTy& AD,
DeclRefExpr* DR, BlockVarDecl* VD) {
assert ( AD.isTracked(VD) && "Unknown VarDecl.");
if (V(VD,AD) == Uninitialized)
if (AlreadyWarned.insert(VD))
Diags.Report(Ctx.getFullLoc(DR->getSourceRange().getBegin()),
diag::warn_uninit_val);
}
};
} // end anonymous namespace
namespace clang {
void CheckUninitializedValues(CFG& cfg, ASTContext &Ctx, Diagnostic &Diags,
bool FullUninitTaint) {
// Compute the unitialized values information.
UninitializedValues U(cfg);
U.getAnalysisData().FullUninitTaint = FullUninitTaint;
Solver S(U);
S.runOnCFG(cfg);
// Scan for DeclRefExprs that use uninitialized values.
UninitializedValuesChecker Observer(Ctx,Diags);
U.getAnalysisData().Observer = &Observer;
S.runOnAllBlocks(cfg);
}
} // end namespace clang
<commit_msg>For uninitialized values analysis, added special treatment for declarations of array types. For things like:<commit_after>//==- UninitializedValues.cpp - Find Unintialized Values --------*- C++ --*-==//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Ted Kremenek and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements Uninitialized Values analysis for source-level CFGs.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/UninitializedValues.h"
#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
#include "clang/Analysis/LocalCheckers.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/ASTContext.h"
#include "clang/Analysis/FlowSensitive/DataflowSolver.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// Dataflow initialization logic.
//===----------------------------------------------------------------------===//
namespace {
class RegisterDecls : public CFGRecStmtDeclVisitor<RegisterDecls> {
UninitializedValues::AnalysisDataTy& AD;
public:
RegisterDecls(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {}
void VisitBlockVarDecl(BlockVarDecl* VD) { AD.Register(VD); }
CFG& getCFG() { return AD.getCFG(); }
};
} // end anonymous namespace
void UninitializedValues::InitializeValues(const CFG& cfg) {
RegisterDecls R(getAnalysisData());
cfg.VisitBlockStmts(R);
}
//===----------------------------------------------------------------------===//
// Transfer functions.
//===----------------------------------------------------------------------===//
namespace {
class TransferFuncs : public CFGStmtVisitor<TransferFuncs,bool> {
UninitializedValues::ValTy V;
UninitializedValues::AnalysisDataTy& AD;
public:
TransferFuncs(UninitializedValues::AnalysisDataTy& ad) : AD(ad) {
V.resetValues(AD);
}
UninitializedValues::ValTy& getVal() { return V; }
CFG& getCFG() { return AD.getCFG(); }
bool VisitDeclRefExpr(DeclRefExpr* DR);
bool VisitBinaryOperator(BinaryOperator* B);
bool VisitUnaryOperator(UnaryOperator* U);
bool VisitStmt(Stmt* S);
bool VisitCallExpr(CallExpr* C);
bool VisitDeclStmt(DeclStmt* D);
bool VisitConditionalOperator(ConditionalOperator* C);
bool Visit(Stmt *S);
bool BlockStmt_VisitExpr(Expr* E);
BlockVarDecl* FindBlockVarDecl(Stmt* S);
};
static const bool Initialized = true;
static const bool Uninitialized = false;
bool TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {
if (BlockVarDecl* VD = dyn_cast<BlockVarDecl>(DR->getDecl())) {
if (AD.Observer) AD.Observer->ObserveDeclRefExpr(V,AD,DR,VD);
// Pseudo-hack to prevent cascade of warnings. If an accessed variable
// is uninitialized, then we are already going to flag a warning for
// this variable, which a "source" of uninitialized values.
// We can otherwise do a full "taint" of uninitialized values. The
// client has both options by toggling AD.FullUninitTaint.
return AD.FullUninitTaint ? V(VD,AD) : Initialized;
}
else return Initialized;
}
BlockVarDecl* TransferFuncs::FindBlockVarDecl(Stmt *S) {
for (;;)
if (ParenExpr* P = dyn_cast<ParenExpr>(S)) {
S = P->getSubExpr(); continue;
}
else if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(S)) {
if (BlockVarDecl* VD = dyn_cast<BlockVarDecl>(DR->getDecl()))
return VD;
else
return NULL;
}
else return NULL;
}
bool TransferFuncs::VisitBinaryOperator(BinaryOperator* B) {
if (BlockVarDecl* VD = FindBlockVarDecl(B->getLHS()))
if (B->isAssignmentOp()) {
if (B->getOpcode() == BinaryOperator::Assign)
return V(VD,AD) = Visit(B->getRHS());
else // Handle +=, -=, *=, etc. We do want '&', not '&&'.
return V(VD,AD) = Visit(B->getLHS()) & Visit(B->getRHS());
}
return VisitStmt(B);
}
bool TransferFuncs::VisitDeclStmt(DeclStmt* S) {
for (ScopedDecl* D = S->getDecl(); D != NULL; D = D->getNextDeclarator())
if (BlockVarDecl* VD = dyn_cast<BlockVarDecl>(D)) {
if (Stmt* I = VD->getInit())
V(VD,AD) = AD.FullUninitTaint ? V(cast<Expr>(I),AD) : Initialized;
else {
// Special case for declarations of array types. For things like:
//
// char x[10];
//
// we should treat "x" as being initialized, because the variable
// "x" really refers to the memory block. Clearly x[1] is
// uninitialized, but expressions like "(char *) x" really do refer to
// an initialized value. This simple dataflow analysis does not reason
// about the contents of arrays, although it could be potentially
// extended to do so if the array were of constant size.
if (VD->getType()->isArrayType())
V(VD,AD) = Initialized;
else
V(VD,AD) = Uninitialized;
}
}
return Uninitialized; // Value is never consumed.
}
bool TransferFuncs::VisitCallExpr(CallExpr* C) {
VisitChildren(C);
return Initialized;
}
bool TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {
switch (U->getOpcode()) {
case UnaryOperator::AddrOf:
if (BlockVarDecl* VD = FindBlockVarDecl(U->getSubExpr()))
return V(VD,AD) = Initialized;
break;
case UnaryOperator::SizeOf:
return Initialized;
default:
break;
}
return Visit(U->getSubExpr());
}
bool TransferFuncs::VisitConditionalOperator(ConditionalOperator* C) {
Visit(C->getCond());
bool rhsResult = Visit(C->getRHS());
// Handle the GNU extension for missing LHS.
if (Expr *lhs = C->getLHS())
return Visit(lhs) & rhsResult; // Yes: we want &, not &&.
else
return rhsResult;
}
bool TransferFuncs::VisitStmt(Stmt* S) {
bool x = Initialized;
// We don't stop at the first subexpression that is Uninitialized because
// evaluating some subexpressions may result in propogating "Uninitialized"
// or "Initialized" to variables referenced in the other subexpressions.
for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I)
if (*I && Visit(*I) == Uninitialized) x = Uninitialized;
return x;
}
bool TransferFuncs::Visit(Stmt *S) {
if (AD.isTracked(static_cast<Expr*>(S))) return V(static_cast<Expr*>(S),AD);
else return static_cast<CFGStmtVisitor<TransferFuncs,bool>*>(this)->Visit(S);
}
bool TransferFuncs::BlockStmt_VisitExpr(Expr* E) {
assert (AD.isTracked(E));
return V(E,AD) =
static_cast<CFGStmtVisitor<TransferFuncs,bool>*>(this)->Visit(E);
}
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Merge operator.
//
// In our transfer functions we take the approach that any
// combination of unintialized values, e.g. Unitialized + ___ = Unitialized.
//
// Merges take the opposite approach.
//
// In the merge of dataflow values we prefer unsoundness, and
// prefer false negatives to false positives. At merges, if a value for a
// tracked Decl is EVER initialized in any of the predecessors we treat it as
// initialized at the confluence point.
//===----------------------------------------------------------------------===//
namespace {
typedef ExprDeclBitVector_Types::Union Merge;
typedef DataflowSolver<UninitializedValues,TransferFuncs,Merge> Solver;
}
//===----------------------------------------------------------------------===//
// Unitialized values checker. Scan an AST and flag variable uses
//===----------------------------------------------------------------------===//
UninitializedValues_ValueTypes::ObserverTy::~ObserverTy() {}
namespace {
class UninitializedValuesChecker : public UninitializedValues::ObserverTy {
ASTContext &Ctx;
Diagnostic &Diags;
llvm::SmallPtrSet<BlockVarDecl*,10> AlreadyWarned;
public:
UninitializedValuesChecker(ASTContext &ctx, Diagnostic &diags)
: Ctx(ctx), Diags(diags) {}
virtual void ObserveDeclRefExpr(UninitializedValues::ValTy& V,
UninitializedValues::AnalysisDataTy& AD,
DeclRefExpr* DR, BlockVarDecl* VD) {
assert ( AD.isTracked(VD) && "Unknown VarDecl.");
if (V(VD,AD) == Uninitialized)
if (AlreadyWarned.insert(VD))
Diags.Report(Ctx.getFullLoc(DR->getSourceRange().getBegin()),
diag::warn_uninit_val);
}
};
} // end anonymous namespace
namespace clang {
void CheckUninitializedValues(CFG& cfg, ASTContext &Ctx, Diagnostic &Diags,
bool FullUninitTaint) {
// Compute the unitialized values information.
UninitializedValues U(cfg);
U.getAnalysisData().FullUninitTaint = FullUninitTaint;
Solver S(U);
S.runOnCFG(cfg);
// Scan for DeclRefExprs that use uninitialized values.
UninitializedValuesChecker Observer(Ctx,Diags);
U.getAnalysisData().Observer = &Observer;
S.runOnAllBlocks(cfg);
}
} // end namespace clang
<|endoftext|> |
<commit_before>#include <boost/lexical_cast.hpp>
#include <gtest/gtest.h>
#include <ostream>
#include "pqrs/string.hpp"
TEST(pqrs_string, string_from_file) {
std::string actual;
int error = 0;
error = pqrs::string::string_from_file(actual, "data/sample");
EXPECT_EQ("{{AAA}} {{BBB}} {{ CCC }}\n", actual);
EXPECT_EQ(0, error);
error = pqrs::string::string_from_file(actual, "data/noexists");
EXPECT_EQ("", actual);
EXPECT_EQ(-1, error);
}
TEST(pqrs_string, string_by_replacing_double_curly_braces_from_file) {
pqrs::string::replacement replacement;
replacement["AAA"] = "1";
replacement["BBB"] = "2222";
replacement["CCC"] = "";
std::string replacement_warnings;
std::string actual;
int error = 0;
error = pqrs::string::string_by_replacing_double_curly_braces_from_file(actual, replacement_warnings, "data/sample", replacement);
EXPECT_EQ("1 2222 \n", actual);
EXPECT_TRUE(replacement_warnings.empty());
EXPECT_EQ(0, error);
error = pqrs::string::string_by_replacing_double_curly_braces_from_file(actual, replacement_warnings, "data/noexists", replacement);
EXPECT_EQ("", actual);
EXPECT_TRUE(replacement_warnings.empty());
EXPECT_EQ(-1, error);
// performance test
{
for (int i = 0; i < 1000; ++i) {
std::string key = std::string("TARGET") + boost::lexical_cast<std::string>(i);
replacement[key] = "REPLACEMENT";
}
const char* filepath = "data/large";
pqrs::string::string_by_replacing_double_curly_braces_from_file(actual, replacement_warnings, filepath, replacement);
}
}
TEST(pqrs_string, string_by_replacing_double_curly_braces_from_string) {
pqrs::string::replacement replacement;
replacement["AAA"] = "1";
replacement["BBB"] = "2222";
replacement["CCC"] = "";
replacement["DDD"] = "44444444444444444444";
replacement["LOOP1"] = "{{ LOOP1 }}";
replacement["LOOP2"] = " {{ LOOP2 }} ";
std::string replacement_warnings;
std::string actual;
// no replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "abc", replacement);
EXPECT_EQ("abc", actual);
EXPECT_TRUE(replacement_warnings.empty());
// normal replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{AAA}} {{BBB}} !{{ CCC }}!{{ DDD }}", replacement);
EXPECT_EQ("1 2222 !!44444444444444444444", actual);
EXPECT_TRUE(replacement_warnings.empty());
// unknown replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{UNKNOWN}}", replacement);
EXPECT_EQ("", actual);
EXPECT_EQ("Warning - \"UNKNOWN\" is not found in replacement.\n", replacement_warnings);
replacement_warnings.clear();
// "} }" is not end.
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{AAA} } BBB}} XXX", replacement);
EXPECT_EQ(" XXX", actual);
EXPECT_EQ("Warning - \"AAA} } BBB\" is not found in replacement.\n", replacement_warnings);
replacement_warnings.clear();
// no }}
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "AAA {{AAA}", replacement);
EXPECT_EQ("AAA ", actual);
EXPECT_TRUE(replacement_warnings.empty());
// no }}
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{ AAA }", replacement);
EXPECT_EQ("", actual);
EXPECT_TRUE(replacement_warnings.empty());
// looped replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{ LOOP1 }}{{ LOOP2 }}", replacement);
EXPECT_EQ("{{ LOOP1 }} {{ LOOP2 }} ", actual);
EXPECT_TRUE(replacement_warnings.empty());
}
TEST(pqrs_string, to_uint32_t) {
boost::optional<uint32_t> actual;
actual = pqrs::string::to_uint32_t("123456");
EXPECT_TRUE(static_cast<bool>(actual));
EXPECT_EQ(static_cast<uint32_t>(123456), *actual);
actual = pqrs::string::to_uint32_t("0");
EXPECT_TRUE(static_cast<bool>(actual));
EXPECT_EQ(static_cast<uint32_t>(0), *actual);
// oct
actual = pqrs::string::to_uint32_t("0100");
EXPECT_TRUE(static_cast<bool>(actual));
EXPECT_EQ(static_cast<uint32_t>(64), *actual);
// hex
actual = pqrs::string::to_uint32_t("0x123456");
EXPECT_TRUE(static_cast<bool>(actual));
EXPECT_EQ(static_cast<uint32_t>(1193046), *actual);
actual = pqrs::string::to_uint32_t("");
EXPECT_FALSE(static_cast<bool>(actual));
actual = pqrs::string::to_uint32_t("0xG");
EXPECT_FALSE(static_cast<bool>(actual));
actual = pqrs::string::to_uint32_t("abc");
EXPECT_FALSE(static_cast<bool>(actual));
// boost::optional<std::string>
actual = pqrs::string::to_uint32_t(boost::none);
EXPECT_FALSE(static_cast<bool>(actual));
actual = pqrs::string::to_uint32_t(boost::optional<std::string>("123"));
EXPECT_EQ(static_cast<uint32_t>(123), *actual);
}
TEST(pqrs_string, tokenizer) {
{
std::string string = "A,B,,C";
pqrs::string::tokenizer tokenizer(string, ',');
std::string actual;
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("A", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("B", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("C", actual);
EXPECT_FALSE(tokenizer.split_removing_empty(actual));
}
{
std::string string = ",";
pqrs::string::tokenizer tokenizer(string, ',');
std::string actual;
EXPECT_FALSE(tokenizer.split_removing_empty(actual));
}
{
std::string string = ",,,A,B,,C,D, , E E ,,";
pqrs::string::tokenizer tokenizer(string, ',');
std::string actual;
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("A", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("B", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("C", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ("D", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ(" ", actual);
EXPECT_TRUE(tokenizer.split_removing_empty(actual));
EXPECT_EQ(" E E ", actual);
EXPECT_FALSE(tokenizer.split_removing_empty(actual));
}
}
TEST(pqrs_string, remove_whitespaces) {
std::string actual = " A B C \r\n \t D ";
pqrs::string::remove_whitespaces(actual);
EXPECT_EQ("ABCD", actual);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>use catch<commit_after>#define CATCH_CONFIG_MAIN
#include "../../include/catch.hpp"
#include <boost/lexical_cast.hpp>
#include <ostream>
#include "pqrs/string.hpp"
TEST_CASE("string_from_file", "[pqrs_string]") {
std::string actual;
int error = 0;
error = pqrs::string::string_from_file(actual, "data/sample");
REQUIRE(actual == "{{AAA}} {{BBB}} {{ CCC }}\n");
REQUIRE(error == 0);
error = pqrs::string::string_from_file(actual, "data/noexists");
REQUIRE(actual == "");
REQUIRE(error == -1);
}
TEST_CASE("string_by_replacing_double_curly_braces_from_file", "[pqrs_string]") {
pqrs::string::replacement replacement;
replacement["AAA"] = "1";
replacement["BBB"] = "2222";
replacement["CCC"] = "";
std::string replacement_warnings;
std::string actual;
int error = 0;
error = pqrs::string::string_by_replacing_double_curly_braces_from_file(actual, replacement_warnings, "data/sample", replacement);
REQUIRE(actual == "1 2222 \n");
REQUIRE(replacement_warnings.empty() == true);
REQUIRE(error == 0);
error = pqrs::string::string_by_replacing_double_curly_braces_from_file(actual, replacement_warnings, "data/noexists", replacement);
REQUIRE(actual == "");
REQUIRE(replacement_warnings.empty() == true);
REQUIRE(error == -1);
// performance test
{
for (int i = 0; i < 1000; ++i) {
std::string key = std::string("TARGET") + boost::lexical_cast<std::string>(i);
replacement[key] = "REPLACEMENT";
}
const char* filepath = "data/large";
pqrs::string::string_by_replacing_double_curly_braces_from_file(actual, replacement_warnings, filepath, replacement);
}
}
TEST_CASE("string_by_replacing_double_curly_braces_from_string", "[pqrs_string]") {
pqrs::string::replacement replacement;
replacement["AAA"] = "1";
replacement["BBB"] = "2222";
replacement["CCC"] = "";
replacement["DDD"] = "44444444444444444444";
replacement["LOOP1"] = "{{ LOOP1 }}";
replacement["LOOP2"] = " {{ LOOP2 }} ";
std::string replacement_warnings;
std::string actual;
// no replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "abc", replacement);
REQUIRE(actual == "abc");
REQUIRE(replacement_warnings.empty() == true);
// normal replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{AAA}} {{BBB}} !{{ CCC }}!{{ DDD }}", replacement);
REQUIRE(actual == "1 2222 !!44444444444444444444");
REQUIRE(replacement_warnings.empty() == true);
// unknown replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{UNKNOWN}}", replacement);
REQUIRE(actual == "");
REQUIRE(replacement_warnings == "Warning - \"UNKNOWN\" is not found in replacement.\n");
replacement_warnings.clear();
// "} }" is not end.
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{AAA} } BBB}} XXX", replacement);
REQUIRE(actual == " XXX");
REQUIRE(replacement_warnings == "Warning - \"AAA} } BBB\" is not found in replacement.\n");
replacement_warnings.clear();
// no }}
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "AAA {{AAA}", replacement);
REQUIRE(actual == "AAA ");
REQUIRE(replacement_warnings.empty() == true);
// no }}
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{ AAA }", replacement);
REQUIRE(actual == "");
REQUIRE(replacement_warnings.empty() == true);
// looped replacing
pqrs::string::string_by_replacing_double_curly_braces_from_string(actual, replacement_warnings, "{{ LOOP1 }}{{ LOOP2 }}", replacement);
REQUIRE(actual == "{{ LOOP1 }} {{ LOOP2 }} ");
REQUIRE(replacement_warnings.empty() == true);
}
TEST_CASE("to_uint32_t", "[pqrs_string]") {
boost::optional<uint32_t> actual;
actual = pqrs::string::to_uint32_t("123456");
REQUIRE(static_cast<bool>(actual) == true);
REQUIRE(*actual == static_cast<uint32_t>(123456));
actual = pqrs::string::to_uint32_t("0");
REQUIRE(static_cast<bool>(actual) == true);
REQUIRE(*actual == static_cast<uint32_t>(0));
// oct
actual = pqrs::string::to_uint32_t("0100");
REQUIRE(static_cast<bool>(actual) == true);
REQUIRE(*actual == static_cast<uint32_t>(64));
// hex
actual = pqrs::string::to_uint32_t("0x123456");
REQUIRE(static_cast<bool>(actual) == true);
REQUIRE(*actual == static_cast<uint32_t>(1193046));
actual = pqrs::string::to_uint32_t("");
REQUIRE(static_cast<bool>(actual) == false);
actual = pqrs::string::to_uint32_t("0xG");
REQUIRE(static_cast<bool>(actual) == false);
actual = pqrs::string::to_uint32_t("abc");
REQUIRE(static_cast<bool>(actual) == false);
// boost::optional<std::string>
actual = pqrs::string::to_uint32_t(boost::none);
REQUIRE(static_cast<bool>(actual) == false);
actual = pqrs::string::to_uint32_t(boost::optional<std::string>("123"));
REQUIRE(*actual == static_cast<uint32_t>(123));
}
TEST_CASE("tokenizer", "[pqrs_string]") {
{
std::string string = "A,B,,C";
pqrs::string::tokenizer tokenizer(string, ',');
std::string actual;
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "A");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "B");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "C");
REQUIRE(tokenizer.split_removing_empty(actual) == false);
}
{
std::string string = ",";
pqrs::string::tokenizer tokenizer(string, ',');
std::string actual;
REQUIRE(tokenizer.split_removing_empty(actual) == false);
}
{
std::string string = ",,,A,B,,C,D, , E E ,,";
pqrs::string::tokenizer tokenizer(string, ',');
std::string actual;
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "A");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "B");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "C");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == "D");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == " ");
REQUIRE(tokenizer.split_removing_empty(actual) == true);
REQUIRE(actual == " E E ");
REQUIRE(tokenizer.split_removing_empty(actual) == false);
}
}
TEST_CASE("remove_whitespaces", "[pqrs_string]") {
std::string actual = " A B C \r\n \t D ";
pqrs::string::remove_whitespaces(actual);
REQUIRE(actual == "ABCD");
}
<|endoftext|> |
<commit_before>// SkipList: A STL-map like container using skip-list
// Copyright (c) 2015 Guo Xiao <guoxiao08@gmail.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <vector>
#include <assert.h>
#include <cstdlib>
#include <stdexcept>
#ifndef NDEBUG
#include <iostream>
#endif
namespace guoxiao {
namespace skiplist {
template <typename KeyType, typename ValueType>
struct SkipNode {
KeyType key;
ValueType value;
size_t level;
std::vector<SkipNode *> next;
SkipNode() : level(0), next(1) {}
SkipNode(SkipNode &&rhs) : level(rhs.level), next(std::move(rhs.next)) {}
SkipNode(const SkipNode &) = delete;
SkipNode &operator=(const SkipNode &) = delete;
};
template <typename T>
class Iterator {
public:
Iterator() : ptr(nullptr){};
Iterator(T *begin) : ptr(begin){};
Iterator operator=(T *begin) {
ptr = begin;
return *this;
}
Iterator &operator++() {
*this = Iterator(ptr->next[0]);
return *this;
}
bool operator!=(const Iterator &rhs) const { return ptr != rhs.ptr; }
bool operator==(const Iterator &rhs) const { return ptr == rhs.ptr; }
bool operator==(const T *p) const { return ptr == p; }
bool operator!=(const T *p) const { return ptr != p; }
operator bool() { return ptr != nullptr; }
operator T *() { return ptr; }
T *operator->() { return ptr; }
T &operator*() { return *ptr; }
private:
T *ptr;
};
template <typename Key, typename T>
class SkipList {
public:
typedef Key key_type;
typedef T mapped_type;
typedef std::pair<Key, T> value_type;
typedef SkipNode<Key, T> node_type;
typedef Iterator<node_type> iterator;
typedef Iterator<node_type> const_iterator;
SkipList() : size_(0), level_(0), head_(new node_type()) {}
~SkipList() {
iterator node = head_, temp;
while (node) {
temp = node;
node = node->next[0];
delete temp;
}
}
// Move Ctor
SkipList(SkipList &&s) noexcept : size_(s.size_),
level_(s.level_),
head_(s.head_) {
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
}
// Copy Ctor
SkipList(const SkipList &s)
: size_(s.size_), level_(s.level_), head_(new node_type()) {
iterator snode = s.head_, node = head_;
std::vector<iterator> last(level_ + 1);
head_->level = level_;
head_->next.resize(level_ + 1);
for (int i = level_; i >= 0; i--) {
last[i] = head_;
}
snode = snode->next[0];
while (snode) {
node = new node_type();
node->key = snode->key;
node->value = snode->value;
node->level = snode->level;
node->next.resize(snode->next.size());
for (int i = snode->level; i >= 0; i--) {
last[i]->next[i] = node;
last[i] = node;
}
snode = snode->next[0];
}
}
// Copy Assignment
SkipList &operator=(const SkipList &s) {
if (this == &s)
return *this;
SkipList tmp(s);
return *this = std::move(tmp);
}
// Move Assignment
SkipList &operator=(SkipList &&s) noexcept {
this->~SkipList();
size_ = s.size_;
level_ = s.level_;
head_ = s.head_;
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
return *this;
}
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
size_t level() const { return level_; }
iterator begin() noexcept { return head_; }
const_iterator begin() const noexcept { return head_; }
const_iterator cbegin() noexcept { return head_; }
const_iterator cend() const noexcept { return nullptr; }
iterator end() noexcept { return nullptr; }
const_iterator end() const noexcept { return nullptr; }
template <typename K, typename V>
iterator emplace(K &&key, V &&value) {
iterator node = head_;
std::vector<iterator> update(level_ + 1 + 1);
for (int i = level_; i >= 0; i--) {
assert(static_cast<int>(node->level) >= i);
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
update[i] = node;
if (node->next[i] && node->next[i]->key == key) {
throw std::runtime_error("conflict");
}
}
node_type *n = new node_type();
n->key = std::forward<K>(key);
n->value = std::forward<V>(value);
size_t level = getRandomLevel();
if (level > level_) {
level = level_ + 1;
head_->next.resize(level + 1);
head_->level = level;
update[level] = head_;
level_ = level;
}
n->next.resize(level + 1);
n->level = level;
for (int i = level; i >= 0; i--) {
if (update[i]) {
n->next[i] = update[i]->next[i];
update[i]->next[i] = n;
}
}
++size_;
return n;
}
iterator insert(const value_type &value) {
return emplace(value.first, value.second);
}
iterator insert(value_type &&value) {
return emplace(std::move(value.first), std::move(value.second));
}
iterator find(const key_type &key) const {
iterator node = head_;
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
return node->next[i];
}
}
return end();
}
void erase(const key_type &key) {
iterator node = head_;
std::vector<iterator> update(level_ + 1);
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
update[i] = node;
}
}
node = node->next[0];
if (node == end()) {
throw std::out_of_range("skiplist::erase");
}
assert(node->key == key);
for (int i = level_; i >= 0; i--) {
if (update[i]) {
assert(node == iterator(update[i]->next[i]));
update[i]->next[i] = node->next[i];
}
}
delete node;
--size_;
if (level_ > 0 && head_->next[level_] == end()) {
level_--;
head_->level = level_;
head_->next.resize(level_ + 1);
}
}
void erase(iterator it) {
erase(it->key);
}
mapped_type &operator[](const key_type &key) {
iterator node = find(key);
if (node == end()) {
mapped_type value;
node = emplace(key, value);
}
return node->value;
}
mapped_type &at(const key_type &key) {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
const mapped_type &at(const key_type &key) const {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
#ifndef NDEBUG
void dump() const {
std::cout << "====== level: " << level_ << " size: " << size_ << std::endl;
for (int i = level_; i >= 0; i--) {
std::cout << "====== level " << i << std::endl;
auto node = head_;
while (node->next[i]) {
std::cout << node->next[i]->key << " : " << node->next[i]->value
<< std::endl;
node = node->next[i];
}
}
}
#endif
private:
size_t size_;
size_t level_;
iterator head_;
static size_t getRandomLevel() {
size_t level = 0;
while (rand() % 2) {
++level;
}
return level;
}
};
} // namespace skiplist
} // namespace guoxiao
<commit_msg>Explicit convert pointer to iterator<commit_after>// SkipList: A STL-map like container using skip-list
// Copyright (c) 2015 Guo Xiao <guoxiao08@gmail.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <vector>
#include <assert.h>
#include <cstdlib>
#include <stdexcept>
#ifndef NDEBUG
#include <iostream>
#endif
namespace guoxiao {
namespace skiplist {
template <typename KeyType, typename ValueType>
struct SkipNode {
KeyType key;
ValueType value;
size_t level;
std::vector<SkipNode *> next;
SkipNode() : level(0), next(1) {}
SkipNode(SkipNode &&rhs) : level(rhs.level), next(std::move(rhs.next)) {}
SkipNode(const SkipNode &) = delete;
SkipNode &operator=(const SkipNode &) = delete;
};
template <typename T>
class Iterator {
public:
Iterator() : ptr(nullptr){};
explicit Iterator(T *begin) : ptr(begin){};
Iterator operator=(T *begin) {
ptr = begin;
return *this;
}
Iterator &operator++() {
*this = Iterator(ptr->next[0]);
return *this;
}
bool operator!=(const Iterator &rhs) const { return ptr != rhs.ptr; }
bool operator==(const Iterator &rhs) const { return ptr == rhs.ptr; }
bool operator==(const T *p) const { return ptr == p; }
bool operator!=(const T *p) const { return ptr != p; }
operator bool() { return ptr != nullptr; }
operator T *() { return ptr; }
T *operator->() { return ptr; }
T &operator*() { return *ptr; }
private:
T *ptr;
};
template <typename Key, typename T>
class SkipList {
public:
typedef Key key_type;
typedef T mapped_type;
typedef std::pair<Key, T> value_type;
typedef SkipNode<Key, T> node_type;
typedef Iterator<node_type> iterator;
typedef Iterator<node_type> const_iterator;
SkipList() : size_(0), level_(0), head_(new node_type()) {}
~SkipList() {
iterator node = head_, temp;
while (node) {
temp = node;
node = node->next[0];
delete temp;
}
}
// Move Ctor
SkipList(SkipList &&s) noexcept : size_(s.size_),
level_(s.level_),
head_(s.head_) {
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
}
// Copy Ctor
SkipList(const SkipList &s)
: size_(s.size_), level_(s.level_), head_(new node_type()) {
iterator snode = s.head_, node = head_;
std::vector<iterator> last(level_ + 1);
head_->level = level_;
head_->next.resize(level_ + 1);
for (int i = level_; i >= 0; i--) {
last[i] = head_;
}
snode = snode->next[0];
while (snode) {
node = new node_type();
node->key = snode->key;
node->value = snode->value;
node->level = snode->level;
node->next.resize(snode->next.size());
for (int i = snode->level; i >= 0; i--) {
last[i]->next[i] = node;
last[i] = node;
}
snode = snode->next[0];
}
}
// Copy Assignment
SkipList &operator=(const SkipList &s) {
if (this == &s)
return *this;
SkipList tmp(s);
return *this = std::move(tmp);
}
// Move Assignment
SkipList &operator=(SkipList &&s) noexcept {
this->~SkipList();
size_ = s.size_;
level_ = s.level_;
head_ = s.head_;
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
return *this;
}
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
size_t level() const { return level_; }
iterator begin() noexcept { return head_; }
const_iterator begin() const noexcept { return head_; }
const_iterator cbegin() noexcept { return head_; }
const_iterator cend() const noexcept { return iterator(); }
iterator end() noexcept { return iterator(); }
const_iterator end() const noexcept { return iterator(); }
template <typename K, typename V>
iterator emplace(K &&key, V &&value) {
iterator node = head_;
std::vector<iterator> update(level_ + 1 + 1);
for (int i = level_; i >= 0; i--) {
assert(static_cast<int>(node->level) >= i);
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
update[i] = node;
if (node->next[i] && node->next[i]->key == key) {
throw std::runtime_error("conflict");
}
}
node_type *n = new node_type();
n->key = std::forward<K>(key);
n->value = std::forward<V>(value);
size_t level = getRandomLevel();
if (level > level_) {
level = level_ + 1;
head_->next.resize(level + 1);
head_->level = level;
update[level] = head_;
level_ = level;
}
n->next.resize(level + 1);
n->level = level;
for (int i = level; i >= 0; i--) {
if (update[i]) {
n->next[i] = update[i]->next[i];
update[i]->next[i] = n;
}
}
++size_;
return iterator(n);
}
iterator insert(const value_type &value) {
return emplace(value.first, value.second);
}
iterator insert(value_type &&value) {
return emplace(std::move(value.first), std::move(value.second));
}
iterator find(const key_type &key) const {
iterator node = head_;
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
return iterator(node->next[i]);
}
}
return end();
}
void erase(const key_type &key) {
iterator node = head_;
std::vector<iterator> update(level_ + 1);
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
update[i] = node;
}
}
node = node->next[0];
if (node == end()) {
throw std::out_of_range("skiplist::erase");
}
assert(node->key == key);
for (int i = level_; i >= 0; i--) {
if (update[i]) {
assert(node == iterator(update[i]->next[i]));
update[i]->next[i] = node->next[i];
}
}
delete node;
--size_;
if (level_ > 0 && head_->next[level_] == end()) {
level_--;
head_->level = level_;
head_->next.resize(level_ + 1);
}
}
void erase(iterator it) {
erase(it->key);
}
mapped_type &operator[](const key_type &key) {
iterator node = find(key);
if (node == end()) {
mapped_type value;
node = emplace(key, value);
}
return node->value;
}
mapped_type &at(const key_type &key) {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
const mapped_type &at(const key_type &key) const {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
#ifndef NDEBUG
void dump() const {
std::cout << "====== level: " << level_ << " size: " << size_ << std::endl;
for (int i = level_; i >= 0; i--) {
std::cout << "====== level " << i << std::endl;
auto node = head_;
while (node->next[i]) {
std::cout << node->next[i]->key << " : " << node->next[i]->value
<< std::endl;
node = node->next[i];
}
}
}
#endif
private:
size_t size_;
size_t level_;
iterator head_;
static size_t getRandomLevel() {
size_t level = 0;
while (rand() % 2) {
++level;
}
return level;
}
};
} // namespace skiplist
} // namespace guoxiao
<|endoftext|> |
<commit_before>#include "onair/okui/FileTexture.h"
#include <gsl.h>
#include <png.h>
#include <turbojpeg.h>
namespace onair {
namespace okui {
namespace {
constexpr bool IsPowerOfTwo(int x) {
return (x != 0) && !(x & (x - 1));
}
constexpr int NextPowerOfTwo(int x) {
if (x < 0) {
return 0;
}
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
struct PNGInput {
PNGInput(const void* data, size_t length) : data(data), length(length) {}
const void* data;
size_t length;
size_t position = 0;
};
void PNGRead(png_structp png, png_bytep data, png_size_t length) {
PNGInput* input = reinterpret_cast<PNGInput*>(png_get_io_ptr(png));
if (length > input->length - input->position) {
png_error(png, "read error (not enough data)");
} else {
memcpy(data, reinterpret_cast<const char*>(input->data) + input->position, length);
input->position += length;
}
}
void PNGError(png_structp png, png_const_charp message) {
longjmp(png_jmpbuf(png), 1);
}
void PNGWarning(png_structp png, png_const_charp message) { /* nop */ }
}
void FileTexture::setData(std::shared_ptr<const std::string> data, const char* name) {
_data = data;
_cacheEntry = nullptr;
if (_readPNGMetadata()) {
_type = Type::kPNG;
} else if (_readJPEGMetadata()) {
_type = Type::kJPEG;
} else {
SCRAPS_LOG_ERROR("unknown file type {}", name ? name : "");
_type = Type::kUnknown;
_data = nullptr;
}
}
GLuint FileTexture::load(opengl::TextureCache* textureCache) {
switch (_type) {
case Type::kPNG:
return _loadPNG(textureCache);
case Type::kJPEG:
return _loadJPEG(textureCache);
default:
return 0;
}
}
bool FileTexture::_readPNGMetadata() {
PNGInput input(_data->data(), _data->size());
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, PNGError, PNGWarning);
png_infop info = png_create_info_struct(png);
auto _ = gsl::finally([&]{ png_destroy_read_struct(&png, &info, nullptr); });
if (setjmp(png_jmpbuf(png))) {
return false;
}
png_set_read_fn(png, &input, &PNGRead);
png_read_info(png, info);
_width = png_get_image_width(png, info);
_height = png_get_image_height(png, info);
return true;
}
bool FileTexture::_readJPEGMetadata() {
auto decompressor = tjInitDecompress();
auto _ = gsl::finally([&]{ tjDestroy(decompressor); });
int width{0}, height{0}, jpegSubsamp{0}, jpegColorspace{0};
if (!tjDecompressHeader3(decompressor, reinterpret_cast<const unsigned char*>(_data->data()), _data->size(), &width, &height, &jpegSubsamp, &jpegColorspace)) {
_width = width;
_height = height;
return true;
}
return false;
}
GLuint FileTexture::_loadPNG(opengl::TextureCache* textureCache) {
PNGInput input(_data->data(), _data->size());
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, PNGError, PNGWarning);
png_infop info = png_create_info_struct(png);
auto _ = gsl::finally([&]{ png_destroy_read_struct(&png, &info, nullptr); });
if (setjmp(png_jmpbuf(png))) {
SCRAPS_LOGF_ERROR("error reading png data");
return 0;
}
png_set_read_fn(png, &input, &PNGRead);
png_read_info(png, info);
auto colorType = png_get_color_type(png, info);
auto glFormat =
#if GL_RED && GL_RG
colorType == PNG_COLOR_TYPE_GRAY ? GL_RED :
colorType == PNG_COLOR_TYPE_GRAY_ALPHA ? GL_RG :
#else
colorType == PNG_COLOR_TYPE_GRAY ? GL_LUMINANCE :
colorType == PNG_COLOR_TYPE_GRAY_ALPHA ? GL_LUMINANCE_ALPHA :
#endif
colorType == PNG_COLOR_TYPE_RGB ? GL_RGB :
colorType == PNG_COLOR_TYPE_RGB_ALPHA ? GL_RGBA :
0;
if (!glFormat) {
SCRAPS_LOGF_ERROR("unsupported color type (%d)", static_cast<int>(colorType));
return 0;
}
int bytesPerRow = png_get_rowbytes(png, info);
int bitDepth = png_get_bit_depth(png, info);
if (bitDepth != 8 && bitDepth != 16) {
SCRAPS_LOGF_ERROR("unsupported bit depth");
return 0;
}
const auto components = ((colorType & PNG_COLOR_MASK_COLOR) ? 3 : 1) + ((colorType & PNG_COLOR_MASK_ALPHA) ? 1 : 0);
if (bytesPerRow != components * (bitDepth >> 3) * _width) {
assert(false);
SCRAPS_LOGF_ERROR("unknown error");
return 0;
}
#if OPENGL_ES
if (bitDepth == 16) {
// opengl es doesn't do 16-bit textures
bitDepth = 8;
png_set_strip_16(png);
}
#endif
if (bitDepth > 8) {
// libpng stores pixels as big endian. we need them in native endianness for opengl
union {
uint32_t i;
char c[4];
} u = {0x01020304};
if (u.c[0] != 1) {
// we're not big endian. swap
png_set_swap(png);
}
}
#if OPENGL_ES
// make powers of 2 so we can use mipmaps
_allocatedWidth = NextPowerOfTwo(_width);
_allocatedHeight = NextPowerOfTwo(_height);
#else
_allocatedWidth = _width;
_allocatedHeight = _height;
#endif
bytesPerRow = components * (bitDepth >> 3) * _allocatedWidth;
// align rows to 4-byte boundaries
if (bytesPerRow % 4) {
bytesPerRow += 4 - (bytesPerRow % 4);
}
std::vector<png_byte> image;
image.resize(bytesPerRow * _allocatedHeight);
std::vector<png_byte*> rowPointers;
for (int i = 0; i < _allocatedHeight; ++i) {
rowPointers.emplace_back(image.data() + i * bytesPerRow);
}
png_read_image(png, rowPointers.data());
// image now contains our raw bytes. send it to the gpu
auto texture = _generateTexture(glFormat, glFormat, bitDepth == 8 ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT, image.data());
#if GL_RED && GL_RG
if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
if (colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_GREEN);
}
}
#endif
SCRAPS_GL_ERROR_CHECK();
_cacheEntry = textureCache->add(texture, texture);
return _cacheEntry->id;
}
GLuint FileTexture::_loadJPEG(opengl::TextureCache* textureCache) {
auto decompressor = tjInitDecompress();
auto _ = gsl::finally([&]{ tjDestroy(decompressor); });
int width{0}, height{0}, jpegSubsamp{0}, jpegColorspace{0};
if (tjDecompressHeader3(decompressor, reinterpret_cast<const unsigned char*>(_data->data()), _data->size(), &width, &height, &jpegSubsamp, &jpegColorspace)) {
SCRAPS_LOG_ERROR("error reading jpeg header: {}", tjGetErrorStr());
return 0;
}
#if OPENGL_ES
// make powers of 2 so we can use mipmaps
_allocatedWidth = NextPowerOfTwo(width);
_allocatedHeight = NextPowerOfTwo(height);
#else
_allocatedWidth = _width;
_allocatedHeight = _height;
#endif
auto pixelFormat = jpegColorspace == TJCS_GRAY ? TJPF_GRAY : TJPF_RGB;
auto bytesPerRow = TJPAD(_allocatedWidth * tjPixelSize[pixelFormat]);
std::vector<uint8_t> image;
image.resize(bytesPerRow * _allocatedHeight);
if (tjDecompress2(decompressor, reinterpret_cast<const unsigned char*>(_data->data()), _data->size(), image.data(), width, bytesPerRow, height, pixelFormat, 0)) {
SCRAPS_LOG_ERROR("error decompressing jpeg: {}", tjGetErrorStr());
return 0;
}
// image now contains our raw bytes. send it to the gpu
#if GL_RED && GL_RG
auto glFormat = jpegColorspace == TJCS_GRAY ? GL_RED : GL_RGB;
#else
auto glFormat = jpegColorspace == TJCS_GRAY ? GL_LUMINANCE : GL_RGB;
#endif
auto texture = _generateTexture(glFormat, glFormat, GL_UNSIGNED_BYTE, image.data());
#if GL_RED && GL_RG
if (jpegColorspace == TJCS_GRAY) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
}
#endif
SCRAPS_GL_ERROR_CHECK();
_cacheEntry = textureCache->add(texture, texture);
return _cacheEntry->id;
}
GLuint FileTexture::_generateTexture(GLint internalformat, GLenum format, GLenum type, const GLvoid* data) {
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexImage2D(GL_TEXTURE_2D, 0, internalformat, _allocatedWidth, _allocatedHeight, 0, format, type, data);
#if OPENGL_ES
bool useMipmaps = IsPowerOfTwo(_allocatedWidth) && IsPowerOfTwo(_allocatedHeight);
#else
constexpr bool useMipmaps = true;
#endif
if (useMipmaps) {
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
} else {
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
glTexParameterf(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);
return texture;
}
}}
<commit_msg>Fix unused warning for OPENGL_ES-only functions<commit_after>#include "onair/okui/FileTexture.h"
#include <gsl.h>
#include <png.h>
#include <turbojpeg.h>
namespace onair {
namespace okui {
namespace {
#if OPENGL_ES
constexpr bool IsPowerOfTwo(int x) {
return (x != 0) && !(x & (x - 1));
}
constexpr int NextPowerOfTwo(int x) {
if (x < 0) {
return 0;
}
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
#endif // OPENGL_ES
struct PNGInput {
PNGInput(const void* data, size_t length) : data(data), length(length) {}
const void* data;
size_t length;
size_t position = 0;
};
void PNGRead(png_structp png, png_bytep data, png_size_t length) {
PNGInput* input = reinterpret_cast<PNGInput*>(png_get_io_ptr(png));
if (length > input->length - input->position) {
png_error(png, "read error (not enough data)");
} else {
memcpy(data, reinterpret_cast<const char*>(input->data) + input->position, length);
input->position += length;
}
}
void PNGError(png_structp png, png_const_charp message) {
longjmp(png_jmpbuf(png), 1);
}
void PNGWarning(png_structp png, png_const_charp message) { /* nop */ }
} // anonymous namespace
void FileTexture::setData(std::shared_ptr<const std::string> data, const char* name) {
_data = data;
_cacheEntry = nullptr;
if (_readPNGMetadata()) {
_type = Type::kPNG;
} else if (_readJPEGMetadata()) {
_type = Type::kJPEG;
} else {
SCRAPS_LOG_ERROR("unknown file type {}", name ? name : "");
_type = Type::kUnknown;
_data = nullptr;
}
}
GLuint FileTexture::load(opengl::TextureCache* textureCache) {
switch (_type) {
case Type::kPNG:
return _loadPNG(textureCache);
case Type::kJPEG:
return _loadJPEG(textureCache);
default:
return 0;
}
}
bool FileTexture::_readPNGMetadata() {
PNGInput input(_data->data(), _data->size());
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, PNGError, PNGWarning);
png_infop info = png_create_info_struct(png);
auto _ = gsl::finally([&]{ png_destroy_read_struct(&png, &info, nullptr); });
if (setjmp(png_jmpbuf(png))) {
return false;
}
png_set_read_fn(png, &input, &PNGRead);
png_read_info(png, info);
_width = png_get_image_width(png, info);
_height = png_get_image_height(png, info);
return true;
}
bool FileTexture::_readJPEGMetadata() {
auto decompressor = tjInitDecompress();
auto _ = gsl::finally([&]{ tjDestroy(decompressor); });
int width{0}, height{0}, jpegSubsamp{0}, jpegColorspace{0};
if (!tjDecompressHeader3(decompressor, reinterpret_cast<const unsigned char*>(_data->data()), _data->size(), &width, &height, &jpegSubsamp, &jpegColorspace)) {
_width = width;
_height = height;
return true;
}
return false;
}
GLuint FileTexture::_loadPNG(opengl::TextureCache* textureCache) {
PNGInput input(_data->data(), _data->size());
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, PNGError, PNGWarning);
png_infop info = png_create_info_struct(png);
auto _ = gsl::finally([&]{ png_destroy_read_struct(&png, &info, nullptr); });
if (setjmp(png_jmpbuf(png))) {
SCRAPS_LOGF_ERROR("error reading png data");
return 0;
}
png_set_read_fn(png, &input, &PNGRead);
png_read_info(png, info);
auto colorType = png_get_color_type(png, info);
auto glFormat =
#if GL_RED && GL_RG
colorType == PNG_COLOR_TYPE_GRAY ? GL_RED :
colorType == PNG_COLOR_TYPE_GRAY_ALPHA ? GL_RG :
#else
colorType == PNG_COLOR_TYPE_GRAY ? GL_LUMINANCE :
colorType == PNG_COLOR_TYPE_GRAY_ALPHA ? GL_LUMINANCE_ALPHA :
#endif
colorType == PNG_COLOR_TYPE_RGB ? GL_RGB :
colorType == PNG_COLOR_TYPE_RGB_ALPHA ? GL_RGBA :
0;
if (!glFormat) {
SCRAPS_LOGF_ERROR("unsupported color type (%d)", static_cast<int>(colorType));
return 0;
}
int bytesPerRow = png_get_rowbytes(png, info);
int bitDepth = png_get_bit_depth(png, info);
if (bitDepth != 8 && bitDepth != 16) {
SCRAPS_LOGF_ERROR("unsupported bit depth");
return 0;
}
const auto components = ((colorType & PNG_COLOR_MASK_COLOR) ? 3 : 1) + ((colorType & PNG_COLOR_MASK_ALPHA) ? 1 : 0);
if (bytesPerRow != components * (bitDepth >> 3) * _width) {
assert(false);
SCRAPS_LOGF_ERROR("unknown error");
return 0;
}
#if OPENGL_ES
if (bitDepth == 16) {
// opengl es doesn't do 16-bit textures
bitDepth = 8;
png_set_strip_16(png);
}
#endif
if (bitDepth > 8) {
// libpng stores pixels as big endian. we need them in native endianness for opengl
union {
uint32_t i;
char c[4];
} u = {0x01020304};
if (u.c[0] != 1) {
// we're not big endian. swap
png_set_swap(png);
}
}
#if OPENGL_ES
// make powers of 2 so we can use mipmaps
_allocatedWidth = NextPowerOfTwo(_width);
_allocatedHeight = NextPowerOfTwo(_height);
#else
_allocatedWidth = _width;
_allocatedHeight = _height;
#endif
bytesPerRow = components * (bitDepth >> 3) * _allocatedWidth;
// align rows to 4-byte boundaries
if (bytesPerRow % 4) {
bytesPerRow += 4 - (bytesPerRow % 4);
}
std::vector<png_byte> image;
image.resize(bytesPerRow * _allocatedHeight);
std::vector<png_byte*> rowPointers;
for (int i = 0; i < _allocatedHeight; ++i) {
rowPointers.emplace_back(image.data() + i * bytesPerRow);
}
png_read_image(png, rowPointers.data());
// image now contains our raw bytes. send it to the gpu
auto texture = _generateTexture(glFormat, glFormat, bitDepth == 8 ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT, image.data());
#if GL_RED && GL_RG
if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
if (colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_GREEN);
}
}
#endif
SCRAPS_GL_ERROR_CHECK();
_cacheEntry = textureCache->add(texture, texture);
return _cacheEntry->id;
}
GLuint FileTexture::_loadJPEG(opengl::TextureCache* textureCache) {
auto decompressor = tjInitDecompress();
auto _ = gsl::finally([&]{ tjDestroy(decompressor); });
int width{0}, height{0}, jpegSubsamp{0}, jpegColorspace{0};
if (tjDecompressHeader3(decompressor, reinterpret_cast<const unsigned char*>(_data->data()), _data->size(), &width, &height, &jpegSubsamp, &jpegColorspace)) {
SCRAPS_LOG_ERROR("error reading jpeg header: {}", tjGetErrorStr());
return 0;
}
#if OPENGL_ES
// make powers of 2 so we can use mipmaps
_allocatedWidth = NextPowerOfTwo(width);
_allocatedHeight = NextPowerOfTwo(height);
#else
_allocatedWidth = _width;
_allocatedHeight = _height;
#endif
auto pixelFormat = jpegColorspace == TJCS_GRAY ? TJPF_GRAY : TJPF_RGB;
auto bytesPerRow = TJPAD(_allocatedWidth * tjPixelSize[pixelFormat]);
std::vector<uint8_t> image;
image.resize(bytesPerRow * _allocatedHeight);
if (tjDecompress2(decompressor, reinterpret_cast<const unsigned char*>(_data->data()), _data->size(), image.data(), width, bytesPerRow, height, pixelFormat, 0)) {
SCRAPS_LOG_ERROR("error decompressing jpeg: {}", tjGetErrorStr());
return 0;
}
// image now contains our raw bytes. send it to the gpu
#if GL_RED && GL_RG
auto glFormat = jpegColorspace == TJCS_GRAY ? GL_RED : GL_RGB;
#else
auto glFormat = jpegColorspace == TJCS_GRAY ? GL_LUMINANCE : GL_RGB;
#endif
auto texture = _generateTexture(glFormat, glFormat, GL_UNSIGNED_BYTE, image.data());
#if GL_RED && GL_RG
if (jpegColorspace == TJCS_GRAY) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
}
#endif
SCRAPS_GL_ERROR_CHECK();
_cacheEntry = textureCache->add(texture, texture);
return _cacheEntry->id;
}
GLuint FileTexture::_generateTexture(GLint internalformat, GLenum format, GLenum type, const GLvoid* data) {
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexImage2D(GL_TEXTURE_2D, 0, internalformat, _allocatedWidth, _allocatedHeight, 0, format, type, data);
#if OPENGL_ES
bool useMipmaps = IsPowerOfTwo(_allocatedWidth) && IsPowerOfTwo(_allocatedHeight);
#else
constexpr bool useMipmaps = true;
#endif
if (useMipmaps) {
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
} else {
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
glTexParameterf(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);
return texture;
}
}}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* spin_box.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 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 "spin_box.h"
#include "core/math/expression.h"
#include "core/os/input.h"
Size2 SpinBox::get_minimum_size() const {
Size2 ms = line_edit->get_combined_minimum_size();
ms.width += last_w;
return ms;
}
void SpinBox::_value_changed(double) {
String value = String::num(get_value(), Math::range_step_decimals(get_step()));
if (prefix != "")
value = prefix + " " + value;
if (suffix != "")
value += " " + suffix;
line_edit->set_text(value);
}
void SpinBox::_text_entered(const String &p_string) {
Ref<Expression> expr;
expr.instance();
// Ignore the prefix and suffix in the expression
Error err = expr->parse(p_string.trim_prefix(prefix + " ").trim_suffix(" " + suffix));
if (err != OK) {
return;
}
Variant value = expr->execute(Array(), NULL, false);
if (value.get_type() != Variant::NIL) {
set_value(value);
_value_changed(0);
}
}
LineEdit *SpinBox::get_line_edit() {
return line_edit;
}
void SpinBox::_line_edit_input(const Ref<InputEvent> &p_event) {
}
void SpinBox::_range_click_timeout() {
if (!drag.enabled && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) {
bool up = get_local_mouse_position().y < (get_size().height / 2);
set_value(get_value() + (up ? get_step() : -get_step()));
if (range_click_timer->is_one_shot()) {
range_click_timer->set_wait_time(0.075);
range_click_timer->set_one_shot(false);
range_click_timer->start();
}
} else {
range_click_timer->stop();
}
}
void SpinBox::_gui_input(const Ref<InputEvent> &p_event) {
if (!is_editable()) {
return;
}
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid() && mb->is_pressed()) {
bool up = mb->get_position().y < (get_size().height / 2);
switch (mb->get_button_index()) {
case BUTTON_LEFT: {
line_edit->grab_focus();
set_value(get_value() + (up ? get_step() : -get_step()));
range_click_timer->set_wait_time(0.6);
range_click_timer->set_one_shot(true);
range_click_timer->start();
drag.allowed = true;
drag.capture_pos = mb->get_position();
} break;
case BUTTON_RIGHT: {
line_edit->grab_focus();
set_value((up ? get_max() : get_min()));
} break;
case BUTTON_WHEEL_UP: {
if (line_edit->has_focus()) {
set_value(get_value() + get_step() * mb->get_factor());
accept_event();
}
} break;
case BUTTON_WHEEL_DOWN: {
if (line_edit->has_focus()) {
set_value(get_value() - get_step() * mb->get_factor());
accept_event();
}
} break;
}
}
if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) {
//set_default_cursor_shape(CURSOR_ARROW);
range_click_timer->stop();
if (drag.enabled) {
drag.enabled = false;
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
warp_mouse(drag.capture_pos);
}
drag.allowed = false;
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_LEFT) {
if (drag.enabled) {
drag.diff_y += mm->get_relative().y;
float diff_y = -0.01 * Math::pow(ABS(drag.diff_y), 1.8f) * SGN(drag.diff_y);
set_value(CLAMP(drag.base_val + get_step() * diff_y, get_min(), get_max()));
} else if (drag.allowed && drag.capture_pos.distance_to(mm->get_position()) > 2) {
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
drag.enabled = true;
drag.base_val = get_value();
drag.diff_y = 0;
}
}
}
void SpinBox::_line_edit_focus_exit() {
// discontinue because the focus_exit was caused by right-click context menu
if (line_edit->get_menu()->is_visible())
return;
_text_entered(line_edit->get_text());
}
inline void SpinBox::_adjust_width_for_icon(const Ref<Texture> &icon) {
int w = icon->get_width();
if (w != last_w) {
line_edit->set_margin(MARGIN_RIGHT, -w);
last_w = w;
}
}
void SpinBox::_notification(int p_what) {
if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> updown = get_icon("updown");
_adjust_width_for_icon(updown);
RID ci = get_canvas_item();
Size2i size = get_size();
updown->draw(ci, Point2i(size.width - updown->get_width(), (size.height - updown->get_height()) / 2));
} else if (p_what == NOTIFICATION_FOCUS_EXIT) {
//_value_changed(0);
} else if (p_what == NOTIFICATION_ENTER_TREE) {
_adjust_width_for_icon(get_icon("updown"));
_value_changed(0);
} else if (p_what == NOTIFICATION_THEME_CHANGED) {
call_deferred("minimum_size_changed");
get_line_edit()->call_deferred("minimum_size_changed");
}
}
void SpinBox::set_align(LineEdit::Align p_align) {
line_edit->set_align(p_align);
}
LineEdit::Align SpinBox::get_align() const {
return line_edit->get_align();
}
void SpinBox::set_suffix(const String &p_suffix) {
suffix = p_suffix;
_value_changed(0);
}
String SpinBox::get_suffix() const {
return suffix;
}
void SpinBox::set_prefix(const String &p_prefix) {
prefix = p_prefix;
_value_changed(0);
}
String SpinBox::get_prefix() const {
return prefix;
}
void SpinBox::set_editable(bool p_editable) {
line_edit->set_editable(p_editable);
}
bool SpinBox::is_editable() const {
return line_edit->is_editable();
}
void SpinBox::apply() {
_text_entered(line_edit->get_text());
}
void SpinBox::_bind_methods() {
//ClassDB::bind_method(D_METHOD("_value_changed"),&SpinBox::_value_changed);
ClassDB::bind_method(D_METHOD("_gui_input"), &SpinBox::_gui_input);
ClassDB::bind_method(D_METHOD("_text_entered"), &SpinBox::_text_entered);
ClassDB::bind_method(D_METHOD("set_align", "align"), &SpinBox::set_align);
ClassDB::bind_method(D_METHOD("get_align"), &SpinBox::get_align);
ClassDB::bind_method(D_METHOD("set_suffix", "suffix"), &SpinBox::set_suffix);
ClassDB::bind_method(D_METHOD("get_suffix"), &SpinBox::get_suffix);
ClassDB::bind_method(D_METHOD("set_prefix", "prefix"), &SpinBox::set_prefix);
ClassDB::bind_method(D_METHOD("get_prefix"), &SpinBox::get_prefix);
ClassDB::bind_method(D_METHOD("set_editable", "editable"), &SpinBox::set_editable);
ClassDB::bind_method(D_METHOD("is_editable"), &SpinBox::is_editable);
ClassDB::bind_method(D_METHOD("apply"), &SpinBox::apply);
ClassDB::bind_method(D_METHOD("_line_edit_focus_exit"), &SpinBox::_line_edit_focus_exit);
ClassDB::bind_method(D_METHOD("get_line_edit"), &SpinBox::get_line_edit);
ClassDB::bind_method(D_METHOD("_line_edit_input"), &SpinBox::_line_edit_input);
ClassDB::bind_method(D_METHOD("_range_click_timeout"), &SpinBox::_range_click_timeout);
ADD_PROPERTY(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_align", "get_align");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "prefix"), "set_prefix", "get_prefix");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "suffix"), "set_suffix", "get_suffix");
}
SpinBox::SpinBox() {
last_w = 0;
line_edit = memnew(LineEdit);
add_child(line_edit);
line_edit->set_anchors_and_margins_preset(Control::PRESET_WIDE);
line_edit->set_mouse_filter(MOUSE_FILTER_PASS);
//connect("value_changed",this,"_value_changed");
line_edit->connect("text_entered", this, "_text_entered", Vector<Variant>(), CONNECT_DEFERRED);
line_edit->connect("focus_exited", this, "_line_edit_focus_exit", Vector<Variant>(), CONNECT_DEFERRED);
line_edit->connect("gui_input", this, "_line_edit_input");
drag.enabled = false;
range_click_timer = memnew(Timer);
range_click_timer->connect("timeout", this, "_range_click_timeout");
add_child(range_click_timer);
}
<commit_msg>Fixed bug where spinbox would not update to it's actual value after non-numeric input<commit_after>/*************************************************************************/
/* spin_box.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 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 "spin_box.h"
#include "core/math/expression.h"
#include "core/os/input.h"
Size2 SpinBox::get_minimum_size() const {
Size2 ms = line_edit->get_combined_minimum_size();
ms.width += last_w;
return ms;
}
void SpinBox::_value_changed(double) {
String value = String::num(get_value(), Math::range_step_decimals(get_step()));
if (prefix != "")
value = prefix + " " + value;
if (suffix != "")
value += " " + suffix;
line_edit->set_text(value);
}
void SpinBox::_text_entered(const String &p_string) {
Ref<Expression> expr;
expr.instance();
// Ignore the prefix and suffix in the expression
Error err = expr->parse(p_string.trim_prefix(prefix + " ").trim_suffix(" " + suffix));
if (err != OK) {
return;
}
Variant value = expr->execute(Array(), NULL, false);
if (value.get_type() != Variant::NIL) {
set_value(value);
}
_value_changed(0);
}
LineEdit *SpinBox::get_line_edit() {
return line_edit;
}
void SpinBox::_line_edit_input(const Ref<InputEvent> &p_event) {
}
void SpinBox::_range_click_timeout() {
if (!drag.enabled && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) {
bool up = get_local_mouse_position().y < (get_size().height / 2);
set_value(get_value() + (up ? get_step() : -get_step()));
if (range_click_timer->is_one_shot()) {
range_click_timer->set_wait_time(0.075);
range_click_timer->set_one_shot(false);
range_click_timer->start();
}
} else {
range_click_timer->stop();
}
}
void SpinBox::_gui_input(const Ref<InputEvent> &p_event) {
if (!is_editable()) {
return;
}
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid() && mb->is_pressed()) {
bool up = mb->get_position().y < (get_size().height / 2);
switch (mb->get_button_index()) {
case BUTTON_LEFT: {
line_edit->grab_focus();
set_value(get_value() + (up ? get_step() : -get_step()));
range_click_timer->set_wait_time(0.6);
range_click_timer->set_one_shot(true);
range_click_timer->start();
drag.allowed = true;
drag.capture_pos = mb->get_position();
} break;
case BUTTON_RIGHT: {
line_edit->grab_focus();
set_value((up ? get_max() : get_min()));
} break;
case BUTTON_WHEEL_UP: {
if (line_edit->has_focus()) {
set_value(get_value() + get_step() * mb->get_factor());
accept_event();
}
} break;
case BUTTON_WHEEL_DOWN: {
if (line_edit->has_focus()) {
set_value(get_value() - get_step() * mb->get_factor());
accept_event();
}
} break;
}
}
if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) {
//set_default_cursor_shape(CURSOR_ARROW);
range_click_timer->stop();
if (drag.enabled) {
drag.enabled = false;
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
warp_mouse(drag.capture_pos);
}
drag.allowed = false;
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_LEFT) {
if (drag.enabled) {
drag.diff_y += mm->get_relative().y;
float diff_y = -0.01 * Math::pow(ABS(drag.diff_y), 1.8f) * SGN(drag.diff_y);
set_value(CLAMP(drag.base_val + get_step() * diff_y, get_min(), get_max()));
} else if (drag.allowed && drag.capture_pos.distance_to(mm->get_position()) > 2) {
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
drag.enabled = true;
drag.base_val = get_value();
drag.diff_y = 0;
}
}
}
void SpinBox::_line_edit_focus_exit() {
// discontinue because the focus_exit was caused by right-click context menu
if (line_edit->get_menu()->is_visible())
return;
_text_entered(line_edit->get_text());
}
inline void SpinBox::_adjust_width_for_icon(const Ref<Texture> &icon) {
int w = icon->get_width();
if (w != last_w) {
line_edit->set_margin(MARGIN_RIGHT, -w);
last_w = w;
}
}
void SpinBox::_notification(int p_what) {
if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> updown = get_icon("updown");
_adjust_width_for_icon(updown);
RID ci = get_canvas_item();
Size2i size = get_size();
updown->draw(ci, Point2i(size.width - updown->get_width(), (size.height - updown->get_height()) / 2));
} else if (p_what == NOTIFICATION_FOCUS_EXIT) {
//_value_changed(0);
} else if (p_what == NOTIFICATION_ENTER_TREE) {
_adjust_width_for_icon(get_icon("updown"));
_value_changed(0);
} else if (p_what == NOTIFICATION_THEME_CHANGED) {
call_deferred("minimum_size_changed");
get_line_edit()->call_deferred("minimum_size_changed");
}
}
void SpinBox::set_align(LineEdit::Align p_align) {
line_edit->set_align(p_align);
}
LineEdit::Align SpinBox::get_align() const {
return line_edit->get_align();
}
void SpinBox::set_suffix(const String &p_suffix) {
suffix = p_suffix;
_value_changed(0);
}
String SpinBox::get_suffix() const {
return suffix;
}
void SpinBox::set_prefix(const String &p_prefix) {
prefix = p_prefix;
_value_changed(0);
}
String SpinBox::get_prefix() const {
return prefix;
}
void SpinBox::set_editable(bool p_editable) {
line_edit->set_editable(p_editable);
}
bool SpinBox::is_editable() const {
return line_edit->is_editable();
}
void SpinBox::apply() {
_text_entered(line_edit->get_text());
}
void SpinBox::_bind_methods() {
//ClassDB::bind_method(D_METHOD("_value_changed"),&SpinBox::_value_changed);
ClassDB::bind_method(D_METHOD("_gui_input"), &SpinBox::_gui_input);
ClassDB::bind_method(D_METHOD("_text_entered"), &SpinBox::_text_entered);
ClassDB::bind_method(D_METHOD("set_align", "align"), &SpinBox::set_align);
ClassDB::bind_method(D_METHOD("get_align"), &SpinBox::get_align);
ClassDB::bind_method(D_METHOD("set_suffix", "suffix"), &SpinBox::set_suffix);
ClassDB::bind_method(D_METHOD("get_suffix"), &SpinBox::get_suffix);
ClassDB::bind_method(D_METHOD("set_prefix", "prefix"), &SpinBox::set_prefix);
ClassDB::bind_method(D_METHOD("get_prefix"), &SpinBox::get_prefix);
ClassDB::bind_method(D_METHOD("set_editable", "editable"), &SpinBox::set_editable);
ClassDB::bind_method(D_METHOD("is_editable"), &SpinBox::is_editable);
ClassDB::bind_method(D_METHOD("apply"), &SpinBox::apply);
ClassDB::bind_method(D_METHOD("_line_edit_focus_exit"), &SpinBox::_line_edit_focus_exit);
ClassDB::bind_method(D_METHOD("get_line_edit"), &SpinBox::get_line_edit);
ClassDB::bind_method(D_METHOD("_line_edit_input"), &SpinBox::_line_edit_input);
ClassDB::bind_method(D_METHOD("_range_click_timeout"), &SpinBox::_range_click_timeout);
ADD_PROPERTY(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_align", "get_align");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "prefix"), "set_prefix", "get_prefix");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "suffix"), "set_suffix", "get_suffix");
}
SpinBox::SpinBox() {
last_w = 0;
line_edit = memnew(LineEdit);
add_child(line_edit);
line_edit->set_anchors_and_margins_preset(Control::PRESET_WIDE);
line_edit->set_mouse_filter(MOUSE_FILTER_PASS);
//connect("value_changed",this,"_value_changed");
line_edit->connect("text_entered", this, "_text_entered", Vector<Variant>(), CONNECT_DEFERRED);
line_edit->connect("focus_exited", this, "_line_edit_focus_exit", Vector<Variant>(), CONNECT_DEFERRED);
line_edit->connect("gui_input", this, "_line_edit_input");
drag.enabled = false;
range_click_timer = memnew(Timer);
range_click_timer->connect("timeout", this, "_range_click_timeout");
add_child(range_click_timer);
}
<|endoftext|> |
<commit_before>/*
Kopete Yahoo Protocol
Notifies about buddy icons
Copyright (c) 2005 André Duffeck <duffeck@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "picturenotifiertask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <QStringList>
#include <kdebug.h>
#include <klocale.h>
PictureNotifierTask::PictureNotifierTask(Task* parent) : Task(parent)
{
kDebug(YAHOO_RAW_DEBUG) ;
}
PictureNotifierTask::~PictureNotifierTask()
{
}
bool PictureNotifierTask::take( Transfer* transfer )
{
if ( !forMe( transfer ) )
return false;
YMSGTransfer *t = 0L;
t = dynamic_cast<YMSGTransfer*>(transfer);
if (!t)
return false;
switch( t->service() )
{
case Yahoo::ServicePictureStatus:
parsePictureStatus( t );
parsePicture( t );
break;
case Yahoo::ServicePictureChecksum:
parsePictureChecksum( t );
parsePicture( t );
break;
case Yahoo::ServicePicture:
parsePicture( t );
break;
case Yahoo::ServicePictureUpload:
parsePictureUploadResponse( t );
break;
default:
break;
}
return true;
}
bool PictureNotifierTask::forMe( const Transfer* transfer ) const
{
const YMSGTransfer *t = 0L;
t = dynamic_cast<const YMSGTransfer*>(transfer);
if (!t)
return false;
if ( t->service() == Yahoo::ServicePictureChecksum ||
t->service() == Yahoo::ServicePicture ||
t->service() == Yahoo::ServicePictureUpdate ||
t->service() == Yahoo::ServicePictureUpload ||
t->service() == Yahoo::ServicePictureStatus )
return true;
else
return false;
}
void PictureNotifierTask::parsePictureStatus( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString nick; /* key = 4 */
int state; /* key = 213 */
nick = t->firstParam( 4 );
state = t->firstParam( 213 ).toInt();
emit pictureStatusNotify( nick, state );
}
void PictureNotifierTask::parsePictureChecksum( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString nick; /* key = 4 */
int checksum; /* key = 192 */
nick = t->firstParam( 4 );
checksum = t->firstParam( 192 ).toInt();
if( nick != client()->userId() )
emit pictureChecksumNotify( nick, checksum );
}
void PictureNotifierTask::parsePicture( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString nick; /* key = 4 */
int type; /* key = 13: 1 = request, 2 = notification, 0 = Just changed */
QString url; /* key = 20 */
int checksum; /* key = 192 */
nick = t->firstParam( 4 );
url = t->firstParam( 20 );
checksum = t->firstParam( 192 ).toInt();
type = t->firstParam( 13 ).toInt();
if( type == 1 )
emit pictureRequest( nick );
else if( type == 0 )
emit pictureInfoNotify( nick, KUrl( url ), checksum );
else if( type == 2 )
emit pictureInfoNotify( nick, KUrl( url ), checksum );
}
void PictureNotifierTask::parsePictureUploadResponse( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString url;
QString error;
int expires;
url = t->firstParam( 20 );
error = t->firstParam( 16 );
expires = t->firstParam( 38 ).toInt();
if( !error.isEmpty() )
client()->notifyError(i18n("The picture was not successfully uploaded"), error, Client::Error );
if( !url.isEmpty() )
{
kDebug(YAHOO_RAW_DEBUG) << "Emitting url: " << url << " Picture expires: " << expires;
emit pictureUploaded( url, expires );
}
}
#include "picturenotifiertask.moc"
<commit_msg>Avatar - Picture must be aslo set here to catch all conditions of changes of Avatar michaelacole<commit_after>/*
Kopete Yahoo Protocol
Notifies about buddy icons
Copyright (c) 2005 André Duffeck <duffeck@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "picturenotifiertask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <QStringList>
#include <kdebug.h>
#include <klocale.h>
PictureNotifierTask::PictureNotifierTask(Task* parent) : Task(parent)
{
kDebug(YAHOO_RAW_DEBUG) ;
}
PictureNotifierTask::~PictureNotifierTask()
{
}
bool PictureNotifierTask::take( Transfer* transfer )
{
if ( !forMe( transfer ) )
return false;
YMSGTransfer *t = 0L;
t = dynamic_cast<YMSGTransfer*>(transfer);
if (!t)
return false;
switch( t->service() )
{
case Yahoo::ServicePictureStatus:
parsePictureStatus( t );
parsePicture( t );
break;
case Yahoo::ServicePictureChecksum:
parsePictureChecksum( t );
parsePicture( t );
break;
case Yahoo::ServicePicture:
parsePicture( t );
break;
case Yahoo::ServicePictureUpload:
parsePictureUploadResponse( t );
break;
default:
break;
}
return true;
}
bool PictureNotifierTask::forMe( const Transfer* transfer ) const
{
const YMSGTransfer *t = 0L;
t = dynamic_cast<const YMSGTransfer*>(transfer);
if (!t)
return false;
if ( t->service() == Yahoo::ServicePictureChecksum ||
t->service() == Yahoo::ServicePicture ||
t->service() == Yahoo::ServicePictureUpdate ||
t->service() == Yahoo::ServicePictureUpload ||
t->service() == Yahoo::ServicePictureStatus )
return true;
else
return false;
}
void PictureNotifierTask::parsePictureStatus( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString nick; /* key = 4 */
int state; /* key = 213 */
nick = t->firstParam( 4 );
state = t->firstParam( 213 ).toInt();
emit pictureStatusNotify( nick, state );
}
void PictureNotifierTask::parsePictureChecksum( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
parsePicture( t );
QString nick; /* key = 4 */
int checksum; /* key = 192 */
nick = t->firstParam( 4 );
checksum = t->firstParam( 192 ).toInt();
if( nick != client()->userId() )
emit pictureChecksumNotify( nick, checksum );
}
void PictureNotifierTask::parsePicture( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString nick; /* key = 4 */
int type; /* key = 13: 1 = request, 2 = notification, 0 = Just changed */
QString url; /* key = 20 */
int checksum; /* key = 192 */
nick = t->firstParam( 4 );
url = t->firstParam( 20 );
checksum = t->firstParam( 192 ).toInt();
type = t->firstParam( 13 ).toInt();
if( type == 1 )
emit pictureRequest( nick );
else if( type == 0 )
emit pictureInfoNotify( nick, KUrl( url ), checksum );
else if( type == 2 )
emit pictureInfoNotify( nick, KUrl( url ), checksum );
}
void PictureNotifierTask::parsePictureUploadResponse( YMSGTransfer *t )
{
kDebug(YAHOO_RAW_DEBUG) ;
QString url;
QString error;
int expires;
url = t->firstParam( 20 );
error = t->firstParam( 16 );
expires = t->firstParam( 38 ).toInt();
if( !error.isEmpty() )
client()->notifyError(i18n("The picture was not successfully uploaded"), error, Client::Error );
if( !url.isEmpty() )
{
kDebug(YAHOO_RAW_DEBUG) << "Emitting url: " << url << " Picture expires: " << expires;
emit pictureUploaded( url, expires );
}
}
#include "picturenotifiertask.moc"
<|endoftext|> |
<commit_before>// RUN: cat %s | %cling -I%p -Xclang -verify 2>&1 | FileCheck %s
// Test the removal of decls from the redeclaration chain, which are marked as
// redeclarables.
extern int my_int;
.rawInput 1
int my_funct();
.rawInput 0
.storeState "testRedeclarables"
#include "Redeclarables.h"
.compareState "testRedeclarables"
// CHECK-NOT: File with AST differencies stored in: testRedeclarablesAST.diff
.rawInput 1
int my_funct() {
return 20;
}
.rawInput 0
int my_int = 20;
my_int
// CHECK: (int) 20
my_funct()
// CHECK: (int) 20
.q
<commit_msg>Check against the new message printed out if there were differences.<commit_after>// RUN: cat %s | %cling -I%p -Xclang -verify 2>&1 | FileCheck %s
// Test the removal of decls from the redeclaration chain, which are marked as
// redeclarables.
extern int my_int;
.rawInput 1
int my_funct();
.rawInput 0
.storeState "testRedeclarables"
#include "Redeclarables.h"
.compareState "testRedeclarables"
// CHECK-NOT: Differences
.rawInput 1
int my_funct() {
return 20;
}
.rawInput 0
int my_int = 20;
my_int
// CHECK: (int) 20
my_funct()
// CHECK: (int) 20
.q
<|endoftext|> |
<commit_before>/* Created and copyrighted by Zachary J. Fields. All rights reserved. */
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "../mcp23s17.h"
#include "MOCK_wiring.h"
class TC_mcp23s17 : public mcp23s17 {
public:
TC_mcp23s17 (
mcp23s17::HardwareAddress hw_addr_
): mcp23s17(hw_addr_)
{}
// Access protected test members
using mcp23s17::getControlRegister;
using mcp23s17::getControlRegisterAddresses;
};
namespace {
class SPITransfer : public ::testing::Test {
protected:
uint8_t _spi_transaction[3];
int _index;
SPITransfer (
void
) :
_index(0)
{
// This happens before SetUp()
}
~SPITransfer() {
// This happens after TearDown()
}
void SetUp (void) {
initMockState();
for ( int i = 0 ; i < sizeof(_spi_transaction) ; ++ i ) { _spi_transaction[i] = '\0'; }
SPI._transfer = [&](uint8_t byte_){
_spi_transaction[_index] = byte_;
++_index;
return 0x00;
};
}
void TearDown (void) {}
};
/*
The first argument is the name of the test case, and the second argument
is the test's name within the test case. Both names must be valid C++
identifiers, and they should not contain underscore (_). A test's full
name consists of its containing test case and its individual name. Tests
from different test cases can have the same individual name.
(e.g. ASSERT_EQ(_EXPECTED_, _ACTUAL_))
*/
TEST(Construction, WHENObjectIsConstructedTHENAddressParameterIsStored) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
EXPECT_EQ(0x4C, gpio_x.getSpiBusAddress());
}
TEST(Construction, WHENObjectIsConstructedTHENControlRegisterAddressesArePopulatedWithBankEqualsZeroValues) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
for ( int i = 0 ; i < static_cast<int>(mcp23s17::ControlRegister::REGISTER_COUNT) ; ++i ) {
EXPECT_EQ(i, gpio_x.getControlRegisterAddresses()[i]) << "Expected value <" << i << ">!";
}
}
TEST(Construction, WHENObjectIsConstructedTHENControlRegisterValuesArePopulated) {
int i = 0;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
for ( ; i < 2 ; ++i ) {
EXPECT_EQ(0xFF, gpio_x.getControlRegister()[i]) << "Error at index <" << i << ">!";
}
for ( ; i < static_cast<int>(mcp23s17::ControlRegister::REGISTER_COUNT) ; ++i ) {
EXPECT_EQ(0x00, gpio_x.getControlRegister()[i]) << "Error at index <" << i << ">!";
}
}
TEST(Construction, WHENObjectIsConstructedTHENSPIBeginIsCalled) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
EXPECT_EQ(true, SPI._has_begun);
}
/*
Like TEST(), the first argument is the test case name, but for TEST_F()
this must be the name of the test fixture class.
*/
TEST_F(SPITransfer, WHENPinModeHasNotBeenCalledTHENTheCallersChipSelectPinIsHigh) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
EXPECT_EQ(HIGH, getPinLatchValue(SS));
}
TEST_F(SPITransfer, WHENPinModeIsCalledTHENTheCallersChipSelectPinIsPulledFromHighToLowAndBack) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(LOW_TO_HIGH, getPinTransition(SS));
}
TEST_F(SPITransfer, WHENPinModeIsCalledTHENAWriteTransactionIsSent) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::INPUT);
EXPECT_EQ(static_cast<uint8_t>(mcp23s17::RegisterTransaction::WRITE), (_spi_transaction[0] & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinLessThanEightTHENTheIODIRARegisterIsTargeted) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::INPUT);
EXPECT_EQ(static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRA), _spi_transaction[1]);
}
//TODO: Consider 16-bit mode
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinGreaterThanOrEqualToEightTHENTheIODIRBRegisterIsTargeted) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRB), _spi_transaction[1]);
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinLessThanEightTHENAMaskWithTheSpecifiedBitUnsetIsSent) {
const uint8_t BIT_POSITION = 3;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinGreaterThanOrEqualToEightTHENAMaskWithTheSpecifiedBitUnsetIsSent) {
const uint8_t BIT_POSITION = 8 % 8;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinLessThanEightTHENAMaskWithTheSpecifiedBitSetIsSent) {
const uint8_t BIT_POSITION = 3;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinGreaterThanOrEqualToEightTHENAMaskWithTheSpecifiedBitSetIsSent) {
const uint8_t BIT_POSITION = 8 % 8;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinFromADifferentPortThanThePreviousCallTHENTheOriginalPinIsNotDisturbed) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(7, mcp23s17::PinMode::OUTPUT);
gpio_x.pinMode(10, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, ((gpio_x.getControlRegister()[static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRA)] >> 7) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinFromTheSamePortAsAPreviousCallTHENTheOriginalPinIsNotDisturbed) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
gpio_x.pinMode(10, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, (gpio_x.getControlRegister()[static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRB)] & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinAlreadyInTheCorrectStateTHENNoSPITransactionOccurs) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
// Make the original call to set the state
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
// Reset the index after the original transaction
_index = 0;
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0, _index);
}
} // namespace
/*
int main (int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
*/
/* Created and copyrighted by Zachary J. Fields. All rights reserved. */
<commit_msg>Refactored test to assert fields have been modified.<commit_after>/* Created and copyrighted by Zachary J. Fields. All rights reserved. */
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "../mcp23s17.h"
#include "MOCK_wiring.h"
class TC_mcp23s17 : public mcp23s17 {
public:
TC_mcp23s17 (
mcp23s17::HardwareAddress hw_addr_
): mcp23s17(hw_addr_)
{}
// Access protected test members
using mcp23s17::getControlRegister;
using mcp23s17::getControlRegisterAddresses;
};
namespace {
class SPITransfer : public ::testing::Test {
protected:
uint8_t _spi_transaction[3];
int _index;
SPITransfer (
void
) :
_index(0)
{
// This happens before SetUp()
}
~SPITransfer() {
// This happens after TearDown()
}
void SetUp (void) {
initMockState();
for ( int i = 0 ; i < sizeof(_spi_transaction) ; ++ i ) { _spi_transaction[i] = 0x00; }
SPI._transfer = [&](uint8_t byte_){
_spi_transaction[_index] = byte_;
++_index;
return 0x00;
};
}
void TearDown (void) {}
};
/*
The first argument is the name of the test case, and the second argument
is the test's name within the test case. Both names must be valid C++
identifiers, and they should not contain underscore (_). A test's full
name consists of its containing test case and its individual name. Tests
from different test cases can have the same individual name.
(e.g. ASSERT_EQ(_EXPECTED_, _ACTUAL_))
*/
TEST(Construction, WHENObjectIsConstructedTHENAddressParameterIsStored) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
EXPECT_EQ(0x4C, gpio_x.getSpiBusAddress());
}
TEST(Construction, WHENObjectIsConstructedTHENControlRegisterAddressesArePopulatedWithBankEqualsZeroValues) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
for ( int i = 0 ; i < static_cast<int>(mcp23s17::ControlRegister::REGISTER_COUNT) ; ++i ) {
EXPECT_EQ(i, gpio_x.getControlRegisterAddresses()[i]) << "Expected value <" << i << ">!";
}
}
TEST(Construction, WHENObjectIsConstructedTHENControlRegisterValuesArePopulated) {
int i = 0;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
for ( ; i < 2 ; ++i ) {
EXPECT_EQ(0xFF, gpio_x.getControlRegister()[i]) << "Error at index <" << i << ">!";
}
for ( ; i < static_cast<int>(mcp23s17::ControlRegister::REGISTER_COUNT) ; ++i ) {
EXPECT_EQ(0x00, gpio_x.getControlRegister()[i]) << "Error at index <" << i << ">!";
}
}
TEST(Construction, WHENObjectIsConstructedTHENSPIBeginIsCalled) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
EXPECT_EQ(true, SPI._has_begun);
}
/*
Like TEST(), the first argument is the test case name, but for TEST_F()
this must be the name of the test fixture class.
*/
TEST_F(SPITransfer, WHENPinModeHasNotBeenCalledTHENTheCallersChipSelectPinIsHigh) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
EXPECT_EQ(HIGH, getPinLatchValue(SS));
}
TEST_F(SPITransfer, WHENPinModeIsCalledTHENTheCallersChipSelectPinIsPulledFromHighToLowAndBack) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(LOW_TO_HIGH, getPinTransition(SS));
}
TEST_F(SPITransfer, WHENPinModeIsCalledTHENAWriteTransactionIsSent) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(0, _index);
EXPECT_EQ(static_cast<uint8_t>(mcp23s17::RegisterTransaction::WRITE), (_spi_transaction[0] & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinLessThanEightTHENTheIODIRARegisterIsTargeted) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(1, _index);
EXPECT_EQ(static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRA), _spi_transaction[1]);
}
//TODO: Consider 16-bit mode
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinGreaterThanOrEqualToEightTHENTheIODIRBRegisterIsTargeted) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(1, _index);
EXPECT_EQ(static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRB), _spi_transaction[1]);
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinLessThanEightTHENAMaskWithTheSpecifiedBitUnsetIsSent) {
const uint8_t BIT_POSITION = 3;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(2, _index);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinGreaterThanOrEqualToEightTHENAMaskWithTheSpecifiedBitUnsetIsSent) {
const uint8_t BIT_POSITION = 8 % 8;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(2, _index);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinLessThanEightTHENAMaskWithTheSpecifiedBitSetIsSent) {
const uint8_t BIT_POSITION = 3;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(3, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(2, _index);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledForOutputOnPinGreaterThanOrEqualToEightTHENAMaskWithTheSpecifiedBitSetIsSent) {
const uint8_t BIT_POSITION = 8 % 8;
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
ASSERT_LT(2, _index);
EXPECT_EQ(0x00, ((_spi_transaction[2] >> BIT_POSITION) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinFromADifferentPortThanThePreviousCallTHENTheOriginalPinIsNotDisturbed) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(7, mcp23s17::PinMode::OUTPUT);
gpio_x.pinMode(10, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, ((gpio_x.getControlRegister()[static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRA)] >> 7) & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinFromTheSamePortAsAPreviousCallTHENTheOriginalPinIsNotDisturbed) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
gpio_x.pinMode(10, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0x00, (gpio_x.getControlRegister()[static_cast<uint8_t>(mcp23s17::ControlRegister::IODIRB)] & 0x01));
}
TEST_F(SPITransfer, WHENPinModeIsCalledOnPinAlreadyInTheCorrectStateTHENNoSPITransactionOccurs) {
TC_mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_6);
// Make the original call to set the state
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
// Reset the index after the original transaction
_index = 0;
gpio_x.pinMode(8, mcp23s17::PinMode::OUTPUT);
EXPECT_EQ(0, _index);
}
} // namespace
/*
int main (int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
*/
/* Created and copyrighted by Zachary J. Fields. All rights reserved. */
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <getopt.h>
#include <ostream>
#include "Nebula.h"
using namespace std;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
static void print_license()
{
cout<< "Copyright 2002-2017, OpenNebula Project, OpenNebula Systems \n\n"
<< Nebula::version() << " is distributed and licensed for use under the"
<< " terms of the\nApache License, Version 2.0 "
<< "(http://www.apache.org/licenses/LICENSE-2.0).\n";
}
static void print_usage(ostream& str)
{
str << "Usage: oned [-h] [-v] [-f] [-i]\n";
}
static void print_help()
{
print_usage(cout);
cout << "\n"
<< "SYNOPSIS\n"
<< " Starts the OpenNebula daemon\n\n"
<< "OPTIONS\n"
<< " -v, --verbose\toutput version information and exit\n"
<< " -h, --help\tdisplay this help and exit\n"
<< " -f, --foreground\tforeground, do not fork the oned daemon\n"
<< " -i, --init-db\tinitialize the dabase and exit\n";
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
static void oned_init()
{
try
{
Nebula& nd = Nebula::instance();
nd.bootstrap_db();
}
catch (exception &e)
{
cerr << e.what() << endl;
return;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
static void oned_main()
{
try
{
Nebula& nd = Nebula::instance();
nd.start();
}
catch (exception &e)
{
cerr << e.what() << endl;
return;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
int opt;
bool foreground = false;
const char * nl;
int fd;
pid_t pid,sid;
string wd;
int rc;
static struct option long_options[] = {
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{"foreground", no_argument, 0, 'f'},
{"init-db", no_argument, 0, 'i'},
{0, 0, 0, 0}
};
int long_index = 0;
while ((opt = getopt_long(argc, argv, "vhif",
long_options, &long_index)) != -1)
{
switch(opt)
{
case 'v':
print_license();
exit(0);
break;
case 'h':
print_help();
exit(0);
break;
case 'i':
oned_init();
exit(0);
break;
case 'f':
foreground = true;
break;
default:
print_usage(cerr);
exit(-1);
break;
}
}
// ---------------------------------
// Check if other oned is running
// ---------------------------------
string lockfile;
string var_location;
nl = getenv("ONE_LOCATION");
if (nl == 0) // OpenNebula in root of FSH
{
var_location = "/var/lib/one/";
lockfile = "/var/lock/one/one";
}
else
{
var_location = nl;
var_location += "/var/";
lockfile = var_location + ".lock";
}
fd = open(lockfile.c_str(), O_CREAT|O_EXCL, 0640);
if( fd == -1)
{
cerr<< "Error: Cannot start oned, opening lock file " << lockfile
<< endl;
exit(-1);
}
close(fd);
// ----------------------------
// Fork & exit main process
// ----------------------------
if (foreground == true)
{
pid = 0; //Do not fork
}
else
{
pid = fork();
}
switch (pid){
case -1: // Error
cerr << "Error: Unable to fork.\n";
exit(-1);
case 0: // Child process
rc = chdir(var_location.c_str());
if (rc != 0)
{
goto error_chdir;
}
if (foreground == false)
{
sid = setsid();
if (sid == -1)
{
goto error_sid;
}
}
oned_main();
unlink(lockfile.c_str());
break;
default: // Parent process
break;
}
return 0;
error_chdir:
cerr << "Error: cannot change to dir " << wd << "\n";
unlink(lockfile.c_str());
exit(-1);
error_sid:
cerr << "Error: creating new session\n";
unlink(lockfile.c_str());
exit(-1);
}
<commit_msg>Oned: Fix typo in help (#553)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <getopt.h>
#include <ostream>
#include "Nebula.h"
using namespace std;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
static void print_license()
{
cout<< "Copyright 2002-2017, OpenNebula Project, OpenNebula Systems \n\n"
<< Nebula::version() << " is distributed and licensed for use under the"
<< " terms of the\nApache License, Version 2.0 "
<< "(http://www.apache.org/licenses/LICENSE-2.0).\n";
}
static void print_usage(ostream& str)
{
str << "Usage: oned [-h] [-v] [-f] [-i]\n";
}
static void print_help()
{
print_usage(cout);
cout << "\n"
<< "SYNOPSIS\n"
<< " Starts the OpenNebula daemon\n\n"
<< "OPTIONS\n"
<< " -v, --verbose\toutput version information and exit\n"
<< " -h, --help\tdisplay this help and exit\n"
<< " -f, --foreground\tforeground, do not fork the oned daemon\n"
<< " -i, --init-db\tinitialize the database and exit\n";
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
static void oned_init()
{
try
{
Nebula& nd = Nebula::instance();
nd.bootstrap_db();
}
catch (exception &e)
{
cerr << e.what() << endl;
return;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
static void oned_main()
{
try
{
Nebula& nd = Nebula::instance();
nd.start();
}
catch (exception &e)
{
cerr << e.what() << endl;
return;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
int opt;
bool foreground = false;
const char * nl;
int fd;
pid_t pid,sid;
string wd;
int rc;
static struct option long_options[] = {
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{"foreground", no_argument, 0, 'f'},
{"init-db", no_argument, 0, 'i'},
{0, 0, 0, 0}
};
int long_index = 0;
while ((opt = getopt_long(argc, argv, "vhif",
long_options, &long_index)) != -1)
{
switch(opt)
{
case 'v':
print_license();
exit(0);
break;
case 'h':
print_help();
exit(0);
break;
case 'i':
oned_init();
exit(0);
break;
case 'f':
foreground = true;
break;
default:
print_usage(cerr);
exit(-1);
break;
}
}
// ---------------------------------
// Check if other oned is running
// ---------------------------------
string lockfile;
string var_location;
nl = getenv("ONE_LOCATION");
if (nl == 0) // OpenNebula in root of FSH
{
var_location = "/var/lib/one/";
lockfile = "/var/lock/one/one";
}
else
{
var_location = nl;
var_location += "/var/";
lockfile = var_location + ".lock";
}
fd = open(lockfile.c_str(), O_CREAT|O_EXCL, 0640);
if( fd == -1)
{
cerr<< "Error: Cannot start oned, opening lock file " << lockfile
<< endl;
exit(-1);
}
close(fd);
// ----------------------------
// Fork & exit main process
// ----------------------------
if (foreground == true)
{
pid = 0; //Do not fork
}
else
{
pid = fork();
}
switch (pid){
case -1: // Error
cerr << "Error: Unable to fork.\n";
exit(-1);
case 0: // Child process
rc = chdir(var_location.c_str());
if (rc != 0)
{
goto error_chdir;
}
if (foreground == false)
{
sid = setsid();
if (sid == -1)
{
goto error_sid;
}
}
oned_main();
unlink(lockfile.c_str());
break;
default: // Parent process
break;
}
return 0;
error_chdir:
cerr << "Error: cannot change to dir " << wd << "\n";
unlink(lockfile.c_str());
exit(-1);
error_sid:
cerr << "Error: creating new session\n";
unlink(lockfile.c_str());
exit(-1);
}
<|endoftext|> |
<commit_before>#include "AppExample03.h"
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <vector>
#include "utils/OpenGLUtils.h"
#include "utils/FileUtils.h"
#include "data.h"
GLuint VAO1, VAO2 = 0;
GLfloat perspectiveMatrix[16];
GLuint programId = 0;
GLuint perspectiveMatrixUnif = 0;
GLuint offsetUniform = 0;
AppExample03::AppExample03() {
}
AppExample03::~AppExample03() {
}
bool AppExample03::init() {
std::string vertexShader = File::getFileContent("./exam03/shader.vert");
std::string fragmentShader = File::getFileContent("./exam03/shader.frag");
programId = OpenGLUtils::initGLStructure(vertexShader.c_str(), fragmentShader.c_str());
// create buffers
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
GLuint IBO;
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
size_t colorDataOffset = sizeof(float) * 3 * numberOfVertices;
// create VAO1
glGenVertexArrays(1, &VAO1);
glBindVertexArray(VAO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glEnableVertexAttribArray(0); // layout 1, position
glEnableVertexAttribArray(1); // layout 2, color
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*) colorDataOffset);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBindVertexArray(NULL);
size_t posDataOffset = sizeof(float) * 3 * (numberOfVertices/2);
colorDataOffset += sizeof(float) * 4 * (numberOfVertices/2);
// create VAO2
glGenVertexArrays(1, &VAO2);
glBindVertexArray(VAO2);
glEnableVertexAttribArray(0); // layout 1, position
glEnableVertexAttribArray(1); // layout 2, color
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*) posDataOffset);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*) colorDataOffset);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBindVertexArray(NULL);
// setup perspective matrix
memset(perspectiveMatrix, 0, sizeof(float) * 16);
perspectiveMatrix[0] = frustumScale;
perspectiveMatrix[5] = frustumScale;
perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar);
perspectiveMatrix[14] = (2 * zFar * zNear) / (zNear - zFar);
perspectiveMatrix[11] = -1.0f;
offsetUniform = glGetUniformLocation(programId, "offset");
perspectiveMatrixUnif = glGetUniformLocation(programId, "perspectiveMatrix");
glUseProgram(programId);
glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, perspectiveMatrix);
glUseProgram(NULL);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0f, 1.0f);
return true;
}
const char * AppExample03::getTitle() {
return "Example 03";
}
void AppExample03::update(float timeStep) {
// Log::print("update %f", timeStep);
}
void AppExample03::render(float timeStep) {
// Log::print("render %f", timeStep);
// initialize clear color
glClearColor(0.9f, 0.9f, 0.9f, 1.f);
// wipe the drawing surface clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(programId);
glBindVertexArray(VAO1);
glUniform3f(offsetUniform, 0.0f, 0.0f, 0.0f);
glDrawElements(GL_TRIANGLES, sizeof(indexData), GL_UNSIGNED_SHORT, 0);
glBindVertexArray(VAO2);
glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f);
glDrawElements(GL_TRIANGLES, sizeof(indexData), GL_UNSIGNED_SHORT, 0);
glBindVertexArray(NULL);
glUseProgram(NULL);
}
void AppExample03::cleanUp() {
Log::print("cleanUp");
}
void AppExample03::reshape(int width, int height) {
Log::print("reshape w:%d h:%d", width, height);
perspectiveMatrix[0] = frustumScale / (width /(float) height);
perspectiveMatrix[5] = frustumScale;
glUseProgram(programId);
glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, perspectiveMatrix);
glUseProgram(NULL);
}
<commit_msg>Optimisation: Base Vertex. Removed a VAO and used glDrawElementsBaseVertex<commit_after>#include "AppExample03.h"
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <vector>
#include "utils/OpenGLUtils.h"
#include "utils/FileUtils.h"
#include "data.h"
GLuint VAO = 0;
GLfloat perspectiveMatrix[16];
GLuint programId = 0;
GLuint perspectiveMatrixUnif = 0;
GLuint offsetUniform = 0;
AppExample03::AppExample03() {
}
AppExample03::~AppExample03() {
}
bool AppExample03::init() {
std::string vertexShader = File::getFileContent("./exam03/shader.vert");
std::string fragmentShader = File::getFileContent("./exam03/shader.frag");
programId = OpenGLUtils::initGLStructure(vertexShader.c_str(), fragmentShader.c_str());
// create buffers
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
GLuint IBO;
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
size_t colorDataOffset = sizeof(float) * 3 * numberOfVertices;
// create VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glEnableVertexAttribArray(0); // layout 1, position
glEnableVertexAttribArray(1); // layout 2, color
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*) colorDataOffset);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBindVertexArray(NULL);
// setup perspective matrix
memset(perspectiveMatrix, 0, sizeof(float) * 16);
perspectiveMatrix[0] = frustumScale;
perspectiveMatrix[5] = frustumScale;
perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar);
perspectiveMatrix[14] = (2 * zFar * zNear) / (zNear - zFar);
perspectiveMatrix[11] = -1.0f;
offsetUniform = glGetUniformLocation(programId, "offset");
perspectiveMatrixUnif = glGetUniformLocation(programId, "perspectiveMatrix");
glUseProgram(programId);
glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, perspectiveMatrix);
glUseProgram(NULL);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0f, 1.0f);
return true;
}
const char * AppExample03::getTitle() {
return "Example 03";
}
void AppExample03::update(float timeStep) {
// Log::print("update %f", timeStep);
}
void AppExample03::render(float timeStep) {
// Log::print("render %f", timeStep);
// initialize clear color
glClearColor(0.9f, 0.9f, 0.9f, 1.f);
// wipe the drawing surface clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(programId);
glBindVertexArray(VAO);
glUniform3f(offsetUniform, 0.0f, 0.0f, 0.85f);
glDrawElements(GL_TRIANGLES, sizeof(indexData), GL_UNSIGNED_SHORT, 0);
glUniform3f(offsetUniform, 0.0f, 0.0f, -0.5f);
glDrawElementsBaseVertex(GL_TRIANGLES, sizeof(indexData), GL_UNSIGNED_SHORT, 0, numberOfVertices/2);
glBindVertexArray(NULL);
glUseProgram(NULL);
}
void AppExample03::cleanUp() {
Log::print("cleanUp");
}
void AppExample03::reshape(int width, int height) {
Log::print("reshape w:%d h:%d", width, height);
perspectiveMatrix[0] = frustumScale / (width /(float) height);
perspectiveMatrix[5] = frustumScale;
glUseProgram(programId);
glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, perspectiveMatrix);
glUseProgram(NULL);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Nu-book 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 "ReadBarcode.h"
#include "TextUtfEncoding.h"
#include "GTIN.h"
#include <cctype>
#include <chrono>
#include <clocale>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
using namespace ZXing;
using namespace TextUtfEncoding;
static void PrintUsage(const char* exePath)
{
std::cout << "Usage: " << exePath << " [-fast] [-norotate] [-format <FORMAT[,...]>] [-pngout <png out path>] [-ispure] [-1] <png image path>...\n"
<< " -fast Skip some lines/pixels during detection (faster)\n"
<< " -norotate Don't try rotated image during detection (faster)\n"
<< " -format Only detect given format(s) (faster)\n"
<< " -multires Image size threshold at which to start multi-resolution scanning, 0 disables it\n"
<< " -ispure Assume the image contains only a 'pure'/perfect code (faster)\n"
<< " -1 Print only file name, text and status on one line per file/barcode\n"
<< " -escape Escape non-graphical characters in angle brackets (ignored for -1 option, which always escapes)\n"
<< " -pngout Write a copy of the input image with barcodes outlined by a red line\n"
<< "\n"
<< "Supported formats are:\n";
for (auto f : BarcodeFormats::all()) {
std::cout << " " << ToString(f) << "\n";
}
std::cout << "Formats can be lowercase, with or without '-', separated by ',' and/or '|'\n";
}
static bool ParseOptions(int argc, char* argv[], DecodeHints& hints, bool& oneLine, bool& angleEscape,
std::vector<std::string>& filePaths, std::string& outPath)
{
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-fast") == 0) {
hints.setTryHarder(false);
} else if (strcmp(argv[i], "-norotate") == 0) {
hints.setTryRotate(false);
} else if (strcmp(argv[i], "-ispure") == 0) {
hints.setIsPure(true);
hints.setBinarizer(Binarizer::FixedThreshold);
} else if (strcmp(argv[i], "-format") == 0) {
if (++i == argc)
return false;
try {
hints.setFormats(BarcodeFormatsFromString(argv[i]));
} catch (const std::exception& e) {
std::cerr << e.what() << "\n";
return false;
}
} else if (strcmp(argv[i], "-multires") == 0) {
if (++i == argc)
return false;
try {
hints.setMultiResolutionThreshold(std::stoi(argv[i]));
} catch (const std::exception& e) {
std::cerr << e.what() << "\n";
return false;
}
} else if (strcmp(argv[i], "-1") == 0) {
oneLine = true;
} else if (strcmp(argv[i], "-escape") == 0) {
angleEscape = true;
} else if (strcmp(argv[i], "-pngout") == 0) {
if (++i == argc)
return false;
outPath = argv[i];
} else {
filePaths.push_back(argv[i]);
}
}
return !filePaths.empty();
}
std::ostream& operator<<(std::ostream& os, const Position& points)
{
for (const auto& p : points)
os << p.x << "x" << p.y << " ";
return os;
}
void drawLine(const ImageView& image, PointI a, PointI b)
{
int steps = maxAbsComponent(b - a);
PointF dir = bresenhamDirection(PointF(b - a));
for (int i = 0; i < steps; ++i) {
auto p = PointI(centered(a + i * dir));
*((uint32_t*)image.data(p.x, p.y)) = 0xff0000ff;
}
}
void drawRect(const ImageView& image, const Position& pos)
{
for (int i = 0; i < 4; ++i)
drawLine(image, pos[i], pos[(i + 1) % 4]);
}
int main(int argc, char* argv[])
{
DecodeHints hints;
std::vector<std::string> filePaths;
std::string outPath;
bool oneLine = false;
bool angleEscape = false;
int ret = 0;
hints.setMultiResolutionThreshold(500); // enable the feature by default
if (!ParseOptions(argc, argv, hints, oneLine, angleEscape, filePaths, outPath)) {
PrintUsage(argv[0]);
return -1;
}
hints.setEanAddOnSymbol(EanAddOnSymbol::Read);
if (oneLine)
angleEscape = true;
if (angleEscape)
std::setlocale(LC_CTYPE, "en_US.UTF-8"); // Needed so `std::iswgraph()` in `ToUtf8(angleEscape)` does not 'swallow' all printable non-ascii utf8 chars
for (const auto& filePath : filePaths) {
int width, height, channels;
std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free);
if (buffer == nullptr) {
std::cerr << "Failed to read image: " << filePath << "\n";
return -1;
}
ImageView image{buffer.get(), width, height, ImageFormat::RGBX};
auto results = ReadBarcodes(image, hints);
// if we did not find anything, insert a dummy to produce some output for each file
if (results.empty())
results.emplace_back(DecodeStatus::NotFound);
for (auto&& result : results) {
if (!outPath.empty())
drawRect(image, result.position());
ret |= static_cast<int>(result.status());
if (oneLine) {
std::cout << filePath << " " << ToString(result.format());
if (result.isValid())
std::cout << " \"" << ToUtf8(result.text(), angleEscape) << "\"";
else if (result.format() != BarcodeFormat::None)
std::cout << " " << ToString(result.status());
std::cout << "\n";
continue;
}
if (filePaths.size() > 1 || results.size() > 1) {
static bool firstFile = true;
if (!firstFile)
std::cout << "\n";
if (filePaths.size() > 1)
std::cout << "File: " << filePath << "\n";
firstFile = false;
}
std::cout << "Text: \"" << ToUtf8(result.text(), angleEscape) << "\"\n"
<< "Format: " << ToString(result.format()) << "\n"
<< "Identifier: " << result.symbologyIdentifier() << "\n"
<< "Position: " << result.position() << "\n"
<< "Rotation: " << result.orientation() << " deg\n"
<< "IsMirrored: " << (result.isMirrored() ? "true" : "false") << "\n"
<< "Error: " << ToString(result.status()) << "\n";
auto printOptional = [](const char* key, const std::string& v) {
if (!v.empty())
std::cout << key << v << "\n";
};
printOptional("EC Level: ", ToUtf8(result.ecLevel()));
if (result.lineCount())
std::cout << "Lines: " << result.lineCount() << "\n";
if ((BarcodeFormat::EAN13 | BarcodeFormat::EAN8 | BarcodeFormat::UPCA | BarcodeFormat::UPCE)
.testFlag(result.format())) {
printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format()));
printOptional("Add-On: ", GTIN::EanAddOn(result));
printOptional("Price: ", GTIN::Price(GTIN::EanAddOn(result)));
printOptional("Issue #: ", GTIN::IssueNr(GTIN::EanAddOn(result)));
} else if (result.format() == BarcodeFormat::ITF && result.text().length() == 14) {
printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format()));
}
if (result.isPartOfSequence())
std::cout << "Structured Append: symbol " << result.sequenceIndex() + 1 << " of "
<< result.sequenceSize() << " (parity/id: '" << result.sequenceId() << "')\n";
if (result.readerInit())
std::cout << "Reader Initialisation/Programming\n";
}
if (Size(filePaths) == 1 && !outPath.empty())
stbi_write_png(outPath.c_str(), image.width(), image.height(), 4, image.data(0, 0), image.rowStride());
}
return ret;
}
<commit_msg>example: use green instead of red to outline the found symbols in -pngout<commit_after>/*
* Copyright 2016 Nu-book 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 "ReadBarcode.h"
#include "TextUtfEncoding.h"
#include "GTIN.h"
#include <cctype>
#include <chrono>
#include <clocale>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
using namespace ZXing;
using namespace TextUtfEncoding;
static void PrintUsage(const char* exePath)
{
std::cout << "Usage: " << exePath << " [-fast] [-norotate] [-format <FORMAT[,...]>] [-pngout <png out path>] [-ispure] [-1] <png image path>...\n"
<< " -fast Skip some lines/pixels during detection (faster)\n"
<< " -norotate Don't try rotated image during detection (faster)\n"
<< " -format Only detect given format(s) (faster)\n"
<< " -multires Image size threshold at which to start multi-resolution scanning, 0 disables it\n"
<< " -ispure Assume the image contains only a 'pure'/perfect code (faster)\n"
<< " -1 Print only file name, text and status on one line per file/barcode\n"
<< " -escape Escape non-graphical characters in angle brackets (ignored for -1 option, which always escapes)\n"
<< " -pngout Write a copy of the input image with barcodes outlined by a red line\n"
<< "\n"
<< "Supported formats are:\n";
for (auto f : BarcodeFormats::all()) {
std::cout << " " << ToString(f) << "\n";
}
std::cout << "Formats can be lowercase, with or without '-', separated by ',' and/or '|'\n";
}
static bool ParseOptions(int argc, char* argv[], DecodeHints& hints, bool& oneLine, bool& angleEscape,
std::vector<std::string>& filePaths, std::string& outPath)
{
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-fast") == 0) {
hints.setTryHarder(false);
} else if (strcmp(argv[i], "-norotate") == 0) {
hints.setTryRotate(false);
} else if (strcmp(argv[i], "-ispure") == 0) {
hints.setIsPure(true);
hints.setBinarizer(Binarizer::FixedThreshold);
} else if (strcmp(argv[i], "-format") == 0) {
if (++i == argc)
return false;
try {
hints.setFormats(BarcodeFormatsFromString(argv[i]));
} catch (const std::exception& e) {
std::cerr << e.what() << "\n";
return false;
}
} else if (strcmp(argv[i], "-multires") == 0) {
if (++i == argc)
return false;
try {
hints.setMultiResolutionThreshold(std::stoi(argv[i]));
} catch (const std::exception& e) {
std::cerr << e.what() << "\n";
return false;
}
} else if (strcmp(argv[i], "-1") == 0) {
oneLine = true;
} else if (strcmp(argv[i], "-escape") == 0) {
angleEscape = true;
} else if (strcmp(argv[i], "-pngout") == 0) {
if (++i == argc)
return false;
outPath = argv[i];
} else {
filePaths.push_back(argv[i]);
}
}
return !filePaths.empty();
}
std::ostream& operator<<(std::ostream& os, const Position& points)
{
for (const auto& p : points)
os << p.x << "x" << p.y << " ";
return os;
}
void drawLine(const ImageView& image, PointI a, PointI b)
{
int steps = maxAbsComponent(b - a);
PointF dir = bresenhamDirection(PointF(b - a));
for (int i = 0; i < steps; ++i) {
auto p = PointI(centered(a + i * dir));
*((uint32_t*)image.data(p.x, p.y)) = 0xff00ff00;
}
}
void drawRect(const ImageView& image, const Position& pos)
{
for (int i = 0; i < 4; ++i)
drawLine(image, pos[i], pos[(i + 1) % 4]);
}
int main(int argc, char* argv[])
{
DecodeHints hints;
std::vector<std::string> filePaths;
std::string outPath;
bool oneLine = false;
bool angleEscape = false;
int ret = 0;
hints.setMultiResolutionThreshold(500); // enable the feature by default
if (!ParseOptions(argc, argv, hints, oneLine, angleEscape, filePaths, outPath)) {
PrintUsage(argv[0]);
return -1;
}
hints.setEanAddOnSymbol(EanAddOnSymbol::Read);
if (oneLine)
angleEscape = true;
if (angleEscape)
std::setlocale(LC_CTYPE, "en_US.UTF-8"); // Needed so `std::iswgraph()` in `ToUtf8(angleEscape)` does not 'swallow' all printable non-ascii utf8 chars
for (const auto& filePath : filePaths) {
int width, height, channels;
std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free);
if (buffer == nullptr) {
std::cerr << "Failed to read image: " << filePath << "\n";
return -1;
}
ImageView image{buffer.get(), width, height, ImageFormat::RGBX};
auto results = ReadBarcodes(image, hints);
// if we did not find anything, insert a dummy to produce some output for each file
if (results.empty())
results.emplace_back(DecodeStatus::NotFound);
for (auto&& result : results) {
if (!outPath.empty())
drawRect(image, result.position());
ret |= static_cast<int>(result.status());
if (oneLine) {
std::cout << filePath << " " << ToString(result.format());
if (result.isValid())
std::cout << " \"" << ToUtf8(result.text(), angleEscape) << "\"";
else if (result.format() != BarcodeFormat::None)
std::cout << " " << ToString(result.status());
std::cout << "\n";
continue;
}
if (filePaths.size() > 1 || results.size() > 1) {
static bool firstFile = true;
if (!firstFile)
std::cout << "\n";
if (filePaths.size() > 1)
std::cout << "File: " << filePath << "\n";
firstFile = false;
}
std::cout << "Text: \"" << ToUtf8(result.text(), angleEscape) << "\"\n"
<< "Format: " << ToString(result.format()) << "\n"
<< "Identifier: " << result.symbologyIdentifier() << "\n"
<< "Position: " << result.position() << "\n"
<< "Rotation: " << result.orientation() << " deg\n"
<< "IsMirrored: " << (result.isMirrored() ? "true" : "false") << "\n"
<< "Error: " << ToString(result.status()) << "\n";
auto printOptional = [](const char* key, const std::string& v) {
if (!v.empty())
std::cout << key << v << "\n";
};
printOptional("EC Level: ", ToUtf8(result.ecLevel()));
if (result.lineCount())
std::cout << "Lines: " << result.lineCount() << "\n";
if ((BarcodeFormat::EAN13 | BarcodeFormat::EAN8 | BarcodeFormat::UPCA | BarcodeFormat::UPCE)
.testFlag(result.format())) {
printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format()));
printOptional("Add-On: ", GTIN::EanAddOn(result));
printOptional("Price: ", GTIN::Price(GTIN::EanAddOn(result)));
printOptional("Issue #: ", GTIN::IssueNr(GTIN::EanAddOn(result)));
} else if (result.format() == BarcodeFormat::ITF && result.text().length() == 14) {
printOptional("Country: ", GTIN::LookupCountryIdentifier(ToUtf8(result.text()), result.format()));
}
if (result.isPartOfSequence())
std::cout << "Structured Append: symbol " << result.sequenceIndex() + 1 << " of "
<< result.sequenceSize() << " (parity/id: '" << result.sequenceId() << "')\n";
if (result.readerInit())
std::cout << "Reader Initialisation/Programming\n";
}
if (Size(filePaths) == 1 && !outPath.empty())
stbi_write_png(outPath.c_str(), image.width(), image.height(), 4, image.data(0, 0), image.rowStride());
}
return ret;
}
<|endoftext|> |
<commit_before>#include "net/telnet.h"
#include "autoconf.h"
#define TELCMDS // To get the array of Telnet command names
#define TELOPTS // To get the array of Telnet option names
#include <arpa/telnet.h>
namespace
{
std::string trim(std::string const& str)
{
// Find the first non-whitespace character
auto first = std::find_if(std::begin(str), std::end(str), [](char const& c)
{
return !std::isspace(c);
});
// Find the last non-whitespace character
auto last = std::find_if(std::rbegin(str), std::rend(str), [](char const& c)
{
return !std::isspace(c);
});
size_t first_pos = first != std::end(str) ? first - std::begin(str) : 0;
size_t length = last != std::rend(str) ? (std::rend(str) - last) - first_pos : str.length();
return str.substr(first_pos, length);
}
}
static constexpr std::size_t telnet_option_count = 256;
struct rethinkmud::net::connections::telnet::telnet_info
{
// What we do, and don't do
bool options[telnet_option_count] = { false };
// Options we have sent and are waiting for reply on
bool sent_will[telnet_option_count] = { false };
bool sent_wont[telnet_option_count] = { false };
bool sent_do[telnet_option_count] = { false };
bool sent_dont[telnet_option_count] = { false };
};
void rethinkmud::net::connections::telnet::telnet_info_deleter::operator()(telnet_info* info)
{
delete info;
}
void rethinkmud::net::connections::telnet::start()
{
std::clog << "Starting telnet connection\n";
info_.reset(new telnet_info);
tcp::start();
}
void rethinkmud::net::connections::telnet::input(std::vector<char> data)
{
// Parse the input for telnet command sequence
// Copy the non-telnet data to a new container
// For now we assume that all sequences are complete
std::string input;
if (!buffer_.empty())
{
input = buffer_;
buffer_ = ""; // Clear the saved buffer from last call
}
for (auto i = std::begin(data); i != std::end(data); ++i)
{
if (static_cast<uint8_t>(*i) == IAC)
{
uint8_t command = static_cast<uint8_t>(*++i);
// TODO: Handle all this
switch (command)
{
case DO:
case DONT:
case WILL:
case WONT:
handle_option(command, *++i);
break;
case SB:
i = handle_sb(i);
break;
case AYT:
// TODO: Use the configured MUD name instead
write("RethinkMUD version " RETHINKMUD_VERSION " is alive and well.\r\n");
break;
case IP:
std::clog << "Closing connection to " << socket().remote_endpoint() << " (Telnet IP)\n";
close();
return;
case EC:
// Remove last character from input
input.erase(std::end(input) - 1);
break;
case EL:
// Remove last "line" from input
erase_line(input);
break;
// TODO: AO: Clear the output queue?
default:
if (TELCMD_OK(command))
std::clog << "Unhandled telnet command " << TELCMD(command) << '\n';
else
std::clog << "Unknown telnet command " << static_cast<unsigned>(command) << '\n';
break;
}
}
else
input += *i;
}
if (input.empty())
return;
std::istringstream iss{input};
std::string line;
while (std::getline(iss, line))
{
if (iss.eof())
{
// Not a complete line at the end of the buffer, save the data for the next call to this function
buffer_ = line;
}
else
{
// Trim leading and trailing white-space
line = trim(line);
if (line == "echo off")
echo_off();
else if (line == "echo on")
echo_on();
else
write("You wrote: " + line + "\r\n");
// TODO: Add input line to queue for command interpreter
}
}
}
void rethinkmud::net::connections::telnet::send_option(uint8_t command, uint8_t option)
{
uint8_t const data[] = {
IAC,
command,
option
};
write(data, sizeof(data));
}
void rethinkmud::net::connections::telnet::send_do(uint8_t option)
{
if (!info_->sent_do[option])
{
send_option(DO, option);
info_->sent_do[option] = true;
}
}
void rethinkmud::net::connections::telnet::send_dont(uint8_t option)
{
if (!info_->sent_dont[option])
{
send_option(DONT, option);
info_->sent_dont[option] = true;
}
}
void rethinkmud::net::connections::telnet::send_will(uint8_t option)
{
if (!info_->sent_will[option])
{
send_option(WILL, option);
info_->sent_will[option] = true;
}
}
void rethinkmud::net::connections::telnet::send_wont(uint8_t option)
{
if (!info_->sent_wont[option])
{
send_option(WONT, option);
info_->sent_wont[option] = true;
}
}
void rethinkmud::net::connections::telnet::echo_on()
{
send_wont(TELOPT_ECHO);
send_do(TELOPT_ECHO);
}
void rethinkmud::net::connections::telnet::echo_off()
{
send_will(TELOPT_ECHO);
send_dont(TELOPT_ECHO);
}
void rethinkmud::net::connections::telnet::handle_option(uint8_t command, uint8_t option)
{
// TODO: Handle all this
switch (command)
{
case DO:
if (info_->sent_will[option])
{
}
else if (info_->sent_wont[option])
{
}
else
{
send_wont(option);
}
break;
case DONT:
if (info_->sent_will[option])
{
}
else if (info_->sent_wont[option])
{
}
else
{
send_wont(option);
}
break;
case WILL:
if (info_->sent_do[option])
{
}
else if (info_->sent_dont[option])
{
}
else
{
send_dont(option);
}
break;
case WONT:
if (info_->sent_do[option])
{
}
else if (info_->sent_dont[option])
{
}
else
{
send_dont(option);
}
break;
default:
break;
}
}
std::vector<char>::iterator rethinkmud::net::connections::telnet::handle_sb(std::vector<char>::iterator i)
{
if (TELOPT_OK(*i))
{
std::clog << "Unhandled telnet SB " << TELOPT(*i) << '\n';
}
else
{
std::clog << "Unknown SB " << *i << '\n';
return skip_sb(i);
}
// TODO: Handle some SB?
return skip_sb(i);
}
std::vector<char>::iterator rethinkmud::net::connections::telnet::skip_sb(std::vector<char>::iterator i)
{
while (static_cast<uint8_t>(*i) != IAC && static_cast<uint8_t>(*(i + 1)) != SE)
{
++i;
}
return i;
}
void rethinkmud::net::connections::telnet::erase_line(std::string& input)
{
std::string::const_reverse_iterator i;
for (i = std::crbegin(input); i != std::crend(input); ++i)
{
// Check for \r\n
if (*i == '\n' && *(i + 1) != std::crend(input) && *(i + 1) == '\r')
{
break;
}
// For safety, check for \n\r too
if (*i == '\r' && *(i + 1) != std::crend(input) && *(i + 1) == '\n')
{
break;
}
}
if (i == std::crend(input))
{
// No newline found, erase all
input.erase();
}
else
{
// Remove up until last newline
input = input.substr(0, std::crend(input) - i);
}
}
<commit_msg>Small fix for erasing lines, and use constant iterators<commit_after>#include "net/telnet.h"
#include "autoconf.h"
#define TELCMDS // To get the array of Telnet command names
#define TELOPTS // To get the array of Telnet option names
#include <arpa/telnet.h>
namespace
{
std::string trim(std::string const& str)
{
// Find the first non-whitespace character
auto first = std::find_if(std::cbegin(str), std::cend(str), [](char const& c)
{
return !std::isspace(c);
});
// Find the last non-whitespace character
auto last = std::find_if(std::crbegin(str), std::crend(str), [](char const& c)
{
return !std::isspace(c);
});
size_t first_pos = first != std::cend(str) ? first - std::cbegin(str) : 0;
size_t length = last != std::crend(str) ? (std::crend(str) - last) - first_pos : str.length();
return str.substr(first_pos, length);
}
}
static constexpr std::size_t telnet_option_count = 256;
struct rethinkmud::net::connections::telnet::telnet_info
{
// What we do, and don't do
bool options[telnet_option_count] = { false };
// Options we have sent and are waiting for reply on
bool sent_will[telnet_option_count] = { false };
bool sent_wont[telnet_option_count] = { false };
bool sent_do[telnet_option_count] = { false };
bool sent_dont[telnet_option_count] = { false };
};
void rethinkmud::net::connections::telnet::telnet_info_deleter::operator()(telnet_info* info)
{
delete info;
}
void rethinkmud::net::connections::telnet::start()
{
std::clog << "Starting telnet connection\n";
info_.reset(new telnet_info);
tcp::start();
}
void rethinkmud::net::connections::telnet::input(std::vector<char> data)
{
// Parse the input for telnet command sequence
// Copy the non-telnet data to a new container
// For now we assume that all sequences are complete
std::string input;
if (!buffer_.empty())
{
input = buffer_;
buffer_ = ""; // Clear the saved buffer from last call
}
for (auto i = std::begin(data); i != std::end(data); ++i)
{
if (static_cast<uint8_t>(*i) == IAC)
{
uint8_t command = static_cast<uint8_t>(*++i);
// TODO: Handle all this
switch (command)
{
case DO:
case DONT:
case WILL:
case WONT:
handle_option(command, *++i);
break;
case SB:
i = handle_sb(i);
break;
case AYT:
// TODO: Use the configured MUD name instead
write("RethinkMUD version " RETHINKMUD_VERSION " is alive and well.\r\n");
break;
case IP:
std::clog << "Closing connection to " << socket().remote_endpoint() << " (Telnet IP)\n";
close();
return;
case EC:
// Remove last character from input
input.erase(std::end(input) - 1);
break;
case EL:
// Remove last "line" from input
erase_line(input);
break;
// TODO: AO: Clear the output queue?
default:
if (TELCMD_OK(command))
std::clog << "Unhandled telnet command " << TELCMD(command) << '\n';
else
std::clog << "Unknown telnet command " << static_cast<unsigned>(command) << '\n';
break;
}
}
else
input += *i;
}
if (input.empty())
return;
std::istringstream iss{input};
std::string line;
while (std::getline(iss, line))
{
if (iss.eof())
{
// Not a complete line at the end of the buffer, save the data for the next call to this function
buffer_ = line;
}
else
{
// Trim leading and trailing white-space
line = trim(line);
if (line == "echo off")
echo_off();
else if (line == "echo on")
echo_on();
else
write("You wrote: " + line + "\r\n");
// TODO: Add input line to queue for command interpreter
}
}
}
void rethinkmud::net::connections::telnet::send_option(uint8_t command, uint8_t option)
{
uint8_t const data[] = {
IAC,
command,
option
};
write(data, sizeof(data));
}
void rethinkmud::net::connections::telnet::send_do(uint8_t option)
{
if (!info_->sent_do[option])
{
send_option(DO, option);
info_->sent_do[option] = true;
}
}
void rethinkmud::net::connections::telnet::send_dont(uint8_t option)
{
if (!info_->sent_dont[option])
{
send_option(DONT, option);
info_->sent_dont[option] = true;
}
}
void rethinkmud::net::connections::telnet::send_will(uint8_t option)
{
if (!info_->sent_will[option])
{
send_option(WILL, option);
info_->sent_will[option] = true;
}
}
void rethinkmud::net::connections::telnet::send_wont(uint8_t option)
{
if (!info_->sent_wont[option])
{
send_option(WONT, option);
info_->sent_wont[option] = true;
}
}
void rethinkmud::net::connections::telnet::echo_on()
{
send_wont(TELOPT_ECHO);
send_do(TELOPT_ECHO);
}
void rethinkmud::net::connections::telnet::echo_off()
{
send_will(TELOPT_ECHO);
send_dont(TELOPT_ECHO);
}
void rethinkmud::net::connections::telnet::handle_option(uint8_t command, uint8_t option)
{
// TODO: Handle all this
switch (command)
{
case DO:
if (info_->sent_will[option])
{
}
else if (info_->sent_wont[option])
{
}
else
{
send_wont(option);
}
break;
case DONT:
if (info_->sent_will[option])
{
}
else if (info_->sent_wont[option])
{
}
else
{
send_wont(option);
}
break;
case WILL:
if (info_->sent_do[option])
{
}
else if (info_->sent_dont[option])
{
}
else
{
send_dont(option);
}
break;
case WONT:
if (info_->sent_do[option])
{
}
else if (info_->sent_dont[option])
{
}
else
{
send_dont(option);
}
break;
default:
break;
}
}
std::vector<char>::iterator rethinkmud::net::connections::telnet::handle_sb(std::vector<char>::iterator i)
{
if (TELOPT_OK(*i))
{
std::clog << "Unhandled telnet SB " << TELOPT(*i) << '\n';
}
else
{
std::clog << "Unknown SB " << *i << '\n';
return skip_sb(i);
}
// TODO: Handle some SB?
return skip_sb(i);
}
std::vector<char>::iterator rethinkmud::net::connections::telnet::skip_sb(std::vector<char>::iterator i)
{
while (static_cast<uint8_t>(*i) != IAC && static_cast<uint8_t>(*(i + 1)) != SE)
{
++i;
}
return i;
}
void rethinkmud::net::connections::telnet::erase_line(std::string& input)
{
std::string::const_reverse_iterator i;
for (i = std::crbegin(input); i != std::crend(input); ++i)
{
// Check for \r\n
if (*i == '\n' && (i + 1) != std::crend(input) && *(i + 1) == '\r')
{
break;
}
// For safety, check for \n\r too
if (*i == '\r' && (i + 1) != std::crend(input) && *(i + 1) == '\n')
{
break;
}
}
if (i == std::crend(input))
{
// No newline found, erase all
input.erase();
}
else
{
// Remove up until last newline
input = input.substr(0, std::crend(input) - i);
}
}
<|endoftext|> |
<commit_before>#ifndef NEURO_TILE_HPP
#define NEURO_TILE_HPP
#include<memory>
#include<set>
#include<list>
#include"ui/Observable.hpp"
namespace neuro {
class Tile;
using TileP = std::shared_ptr< Tile >;
/**
* @brief All the possible types of tiles.
*/
enum class TileType {
INSTANT_ACTION,
HQ,
MODULE,
UNIT,
FOUNDATION
};
/**
* @brief The possible types of targetting.
*/
enum class TargettingType {
LOCAL,
FREE,
BLOB,
ADJECENT,
PATH,
AWAY,
HAND
};
/**
* @brief A class controlling the placement of a Tile.
*/
class Placing {
public:
/**
* @brief Whether the supplied list of arguments is suitable for this tile.
* @param[in] args A std::list of pointers to tiles which should be affected by the
* placing.
* @return Whether the given arguments are acceptable for this tile's
* placing.
*/
bool verifyArguments( std::list< TileP > args );
/**
* @brief Place the Tile ad affect the provided targets.
* @param[in,out] targets The tiles that might be modified by the placed
* tile.
* @return Whether the tile should end up on the board after the actions have
* been performed.
*/
bool placeTile( std::list< TileP > targets );
/**
* @brief Get a description of the possible shape of the targetted fields.
* @return A std::pair of an integer equal to the number of fields that will
* be targetted and a TargettingType defining the shape the fields can be in.
*/
std::pair< int, TargettingType > getTargettingDescription() const { return std::make_pair( targetsNumber, targettingType ); }
private:
TargettingType targettingType;
int targetsNumber;
std::string placeActions;
void dealDamage(int amount, TileP target);
void destroyTile(TileP target);
void moveTile(TileP target);
void pushTile(TileP target);
void castleTiles(TileP first, TileP second);
void terrorize();
};
/**
* @brief A class controlling the health, damage and destruction of a Tile.
*/
class Life {
public:
/**
* @brief Whether the tile is still alive.
*/
bool isAlive() const;
/**
* @brief Returns the full health of the tile.
*/
int getHealth() const;
/**
* @brief Returns the amount of damage dealt to the tile.
*/
int getDamage() const;
/**
* @brief Tries to deal the specified amount of damage to the tile.
* @param[in] dmg The amount of damage to deal.
* @param[in] ignoreRedirect Whether to ignore redirections.
*/
void dealDamage(int dmg, bool ignoreRedirect = false);
/**
* @brief Tries to destroy the tile.
* @param[in] ignoreRedirect Whether to ignore redirections.
*/
void destroy( bool ignoreRedirect = false );
/**
* @brief Registers an entity to which to redirect incoming attacks.
* @param[in] redir A pointer to the tile handling the damage.
*/
void registerRedirectior( TileP redir );
private:
bool alive;
int health;
int damage;
std::list< TileP > redirectors;
};
/**
* @brief A class representing an activated ability of a tile.
*/
class Ability {
public:
/**
* @brief Get the name of the ability.
* @return A std::string containing the name of the ability.
*/
std::string getName() const { return name; }
/**
* @brief Get a description of the ability.
* @return A std::string containing the description of the ability.
*/
std::string getDescription() const { return description; }
/**
* @brief Get a description of the possible shape of the targetted fields.
* @return A std::pair of an integer equal to the number of fields that will
* be targetted and a TargettingType defining the shape the fields can be in.
*/
std::pair< int, TargettingType > getTargettingDescription() const { return std::make_pair( targetsNumber, targettingType ); }
/**
* @brief Whether the supplied list of arguments is suitable for this ability.
* @param[in] args A std::list of pointers to tiles which should be affected by the
* abililty.
* @return Whether the given arguments are acceptable for this ability.
*/
bool verifyArguments( std::list< TileP > args );
/**
* @brief Use the ability on the specified tiles.
* @param[in] targets A std::list of pointers to tiles to be affected by the
* ability.
*/
void useAbility( std::list< TileP > targets );
private:
std::string name;
std::string description;
TargettingType targettingType;
int targetsNumber;
std::string abilityActions;
void push( TileP tile );
void substitute( TileP tile );
};
/**
* @brief A class representing an attack of a tile, usually in a direction.
*/
class Attack {
public:
/**
* @brief Get a description of the possible shape of the targetted fields.
* @return A std::pair of an integer equal to the number of fields that will
* be targetted and a TargettingType defining the shape the fields can be in.
*/
std::pair< int, TargettingType > getTargettingDescription() const { return std::make_pair( targetsNumber, targettingType ); }
/**
* @brief Whether the attack is melee.
*/
bool isMelee() const { return melee; }
/**
* @brief Whether the attack is ranged.
*/
bool isRanged() const { return ranged; }
/**
* @brief Execute the attack on the given tiles.
* @param[in] targets A std::list of affected tiles.
* @param[in] direction The direction in which the attack is executed.
* Important for some defensive abilities.
*/
void executeAttack( std::list< TileP > targets, int direction );
private:
TargettingType targettingType;
int targetsNumber;
bool melee;
bool ranged;
int strength;
std::string attackActions;
void hit( TileP tile, int direction );
};
/**
* @brief A class representing a passive modifier, usually in a direction.
*/
class Modifier {
public:
/**
* @brief Modify the given tile.
* @param[in] tile The tile to modify.
*/
void modifyTile( TileP tile );
private:
bool wholeBoard;
std::string modifyActions;
};
/**
* @brief A class representing the initiative of a tile.
*/
class Initiative {
public:
/**
* @brief Whether the tile has initiative at the given battle stage.
*/
bool hasInitiative( int battleStage ) { return ( initiative.count( battleStage ) > 0 ); }
/**
* @brief Add one initiative after every existing one.
*/
void duplicateInitiatives();
/**
* @brief Modify all the initiatives.
* @param[in] change The amount by which to modify the initiative.
* @param[in] fix Whether to make the initiative unmodifiable. Defaults to
* false.
*/
void modifyInitiatives( int change, bool fix = false );
private:
bool modifiable;
std::set< int > initiative;
};
/**
* @brief A tile to be created in an army and later played.
* @todo Lists of abilities:
* -playing
* -on board
* -permanent edge x6
* -battle edge x6
*/
class Tile : public ui::Observable<Tile> {
public:
/**
* @brief Construct a tile with a specific type.
* @param[in] type Type of the tile.
*/
Tile(TileType type) : type(type) {}
/**
* @brief Returns the type of the tile.
*/
TileType getType() const { return type; }
/**
* @brief Returns the owner of the tile.
*/
int getOwner() const { return owner; }
/**
* @brief Returns the current controller of the tile.
*/
int getController() const { return controller; }
/**
* @brief Tells whether the tile is considered a solid object.
*/
bool isSolid() const { return !( (type == TileType::INSTANT_ACTION) || (type == TileType::FOUNDATION) ); }
/**
* @brief Sets the owner and original controller of the tile.
* @param[in] player The player to become the owner.
*/
void setOwner(int player) {
owner = player;
controller = player;
}
/**
* @brief Changes the controller of the tile.
* @param[in] player The new controller of the tile.
*/
void changeController(int player) {
controller = player;
sigModified(*this);
}
/**
* @brief At which player's turn should terror end. No terror if -1.
*/
static int terrorEndOnPlayer;
private:
TileType type;
int owner;
int controller;
Placing placing;
std::array< std::list< Attack >, 6 > attacksInDirections;
std::list< Attack > otherAttacks;
std::array< std::list< Modifier >, 6 > modifiersInDirections;
std::list< Modifier > otherModifiers;
std::array< std::list< Ability >, 6 > onBattleStartInDirections;
std::list< Ability > otherOnBattleStart;
std::list< Ability > activeAbilities;
Life life;
Initiative initiative;
};
using TileP = std::shared_ptr< Tile >;
}
#endif
<commit_msg>Completed initial rewrite of Tile<commit_after>#ifndef NEURO_TILE_HPP
#define NEURO_TILE_HPP
#include<memory>
#include<set>
#include<list>
#include"ui/Observable.hpp"
namespace neuro {
class Tile;
using TileP = std::shared_ptr< Tile >;
/**
* @brief All the possible types of tiles.
*/
enum class TileType {
INSTANT_ACTION,
HQ,
MODULE,
UNIT,
FOUNDATION
};
/**
* @brief The possible types of targetting.
*/
enum class TargettingType {
LOCAL,
FREE,
BLOB,
ADJECENT,
PATH,
AWAY,
HAND
};
/**
* @brief A tile to be created in an army and later played.
* @todo Fill in functions while creating armies.
*/
class Tile : public ui::Observable<Tile> {
public:
/**
* @brief A class controlling the placement of a Tile.
*/
class Placing {
public:
/**
* @brief Whether the supplied list of arguments is suitable for this tile.
* @param[in] args A std::list of pointers to tiles which should be affected by the
* placing.
* @return Whether the given arguments are acceptable for this tile's
* placing.
*/
bool verifyArguments( std::list< TileP > args );
/**
* @brief Place the Tile ad affect the provided targets.
* @param[in,out] targets The tiles that might be modified by the placed
* tile.
* @return Whether the tile should end up on the board after the actions have
* been performed.
*/
bool placeTile( std::list< TileP > targets );
/**
* @brief Get a description of the possible shape of the targetted fields.
* @return A std::pair of an integer equal to the number of fields that will
* be targetted and a TargettingType defining the shape the fields can be in.
*/
std::pair< int, TargettingType > getTargettingDescription() const { return std::make_pair( targetsNumber, targettingType ); }
private:
TargettingType targettingType;
int targetsNumber;
std::string placeActions;
void dealDamage(int amount, TileP target);
void destroyTile(TileP target);
void moveTile(TileP target);
void pushTile(TileP target);
void castleTiles(TileP first, TileP second);
void terrorize();
};
/**
* @brief A class controlling the health, damage and destruction of a Tile.
*/
class Life {
public:
/**
* @brief Whether the tile is still alive.
*/
bool isAlive() const;
/**
* @brief Returns the full health of the tile.
*/
int getHealth() const;
/**
* @brief Returns the amount of damage dealt to the tile.
*/
int getDamage() const;
/**
* @brief Tries to deal the specified amount of damage to the tile.
* @param[in] dmg The amount of damage to deal.
* @param[in] ignoreRedirect Whether to ignore redirections.
*/
void dealDamage(int dmg, bool ignoreRedirect = false);
/**
* @brief Tries to destroy the tile.
* @param[in] ignoreRedirect Whether to ignore redirections.
*/
void destroy( bool ignoreRedirect = false );
/**
* @brief Registers an entity to which to redirect incoming attacks.
* @param[in] redir A pointer to the tile handling the damage.
*/
void registerRedirectior( TileP redir );
private:
bool alive;
int health;
int damage;
std::list< TileP > redirectors;
};
/**
* @brief A class representing an activated ability of a tile.
*/
class Ability {
public:
/**
* @brief Get the name of the ability.
* @return A std::string containing the name of the ability.
*/
std::string getName() const { return name; }
/**
* @brief Get a description of the ability.
* @return A std::string containing the description of the ability.
*/
std::string getDescription() const { return description; }
/**
* @brief Get a description of the possible shape of the targetted fields.
* @return A std::pair of an integer equal to the number of fields that will
* be targetted and a TargettingType defining the shape the fields can be in.
*/
std::pair< int, TargettingType > getTargettingDescription() const { return std::make_pair( targetsNumber, targettingType ); }
/**
* @brief Whether the supplied list of arguments is suitable for this ability.
* @param[in] args A std::list of pointers to tiles which should be affected by the
* abililty.
* @return Whether the given arguments are acceptable for this ability.
*/
bool verifyArguments( std::list< TileP > args );
/**
* @brief Use the ability on the specified tiles.
* @param[in] targets A std::list of pointers to tiles to be affected by the
* ability.
*/
void useAbility( std::list< TileP > targets );
private:
std::string name;
std::string description;
TargettingType targettingType;
int targetsNumber;
std::string abilityActions;
void push( TileP tile );
void substitute( TileP tile );
};
/**
* @brief A class representing an attack of a tile, usually in a direction.
*/
class Attack {
public:
/**
* @brief Get a description of the possible shape of the targetted fields.
* @return A std::pair of an integer equal to the number of fields that will
* be targetted and a TargettingType defining the shape the fields can be in.
*/
std::pair< int, TargettingType > getTargettingDescription() const { return std::make_pair( targetsNumber, targettingType ); }
/**
* @brief Whether the attack is melee.
*/
bool isMelee() const { return melee; }
/**
* @brief Whether the attack is ranged.
*/
bool isRanged() const { return ranged; }
/**
* @brief Execute the attack on the given tiles.
* @param[in] targets A std::list of affected tiles.
* @param[in] direction The direction in which the attack is executed.
* Important for some defensive abilities.
*/
void executeAttack( std::list< TileP > targets, int direction );
private:
TargettingType targettingType;
int targetsNumber;
bool melee;
bool ranged;
int strength;
std::string attackActions;
void hit( TileP tile, int direction );
};
/**
* @brief A class representing a passive modifier, usually in a direction.
*/
class Modifier {
public:
/**
* @brief Modify the given tile.
* @param[in] tile The tile to modify.
*/
void modifyTile( TileP tile );
private:
std::string modifyActions;
};
/**
* @brief A class representing the initiative of a tile.
*/
class Initiative {
public:
/**
* @brief Whether the tile has initiative at the given battle stage.
*/
bool hasInitiative( int battleStage ) { return ( initiative.count( battleStage ) > 0 ); }
/**
* @brief Add one initiative after every existing one.
*/
void duplicateInitiatives();
/**
* @brief Modify all the initiatives.
* @param[in] change The amount by which to modify the initiative.
* @param[in] fix Whether to make the initiative unmodifiable. Defaults to
* false.
*/
void modifyInitiatives( int change, bool fix = false );
private:
bool modifiable;
std::set< int > initiative;
};
/**
* @brief Construct a tile with a specific type.
* @param[in] type Type of the tile.
*/
Tile(TileType type) : type(type) {}
/**
* @brief Returns the type of the tile.
*/
TileType getType() const { return type; }
/**
* @brief Returns the owner of the tile.
*/
int getOwner() const { return owner; }
/**
* @brief Returns the current controller of the tile.
*/
int getController() const { return controller; }
/**
* @brief Tells whether the tile is considered a solid object.
*/
bool isSolid() const { return !( (type == TileType::INSTANT_ACTION) || (type == TileType::FOUNDATION) ); }
/**
* @brief Sets the owner and original controller of the tile.
* @param[in] player The player to become the owner.
*/
void setOwner(int player) {
owner = player;
controller = player;
}
/**
* @brief Changes the controller of the tile.
* @param[in] player The new controller of the tile.
*/
void changeController(int player) {
controller = player;
sigModified(*this);
}
/**
* @brief Attempt to deal damage to the tile.
* @param[in] strength The amount of damage.
* @param[in] direction The direction from which the damage is coming. The
* default is -1, meaning no direction.
* @param[in] ranged Whether the attack is ranged, defaults to false.
*/
void dealDamage( int strength, int direction = -1, bool ranged = false );
/**
* @brief The object responsible for placing this tile.
*/
Placing placing;
/**
* @brief Abilities to use at the start of every battle in all directions.
*/
std::array< std::list< Ability >, 6 > onBattleStartInDirections;
/**
* @brief Abilities to use at the start of every battle.
*/
std::list< Ability > otherOnBattleStart;
/**
* @brief Attacks to launch at every own initiative in all directions.
*/
std::array< std::list< Attack >, 6 > attacksInDirections;
/**
* @brief Attacks to launch at every own initiative.
*/
std::list< Attack > otherAttacks;
/**
* @brief Modifiers to tiles in all directions.
*/
std::array< std::list< Modifier >, 6 > modifiersInDirections;
/**
* @brief Modifiers to tiles anywhere.
*/
std::list< Modifier > otherModifiers;
/**
* @brief Abilities the controller may use in every turn.
*/
std::list< Ability > activeAbilities;
/**
* @brief Abilities that might affect incoming attacks.
*/
std::array< std::list< Ability >, 6 > defensiveAbilities;
/**
* @brief The life of the tile.
*/
Life life;
/**
* @brief The initiative of the tile.
*/
Initiative initiative;
/**
* @brief At which player's turn should terror end. No terror if -1.
*/
static int terrorEndOnPlayer;
private:
TileType type;
int owner;
int controller;
};
using TileP = std::shared_ptr< Tile >;
}
#endif
<|endoftext|> |
<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES
#include "vendor/better-enums/enum_strict.hpp"
#include "vendor/fmt/format.hpp"
#include "vendor/range/v3/view/transform.hpp"
#include "vendor/docopt/docopt.hpp"
#include "vendor/range/v3/view/filter.hpp"
#include "vendor/range/v3/to_container.hpp"
#include "vendor/json.hpp"
#include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp>
#include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/match_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/exception_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/ast_node.hpp>
#include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp>
#include <thewizardplusplus/wizard_parser/lexer/token.hpp>
#include <thewizardplusplus/wizard_parser/utilities/utilities.hpp>
#include <regex>
#include <cstdint>
#include <stdexcept>
#include <cstddef>
#include <iostream>
#include <string>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <exception>
using namespace thewizardplusplus::wizard_parser::lexer;
using namespace thewizardplusplus::wizard_parser::parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
using namespace thewizardplusplus::wizard_parser::utilities;
const auto usage =
R"(Usage:
./example -h | --help
./example [-t | --tokens] [--] <expression>
./example [-t | --tokens] (-s | --stdin)
Options:
-h, --help - show this message;
-t, --tokens - show a token list instead an AST;
-s, --stdin - read an expression from stdin.)";
const auto lexemes = lexeme_group{
{std::regex{"=="}, "equal"},
{std::regex{"/="}, "not_equal"},
{std::regex{"<="}, "less_or_equal"},
{std::regex{"<"}, "less"},
{std::regex{">="}, "great_or_equal"},
{std::regex{">"}, "great"},
{std::regex{R"(\+)"}, "plus"},
{std::regex{"-"}, "minus"},
{std::regex{R"(\*)"}, "star"},
{std::regex{"/"}, "slash"},
{std::regex{"%"}, "percent"},
{std::regex{R"(\()"}, "opening_parenthesis"},
{std::regex{R"(\))"}, "closing_parenthesis"},
{std::regex{","}, "comma"},
{std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"},
{std::regex{R"([A-Za-z_]\w*)"}, "base_identifier"},
{std::regex{R"(\s+)"}, "whitespace"}
};
BETTER_ENUM(entity_type, std::uint8_t, symbol, token, eoi)
template<entity_type::_integral type>
struct unexpected_entity_exception final: std::runtime_error {
static_assert(entity_type::_is_valid(type));
explicit unexpected_entity_exception(const std::size_t& offset);
};
template<entity_type::_integral type>
unexpected_entity_exception<type>::unexpected_entity_exception(
const std::size_t& offset
):
std::runtime_error{fmt::format(
"unexpected {:s} (offset: {:d})",
entity_type::_from_integral(type)._to_string(),
offset
)}
{}
void stop(const int& code, std::ostream& stream, const std::string& message) {
stream << fmt::format("{:s}\n", message);
std::exit(code);
}
rule_parser::pointer make_parser() {
const auto expression_dummy = dummy();
RULE(key_words) = "not"_v | "and"_v | "or"_v;
RULE(identifier) = "base_identifier"_t - key_words;
RULE(function_call) = identifier >> &"("_v >>
-(expression_dummy >> *(&","_v >> expression_dummy))
>> &")"_v;
RULE(atom) = "number"_t
| function_call
| identifier
| (&"("_v >> expression_dummy >> &")"_v);
RULE(unary) = *("-"_v | "not"_v) >> atom;
RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary);
RULE(sum) = product >> *(("+"_v | "-"_v) >> product);
RULE(comparison) = sum >> *(("<"_v | "<="_v | ">"_v | ">="_v) >> sum);
RULE(equality) = comparison >> *(("=="_v | "/="_v) >> comparison);
RULE(conjunction) = equality >> *(&"and"_v >> equality);
RULE(disjunction) = conjunction >> *(&"or"_v >> conjunction);
expression_dummy->set_parser(disjunction);
return disjunction;
}
ast_node walk_ast(
const ast_node& ast,
const std::function<ast_node(const ast_node&)>& handler
) {
const auto new_ast = handler(ast);
const auto new_children = new_ast.children
| ranges::view::transform([&] (const auto& ast) {
return walk_ast(ast, handler);
});
return {new_ast.type, new_ast.value, new_children, new_ast.offset};
}
int main(int argc, char* argv[]) try {
const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);
const auto code = options.at("--stdin").asBool()
? std::string{std::istreambuf_iterator<char>{std::cin}, {}}
: options.at("<expression>").asString();
const auto [tokens, rest_offset] = tokenize(lexemes, code);
if (rest_offset != code.size()) {
throw unexpected_entity_exception<entity_type::symbol>{rest_offset};
}
auto cleaned_tokens = tokens
| ranges::view::filter([] (const auto& token) {
return token.type != "whitespace";
})
| ranges::to_<token_group>();
if (options.at("--tokens").asBool()) {
stop(EXIT_SUCCESS, std::cout, nlohmann::json(cleaned_tokens).dump());
}
const auto parser = make_parser();
const auto ast = parser->parse(cleaned_tokens);
if (!ast.rest_tokens.empty()) {
throw unexpected_entity_exception<entity_type::token>{
get_offset(ast.rest_tokens)
};
}
if (!ast.node) {
throw unexpected_entity_exception<entity_type::eoi>{code.size()};
}
const auto transformed_ast = walk_ast(*ast.node, [&] (const auto& ast) {
const auto offset = ast.offset && *ast.offset == integral_infinity
? code.size()
: ast.offset;
return ast_node{ast.type, ast.value, ast.children, offset};
});
stop(EXIT_SUCCESS, std::cout, nlohmann::json(transformed_ast).dump());
} catch (const std::exception& exception) {
stop(EXIT_FAILURE, std::cerr, fmt::format("error: {:s}", exception.what()));
}
<commit_msg>Fix a code style in the example<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES
#include "vendor/better-enums/enum_strict.hpp"
#include "vendor/fmt/format.hpp"
#include "vendor/range/v3/view/transform.hpp"
#include "vendor/docopt/docopt.hpp"
#include "vendor/range/v3/view/filter.hpp"
#include "vendor/range/v3/to_container.hpp"
#include "vendor/json.hpp"
#include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp>
#include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/match_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/exception_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/ast_node.hpp>
#include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp>
#include <thewizardplusplus/wizard_parser/lexer/token.hpp>
#include <thewizardplusplus/wizard_parser/utilities/utilities.hpp>
#include <regex>
#include <cstdint>
#include <stdexcept>
#include <cstddef>
#include <iostream>
#include <string>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <exception>
using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
const auto usage =
R"(Usage:
./example -h | --help
./example [-t | --tokens] [--] <expression>
./example [-t | --tokens] (-s | --stdin)
Options:
-h, --help - show this message;
-t, --tokens - show a token list instead an AST;
-s, --stdin - read an expression from stdin.)";
const auto lexemes = lexer::lexeme_group{
{std::regex{"=="}, "equal"},
{std::regex{"/="}, "not_equal"},
{std::regex{"<="}, "less_or_equal"},
{std::regex{"<"}, "less"},
{std::regex{">="}, "great_or_equal"},
{std::regex{">"}, "great"},
{std::regex{R"(\+)"}, "plus"},
{std::regex{"-"}, "minus"},
{std::regex{R"(\*)"}, "star"},
{std::regex{"/"}, "slash"},
{std::regex{"%"}, "percent"},
{std::regex{R"(\()"}, "opening_parenthesis"},
{std::regex{R"(\))"}, "closing_parenthesis"},
{std::regex{","}, "comma"},
{std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"},
{std::regex{R"([A-Za-z_]\w*)"}, "base_identifier"},
{std::regex{R"(\s+)"}, "whitespace"}
};
BETTER_ENUM(entity_type, std::uint8_t, symbol, token, eoi)
template<entity_type::_integral type>
struct unexpected_entity_exception final: std::runtime_error {
static_assert(entity_type::_is_valid(type));
explicit unexpected_entity_exception(const std::size_t& offset);
};
template<entity_type::_integral type>
unexpected_entity_exception<type>::unexpected_entity_exception(
const std::size_t& offset
):
std::runtime_error{fmt::format(
"unexpected {:s} (offset: {:d})",
entity_type::_from_integral(type)._to_string(),
offset
)}
{}
void stop(const int& code, std::ostream& stream, const std::string& message) {
stream << fmt::format("{:s}\n", message);
std::exit(code);
}
parser::rule_parser::pointer make_parser() {
const auto expression_dummy = parser::dummy();
RULE(key_words) = "not"_v | "and"_v | "or"_v;
RULE(identifier) = "base_identifier"_t - key_words;
RULE(function_call) = identifier >> &"("_v >>
-(expression_dummy >> *(&","_v >> expression_dummy))
>> &")"_v;
RULE(atom) = "number"_t
| function_call
| identifier
| (&"("_v >> expression_dummy >> &")"_v);
RULE(unary) = *("-"_v | "not"_v) >> atom;
RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary);
RULE(sum) = product >> *(("+"_v | "-"_v) >> product);
RULE(comparison) = sum >> *(("<"_v | "<="_v | ">"_v | ">="_v) >> sum);
RULE(equality) = comparison >> *(("=="_v | "/="_v) >> comparison);
RULE(conjunction) = equality >> *(&"and"_v >> equality);
RULE(disjunction) = conjunction >> *(&"or"_v >> conjunction);
expression_dummy->set_parser(disjunction);
return disjunction;
}
parser::ast_node walk_ast(
const parser::ast_node& ast,
const std::function<parser::ast_node(const parser::ast_node&)>& handler
) {
const auto new_ast = handler(ast);
const auto new_children = new_ast.children
| ranges::view::transform([&] (const auto& ast) {
return walk_ast(ast, handler);
});
return {new_ast.type, new_ast.value, new_children, new_ast.offset};
}
int main(int argc, char* argv[]) try {
const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);
const auto code = options.at("--stdin").asBool()
? std::string{std::istreambuf_iterator<char>{std::cin}, {}}
: options.at("<expression>").asString();
const auto [tokens, rest_offset] = tokenize(lexemes, code);
if (rest_offset != code.size()) {
throw unexpected_entity_exception<entity_type::symbol>{rest_offset};
}
auto cleaned_tokens = tokens
| ranges::view::filter([] (const auto& token) {
return token.type != "whitespace";
})
| ranges::to_<lexer::token_group>();
if (options.at("--tokens").asBool()) {
stop(EXIT_SUCCESS, std::cout, nlohmann::json(cleaned_tokens).dump());
}
const auto ast = make_parser()->parse(cleaned_tokens);
if (!ast.rest_tokens.empty()) {
throw unexpected_entity_exception<entity_type::token>{
get_offset(ast.rest_tokens)
};
}
if (!ast.node) {
throw unexpected_entity_exception<entity_type::eoi>{code.size()};
}
const auto transformed_ast = walk_ast(*ast.node, [&] (const auto& ast) {
const auto offset = ast.offset == utilities::integral_infinity
? code.size()
: ast.offset;
return parser::ast_node{ast.type, ast.value, ast.children, offset};
});
stop(EXIT_SUCCESS, std::cout, nlohmann::json(transformed_ast).dump());
} catch (const std::exception& exception) {
stop(EXIT_FAILURE, std::cerr, fmt::format("error: {:s}", exception.what()));
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cassert>
using namespace std;
template <typename T>
class SmartPtr {
public:
explicit SmartPtr(T *p = nullptr)
: count_(new size_t(1)), obj_ptr_(p) { }
~SmartPtr() {
dispose();
}
SmartPtr(const SmartPtr<T> &other)
:count_(other.count_),
obj_ptr_(other.obj_ptr_)
{ ++*count_; }
SmartPtr<T>& operator=(const SmartPtr<T> &rhs) {
++(*rhs.count_); // in case self copy
dispose();
count_ = rhs.count_;
obj_ptr_ = rhs.obj_ptr_;
return *this;
}
T& operator*() const { return *obj_ptr_; }
T* operator->() const { return obj_ptr_; }
size_t count() const { return *count_; }
T* get() const { return obj_ptr_; }
explicit operator bool() { return obj_ptr_ != nullptr; }
void swap(SmartPtr<T> &other) {
std::swap(obj_ptr_, other.obj_ptr_);
//std::swap(obj_ptr_, other.get()); // no matching swap!!! ???
std::swap(count_, other.count_);
}
void reset(T *ptr = nullptr) {
dispose();
obj_ptr_ = ptr;
count_ = new size_t(1);
}
bool unique() { return *count_ == 1; }
private:
void dispose() {
if (--*count_ == 0) {
delete count_;
delete obj_ptr_;
}
}
size_t *count_;
T *obj_ptr_;
};
int main()
{
cout << "TEST SMARTPTR" << endl;
SmartPtr<int> sptr, sptr2;
assert(sptr.unique());
sptr.swap(sptr2);
assert(!sptr);
SmartPtr<int> sptr3(new int(2));
cout << "TEST SMARTPTR operator=()" << endl;
sptr = sptr3;
assert(sptr);
assert(!sptr.unique());
assert(sptr3);
cout << "TEST SMARTPTR reset" << endl;
sptr3.reset();
assert(sptr);
assert(sptr.unique());
cout << "TEST SMARTPTR copy constructor" << endl;
SmartPtr<int> sptr4(sptr3);
assert(!sptr4);
assert(!sptr4.unique());
assert(sptr4.count() == 2);
return 0;
}
<commit_msg>add why std::swap(obj_ptr_, other.get()) failed<commit_after>#include <iostream>
#include <cassert>
using namespace std;
template <typename T>
class SmartPtr {
public:
explicit SmartPtr(T *p = nullptr)
: count_(new size_t(1)), obj_ptr_(p) { }
~SmartPtr() {
dispose();
}
SmartPtr(const SmartPtr<T> &other)
:count_(other.count_),
obj_ptr_(other.obj_ptr_)
{ ++*count_; }
SmartPtr<T>& operator=(const SmartPtr<T> &rhs) {
++(*rhs.count_); // in case self copy
dispose();
count_ = rhs.count_;
obj_ptr_ = rhs.obj_ptr_;
return *this;
}
T& operator*() const { return *obj_ptr_; }
T* operator->() const { return obj_ptr_; }
size_t count() const { return *count_; }
T* get() const { return obj_ptr_; }
explicit operator bool() { return obj_ptr_ != nullptr; }
void swap(SmartPtr<T> &other) {
std::swap(obj_ptr_, other.obj_ptr_);
// TRUTH is other.get() return an rvalue, rvalue cannot be bind
// to non-const reference
// if you write :
// T *tmp = other.get();
// std::swap(obj_ptr_, tmp);
// this get passed
//
// std::swap(obj_ptr_, other.get()); // no matching swap!!!
std::swap(count_, other.count_);
}
void reset(T *ptr = nullptr) {
dispose();
obj_ptr_ = ptr;
count_ = new size_t(1);
}
bool unique() { return *count_ == 1; }
private:
void dispose() {
if (--*count_ == 0) {
delete count_;
delete obj_ptr_;
}
}
size_t *count_;
T *obj_ptr_;
};
int main()
{
cout << "TEST SMARTPTR" << endl;
SmartPtr<int> sptr, sptr2;
assert(sptr.unique());
sptr.swap(sptr2);
assert(!sptr);
SmartPtr<int> sptr3(new int(2));
cout << "TEST SMARTPTR operator=()" << endl;
sptr = sptr3;
assert(sptr);
assert(!sptr.unique());
assert(sptr3);
cout << "TEST SMARTPTR reset" << endl;
sptr3.reset();
assert(sptr);
assert(sptr.unique());
cout << "TEST SMARTPTR copy constructor" << endl;
SmartPtr<int> sptr4(sptr3);
assert(!sptr4);
assert(!sptr4.unique());
assert(sptr4.count() == 2);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED
#define METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED
#include "Methcla/Audio.hpp"
#include "Methcla/Memory.hpp"
#include <cstring>
namespace Methcla { namespace Audio {
class MultiChannelBuffer
{
public:
MultiChannelBuffer(size_t numChannels, size_t numFrames)
: m_numChannels(numChannels)
, m_numFrames(numFrames)
, m_data(makeBuffers(m_numChannels, m_numFrames))
{ }
~MultiChannelBuffer()
{
freeBuffers(m_numChannels, m_data);
}
size_t numChannels() const
{
return m_numChannels;
}
size_t numFrames() const
{
return m_numFrames;
}
Methcla_AudioSample* const* data()
{
return m_data;
}
const Methcla_AudioSample* const* data() const
{
return m_data;
}
void deinterleave(const Methcla_AudioSample* src, size_t srcFrames)
{
Methcla::Audio::deinterleave(data(), src, numChannels(), std::min(numFrames(), srcFrames));
}
void deinterleave(const Methcla_AudioSample* src)
{
deinterleave(src, numFrames());
}
void interleave(Methcla_AudioSample* dst, size_t dstFrames) const
{
Methcla::Audio::interleave(dst, data(), numChannels(), std::min(numFrames(), dstFrames));
}
void interleave(Methcla_AudioSample* dst) const
{
interleave(dst, numFrames());
}
void zero()
{
for (size_t i=0; i < numChannels(); i++)
{
std::memset(data()[i], 0, numFrames() * sizeof(Methcla_AudioSample));
}
}
inline static Methcla_AudioSample** makeBuffers(size_t numChannels, size_t numFrames)
{
if (numChannels > 0)
{
Methcla_AudioSample** buffers = Methcla::Memory::allocOf<Methcla_AudioSample*>(numChannels);
for (size_t i=0; i < numChannels; i++)
{
buffers[i] = numFrames > 0
? Methcla::Memory::allocAlignedOf<Methcla_AudioSample>(Methcla::Memory::kSIMDAlignment, numFrames)
: nullptr;
}
return buffers;
}
return nullptr;
}
inline static void freeBuffers(size_t numChannels, Methcla_AudioSample** buffers)
{
if (numChannels > 0 && buffers != nullptr)
{
for (size_t i=0; i < numChannels; i++)
{
Methcla::Memory::free(buffers[i]);
}
Memory::free(buffers);
}
}
private:
size_t m_numChannels;
size_t m_numFrames;
Methcla_AudioSample** m_data;
};
} }
#endif // METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED
<commit_msg>Add numSamples method to MultiChannelBuffer<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED
#define METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED
#include "Methcla/Audio.hpp"
#include "Methcla/Memory.hpp"
#include <cstring>
namespace Methcla { namespace Audio {
class MultiChannelBuffer
{
public:
MultiChannelBuffer(size_t numChannels, size_t numFrames)
: m_numChannels(numChannels)
, m_numFrames(numFrames)
, m_data(makeBuffers(m_numChannels, m_numFrames))
{ }
~MultiChannelBuffer()
{
freeBuffers(m_numChannels, m_data);
}
size_t numChannels() const
{
return m_numChannels;
}
size_t numFrames() const
{
return m_numFrames;
}
size_t numSamples() const
{
return numChannels() * numFrames();
}
Methcla_AudioSample* const* data()
{
return m_data;
}
const Methcla_AudioSample* const* data() const
{
return m_data;
}
void deinterleave(const Methcla_AudioSample* src, size_t srcFrames)
{
Methcla::Audio::deinterleave(data(), src, numChannels(), std::min(numFrames(), srcFrames));
}
void deinterleave(const Methcla_AudioSample* src)
{
deinterleave(src, numFrames());
}
void interleave(Methcla_AudioSample* dst, size_t dstFrames) const
{
Methcla::Audio::interleave(dst, data(), numChannels(), std::min(numFrames(), dstFrames));
}
void interleave(Methcla_AudioSample* dst) const
{
interleave(dst, numFrames());
}
void zero()
{
for (size_t i=0; i < numChannels(); i++)
{
std::memset(data()[i], 0, numFrames() * sizeof(Methcla_AudioSample));
}
}
inline static Methcla_AudioSample** makeBuffers(size_t numChannels, size_t numFrames)
{
if (numChannels > 0)
{
Methcla_AudioSample** buffers = Methcla::Memory::allocOf<Methcla_AudioSample*>(numChannels);
for (size_t i=0; i < numChannels; i++)
{
buffers[i] = numFrames > 0
? Methcla::Memory::allocAlignedOf<Methcla_AudioSample>(Methcla::Memory::kSIMDAlignment, numFrames)
: nullptr;
}
return buffers;
}
return nullptr;
}
inline static void freeBuffers(size_t numChannels, Methcla_AudioSample** buffers)
{
if (numChannels > 0 && buffers != nullptr)
{
for (size_t i=0; i < numChannels; i++)
{
Methcla::Memory::free(buffers[i]);
}
Memory::free(buffers);
}
}
private:
size_t m_numChannels;
size_t m_numFrames;
Methcla_AudioSample** m_data;
};
} }
#endif // METHCLA_AUDIO_MULTICHANNELBUFFER_HPP_INCLUDED
<|endoftext|> |
<commit_before>#ifndef _TCUINTERVAL_HPP
#define _TCUINTERVAL_HPP
/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 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 Interval arithmetic and floating point precisions.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "deMath.h"
#include <iostream>
#include <limits>
#define TCU_INFINITY (::std::numeric_limits<float>::infinity())
#define TCU_NAN (::std::numeric_limits<float>::quiet_NaN())
namespace tcu
{
// RAII context for temporarily changing the rounding mode
class ScopedRoundingMode
{
public:
ScopedRoundingMode (deRoundingMode mode)
: m_oldMode (deGetRoundingMode()) { deSetRoundingMode(mode); }
ScopedRoundingMode (void) : m_oldMode (deGetRoundingMode()) {}
~ScopedRoundingMode (void) { deSetRoundingMode(m_oldMode); }
private:
ScopedRoundingMode (const ScopedRoundingMode&);
ScopedRoundingMode& operator= (const ScopedRoundingMode&);
const deRoundingMode m_oldMode;
};
class Interval
{
public:
// Empty interval.
Interval (void)
: m_hasNaN (false)
, m_lo (TCU_INFINITY)
, m_hi (-TCU_INFINITY)
, m_warningLo (-TCU_INFINITY)
, m_warningHi (TCU_INFINITY) {}
// Intentionally not explicit. Conversion from double to Interval is common
// and reasonable.
Interval (double val)
: m_hasNaN (!!deIsNaN(val))
, m_lo (m_hasNaN ? TCU_INFINITY : val)
, m_hi (m_hasNaN ? -TCU_INFINITY : val)
, m_warningLo (-TCU_INFINITY)
, m_warningHi (TCU_INFINITY) {}
Interval(bool hasNaN_, double lo_, double hi_)
: m_hasNaN(hasNaN_), m_lo(lo_), m_hi(hi_), m_warningLo(-TCU_INFINITY), m_warningHi(TCU_INFINITY) {}
Interval(bool hasNaN_, double lo_, double hi_, double wlo_, double whi_)
: m_hasNaN(hasNaN_), m_lo(lo_), m_hi(hi_), m_warningLo(wlo_), m_warningHi(whi_) {}
Interval (const Interval& a, const Interval& b)
: m_hasNaN (a.m_hasNaN || b.m_hasNaN)
, m_lo (de::min(a.lo(), b.lo()))
, m_hi (de::max(a.hi(), b.hi()))
, m_warningLo (de::min(a.warningLo(), b.warningLo()))
, m_warningHi (de::max(a.warningHi(), b.warningHi())) {}
double length (void) const { return m_hi - m_lo; }
double lo (void) const { return m_lo; }
double hi (void) const { return m_hi; }
double warningLo (void) const { return m_warningLo; }
double warningHi (void) const { return m_warningHi; }
bool hasNaN (void) const { return m_hasNaN; }
Interval nan (void) const { return m_hasNaN ? TCU_NAN : Interval(); }
bool empty (void) const { return m_lo > m_hi; }
bool isFinite (void) const { return m_lo > -TCU_INFINITY && m_hi < TCU_INFINITY; }
bool isOrdinary (void) const { return !hasNaN() && !empty() && isFinite(); }
void warning (double lo, double hi)
{
m_warningLo = lo;
m_warningHi = hi;
}
Interval operator| (const Interval& other) const
{
return Interval(m_hasNaN || other.m_hasNaN,
de::min(m_lo, other.m_lo),
de::max(m_hi, other.m_hi),
de::min(m_warningLo, other.m_warningLo),
de::max(m_warningHi, other.m_warningHi));
}
Interval& operator|= (const Interval& other)
{
return (*this = *this | other);
}
Interval operator& (const Interval& other) const
{
return Interval(m_hasNaN && other.m_hasNaN,
de::max(m_lo, other.m_lo),
de::min(m_hi, other.m_hi),
de::max(m_warningLo, other.m_warningLo),
de::min(m_warningHi, other.m_warningHi));
}
Interval& operator&= (const Interval& other)
{
return (*this = *this & other);
}
bool contains (const Interval& other) const
{
return (other.lo() >= lo() && other.hi() <= hi() &&
(!other.hasNaN() || hasNaN()));
}
bool containsWarning(const Interval& other) const
{
return (other.lo() >= warningLo() && other.hi() <= warningHi() &&
(!other.hasNaN() || hasNaN()));
}
bool intersects (const Interval& other) const
{
return ((other.hi() >= lo() && other.lo() <= hi()) ||
(other.hasNaN() && hasNaN()));
}
Interval operator- (void) const
{
return Interval(hasNaN(), -hi(), -lo(), -warningHi(), -warningLo());
}
static Interval unbounded (bool nan = false)
{
return Interval(nan, -TCU_INFINITY, TCU_INFINITY);
}
double midpoint (void) const
{
return 0.5 * (hi() + lo()); // returns NaN when not bounded
}
bool operator== (const Interval& other) const
{
return ((m_hasNaN == other.m_hasNaN) &&
((empty() && other.empty()) ||
(m_lo == other.m_lo && m_hi == other.m_hi)));
}
private:
bool m_hasNaN;
double m_lo;
double m_hi;
double m_warningLo;
double m_warningHi;
} DE_WARN_UNUSED_TYPE;
inline Interval operator+ (const Interval& x) { return x; }
Interval exp2 (const Interval& x);
Interval exp (const Interval& x);
int sign (const Interval& x);
Interval abs (const Interval& x);
Interval inverseSqrt (const Interval& x);
Interval operator+ (const Interval& x, const Interval& y);
Interval operator- (const Interval& x, const Interval& y);
Interval operator* (const Interval& x, const Interval& y);
Interval operator/ (const Interval& nom, const Interval& den);
inline Interval& operator+= (Interval& x, const Interval& y) { return (x = x + y); }
inline Interval& operator-= (Interval& x, const Interval& y) { return (x = x - y); }
inline Interval& operator*= (Interval& x, const Interval& y) { return (x = x * y); }
inline Interval& operator/= (Interval& x, const Interval& y) { return (x = x / y); }
std::ostream& operator<< (std::ostream& os, const Interval& interval);
#define TCU_SET_INTERVAL_BOUNDS(DST, VAR, SETLOW, SETHIGH) do \
{ \
::tcu::ScopedRoundingMode VAR##_ctx_; \
::tcu::Interval& VAR##_dst_ = (DST); \
::tcu::Interval VAR##_lo_; \
::tcu::Interval VAR##_hi_; \
\
{ \
::tcu::Interval& (VAR) = VAR##_lo_; \
::deSetRoundingMode(DE_ROUNDINGMODE_TO_NEGATIVE_INF); \
SETLOW; \
} \
{ \
::tcu::Interval& (VAR) = VAR##_hi_; \
::deSetRoundingMode(DE_ROUNDINGMODE_TO_POSITIVE_INF); \
SETHIGH; \
} \
\
VAR##_dst_ = VAR##_lo_ | VAR##_hi_; \
} while (::deGetFalse())
#define TCU_SET_INTERVAL(DST, VAR, BODY) \
TCU_SET_INTERVAL_BOUNDS(DST, VAR, BODY, BODY)
//! Set the interval DST to the image of BODY on ARG, assuming that BODY on
//! ARG is a monotone function. In practice, BODY is evaluated on both the
//! upper and lower bound of ARG, and DST is set to the union of these
//! results. While evaluating BODY, PARAM is bound to the bound of ARG, and
//! the output of BODY should be stored in VAR.
#define TCU_INTERVAL_APPLY_MONOTONE1(DST, PARAM, ARG, VAR, BODY) do \
{ \
const ::tcu::Interval& VAR##_arg_ = (ARG); \
::tcu::Interval& VAR##_dst_ = (DST); \
::tcu::Interval VAR##_lo_; \
::tcu::Interval VAR##_hi_; \
if (VAR##_arg_.empty()) \
VAR##_dst_ = Interval(); \
else \
{ \
{ \
const double (PARAM) = VAR##_arg_.lo(); \
::tcu::Interval& (VAR) = VAR##_lo_; \
BODY; \
} \
{ \
const double (PARAM) = VAR##_arg_.hi(); \
::tcu::Interval& (VAR) = VAR##_hi_; \
BODY; \
} \
VAR##_dst_ = VAR##_lo_ | VAR##_hi_; \
} \
if (VAR##_arg_.hasNaN()) \
VAR##_dst_ |= TCU_NAN; \
} while (::deGetFalse())
#define TCU_INTERVAL_APPLY_MONOTONE2(DST, P0, A0, P1, A1, VAR, BODY) \
TCU_INTERVAL_APPLY_MONOTONE1( \
DST, P0, A0, tmp2_, \
TCU_INTERVAL_APPLY_MONOTONE1(tmp2_, P1, A1, VAR, BODY))
#define TCU_INTERVAL_APPLY_MONOTONE3(DST, P0, A0, P1, A1, P2, A2, VAR, BODY) \
TCU_INTERVAL_APPLY_MONOTONE1( \
DST, P0, A0, tmp3_, \
TCU_INTERVAL_APPLY_MONOTONE2(tmp3_, P1, A1, P2, A2, VAR, BODY))
typedef double DoubleFunc1 (double);
typedef double DoubleFunc2 (double, double);
typedef double DoubleFunc3 (double, double, double);
typedef Interval DoubleIntervalFunc1 (double);
typedef Interval DoubleIntervalFunc2 (double, double);
typedef Interval DoubleIntervalFunc3 (double, double, double);
Interval applyMonotone (DoubleFunc1& func,
const Interval& arg0);
Interval applyMonotone (DoubleFunc2& func,
const Interval& arg0,
const Interval& arg1);
Interval applyMonotone (DoubleIntervalFunc1& func,
const Interval& arg0);
Interval applyMonotone (DoubleIntervalFunc2& func,
const Interval& arg0,
const Interval& arg1);
} // tcu
#endif // _TCUINTERVAL_HPP
<commit_msg>Rename Interval::warning's parameters to avoid shadowing<commit_after>#ifndef _TCUINTERVAL_HPP
#define _TCUINTERVAL_HPP
/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 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 Interval arithmetic and floating point precisions.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "deMath.h"
#include <iostream>
#include <limits>
#define TCU_INFINITY (::std::numeric_limits<float>::infinity())
#define TCU_NAN (::std::numeric_limits<float>::quiet_NaN())
namespace tcu
{
// RAII context for temporarily changing the rounding mode
class ScopedRoundingMode
{
public:
ScopedRoundingMode (deRoundingMode mode)
: m_oldMode (deGetRoundingMode()) { deSetRoundingMode(mode); }
ScopedRoundingMode (void) : m_oldMode (deGetRoundingMode()) {}
~ScopedRoundingMode (void) { deSetRoundingMode(m_oldMode); }
private:
ScopedRoundingMode (const ScopedRoundingMode&);
ScopedRoundingMode& operator= (const ScopedRoundingMode&);
const deRoundingMode m_oldMode;
};
class Interval
{
public:
// Empty interval.
Interval (void)
: m_hasNaN (false)
, m_lo (TCU_INFINITY)
, m_hi (-TCU_INFINITY)
, m_warningLo (-TCU_INFINITY)
, m_warningHi (TCU_INFINITY) {}
// Intentionally not explicit. Conversion from double to Interval is common
// and reasonable.
Interval (double val)
: m_hasNaN (!!deIsNaN(val))
, m_lo (m_hasNaN ? TCU_INFINITY : val)
, m_hi (m_hasNaN ? -TCU_INFINITY : val)
, m_warningLo (-TCU_INFINITY)
, m_warningHi (TCU_INFINITY) {}
Interval(bool hasNaN_, double lo_, double hi_)
: m_hasNaN(hasNaN_), m_lo(lo_), m_hi(hi_), m_warningLo(-TCU_INFINITY), m_warningHi(TCU_INFINITY) {}
Interval(bool hasNaN_, double lo_, double hi_, double wlo_, double whi_)
: m_hasNaN(hasNaN_), m_lo(lo_), m_hi(hi_), m_warningLo(wlo_), m_warningHi(whi_) {}
Interval (const Interval& a, const Interval& b)
: m_hasNaN (a.m_hasNaN || b.m_hasNaN)
, m_lo (de::min(a.lo(), b.lo()))
, m_hi (de::max(a.hi(), b.hi()))
, m_warningLo (de::min(a.warningLo(), b.warningLo()))
, m_warningHi (de::max(a.warningHi(), b.warningHi())) {}
double length (void) const { return m_hi - m_lo; }
double lo (void) const { return m_lo; }
double hi (void) const { return m_hi; }
double warningLo (void) const { return m_warningLo; }
double warningHi (void) const { return m_warningHi; }
bool hasNaN (void) const { return m_hasNaN; }
Interval nan (void) const { return m_hasNaN ? TCU_NAN : Interval(); }
bool empty (void) const { return m_lo > m_hi; }
bool isFinite (void) const { return m_lo > -TCU_INFINITY && m_hi < TCU_INFINITY; }
bool isOrdinary (void) const { return !hasNaN() && !empty() && isFinite(); }
void warning (double lo_, double hi_)
{
m_warningLo = lo_;
m_warningHi = hi_;
}
Interval operator| (const Interval& other) const
{
return Interval(m_hasNaN || other.m_hasNaN,
de::min(m_lo, other.m_lo),
de::max(m_hi, other.m_hi),
de::min(m_warningLo, other.m_warningLo),
de::max(m_warningHi, other.m_warningHi));
}
Interval& operator|= (const Interval& other)
{
return (*this = *this | other);
}
Interval operator& (const Interval& other) const
{
return Interval(m_hasNaN && other.m_hasNaN,
de::max(m_lo, other.m_lo),
de::min(m_hi, other.m_hi),
de::max(m_warningLo, other.m_warningLo),
de::min(m_warningHi, other.m_warningHi));
}
Interval& operator&= (const Interval& other)
{
return (*this = *this & other);
}
bool contains (const Interval& other) const
{
return (other.lo() >= lo() && other.hi() <= hi() &&
(!other.hasNaN() || hasNaN()));
}
bool containsWarning(const Interval& other) const
{
return (other.lo() >= warningLo() && other.hi() <= warningHi() &&
(!other.hasNaN() || hasNaN()));
}
bool intersects (const Interval& other) const
{
return ((other.hi() >= lo() && other.lo() <= hi()) ||
(other.hasNaN() && hasNaN()));
}
Interval operator- (void) const
{
return Interval(hasNaN(), -hi(), -lo(), -warningHi(), -warningLo());
}
static Interval unbounded (bool nan = false)
{
return Interval(nan, -TCU_INFINITY, TCU_INFINITY);
}
double midpoint (void) const
{
return 0.5 * (hi() + lo()); // returns NaN when not bounded
}
bool operator== (const Interval& other) const
{
return ((m_hasNaN == other.m_hasNaN) &&
((empty() && other.empty()) ||
(m_lo == other.m_lo && m_hi == other.m_hi)));
}
private:
bool m_hasNaN;
double m_lo;
double m_hi;
double m_warningLo;
double m_warningHi;
} DE_WARN_UNUSED_TYPE;
inline Interval operator+ (const Interval& x) { return x; }
Interval exp2 (const Interval& x);
Interval exp (const Interval& x);
int sign (const Interval& x);
Interval abs (const Interval& x);
Interval inverseSqrt (const Interval& x);
Interval operator+ (const Interval& x, const Interval& y);
Interval operator- (const Interval& x, const Interval& y);
Interval operator* (const Interval& x, const Interval& y);
Interval operator/ (const Interval& nom, const Interval& den);
inline Interval& operator+= (Interval& x, const Interval& y) { return (x = x + y); }
inline Interval& operator-= (Interval& x, const Interval& y) { return (x = x - y); }
inline Interval& operator*= (Interval& x, const Interval& y) { return (x = x * y); }
inline Interval& operator/= (Interval& x, const Interval& y) { return (x = x / y); }
std::ostream& operator<< (std::ostream& os, const Interval& interval);
#define TCU_SET_INTERVAL_BOUNDS(DST, VAR, SETLOW, SETHIGH) do \
{ \
::tcu::ScopedRoundingMode VAR##_ctx_; \
::tcu::Interval& VAR##_dst_ = (DST); \
::tcu::Interval VAR##_lo_; \
::tcu::Interval VAR##_hi_; \
\
{ \
::tcu::Interval& (VAR) = VAR##_lo_; \
::deSetRoundingMode(DE_ROUNDINGMODE_TO_NEGATIVE_INF); \
SETLOW; \
} \
{ \
::tcu::Interval& (VAR) = VAR##_hi_; \
::deSetRoundingMode(DE_ROUNDINGMODE_TO_POSITIVE_INF); \
SETHIGH; \
} \
\
VAR##_dst_ = VAR##_lo_ | VAR##_hi_; \
} while (::deGetFalse())
#define TCU_SET_INTERVAL(DST, VAR, BODY) \
TCU_SET_INTERVAL_BOUNDS(DST, VAR, BODY, BODY)
//! Set the interval DST to the image of BODY on ARG, assuming that BODY on
//! ARG is a monotone function. In practice, BODY is evaluated on both the
//! upper and lower bound of ARG, and DST is set to the union of these
//! results. While evaluating BODY, PARAM is bound to the bound of ARG, and
//! the output of BODY should be stored in VAR.
#define TCU_INTERVAL_APPLY_MONOTONE1(DST, PARAM, ARG, VAR, BODY) do \
{ \
const ::tcu::Interval& VAR##_arg_ = (ARG); \
::tcu::Interval& VAR##_dst_ = (DST); \
::tcu::Interval VAR##_lo_; \
::tcu::Interval VAR##_hi_; \
if (VAR##_arg_.empty()) \
VAR##_dst_ = Interval(); \
else \
{ \
{ \
const double (PARAM) = VAR##_arg_.lo(); \
::tcu::Interval& (VAR) = VAR##_lo_; \
BODY; \
} \
{ \
const double (PARAM) = VAR##_arg_.hi(); \
::tcu::Interval& (VAR) = VAR##_hi_; \
BODY; \
} \
VAR##_dst_ = VAR##_lo_ | VAR##_hi_; \
} \
if (VAR##_arg_.hasNaN()) \
VAR##_dst_ |= TCU_NAN; \
} while (::deGetFalse())
#define TCU_INTERVAL_APPLY_MONOTONE2(DST, P0, A0, P1, A1, VAR, BODY) \
TCU_INTERVAL_APPLY_MONOTONE1( \
DST, P0, A0, tmp2_, \
TCU_INTERVAL_APPLY_MONOTONE1(tmp2_, P1, A1, VAR, BODY))
#define TCU_INTERVAL_APPLY_MONOTONE3(DST, P0, A0, P1, A1, P2, A2, VAR, BODY) \
TCU_INTERVAL_APPLY_MONOTONE1( \
DST, P0, A0, tmp3_, \
TCU_INTERVAL_APPLY_MONOTONE2(tmp3_, P1, A1, P2, A2, VAR, BODY))
typedef double DoubleFunc1 (double);
typedef double DoubleFunc2 (double, double);
typedef double DoubleFunc3 (double, double, double);
typedef Interval DoubleIntervalFunc1 (double);
typedef Interval DoubleIntervalFunc2 (double, double);
typedef Interval DoubleIntervalFunc3 (double, double, double);
Interval applyMonotone (DoubleFunc1& func,
const Interval& arg0);
Interval applyMonotone (DoubleFunc2& func,
const Interval& arg0,
const Interval& arg1);
Interval applyMonotone (DoubleIntervalFunc1& func,
const Interval& arg0);
Interval applyMonotone (DoubleIntervalFunc2& func,
const Interval& arg0,
const Interval& arg1);
} // tcu
#endif // _TCUINTERVAL_HPP
<|endoftext|> |
<commit_before>#ifdef _RPI_
#include "components/VideoPlayerComponent.h"
#include "utils/StringUtil.h"
#include "AudioManager.h"
#include "Renderer.h"
#include "Settings.h"
#include <fcntl.h>
#include <unistd.h>
#include <wait.h>
class VolumeControl
{
public:
static std::shared_ptr<VolumeControl> & getInstance();
int getVolume() const;
};
VideoPlayerComponent::VideoPlayerComponent(Window* window, std::string path) :
VideoComponent(window),
mPlayerPid(-1),
subtitlePath(path)
{
}
VideoPlayerComponent::~VideoPlayerComponent()
{
stopVideo();
}
void VideoPlayerComponent::render(const Transform4x4f& parentTrans)
{
VideoComponent::render(parentTrans);
if (!mIsPlaying || mPlayerPid == -1)
VideoComponent::renderSnapshot(parentTrans);
}
void VideoPlayerComponent::setResize(float width, float height)
{
setSize(width, height);
mTargetSize = Vector2f(width, height);
mTargetIsMax = false;
mStaticImage.setSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::setMaxSize(float width, float height)
{
setSize(width, height);
mTargetSize = Vector2f(width, height);
mTargetIsMax = true;
mStaticImage.setMaxSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::startVideo()
{
if (!mIsPlaying)
{
mVideoWidth = 0;
mVideoHeight = 0;
std::string path(mVideoPath.c_str());
// Make sure we have a video path
if ((path.size() > 0) && (mPlayerPid == -1))
{
// Set the video that we are going to be playing so we don't attempt to restart it
mPlayingVideoPath = mVideoPath;
// Disable AudioManager so video can play, in case we're requesting ALSA
if (Utils::String::startsWith(Settings::getInstance()->getString("OMXAudioDev").c_str(), "alsa"))
{
AudioManager::getInstance()->deinit();
}
// Start the player process
pid_t pid = fork();
if (pid == -1)
{
// Failed
mPlayingVideoPath = "";
}
else if (pid > 0)
{
mPlayerPid = pid;
// Update the playing state
signal(SIGCHLD, catch_child);
mIsPlaying = true;
mFadeIn = 0.0f;
}
else
{
// Find out the pixel position of the video view and build a command line for
// omxplayer to position it in the right place
char buf1[32];
char buf2[32];
float x = mPosition.x() - (mOrigin.x() * mSize.x());
float y = mPosition.y() - (mOrigin.y() * mSize.y());
// fix x and y
switch(Renderer::getScreenRotate())
{
case 0:
{
const int x1 = (int)(Renderer::getScreenOffsetX() + x);
const int y1 = (int)(Renderer::getScreenOffsetY() + y);
const int x2 = (int)(x1 + mSize.x());
const int y2 = (int)(y1 + mSize.y());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
case 1:
{
const int x1 = (int)(Renderer::getScreenOffsetY() + Renderer::getScreenHeight() - y - mSize.y());
const int y1 = (int)(Renderer::getScreenOffsetX() + x);
const int x2 = (int)(x1 + mSize.y());
const int y2 = (int)(y1 + mSize.x());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
case 2:
{
const int x1 = (int)(Renderer::getScreenOffsetX() + Renderer::getScreenWidth() - x - mSize.x());
const int y1 = (int)(Renderer::getScreenOffsetY() + Renderer::getScreenHeight() - y - mSize.y());
const int x2 = (int)(x1 + mSize.x());
const int y2 = (int)(y1 + mSize.y());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
case 3:
{
const int x1 = (int)(Renderer::getScreenOffsetY() + y);
const int y1 = (int)(Renderer::getScreenOffsetX() + Renderer::getScreenWidth() - x - mSize.x());
const int x2 = (int)(x1 + mSize.y());
const int y2 = (int)(y1 + mSize.x());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
}
// rotate the video
switch(Renderer::getScreenRotate())
{
case 0: { sprintf(buf2, "%d", (int) 0); } break;
case 1: { sprintf(buf2, "%d", (int) 90); } break;
case 2: { sprintf(buf2, "%d", (int)180); } break;
case 3: { sprintf(buf2, "%d", (int)270); } break;
}
// We need to specify the layer of 10000 or above to ensure the video is displayed on top
// of our SDL display
const char* argv[] = { "", "--layer", "10010", "--loop", "--no-osd", "--aspect-mode", "letterbox", "--vol", "0", "-o", "both","--win", buf1, "--orientation", buf2, "", "", "", "", NULL };
// check if we want to mute the audio
if (!Settings::getInstance()->getBool("VideoAudio") || (float)VolumeControl::getInstance()->getVolume() == 0)
{
argv[8] = "-1000000";
}
else
{
float percentVolume = (float)VolumeControl::getInstance()->getVolume();
int OMXVolume = (int)((percentVolume-98)*105);
argv[8] = std::to_string(OMXVolume).c_str();
}
// test if there's a path for possible subtitles, meaning we're a screensaver video
if (!subtitlePath.empty())
{
// if we are rendering a screensaver
// check if we want to stretch the image
if (Settings::getInstance()->getBool("StretchVideoOnScreenSaver"))
{
argv[6] = "stretch";
}
if (Settings::getInstance()->getString("ScreenSaverGameInfo") != "never")
{
// if we have chosen to render subtitles
argv[15] = "--subtitles";
argv[16] = subtitlePath.c_str();
argv[17] = mPlayingVideoPath.c_str();
}
else
{
// if we have chosen NOT to render subtitles in the screensaver
argv[15] = mPlayingVideoPath.c_str();
}
}
else
{
// if we are rendering a video gamelist
if (!mTargetIsMax)
{
argv[6] = "stretch";
}
argv[15] = mPlayingVideoPath.c_str();
}
argv[10] = Settings::getInstance()->getString("OMXAudioDev").c_str();
//const char* argv[] = args;
const char* env[] = { "LD_LIBRARY_PATH=/opt/vc/libs:/usr/lib/omxplayer", NULL };
// Redirect stdout
int fdin = open("/dev/null", O_RDONLY);
int fdout = open("/dev/null", O_WRONLY);
dup2(fdin, 0);
dup2(fdout, 1);
// Run the omxplayer binary
execve("/usr/bin/omxplayer.bin", (char**)argv, (char**)env);
_exit(EXIT_FAILURE);
}
}
}
}
void catch_child(int sig_num)
{
/* when we get here, we know there's a zombie child waiting */
int child_status;
wait(&child_status);
}
void VideoPlayerComponent::stopVideo()
{
mIsPlaying = false;
mStartDelayed = false;
// Stop the player process
if (mPlayerPid != -1)
{
int status;
kill(mPlayerPid, SIGKILL);
waitpid(mPlayerPid, &status, WNOHANG);
mPlayerPid = -1;
}
}
#endif
<commit_msg>Fix mStaticImage to use setResize<commit_after>#ifdef _RPI_
#include "components/VideoPlayerComponent.h"
#include "utils/StringUtil.h"
#include "AudioManager.h"
#include "Renderer.h"
#include "Settings.h"
#include <fcntl.h>
#include <unistd.h>
#include <wait.h>
class VolumeControl
{
public:
static std::shared_ptr<VolumeControl> & getInstance();
int getVolume() const;
};
VideoPlayerComponent::VideoPlayerComponent(Window* window, std::string path) :
VideoComponent(window),
mPlayerPid(-1),
subtitlePath(path)
{
}
VideoPlayerComponent::~VideoPlayerComponent()
{
stopVideo();
}
void VideoPlayerComponent::render(const Transform4x4f& parentTrans)
{
VideoComponent::render(parentTrans);
if (!mIsPlaying || mPlayerPid == -1)
VideoComponent::renderSnapshot(parentTrans);
}
void VideoPlayerComponent::setResize(float width, float height)
{
setSize(width, height);
mTargetSize = Vector2f(width, height);
mTargetIsMax = false;
mStaticImage.setResize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::setMaxSize(float width, float height)
{
setSize(width, height);
mTargetSize = Vector2f(width, height);
mTargetIsMax = true;
mStaticImage.setMaxSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::startVideo()
{
if (!mIsPlaying)
{
mVideoWidth = 0;
mVideoHeight = 0;
std::string path(mVideoPath.c_str());
// Make sure we have a video path
if ((path.size() > 0) && (mPlayerPid == -1))
{
// Set the video that we are going to be playing so we don't attempt to restart it
mPlayingVideoPath = mVideoPath;
// Disable AudioManager so video can play, in case we're requesting ALSA
if (Utils::String::startsWith(Settings::getInstance()->getString("OMXAudioDev").c_str(), "alsa"))
{
AudioManager::getInstance()->deinit();
}
// Start the player process
pid_t pid = fork();
if (pid == -1)
{
// Failed
mPlayingVideoPath = "";
}
else if (pid > 0)
{
mPlayerPid = pid;
// Update the playing state
signal(SIGCHLD, catch_child);
mIsPlaying = true;
mFadeIn = 0.0f;
}
else
{
// Find out the pixel position of the video view and build a command line for
// omxplayer to position it in the right place
char buf1[32];
char buf2[32];
float x = mPosition.x() - (mOrigin.x() * mSize.x());
float y = mPosition.y() - (mOrigin.y() * mSize.y());
// fix x and y
switch(Renderer::getScreenRotate())
{
case 0:
{
const int x1 = (int)(Renderer::getScreenOffsetX() + x);
const int y1 = (int)(Renderer::getScreenOffsetY() + y);
const int x2 = (int)(x1 + mSize.x());
const int y2 = (int)(y1 + mSize.y());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
case 1:
{
const int x1 = (int)(Renderer::getScreenOffsetY() + Renderer::getScreenHeight() - y - mSize.y());
const int y1 = (int)(Renderer::getScreenOffsetX() + x);
const int x2 = (int)(x1 + mSize.y());
const int y2 = (int)(y1 + mSize.x());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
case 2:
{
const int x1 = (int)(Renderer::getScreenOffsetX() + Renderer::getScreenWidth() - x - mSize.x());
const int y1 = (int)(Renderer::getScreenOffsetY() + Renderer::getScreenHeight() - y - mSize.y());
const int x2 = (int)(x1 + mSize.x());
const int y2 = (int)(y1 + mSize.y());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
case 3:
{
const int x1 = (int)(Renderer::getScreenOffsetY() + y);
const int y1 = (int)(Renderer::getScreenOffsetX() + Renderer::getScreenWidth() - x - mSize.x());
const int x2 = (int)(x1 + mSize.y());
const int y2 = (int)(y1 + mSize.x());
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
}
break;
}
// rotate the video
switch(Renderer::getScreenRotate())
{
case 0: { sprintf(buf2, "%d", (int) 0); } break;
case 1: { sprintf(buf2, "%d", (int) 90); } break;
case 2: { sprintf(buf2, "%d", (int)180); } break;
case 3: { sprintf(buf2, "%d", (int)270); } break;
}
// We need to specify the layer of 10000 or above to ensure the video is displayed on top
// of our SDL display
const char* argv[] = { "", "--layer", "10010", "--loop", "--no-osd", "--aspect-mode", "letterbox", "--vol", "0", "-o", "both","--win", buf1, "--orientation", buf2, "", "", "", "", NULL };
// check if we want to mute the audio
if (!Settings::getInstance()->getBool("VideoAudio") || (float)VolumeControl::getInstance()->getVolume() == 0)
{
argv[8] = "-1000000";
}
else
{
float percentVolume = (float)VolumeControl::getInstance()->getVolume();
int OMXVolume = (int)((percentVolume-98)*105);
argv[8] = std::to_string(OMXVolume).c_str();
}
// test if there's a path for possible subtitles, meaning we're a screensaver video
if (!subtitlePath.empty())
{
// if we are rendering a screensaver
// check if we want to stretch the image
if (Settings::getInstance()->getBool("StretchVideoOnScreenSaver"))
{
argv[6] = "stretch";
}
if (Settings::getInstance()->getString("ScreenSaverGameInfo") != "never")
{
// if we have chosen to render subtitles
argv[15] = "--subtitles";
argv[16] = subtitlePath.c_str();
argv[17] = mPlayingVideoPath.c_str();
}
else
{
// if we have chosen NOT to render subtitles in the screensaver
argv[15] = mPlayingVideoPath.c_str();
}
}
else
{
// if we are rendering a video gamelist
if (!mTargetIsMax)
{
argv[6] = "stretch";
}
argv[15] = mPlayingVideoPath.c_str();
}
argv[10] = Settings::getInstance()->getString("OMXAudioDev").c_str();
//const char* argv[] = args;
const char* env[] = { "LD_LIBRARY_PATH=/opt/vc/libs:/usr/lib/omxplayer", NULL };
// Redirect stdout
int fdin = open("/dev/null", O_RDONLY);
int fdout = open("/dev/null", O_WRONLY);
dup2(fdin, 0);
dup2(fdout, 1);
// Run the omxplayer binary
execve("/usr/bin/omxplayer.bin", (char**)argv, (char**)env);
_exit(EXIT_FAILURE);
}
}
}
}
void catch_child(int sig_num)
{
/* when we get here, we know there's a zombie child waiting */
int child_status;
wait(&child_status);
}
void VideoPlayerComponent::stopVideo()
{
mIsPlaying = false;
mStartDelayed = false;
// Stop the player process
if (mPlayerPid != -1)
{
int status;
kill(mPlayerPid, SIGKILL);
waitpid(mPlayerPid, &status, WNOHANG);
mPlayerPid = -1;
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Example of using Bayesian Filter Class to solve a simple problem.
* A linear filter with one state and constant noises
*/
#include <iostream>
// Include all the Bayes++ Bayesian filtering library
#include "BayesFilter/allFlt.h"
using namespace std;
using namespace Bayesian_filter;
using namespace Bayesian_filter_matrix;
/*
* Simple Prediction model
*/
class Simple_predict : public Linear_predict_model
{
public:
Simple_predict() : Linear_predict_model(1,1)
// Construct a constant model
{
// Stationary Prediction model (Identity)
Fx(0,0) = 1.;
// Constant Noise model with a small variance
q[0] = 0.1;
G(0,0) = 1.;
}
};
/*
* Simple Observation model
*/
class Simple_observe : public Linear_uncorrelated_observe_model
{
public:
Simple_observe () : Linear_uncorrelated_observe_model(1,1)
// Construct a constant model
{
// Linear model
Hx(0,0) = 1;
// Constant Observation Noise model with variance of one
Zv[0] = 1.;
}
};
template <class BaseR>
inline void mstest(BaseR R)
{
R.size();
}
/*
* Filter a simple example
*/
int main()
{
// Global setup for test output
cout.flags(ios::fixed); cout.precision(4);
// Construct simple Prediction and Observation models
Simple_predict my_predict;
Simple_observe my_observe;
// Use an 'unscented' filter with one state
Unscented_filter my_filter(1);
// Setup the initial state and covariance
Vec x_init (1); SymMatrix X_init (1, 1);
x_init[0] = 10.; // Start at 10 with no uncertainty
X_init(0,0) = 0.;
my_filter.init_kalman (x_init, X_init);
cout << "Initial " << my_filter.x << my_filter.X << endl;
// Predict the filter forward
my_filter.predict (my_predict);
my_filter.update(); // Update the filter, so state and covariance are available
cout << "Predict " << my_filter.x << my_filter.X << endl;
// Make an observation
Vec z(1);
z[0] = 20.; // Observe that we should be at 20
my_filter.observe (my_observe, z);
my_filter.update(); // Update the filter to state and covariance are available
cout << "Filtered " << my_filter.x << my_filter.X << endl;
return 0;
}
<commit_msg>All web on SF<commit_after>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Example of using Bayesian Filter Class to solve a simple problem.
* A linear filter with one state and constant noises
*/
#include <iostream>
// Include all the Bayes++ Bayesian filtering classes
#include "BayesFilter/allFlt.h"
using namespace std;
using namespace Bayesian_filter;
using namespace Bayesian_filter_matrix;
/*
* Simple Prediction model
*/
class Simple_predict : public Linear_predict_model
{
public:
Simple_predict() : Linear_predict_model(1,1)
// Construct a constant model
{
// Stationary Prediction model (Identity)
Fx(0,0) = 1.;
// Constant Noise model with a small variance
q[0] = 0.1;
G(0,0) = 1.;
}
};
/*
* Simple Observation model
*/
class Simple_observe : public Linear_uncorrelated_observe_model
{
public:
Simple_observe () : Linear_uncorrelated_observe_model(1,1)
// Construct a constant model
{
// Linear model
Hx(0,0) = 1;
// Constant Observation Noise model with variance of one
Zv[0] = 1.;
}
};
template <class BaseR>
inline void mstest(BaseR R)
{
R.size();
}
/*
* Filter a simple example
*/
int main()
{
// Global setup for test output
cout.flags(ios::fixed); cout.precision(4);
// Construct simple Prediction and Observation models
Simple_predict my_predict;
Simple_observe my_observe;
// Use an 'unscented' filter with one state
Unscented_filter my_filter(1);
// Setup the initial state and covariance
Vec x_init (1); SymMatrix X_init (1, 1);
x_init[0] = 10.; // Start at 10 with no uncertainty
X_init(0,0) = 0.;
my_filter.init_kalman (x_init, X_init);
cout << "Initial " << my_filter.x << my_filter.X << endl;
// Predict the filter forward
my_filter.predict (my_predict);
my_filter.update(); // Update the filter, so state and covariance are available
cout << "Predict " << my_filter.x << my_filter.X << endl;
// Make an observation
Vec z(1);
z[0] = 20.; // Observe that we should be at 20
my_filter.observe (my_observe, z);
my_filter.update(); // Update the filter to state and covariance are available
cout << "Filtered " << my_filter.x << my_filter.X << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2018, Alexey Dynda
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.
*/
#ifdef SDL_EMULATION
#include "sdl_core.h"
#endif
extern void setup(void);
extern void loop(void);
extern "C" {
void app_main(void)
{
setup();
for(;;)
{
loop();
#ifdef SDL_EMULATION
sdl_read_analog(0);
#endif
}
}
}
<commit_msg>Added main task for FreeRTOS<commit_after>/*
MIT License
Copyright (c) 2018, Alexey Dynda
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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#ifdef SDL_EMULATION
#include "sdl_core.h"
#endif
extern void setup(void);
extern void loop(void);
#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif
void main_task(void *args)
{
setup();
for(;;) {
loop();
#ifdef SDL_EMULATION
sdl_read_analog(0);
#endif
}
}
extern "C" void app_main(void)
{
xTaskCreatePinnedToCore(main_task, "mainTask", 8192, NULL, 1, NULL, ARDUINO_RUNNING_CORE);
}
<|endoftext|> |
<commit_before>#ifdef _RPI_
#include "components/VideoPlayerComponent.h"
#include <boost/algorithm/string/predicate.hpp>
#include "AudioManager.h"
#include "Renderer.h"
#include "ThemeData.h"
#include "Settings.h"
#include "Util.h"
#include <signal.h>
#include <wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
class VolumeControl
{
public:
static std::shared_ptr<VolumeControl> & getInstance();
int getVolume() const;
};
VideoPlayerComponent::VideoPlayerComponent(Window* window, std::string path) :
VideoComponent(window),
mPlayerPid(-1),
subtitlePath(path)
{
}
VideoPlayerComponent::~VideoPlayerComponent()
{
stopVideo();
}
void VideoPlayerComponent::render(const Transform4x4f& parentTrans)
{
VideoComponent::render(parentTrans);
if (!mIsPlaying || mPlayerPid == -1)
VideoComponent::renderSnapshot(parentTrans);
}
void VideoPlayerComponent::setResize(float width, float height)
{
setSize(width, height);
mTargetSize << width, height;
mTargetIsMax = false;
mStaticImage.setSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::setMaxSize(float width, float height)
{
setSize(width, height);
mTargetSize << width, height;
mTargetIsMax = true;
mStaticImage.setMaxSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::startVideo()
{
if (!mIsPlaying)
{
mVideoWidth = 0;
mVideoHeight = 0;
std::string path(mVideoPath.c_str());
// Make sure we have a video path
if ((path.size() > 0) && (mPlayerPid == -1))
{
// Set the video that we are going to be playing so we don't attempt to restart it
mPlayingVideoPath = mVideoPath;
// Disable AudioManager so video can play, in case we're requesting ALSA
if (boost::starts_with(Settings::getInstance()->getString("OMXAudioDev").c_str(), "alsa"))
{
AudioManager::getInstance()->deinit();
}
// Start the player process
pid_t pid = fork();
if (pid == -1)
{
// Failed
mPlayingVideoPath = "";
}
else if (pid > 0)
{
mPlayerPid = pid;
// Update the playing state
signal(SIGCHLD, catch_child);
mIsPlaying = true;
mFadeIn = 0.0f;
}
else
{
// Find out the pixel position of the video view and build a command line for
// omxplayer to position it in the right place
char buf[32];
float x = mPosition.x() - (mOrigin.x() * mSize.x());
float y = mPosition.y() - (mOrigin.y() * mSize.y());
sprintf(buf, "%d,%d,%d,%d", (int)x, (int)y, (int)(x + mSize.x()), (int)(y + mSize.y()));
// We need to specify the layer of 10000 or above to ensure the video is displayed on top
// of our SDL display
const char* argv[] = { "", "--layer", "10010", "--loop", "--no-osd", "--aspect-mode", "letterbox", "--vol", "0", "-o", "both","--win", buf, "--no-ghost-box", "", "", "", "", NULL };
// check if we want to mute the audio
if (!Settings::getInstance()->getBool("VideoAudio") || (float)VolumeControl::getInstance()->getVolume() == 0)
{
argv[8] = "-1000000";
}
else
{
float percentVolume = (float)VolumeControl::getInstance()->getVolume();
int OMXVolume = (int)((percentVolume-98)*105);
argv[8] = std::to_string(OMXVolume).c_str();
}
// test if there's a path for possible subtitles, meaning we're a screensaver video
if (!subtitlePath.empty())
{
// if we are rendering a screensaver
// check if we want to stretch the image
if (Settings::getInstance()->getBool("StretchVideoOnScreenSaver"))
{
argv[6] = "stretch";
}
if (Settings::getInstance()->getString("ScreenSaverGameInfo") != "never")
{
// if we have chosen to render subtitles
argv[13] = "--subtitles";
argv[14] = subtitlePath.c_str();
argv[15] = mPlayingVideoPath.c_str();
}
else
{
// if we have chosen NOT to render subtitles in the screensaver
argv[13] = mPlayingVideoPath.c_str();
}
}
else
{
// if we are rendering a video gamelist
if (!mTargetIsMax)
{
argv[6] = "stretch";
}
argv[13] = mPlayingVideoPath.c_str();
}
argv[10] = Settings::getInstance()->getString("OMXAudioDev").c_str();
//const char* argv[] = args;
const char* env[] = { "LD_LIBRARY_PATH=/opt/vc/libs:/usr/lib/omxplayer", NULL };
// Redirect stdout
int fdin = open("/dev/null", O_RDONLY);
int fdout = open("/dev/null", O_WRONLY);
dup2(fdin, 0);
dup2(fdout, 1);
// Run the omxplayer binary
execve("/usr/bin/omxplayer.bin", (char**)argv, (char**)env);
_exit(EXIT_FAILURE);
}
}
}
}
void catch_child(int sig_num)
{
/* when we get here, we know there's a zombie child waiting */
int child_status;
wait(&child_status);
}
void VideoPlayerComponent::stopVideo()
{
mIsPlaying = false;
mStartDelayed = false;
// Stop the player process
if (mPlayerPid != -1)
{
int status;
kill(mPlayerPid, SIGKILL);
waitpid(mPlayerPid, &status, WNOHANG);
mPlayerPid = -1;
}
}
#endif
<commit_msg>Implement missed inhouse vector replacements<commit_after>#ifdef _RPI_
#include "components/VideoPlayerComponent.h"
#include <boost/algorithm/string/predicate.hpp>
#include "AudioManager.h"
#include "Renderer.h"
#include "ThemeData.h"
#include "Settings.h"
#include "Util.h"
#include <signal.h>
#include <wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
class VolumeControl
{
public:
static std::shared_ptr<VolumeControl> & getInstance();
int getVolume() const;
};
VideoPlayerComponent::VideoPlayerComponent(Window* window, std::string path) :
VideoComponent(window),
mPlayerPid(-1),
subtitlePath(path)
{
}
VideoPlayerComponent::~VideoPlayerComponent()
{
stopVideo();
}
void VideoPlayerComponent::render(const Transform4x4f& parentTrans)
{
VideoComponent::render(parentTrans);
if (!mIsPlaying || mPlayerPid == -1)
VideoComponent::renderSnapshot(parentTrans);
}
void VideoPlayerComponent::setResize(float width, float height)
{
setSize(width, height);
mTargetSize = Vector2f(width, height);
mTargetIsMax = false;
mStaticImage.setSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::setMaxSize(float width, float height)
{
setSize(width, height);
mTargetSize = Vector2f(width, height);
mTargetIsMax = true;
mStaticImage.setMaxSize(width, height);
onSizeChanged();
}
void VideoPlayerComponent::startVideo()
{
if (!mIsPlaying)
{
mVideoWidth = 0;
mVideoHeight = 0;
std::string path(mVideoPath.c_str());
// Make sure we have a video path
if ((path.size() > 0) && (mPlayerPid == -1))
{
// Set the video that we are going to be playing so we don't attempt to restart it
mPlayingVideoPath = mVideoPath;
// Disable AudioManager so video can play, in case we're requesting ALSA
if (boost::starts_with(Settings::getInstance()->getString("OMXAudioDev").c_str(), "alsa"))
{
AudioManager::getInstance()->deinit();
}
// Start the player process
pid_t pid = fork();
if (pid == -1)
{
// Failed
mPlayingVideoPath = "";
}
else if (pid > 0)
{
mPlayerPid = pid;
// Update the playing state
signal(SIGCHLD, catch_child);
mIsPlaying = true;
mFadeIn = 0.0f;
}
else
{
// Find out the pixel position of the video view and build a command line for
// omxplayer to position it in the right place
char buf[32];
float x = mPosition.x() - (mOrigin.x() * mSize.x());
float y = mPosition.y() - (mOrigin.y() * mSize.y());
sprintf(buf, "%d,%d,%d,%d", (int)x, (int)y, (int)(x + mSize.x()), (int)(y + mSize.y()));
// We need to specify the layer of 10000 or above to ensure the video is displayed on top
// of our SDL display
const char* argv[] = { "", "--layer", "10010", "--loop", "--no-osd", "--aspect-mode", "letterbox", "--vol", "0", "-o", "both","--win", buf, "--no-ghost-box", "", "", "", "", NULL };
// check if we want to mute the audio
if (!Settings::getInstance()->getBool("VideoAudio") || (float)VolumeControl::getInstance()->getVolume() == 0)
{
argv[8] = "-1000000";
}
else
{
float percentVolume = (float)VolumeControl::getInstance()->getVolume();
int OMXVolume = (int)((percentVolume-98)*105);
argv[8] = std::to_string(OMXVolume).c_str();
}
// test if there's a path for possible subtitles, meaning we're a screensaver video
if (!subtitlePath.empty())
{
// if we are rendering a screensaver
// check if we want to stretch the image
if (Settings::getInstance()->getBool("StretchVideoOnScreenSaver"))
{
argv[6] = "stretch";
}
if (Settings::getInstance()->getString("ScreenSaverGameInfo") != "never")
{
// if we have chosen to render subtitles
argv[13] = "--subtitles";
argv[14] = subtitlePath.c_str();
argv[15] = mPlayingVideoPath.c_str();
}
else
{
// if we have chosen NOT to render subtitles in the screensaver
argv[13] = mPlayingVideoPath.c_str();
}
}
else
{
// if we are rendering a video gamelist
if (!mTargetIsMax)
{
argv[6] = "stretch";
}
argv[13] = mPlayingVideoPath.c_str();
}
argv[10] = Settings::getInstance()->getString("OMXAudioDev").c_str();
//const char* argv[] = args;
const char* env[] = { "LD_LIBRARY_PATH=/opt/vc/libs:/usr/lib/omxplayer", NULL };
// Redirect stdout
int fdin = open("/dev/null", O_RDONLY);
int fdout = open("/dev/null", O_WRONLY);
dup2(fdin, 0);
dup2(fdout, 1);
// Run the omxplayer binary
execve("/usr/bin/omxplayer.bin", (char**)argv, (char**)env);
_exit(EXIT_FAILURE);
}
}
}
}
void catch_child(int sig_num)
{
/* when we get here, we know there's a zombie child waiting */
int child_status;
wait(&child_status);
}
void VideoPlayerComponent::stopVideo()
{
mIsPlaying = false;
mStartDelayed = false;
// Stop the player process
if (mPlayerPid != -1)
{
int status;
kill(mPlayerPid, SIGKILL);
waitpid(mPlayerPid, &status, WNOHANG);
mPlayerPid = -1;
}
}
#endif
<|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.
//
// Uncapacitated Facility Location Problem.
// A description of the problem can be found here:
// https://en.wikipedia.org/wiki/Facility_location_problem.
// The variant which is tackled by this model does not consider capacities
// for facilities. Moreover, all cost are based on euclidean distance factors,
// i.e. the problem we really solve is a Metric Facility Location. For the
// sake of simplicity, facilities and demands are randomly located. Distances
// are assumed to be in meters and times in seconds.
#include <cstdio>
#include <vector>
#include "google/protobuf/text_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/random.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/linear_solver/linear_solver.h"
DEFINE_int32(verbose, 0, "Verbosity level.");
DEFINE_int32(facilities, 20, "Candidate facilities to consider.");
DEFINE_int32(clients, 100, "Clients to serve.");
DEFINE_double(fix_cost, 5000, "Cost of opening a facility.");
namespace operations_research {
typedef struct {
double x{0};
double y{0};
} Location;
typedef struct {
int f{-1};
int c{-1};
MPVariable* x{nullptr};
} Edge;
static double Distance(const Location& src, const Location& dst) {
return sqrt((src.x-dst.x)*(src.x-dst.x) + (src.y-dst.y)*(src.y-dst.y));
}
static void UncapacitatedFacilityLocation(int32 facilities,
int32 clients, double fix_cost,
MPSolver::OptimizationProblemType optimization_problem_type) {
LOG(INFO) << "Starting " << __func__;
// Local Constants
const int32 kXMax = 1000;
const int32 kYMax = 1000;
const double kMaxDistance = 6*sqrt((kXMax*kYMax))/facilities;
int kStrLen{1024};
// char buffer for names
char name_buffer[kStrLen+1];
name_buffer[kStrLen] = '\0';
LOG(INFO) << "Facilities/Clients/Fix cost/MaxDist: " << facilities << "/"
<< clients << "/" << fix_cost << "/" << kMaxDistance;
// Setting up facilities and demand points
MTRandom randomizer(/*fixed seed*/20191029);
std::vector<Location> facility(facilities);
std::vector<Location> client(clients);
for (int i = 0; i < facilities; ++i) {
facility[i].x = randomizer.Uniform(kXMax + 1);
facility[i].y = randomizer.Uniform(kYMax + 1);
}
for (int i = 0; i < clients; ++i) {
client[i].x = randomizer.Uniform(kXMax + 1);
client[i].y = randomizer.Uniform(kYMax + 1);
}
// Setup uncapacitated facility location model:
// Min sum( c_f * x_f : f in Facilities) + sum(x_{f,c} * x_{f,c} : {f,c} in E)
// s.t. (1) sum(x_{f,c} : f in Facilities) >= 1 forall c in Clients
// (2) x_f - x_{f,c} >= 0 forall {f,c} in E
// (3) x_f in {0,1} forall f in Facilities
//
// We consider E as the pairs {f,c} in Facilities x Clients such that
// Distance(f,c) <= kMaxDistance
MPSolver solver("UncapacitatedFacilityLocation", optimization_problem_type);
const double infinity = solver.infinity();
MPObjective* objective = solver.MutableObjective();
objective->SetMinimization();
// Add binary facilities variables
std::vector<MPVariable*> xf{};
for (int f = 0; f < facilities; ++f) {
snprintf(name_buffer, kStrLen, "x[%d](%g,%g)", f,
facility[f].x, facility[f].y);
MPVariable* x = solver.MakeBoolVar(name_buffer);
xf.push_back(x);
objective->SetCoefficient(x, fix_cost);
}
// Build edge variables
std::vector<Edge> edges;
for (int c = 0; c < clients; ++c) {
snprintf(name_buffer, kStrLen, "R-Client[%d](%g,%g)", c,
client[c].x, client[c].y);
MPConstraint* client_constraint = solver.MakeRowConstraint(/* lb */1,
/* ub */infinity, name_buffer);
for (int f = 0; f < facilities; ++f) {
double distance = Distance(facility[f], client[c]);
if (distance > kMaxDistance) continue;
Edge edge{};
snprintf(name_buffer, kStrLen, "x[%d,%d]", f, c);
edge.x = solver.MakeNumVar(/* lb */0, /*ub */1, name_buffer);
edge.f = f;
edge.c = c;
edges.push_back(edge);
objective->SetCoefficient(edge.x, distance);
// coefficient for constraint (1)
client_constraint->SetCoefficient(edge.x, 1);
// add constraint (2)
snprintf(name_buffer, kStrLen, "R-Edge[%d,%d]", f, c);
MPConstraint* edge_constraint = solver.MakeRowConstraint(/* lb */0,
/* ub */infinity, name_buffer);
edge_constraint->SetCoefficient(edge.x, -1);
edge_constraint->SetCoefficient(xf[f], 1);
}
}// End adding all edge variables
LOG(INFO) << "Number of variables = " << solver.NumVariables();
LOG(INFO) << "Number of constraints = " << solver.NumConstraints();
// display on screen LP if small enough
if (clients <= 10 && facilities <= 10) {
std::string lp_string{};
solver.ExportModelAsLpFormat(/* obfuscate */false, &lp_string);
std::cout << "LP-Model:\n" << lp_string << std::endl;
}
// Set options and solve
solver.SetNumThreads(8);
solver.EnableOutput();
const MPSolver::ResultStatus result_status = solver.Solve();
// Check that the problem has an optimal solution.
if (result_status != MPSolver::OPTIMAL) {
LOG(FATAL) << "The problem does not have an optimal solution!";
} else {
LOG(INFO) << "Optimal objective value = " << objective->Value();
if (FLAGS_verbose) {
std::vector<std::vector<int>> solution(facilities);
for (auto& edge : edges) {
if (edge.x->solution_value() < 0.5) continue;
solution[edge.f].push_back(edge.c);
}
std::cout << "\tSolution:\n";
for (int f = 0; f < facilities; ++f) {
if (solution[f].size() < 1) continue;
assert(xf[f]->solution_value() > 0.5);
snprintf(name_buffer, kStrLen, "\t Facility[%d](%g,%g):", f,
facility[f].x, facility[f].y);
std::cout << name_buffer;
int i = 1;
for (auto c : solution[f]) {
snprintf(name_buffer, kStrLen, " Client[%d](%g,%g)", c,
client[c].x, client[c].y);
if(i++ >= 5) {
std::cout << "\n\t\t";
i = 1;
}
std::cout << name_buffer;
}
std::cout << "\n";
}
}
std::cout << "\n";
LOG(INFO) << "";
LOG(INFO) << "Advanced usage:";
LOG(INFO) << "Problem solved in " << solver.DurationSinceConstruction()
<< " milliseconds";
LOG(INFO) << "Problem solved in " << solver.iterations() << " iterations";
LOG(INFO) << "Problem solved in " << solver.nodes()
<< " branch-and-bound nodes";
}
}
void RunAllExamples(int32 facilities, int32 clients, double fix_cost) {
#if defined(USE_CBC)
LOG(INFO) << "---- Integer programming example with CBC ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_GLPK)
LOG(INFO) << "---- Integer programming example with GLPK ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_SCIP)
LOG(INFO) << "---- Integer programming example with SCIP ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_GUROBI)
LOG(INFO) << "---- Integer programming example with Gurobi ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING);
#endif // USE_GUROBI
#if defined(USE_CPLEX)
LOG(INFO) << "---- Integer programming example with CPLEX ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING);
#endif // USE_CPLEX
}
} // namespace operations_research
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
gflags::SetUsageMessage(
std::string("This program solve a (randomly generated)\n") +
std::string("Uncapacitated Facility Location Problem. Sample Usage:\n"));
gflags::ParseCommandLineFlags(&argc, &argv, true);
CHECK_LT(0, FLAGS_facilities) << "Specify an instance size greater than 0.";
CHECK_LT(0, FLAGS_clients) << "Specify a non-null client size.";
CHECK_LT(0, FLAGS_fix_cost) << "Specify a non-null client size.";
FLAGS_logtostderr = 1;
operations_research::RunAllExamples(FLAGS_facilities, FLAGS_clients,
FLAGS_fix_cost);
return EXIT_SUCCESS;
}
<commit_msg>fix windows compilation, add CP-SAT backend<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.
//
// Uncapacitated Facility Location Problem.
// A description of the problem can be found here:
// https://en.wikipedia.org/wiki/Facility_location_problem.
// The variant which is tackled by this model does not consider capacities
// for facilities. Moreover, all cost are based on euclidean distance factors,
// i.e. the problem we really solve is a Metric Facility Location. For the
// sake of simplicity, facilities and demands are randomly located. Distances
// are assumed to be in meters and times in seconds.
#include <cstdio>
#include <vector>
#include "google/protobuf/text_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/random.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/linear_solver/linear_solver.h"
DEFINE_int32(verbose, 0, "Verbosity level.");
DEFINE_int32(facilities, 20, "Candidate facilities to consider.");
DEFINE_int32(clients, 100, "Clients to serve.");
DEFINE_double(fix_cost, 5000, "Cost of opening a facility.");
namespace operations_research {
typedef struct {
double x{0};
double y{0};
} Location;
typedef struct {
int f{-1};
int c{-1};
MPVariable* x{nullptr};
} Edge;
static double Distance(const Location& src, const Location& dst) {
return sqrt((src.x-dst.x)*(src.x-dst.x) + (src.y-dst.y)*(src.y-dst.y));
}
static void UncapacitatedFacilityLocation(int32 facilities,
int32 clients, double fix_cost,
MPSolver::OptimizationProblemType optimization_problem_type) {
LOG(INFO) << "Starting " << __func__;
// Local Constants
const int32 kXMax = 1000;
const int32 kYMax = 1000;
const double kMaxDistance = 6*sqrt((kXMax*kYMax))/facilities;
const int kStrLen = 1024;
// char buffer for names
char name_buffer[kStrLen+1];
name_buffer[kStrLen] = '\0';
LOG(INFO) << "Facilities/Clients/Fix cost/MaxDist: " << facilities << "/"
<< clients << "/" << fix_cost << "/" << kMaxDistance;
// Setting up facilities and demand points
MTRandom randomizer(/*fixed seed*/20191029);
std::vector<Location> facility(facilities);
std::vector<Location> client(clients);
for (int i = 0; i < facilities; ++i) {
facility[i].x = randomizer.Uniform(kXMax + 1);
facility[i].y = randomizer.Uniform(kYMax + 1);
}
for (int i = 0; i < clients; ++i) {
client[i].x = randomizer.Uniform(kXMax + 1);
client[i].y = randomizer.Uniform(kYMax + 1);
}
// Setup uncapacitated facility location model:
// Min sum( c_f * x_f : f in Facilities) + sum(x_{f,c} * x_{f,c} : {f,c} in E)
// s.t. (1) sum(x_{f,c} : f in Facilities) >= 1 forall c in Clients
// (2) x_f - x_{f,c} >= 0 forall {f,c} in E
// (3) x_f in {0,1} forall f in Facilities
//
// We consider E as the pairs {f,c} in Facilities x Clients such that
// Distance(f,c) <= kMaxDistance
MPSolver solver("UncapacitatedFacilityLocation", optimization_problem_type);
const double infinity = solver.infinity();
MPObjective* objective = solver.MutableObjective();
objective->SetMinimization();
// Add binary facilities variables
std::vector<MPVariable*> xf{};
for (int f = 0; f < facilities; ++f) {
snprintf(name_buffer, kStrLen, "x[%d](%g,%g)", f,
facility[f].x, facility[f].y);
MPVariable* x = solver.MakeBoolVar(name_buffer);
xf.push_back(x);
objective->SetCoefficient(x, fix_cost);
}
// Build edge variables
std::vector<Edge> edges;
for (int c = 0; c < clients; ++c) {
snprintf(name_buffer, kStrLen, "R-Client[%d](%g,%g)", c,
client[c].x, client[c].y);
MPConstraint* client_constraint = solver.MakeRowConstraint(/* lb */1,
/* ub */infinity, name_buffer);
for (int f = 0; f < facilities; ++f) {
double distance = Distance(facility[f], client[c]);
if (distance > kMaxDistance) continue;
Edge edge{};
snprintf(name_buffer, kStrLen, "x[%d,%d]", f, c);
edge.x = solver.MakeNumVar(/* lb */0, /*ub */1, name_buffer);
edge.f = f;
edge.c = c;
edges.push_back(edge);
objective->SetCoefficient(edge.x, distance);
// coefficient for constraint (1)
client_constraint->SetCoefficient(edge.x, 1);
// add constraint (2)
snprintf(name_buffer, kStrLen, "R-Edge[%d,%d]", f, c);
MPConstraint* edge_constraint = solver.MakeRowConstraint(/* lb */0,
/* ub */infinity, name_buffer);
edge_constraint->SetCoefficient(edge.x, -1);
edge_constraint->SetCoefficient(xf[f], 1);
}
}// End adding all edge variables
LOG(INFO) << "Number of variables = " << solver.NumVariables();
LOG(INFO) << "Number of constraints = " << solver.NumConstraints();
// display on screen LP if small enough
if (clients <= 10 && facilities <= 10) {
std::string lp_string{};
solver.ExportModelAsLpFormat(/* obfuscate */false, &lp_string);
std::cout << "LP-Model:\n" << lp_string << std::endl;
}
// Set options and solve
solver.SetNumThreads(8);
solver.EnableOutput();
const MPSolver::ResultStatus result_status = solver.Solve();
// Check that the problem has an optimal solution.
if (result_status != MPSolver::OPTIMAL) {
LOG(FATAL) << "The problem does not have an optimal solution!";
} else {
LOG(INFO) << "Optimal objective value = " << objective->Value();
if (FLAGS_verbose) {
std::vector<std::vector<int>> solution(facilities);
for (auto& edge : edges) {
if (edge.x->solution_value() < 0.5) continue;
solution[edge.f].push_back(edge.c);
}
std::cout << "\tSolution:\n";
for (int f = 0; f < facilities; ++f) {
if (solution[f].size() < 1) continue;
assert(xf[f]->solution_value() > 0.5);
snprintf(name_buffer, kStrLen, "\t Facility[%d](%g,%g):", f,
facility[f].x, facility[f].y);
std::cout << name_buffer;
int i = 1;
for (auto c : solution[f]) {
snprintf(name_buffer, kStrLen, " Client[%d](%g,%g)", c,
client[c].x, client[c].y);
if(i++ >= 5) {
std::cout << "\n\t\t";
i = 1;
}
std::cout << name_buffer;
}
std::cout << "\n";
}
}
std::cout << "\n";
LOG(INFO) << "";
LOG(INFO) << "Advanced usage:";
LOG(INFO) << "Problem solved in " << solver.DurationSinceConstruction()
<< " milliseconds";
LOG(INFO) << "Problem solved in " << solver.iterations() << " iterations";
LOG(INFO) << "Problem solved in " << solver.nodes()
<< " branch-and-bound nodes";
}
}
void RunAllExamples(int32 facilities, int32 clients, double fix_cost) {
#if defined(USE_CBC)
LOG(INFO) << "---- Integer programming example with CBC ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_GLPK)
LOG(INFO) << "---- Integer programming example with GLPK ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_SCIP)
LOG(INFO) << "---- Integer programming example with SCIP ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_GUROBI)
LOG(INFO) << "---- Integer programming example with Gurobi ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING);
#endif // USE_GUROBI
#if defined(USE_CPLEX)
LOG(INFO) << "---- Integer programming example with CPLEX ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING);
#endif // USE_CPLEX
LOG(INFO) << "---- Integer programming example with CP-SAT ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::SAT_INTEGER_PROGRAMMING);
}
} // namespace operations_research
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
gflags::SetUsageMessage(
std::string("This program solve a (randomly generated)\n") +
std::string("Uncapacitated Facility Location Problem. Sample Usage:\n"));
gflags::ParseCommandLineFlags(&argc, &argv, true);
CHECK_LT(0, FLAGS_facilities) << "Specify an instance size greater than 0.";
CHECK_LT(0, FLAGS_clients) << "Specify a non-null client size.";
CHECK_LT(0, FLAGS_fix_cost) << "Specify a non-null client size.";
FLAGS_logtostderr = 1;
operations_research::RunAllExamples(FLAGS_facilities, FLAGS_clients,
FLAGS_fix_cost);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_SIGNAL_HPP_
#define _KUL_SIGNAL_HPP_
#include "kul/proc.hpp"
#include <signal.h>
#include <execinfo.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <ucontext.h>
#ifndef REG_EIP
#ifdef __x86_64__
#define REG_EIP REG_RIP
#endif
if defined(__NetBSD__)
#define REG_EIP _REG_RIP
#endif
#endif
static void kul_sig_handler(int s, siginfo_t* info, void* v);
namespace kul{
class Signal;
class SignalStatic{
private:
bool addr = 0, q = 0;
struct sigaction sigHandler;
std::vector<std::function<void(int)>> ab, in, se;
SignalStatic(){
addr = kul::env::WHICH("addr2line");
sigemptyset(&sigHandler.sa_mask);
sigHandler.sa_flags = SA_SIGINFO;
sigHandler.sa_sigaction = kul_sig_handler;
sigaction(SIGSEGV, &sigHandler, NULL);
}
static SignalStatic& INSTANCE(){
static SignalStatic ss;
return ss;
}
public:
void quiet(){ q = 1; }
friend class Signal;
friend void ::kul_sig_handler(int s, siginfo_t* i, void* v);
};
class Signal{
public:
Signal(){
kul::SignalStatic::INSTANCE();
}
void abrt(const std::function<void(int)>& f){ kul::SignalStatic::INSTANCE().ab.push_back(f); }
void intr(const std::function<void(int)>& f){ kul::SignalStatic::INSTANCE().in.push_back(f); }
void segv(const std::function<void(int)>& f){ kul::SignalStatic::INSTANCE().se.push_back(f); }
void quiet(){ kul::SignalStatic::INSTANCE().q = 1; }
};
}
void kul_sig_handler(int s, siginfo_t* info, void* v) {
if(info->si_pid == 0 || info->si_pid == kul::this_proc::id()){
if(s == SIGSEGV) for(auto& f : kul::SignalStatic::INSTANCE().se) f(s);
if(!kul::SignalStatic::INSTANCE().q){
ucontext_t *uc = (ucontext_t *) v;
void *trace[16];
char **messages = (char **)NULL;
int i, trace_size = 0;
trace_size = backtrace(trace, 16);
#if defined(__arm__)
trace[1] = (void *) uc->uc_mcontext.arm_r0;
#elif defined(__APPLE__)
trace[1] = (void *) uc->uc_mcontext->__ss.__rip;
#elif defined(__NetBSD__)
trace[1] = (void *) uc->uc_mcontext.__gregs[REG_EIP];
#else
trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];
#endif
messages = backtrace_symbols(trace, trace_size);
printf("[bt] Stacktrace:\n");
for (i=2; i<trace_size; ++i){
printf("[bt] %s : ", messages[i]);
size_t p = 0;
while(messages[i][p] != '(' && messages[i][p] != ' '&& messages[i][p] != 0) ++p;
std::string s(messages[i]);
s = s.substr(0, p);
if(kul::SignalStatic::INSTANCE().addr)
kul::Process("addr2line").arg(trace[i]).arg("-e").arg(s).start();
}
}
exit(s);
}
}
namespace kul{
}// END NAMESPACE kul
// kul::Signals sig;
#endif /* _KUL_SIGNAL_HPP_ */
<commit_msg>bsd checks<commit_after>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_SIGNAL_HPP_
#define _KUL_SIGNAL_HPP_
#include "kul/proc.hpp"
#include <signal.h>
#include <execinfo.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif /* __USE_GNU */
#include <ucontext.h>
#ifndef REG_EIP
#ifdef __x86_64__
#define REG_EIP REG_RIP
#endif /* __x86_64__ */
#if defined(__NetBSD__)
#define REG_EIP _REG_RIP
#endif /* __NetBSD__ */
#endif /* REG_EIP */
static void kul_sig_handler(int s, siginfo_t* info, void* v);
namespace kul{
class Signal;
class SignalStatic{
private:
bool addr = 0, q = 0;
struct sigaction sigHandler;
std::vector<std::function<void(int)>> ab, in, se;
SignalStatic(){
addr = kul::env::WHICH("addr2line");
sigemptyset(&sigHandler.sa_mask);
sigHandler.sa_flags = SA_SIGINFO;
sigHandler.sa_sigaction = kul_sig_handler;
sigaction(SIGSEGV, &sigHandler, NULL);
}
static SignalStatic& INSTANCE(){
static SignalStatic ss;
return ss;
}
public:
void quiet(){ q = 1; }
friend class Signal;
friend void ::kul_sig_handler(int s, siginfo_t* i, void* v);
};
class Signal{
public:
Signal(){
kul::SignalStatic::INSTANCE();
}
void abrt(const std::function<void(int)>& f){ kul::SignalStatic::INSTANCE().ab.push_back(f); }
void intr(const std::function<void(int)>& f){ kul::SignalStatic::INSTANCE().in.push_back(f); }
void segv(const std::function<void(int)>& f){ kul::SignalStatic::INSTANCE().se.push_back(f); }
void quiet(){ kul::SignalStatic::INSTANCE().q = 1; }
};
}
void kul_sig_handler(int s, siginfo_t* info, void* v) {
if(info->si_pid == 0 || info->si_pid == kul::this_proc::id()){
if(s == SIGSEGV) for(auto& f : kul::SignalStatic::INSTANCE().se) f(s);
if(!kul::SignalStatic::INSTANCE().q){
ucontext_t *uc = (ucontext_t *) v;
void *trace[16];
char **messages = (char **)NULL;
int i, trace_size = 0;
trace_size = backtrace(trace, 16);
#if defined(__arm__)
trace[1] = (void *) uc->uc_mcontext.arm_r0;
#elif defined(__APPLE__)
trace[1] = (void *) uc->uc_mcontext->__ss.__rip;
#elif defined(__NetBSD__)
trace[1] = (void *) uc->uc_mcontext.__gregs[REG_EIP];
#else
trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];
#endif
messages = backtrace_symbols(trace, trace_size);
printf("[bt] Stacktrace:\n");
for (i=2; i<trace_size; ++i){
printf("[bt] %s : ", messages[i]);
size_t p = 0;
while(messages[i][p] != '(' && messages[i][p] != ' '&& messages[i][p] != 0) ++p;
std::string s(messages[i]);
s = s.substr(0, p);
if(kul::SignalStatic::INSTANCE().addr)
kul::Process("addr2line").arg(trace[i]).arg("-e").arg(s).start();
}
}
exit(s);
}
}
namespace kul{
}// END NAMESPACE kul
// kul::Signals sig;
#endif /* _KUL_SIGNAL_HPP_ */
<|endoftext|> |
<commit_before>
#include "joystickDrive.hpp"
//static SDL_Joystick *joystick;
int main()
{
joystickDrive jD;
for(;;)
{
jD.setMotor();
usleep(1000);
}
}
joystickDrive::joystickDrive()
{
joystick_open();
m_motorCtr.SetupSerial();
}
joystickDrive::~joystickDrive()
{
joystick_close();
}
//return [0,2 PI], normal math def
inline double joystickDrive::getHeading()
{
//double theta = atan2(-1*rightAnalogY, rightAnalogX);
double theta = atan2(-1*leftAnalogY, leftAnalogX);
return theta;
}
inline double scaleThrottle(double t)
{
const double slope = (double)100/(double)255;
std::cout << "t: " << t << "\tf(t):" << (t-50)*slope + 50 << std::endl;
return( (t-50)*slope + 50 );
}
void joystickDrive::setMotorTank()
{
readJoystick();
int lvel = (-1*leftAnalogY+32768) / (double)65536 * (double)255-128;
int rvel = (-1*rightAnalogY+32768) / (double)65536 * (double)255-128;
std::cout << "init scale lvel: "<< lvel << std::endl;
if( (abs(lvel) - 50 < 0) || isnan(lvel) || isinf(lvel))//dead zone
{
lvel = 0;
std::cout << "first" << std::endl;
}
else if(lvel > 127 || lvel < -128)//stupid input check ("range check")
{
lvel = 0;
std::cout << "second" << std::endl;
}
else if( (abs(scaleThrottle(lvel)) > 127) )//scale check
{
lvel = 127;
}
else
{
lvel = scaleThrottle(lvel);
}
if( (abs(rvel) - 50 < 0) || isnan(rvel) || isinf(rvel))//dead zone
{
rvel = 0;
}
else if(rvel > 127 || rvel < -128)//stupid input check ("range check")
{
rvel = 0;
}
else if( (abs(scaleThrottle(rvel)) > 127) )//scale check
{
rvel = 127;
}
else
{
rvel = scaleThrottle(rvel);
}
std::cout << "right at ("<< rightAnalogX << "," << rightAnalogY << ")\trvel: " << rvel << std::endl;
std::cout << "left at ("<< leftAnalogX << "," << leftAnalogY << ")\tlvel: " << lvel << std::endl;
m_motorCtr.set_motors(lvel, rvel);
}
void joystickDrive::setMotor()
{
readJoystick();
char theta = -1*(getHeading() * 128/(M_PI) + 64 + 128);
//double mag = sqrt(rightAnalogX*rightAnalogX + rightAnalogY*rightAnalogY);
double mag = sqrt(leftAnalogX*leftAnalogX + leftAnalogY*leftAnalogY);
double norm_mag = mag / (32768*sqrt(2));
double vel = norm_mag * 255;
if(vel < 50 || isnan(vel) || isinf(vel) || vel > 255)//dead zone
{
vel = 0;
theta = 0;
}
else if((vel > 128) && (scaleThrottle(vel) > 128))//max
{
vel = 128;
}
else if( theta > 120 || theta < -120 )
{
vel = scaleThrottle(vel);
m_motorCtr.set_motors(-1*vel, -1*vel);
}
else
{
vel = scaleThrottle(vel);
}
//std::cout << "right at ("<< rightAnalogX << "," << rightAnalogY << ")\twould have set vel: " << vel << " head: " << (int)theta << std::endl;
std::cout << "right at ("<< leftAnalogX << "," << leftAnalogY << ")\twould have set vel: " << vel << " head: " << (int)theta << std::endl;
m_motorCtr.set_heading(vel,theta);
}
void joystickDrive::joystick_close(void) {
// Send an SDL_QUIT event to the joystick event loop
SDL_QuitEvent quitEvent = { SDL_QUIT };
SDL_PushEvent((SDL_Event*) &quitEvent);
}
/**
* Opens the joystick.
*
* @return NULL if success;
* or a message if error.
*/
const char* joystickDrive::joystick_open(void) {
int err;
// Initialize SDL
if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0 ) {
return SDL_GetError();
}
joystick = SDL_JoystickOpen(0);
if (!SDL_JoystickOpened(0)) {
// TODO: would it work to return SDL_GetError() here?
return "SDL_JoystickOpen failed";
}
// Call joystick_run() in new thread
//err = pthread_create(&joystick_thread, NULL, &joystick_run, NULL);
switch (err) {
case EAGAIN:
return "insufficient thread resources";
case EINVAL:
return "invalid thread attributes";
default:
break;
}
return NULL; // no error
}
void joystickDrive::readJoystick() {
int i;
int done;
SDL_Event event;
/*
// Ignore initial events during startup
for (i=0;i<20;i++) {
SDL_PollEvent(&event);
}
*/
// Poll the joystick for events, and update globals
done = 0;
while ( SDL_PollEvent(&event) ) {
switch (event.type) {
case SDL_JOYAXISMOTION:
switch (event.jaxis.axis) {
case 0:
leftAnalogX = event.jaxis.value;
break;
case 1:
leftAnalogY = event.jaxis.value;
break;
case 2:
rightAnalogX = event.jaxis.value;
break;
case 3:
rightAnalogY = event.jaxis.value;
break;
case 4:
dPadX = event.jaxis.value;
break;
case 5:
dPadY = event.jaxis.value;
break;
default:
break;
}
break;
case SDL_JOYBUTTONDOWN:
joystickButtons |= (1 << event.jbutton.button);
break;
case SDL_JOYBUTTONUP:
joystickButtons &= ~(1 << event.jbutton.button);
break;
/*
case SDL_KEYDOWN:
if ( event.key.keysym.sym != SDLK_ESCAPE ) {//this line doesnt work
break;
}
// Fall through to signal quit
*/
case SDL_QUIT:
done = 1;
break;
default:
break;
}
}
}
<commit_msg><commit_after>
#include "joystickDrive.hpp"
//static SDL_Joystick *joystick;
int main()
{
joystickDrive jD;
for(;;)
{
jD.setMotor();
usleep(1000);
}
}
joystickDrive::joystickDrive()
{
joystick_open();
m_motorCtr.SetupSerial();
}
joystickDrive::~joystickDrive()
{
joystick_close();
}
//return [0,2 PI], normal math def
inline double joystickDrive::getHeading()
{
//double theta = atan2(-1*rightAnalogY, rightAnalogX);
double theta = atan2(-1*leftAnalogY, leftAnalogX);
return theta;
}
inline double scaleThrottle(double t)
{
const double slope = (double)100/(double)255;
std::cout << "t: " << t << "\tf(t):" << (t-50)*slope + 50 << std::endl;
return( (t-50)*slope + 50 );
}
void joystickDrive::setMotorTank()
{
readJoystick();
int lvel = (-1*leftAnalogY+32768) / (double)65536 * (double)255-128;
int rvel = (-1*rightAnalogY+32768) / (double)65536 * (double)255-128;
std::cout << "init scale lvel: "<< lvel << std::endl;
if( (abs(lvel) - 50 < 0) || isnan(lvel) || isinf(lvel))//dead zone
{
lvel = 0;
std::cout << "first" << std::endl;
}
else if(lvel > 127 || lvel < -128)//stupid input check ("range check")
{
lvel = 0;
std::cout << "second" << std::endl;
}
else if( (abs(scaleThrottle(lvel)) > 127) )//scale check
{
lvel = 127;
}
else
{
lvel = scaleThrottle(lvel);
}
if( (abs(rvel) - 50 < 0) || isnan(rvel) || isinf(rvel))//dead zone
{
rvel = 0;
}
else if(rvel > 127 || rvel < -128)//stupid input check ("range check")
{
rvel = 0;
}
else if( (abs(scaleThrottle(rvel)) > 127) )//scale check
{
rvel = 127;
}
else
{
rvel = scaleThrottle(rvel);
}
std::cout << "right at ("<< rightAnalogX << "," << rightAnalogY << ")\trvel: " << rvel << std::endl;
std::cout << "left at ("<< leftAnalogX << "," << leftAnalogY << ")\tlvel: " << lvel << std::endl;
m_motorCtr.set_motors(lvel, rvel);
}
void joystickDrive::setMotor()
{
readJoystick();
char theta = -1*(getHeading() * 128/(M_PI) + 64 + 128);
//double mag = sqrt(rightAnalogX*rightAnalogX + rightAnalogY*rightAnalogY);
double mag = sqrt(leftAnalogX*leftAnalogX + leftAnalogY*leftAnalogY);
double norm_mag = mag / (32768*sqrt(2));
double vel = norm_mag * 255;
if(vel < 50 || isnan(vel) || isinf(vel) || vel > 255)//dead zone
{
vel = 0;
theta = 0;
}
else if((vel > 128) && (scaleThrottle(vel) > 128))//max
{
vel = 128;
}
else if( theta > 120 || theta < -120 )
{
vel = scaleThrottle(vel);
m_motorCtr.set_motors(-1*vel, -1*vel);
}
else
{
vel = scaleThrottle(vel);
}
//std::cout << "right at ("<< rightAnalogX << "," << rightAnalogY << ")\twould have set vel: " << vel << " head: " << (int)theta << std::endl;
std::cout << "right at ("<< leftAnalogX << "," << leftAnalogY << ")\twould have set vel: " << vel << " head: " << (int)theta << std::endl;
m_motorCtr.set_heading(vel,theta);
}
void joystickDrive::joystick_close(void) {
// Send an SDL_QUIT event to the joystick event loop
SDL_QuitEvent quitEvent = { SDL_QUIT };
SDL_PushEvent((SDL_Event*) &quitEvent);
}
/**
* Opens the joystick.
*
* @return NULL if success;
* or a message if error.
*/
const char* joystickDrive::joystick_open(void) {
int err;
// Initialize SDL
if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0 ) {
return SDL_GetError();
}
joystick = SDL_JoystickOpen(0);
if (!SDL_JoystickOpened(0)) {
// TODO: would it work to return SDL_GetError() here?
return "SDL_JoystickOpen failed";
}
// Call joystick_run() in new thread
//err = pthread_create(&joystick_thread, NULL, &joystick_run, NULL);
switch (err) {
case EAGAIN:
return "insufficient thread resources";
case EINVAL:
return "invalid thread attributes";
default:
break;
}
return NULL; // no error
}
void joystickDrive::readJoystick() {
int i;
int done;
SDL_Event event;
/*
// Ignore initial events during startup
for (i=0;i<20;i++) {
SDL_PollEvent(&event);
}
*/
// Poll the joystick for events, and update globals
done = 0;
while ( SDL_PollEvent(&event) ) {
switch (event.type) {
case SDL_JOYAXISMOTION:
switch (event.jaxis.axis) {
case 0:
leftAnalogX = event.jaxis.value;
break;
case 1:
leftAnalogY = event.jaxis.value;
break;
case 2:
rightAnalogX = event.jaxis.value;
break;
case 3:
rightAnalogY = event.jaxis.value;
break;
case 4:
dPadX = event.jaxis.value;
break;
case 5:
dPadY = event.jaxis.value;
break;
default:
break;
}
break;
case SDL_JOYBUTTONDOWN:
joystickButtons |= (1 << event.jbutton.button);
break;
case SDL_JOYBUTTONUP:
joystickButtons &= ~(1 << event.jbutton.button);
break;
/*
case SDL_KEYDOWN:
if ( event.key.keysym.sym != SDLK_ESCAPE ) {//this line doesnt work
break;
}
// Fall through to signal quit
*/
case SDL_QUIT:
//done = 1;
exit(-1);
break;
default:
break;
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <functional>
#include <list>
#include <map>
#include <memory>
#include "base/not_null.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/named_quantities.hpp"
#include "serialization/physics.pb.h"
using principia::base::not_null;
using principia::geometry::Instant;
using principia::geometry::Vector;
using principia::geometry::Velocity;
using principia::quantities::Acceleration;
using principia::quantities::Length;
using principia::quantities::Speed;
namespace principia {
namespace physics {
class Body;
template<typename Frame>
class Trajectory {
public:
class NativeIterator;
template<typename ToFrame>
class TransformingIterator;
// A function that transforms the coordinates to a different frame.
template<typename ToFrame>
using Transform = std::function<DegreesOfFreedom<ToFrame>(
Instant const&,
DegreesOfFreedom<Frame> const&,
not_null<Trajectory<Frame> const*> const)>;
// No transfer of ownership. |body| must live longer than the trajectory as
// the trajectory holds a reference to it. If |body| is oblate it must be
// expressed in the same frame as the trajectory.
explicit Trajectory(not_null<Body const*> const body);
~Trajectory() = default;
// Returns an iterator at the first point of the trajectory. Complexity is
// O(|depth|). The result may be at end if the trajectory is empty.
NativeIterator first() const;
// Returns at the first point of the trajectory which is on or after |time|.
// Complexity is O(|depth| + Ln(|length|)). The result may be at end if the
// |time| is after the end of the trajectory.
NativeIterator on_or_after(Instant const& time) const;
// Returns an iterator at the last point of the trajectory. Complexity is
// O(1). The trajectory must not be empty.
NativeIterator last() const;
// Same as |first| above, but returns an iterator that performs a coordinate
// tranformation to ToFrame.
template<typename ToFrame>
TransformingIterator<ToFrame> first_with_transform(
Transform<ToFrame> const& transform) const;
// Returns at the first point of the trajectory which is on or after |time|.
// Complexity is O(|depth| + Ln(|length|)). The result may be at end if the
// |time| is after the end of the trajectory.
template<typename ToFrame>
TransformingIterator<ToFrame> on_or_after_with_transform(
Instant const& time,
Transform<ToFrame> const& transform) const;
// Same as |last| above, but returns an iterator that performs a coordinate
// tranformation to ToFrame.
template<typename ToFrame>
TransformingIterator<ToFrame> last_with_transform(
Transform<ToFrame> const& transform) const;
// These functions return the series of positions/velocities/times for the
// trajectory of the body. All three containers are guaranteed to have the
// same size. These functions are O(|depth| + |length|).
std::map<Instant, Position<Frame>> Positions() const;
std::map<Instant, Velocity<Frame>> Velocities() const;
std::list<Instant> Times() const;
// Appends one point to the trajectory.
void Append(Instant const& time,
DegreesOfFreedom<Frame> const& degrees_of_freedom);
// Removes all data for times (strictly) greater than |time|, as well as all
// child trajectories forked at times (strictly) greater than |time|.
void ForgetAfter(Instant const& time);
// Removes all data for times less than or equal to |time|, as well as all
// child trajectories forked at times less than or equal to |time|. This
// trajectory must be a root.
void ForgetBefore(Instant const& time);
// Creates a new child trajectory forked at time |time|, and returns it. The
// child trajectory may be changed independently from the parent trajectory
// for any time (strictly) greater than |time|. The child trajectory is owned
// by its parent trajectory. Calling ForgetAfter or ForgetBefore on the
// parent trajectory with an argument that causes the time |time| to be
// removed deletes the child trajectory. Deleting the parent trajectory
// deletes all child trajectories. |time| must be one of the times of the
// current trajectory (as returned by Times()). No transfer of ownership.
not_null<Trajectory*> Fork(Instant const& time);
// Deletes the child trajectory denoted by |*fork|, which must be a pointer
// previously returned by Fork for this object. Nulls |*fork|.
void DeleteFork(not_null<Trajectory**> const fork);
// Returns true if this is a root trajectory.
bool is_root() const;
// Returns the root trajectory.
not_null<Trajectory const*> root() const;
not_null<Trajectory*> root();
// Returns the fork time for a nonroot trajectory and null for a root
// trajectory.
Instant const* fork_time() const;
// The body to which this trajectory pertains. The body is cast to the type
// B. An error occurs in debug mode if the cast fails.
template<typename B>
std::enable_if_t<std::is_base_of<Body, B>::value,
not_null<B const*>> body() const;
// This function represents the intrinsic acceleration of a body, irrespective
// of any external field. It can be due e.g., to an engine burn.
using IntrinsicAcceleration =
std::function<Vector<Acceleration, Frame>(Instant const& time)>;
// Sets the intrinsic acceleration for the trajectory of a massless body.
// For a nonroot trajectory the intrinsic acceleration only applies to times
// (strictly) greater than |fork_time()|. In other words, the function
// |acceleration| is never called with times less than or equal to
// |fork_time()|. It may, however, be called with times beyond |last_time()|.
// For a root trajectory the intrinsic acceleration applies to times greater
// than or equal to the first time of the trajectory. Again, it may apply
// beyond |last_time()|.
// It is an error to call this function for a trajectory that already has an
// intrinsic acceleration, or for the trajectory of a massive body.
void set_intrinsic_acceleration(IntrinsicAcceleration const acceleration);
// Removes any intrinsic acceleration for the trajectory.
void clear_intrinsic_acceleration();
// Returns true if this trajectory has an intrinsic acceleration.
bool has_intrinsic_acceleration() const;
// Computes the intrinsic acceleration for this trajectory at time |time|. If
// |has_intrinsic_acceleration()| return false, or if |time| is before the
// |fork_time()| (or initial time) of this trajectory, the returned
// acceleration is zero.
Vector<Acceleration, Frame> evaluate_intrinsic_acceleration(
Instant const& time) const;
// This trajectory must be a root.
void WriteToMessage(not_null<serialization::Trajectory*> const message) const;
// TODO(egg): implement when |Body| is serializable.
static Trajectory ReadFromMessage(serialization::Trajectory const& message);
// A base class for iterating over the timeline of a trajectory, taking forks
// into account. Objects of this class cannot be created.
class Iterator {
public:
Iterator& operator++();
bool at_end() const;
Instant const& time() const;
protected:
using Timeline = std::map<Instant, DegreesOfFreedom<Frame>>;
Iterator() = default;
// No transfer of ownership.
void InitializeFirst(not_null<Trajectory const*> const trajectory);
void InitializeOnOrAfter(Instant const& time,
not_null<Trajectory const*> const trajectory);
void InitializeLast(not_null<Trajectory const*> const trajectory);
typename Timeline::const_iterator current() const;
not_null<Trajectory const*> trajectory() const;
private:
typename Timeline::const_iterator current_;
std::list<not_null<Trajectory const*>> ancestry_; // Pointers not owned.
std::list<typename Timeline::iterator> forks_;
};
// An iterator which returns the coordinates in the native frame of the
// trajectory, i.e., |Frame|.
class NativeIterator : public Iterator {
public:
DegreesOfFreedom<Frame> const& degrees_of_freedom() const;
private:
NativeIterator() = default;
friend class Trajectory;
};
// An iterator which returns the coordinates in another frame.
template<typename ToFrame>
class TransformingIterator : public Iterator {
public:
DegreesOfFreedom<ToFrame> degrees_of_freedom() const;
private:
explicit TransformingIterator(Transform<ToFrame> const& transform);
Transform<ToFrame> transform_;
friend class Trajectory;
};
private:
using Timeline = std::map<Instant, DegreesOfFreedom<Frame>>;
// A constructor for creating a child trajectory during forking.
Trajectory(not_null<Body const*> const body,
not_null<Trajectory*> const parent,
typename Timeline::iterator const& fork);
// This trajectory need not be a root.
void WriteSubTreeToMessage(
not_null<serialization::Trajectory*> const message) const;
not_null<Body const*> const body_;
Trajectory* const parent_; // Null for a root trajectory.
// Null for a root trajectory.
std::unique_ptr<typename Timeline::iterator> fork_;
// There may be several forks starting from the same time, hence the multimap.
// Child trajectories are owned.
std::multimap<Instant, not_null<std::unique_ptr<Trajectory>>> children_;
Timeline timeline_;
std::unique_ptr<IntrinsicAcceleration> intrinsic_acceleration_;
};
} // namespace physics
} // namespace principia
#include "trajectory_body.hpp"
<commit_msg>Improve comments.<commit_after>#pragma once
#include <functional>
#include <list>
#include <map>
#include <memory>
#include "base/not_null.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/named_quantities.hpp"
#include "serialization/physics.pb.h"
using principia::base::not_null;
using principia::geometry::Instant;
using principia::geometry::Vector;
using principia::geometry::Velocity;
using principia::quantities::Acceleration;
using principia::quantities::Length;
using principia::quantities::Speed;
namespace principia {
namespace physics {
class Body;
template<typename Frame>
class Trajectory {
public:
class NativeIterator;
template<typename ToFrame>
class TransformingIterator;
// A function that transforms the coordinates to a different frame.
template<typename ToFrame>
using Transform = std::function<DegreesOfFreedom<ToFrame>(
Instant const&,
DegreesOfFreedom<Frame> const&,
not_null<Trajectory<Frame> const*> const)>;
// No transfer of ownership. |body| must live longer than the trajectory as
// the trajectory holds a reference to it. If |body| is oblate it must be
// expressed in the same frame as the trajectory.
explicit Trajectory(not_null<Body const*> const body);
~Trajectory() = default;
// Returns an iterator at the first point of the trajectory. Complexity is
// O(|depth|). The result may be at end if the trajectory is empty.
NativeIterator first() const;
// Returns at the first point of the trajectory which is on or after |time|.
// Complexity is O(|depth| + Ln(|length|)). The result may be at end if the
// |time| is after the end of the trajectory.
NativeIterator on_or_after(Instant const& time) const;
// Returns an iterator at the last point of the trajectory. Complexity is
// O(1). The trajectory must not be empty.
NativeIterator last() const;
// Same as |first| above, but returns an iterator that performs a coordinate
// tranformation to ToFrame.
template<typename ToFrame>
TransformingIterator<ToFrame> first_with_transform(
Transform<ToFrame> const& transform) const;
// Returns at the first point of the trajectory which is on or after |time|.
// Complexity is O(|depth| + Ln(|length|)). The result may be at end if the
// |time| is after the end of the trajectory.
template<typename ToFrame>
TransformingIterator<ToFrame> on_or_after_with_transform(
Instant const& time,
Transform<ToFrame> const& transform) const;
// Same as |last| above, but returns an iterator that performs a coordinate
// tranformation to ToFrame.
template<typename ToFrame>
TransformingIterator<ToFrame> last_with_transform(
Transform<ToFrame> const& transform) const;
// These functions return the series of positions/velocities/times for the
// trajectory of the body. All three containers are guaranteed to have the
// same size. These functions are O(|depth| + |length|).
std::map<Instant, Position<Frame>> Positions() const;
std::map<Instant, Velocity<Frame>> Velocities() const;
std::list<Instant> Times() const;
// Appends one point to the trajectory.
void Append(Instant const& time,
DegreesOfFreedom<Frame> const& degrees_of_freedom);
// Removes all data for times (strictly) greater than |time|, as well as all
// child trajectories forked at times (strictly) greater than |time|.
void ForgetAfter(Instant const& time);
// Removes all data for times less than or equal to |time|, as well as all
// child trajectories forked at times less than or equal to |time|. This
// trajectory must be a root.
void ForgetBefore(Instant const& time);
// Creates a new child trajectory forked at time |time|, and returns it. The
// child trajectory is an exact copy of the current trajectory (including for
// times greater than |time|). It may be changed independently from the
// parent trajectory for any time (strictly) greater than |time|. The child
// trajectory is owned by its parent trajectory. Calling ForgetAfter or
// ForgetBefore on the parent trajectory with an argument that causes the time
// |time| to be removed deletes the child trajectory. Deleting the parent
// trajectory deletes all child trajectories. |time| must be one of the times
// of the current trajectory (as returned by Times()). No transfer of
// ownership.
not_null<Trajectory*> Fork(Instant const& time);
// Deletes the child trajectory denoted by |*fork|, which must be a pointer
// previously returned by Fork for this object. Nulls |*fork|.
void DeleteFork(not_null<Trajectory**> const fork);
// Returns true if this is a root trajectory.
bool is_root() const;
// Returns the root trajectory.
not_null<Trajectory const*> root() const;
not_null<Trajectory*> root();
// Returns the fork time for a nonroot trajectory and null for a root
// trajectory.
Instant const* fork_time() const;
// The body to which this trajectory pertains. The body is cast to the type
// B. An error occurs in debug mode if the cast fails.
template<typename B>
std::enable_if_t<std::is_base_of<Body, B>::value,
not_null<B const*>> body() const;
// This function represents the intrinsic acceleration of a body, irrespective
// of any external field. It can be due e.g., to an engine burn.
using IntrinsicAcceleration =
std::function<Vector<Acceleration, Frame>(Instant const& time)>;
// Sets the intrinsic acceleration for the trajectory of a massless body.
// For a nonroot trajectory the intrinsic acceleration only applies to times
// (strictly) greater than |fork_time()|. In other words, the function
// |acceleration| is never called with times less than or equal to
// |fork_time()|. It may, however, be called with times beyond |last_time()|.
// For a root trajectory the intrinsic acceleration applies to times greater
// than or equal to the first time of the trajectory. Again, it may apply
// beyond |last_time()|.
// It is an error to call this function for a trajectory that already has an
// intrinsic acceleration, or for the trajectory of a massive body.
void set_intrinsic_acceleration(IntrinsicAcceleration const acceleration);
// Removes any intrinsic acceleration for the trajectory.
void clear_intrinsic_acceleration();
// Returns true if this trajectory has an intrinsic acceleration.
bool has_intrinsic_acceleration() const;
// Computes the intrinsic acceleration for this trajectory at time |time|. If
// |has_intrinsic_acceleration()| return false, or if |time| is before the
// |fork_time()| (or initial time) of this trajectory, the returned
// acceleration is zero.
Vector<Acceleration, Frame> evaluate_intrinsic_acceleration(
Instant const& time) const;
// This trajectory must be a root.
void WriteToMessage(not_null<serialization::Trajectory*> const message) const;
// TODO(egg): implement when |Body| is serializable.
static Trajectory ReadFromMessage(serialization::Trajectory const& message);
// A base class for iterating over the timeline of a trajectory, taking forks
// into account. Objects of this class cannot be created.
class Iterator {
public:
Iterator& operator++();
bool at_end() const;
Instant const& time() const;
protected:
using Timeline = std::map<Instant, DegreesOfFreedom<Frame>>;
Iterator() = default;
// No transfer of ownership.
void InitializeFirst(not_null<Trajectory const*> const trajectory);
void InitializeOnOrAfter(Instant const& time,
not_null<Trajectory const*> const trajectory);
void InitializeLast(not_null<Trajectory const*> const trajectory);
typename Timeline::const_iterator current() const;
not_null<Trajectory const*> trajectory() const;
private:
typename Timeline::const_iterator current_;
std::list<not_null<Trajectory const*>> ancestry_; // Pointers not owned.
std::list<typename Timeline::iterator> forks_;
};
// An iterator which returns the coordinates in the native frame of the
// trajectory, i.e., |Frame|.
class NativeIterator : public Iterator {
public:
DegreesOfFreedom<Frame> const& degrees_of_freedom() const;
private:
NativeIterator() = default;
friend class Trajectory;
};
// An iterator which returns the coordinates in another frame.
template<typename ToFrame>
class TransformingIterator : public Iterator {
public:
DegreesOfFreedom<ToFrame> degrees_of_freedom() const;
private:
explicit TransformingIterator(Transform<ToFrame> const& transform);
Transform<ToFrame> transform_;
friend class Trajectory;
};
private:
using Timeline = std::map<Instant, DegreesOfFreedom<Frame>>;
// A constructor for creating a child trajectory during forking.
Trajectory(not_null<Body const*> const body,
not_null<Trajectory*> const parent,
typename Timeline::iterator const& fork);
// This trajectory need not be a root.
void WriteSubTreeToMessage(
not_null<serialization::Trajectory*> const message) const;
not_null<Body const*> const body_;
Trajectory* const parent_; // Null for a root trajectory.
// Null for a root trajectory.
std::unique_ptr<typename Timeline::iterator> fork_;
// There may be several forks starting from the same time, hence the multimap.
// Child trajectories are owned.
std::multimap<Instant, not_null<std::unique_ptr<Trajectory>>> children_;
Timeline timeline_;
std::unique_ptr<IntrinsicAcceleration> intrinsic_acceleration_;
};
} // namespace physics
} // namespace principia
#include "trajectory_body.hpp"
<|endoftext|> |
<commit_before>#include "Image.hpp"
#include "StringEx.hpp"
#include "TargaImage.hpp"
#include "PNGImage.hpp"
using namespace std;
using namespace MPACK::Core;
namespace MPACK
{
namespace Graphics
{
Image::Image()
: m_width(0), m_height(0), m_GLFormatType(0), m_bytesPerPixel(0),
m_imageBuffer(NULL), m_internalFormatType(Image::InternalFormatType::NONE)
{
}
Image::~Image()
{
Unload();
}
void Image::Init(const int &width, const int &height)
{
Unload();
if (width < 0)
{
LOGW("PNGImage::Init() invalid width!");
m_width = 1;
}
else
{
m_width = width;
}
if (height < 0)
{
LOGW("PNGImage::Init() invalid height!");
m_height = 1;
}
else
{
m_height = height;
}
m_bytesPerPixel = 4;
m_GLFormatType = GL_RGBA;
m_imageBuffer = new BYTE[m_width * m_height * m_bytesPerPixel];
}
ReturnValue Image::Load(const std::string& path, FileFormatType fileFormatType)
{
Unload();
if (fileFormatType == FileFormatType::AUTO)
{
string ext;
Core::StringEx::GetExtension(path.c_str(), ext);
Core::StringEx::Upper(ext);
if(ext == "TGA")
{
fileFormatType = FileFormatType::TGA;
}
else if(ext == "PNG")
{
fileFormatType = FileFormatType::PNG;
}
else if(ext == "PPM")
{
fileFormatType = FileFormatType::PPM;
}
else
{
LOGE("Image::Load() format auto-detect fail: invalid extension: %s", path.c_str());
return RETURN_VALUE_KO;
}
}
switch(fileFormatType)
{
case FileFormatType::TGA:
if (LoadTGA(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Load() fail to load TGA image: %s", path.c_str());
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PNG:
if (LoadPNG(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Load() fail to load PNG image: %s", path.c_str());
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PPM:
if (LoadPPM(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Load() fail to load PPM image: %s", path.c_str());
return RETURN_VALUE_KO;
}
break;
}
return RETURN_VALUE_OK;
}
ReturnValue Image::Save(const std::string& path, FileFormatType fileFormatType)
{
if (fileFormatType == FileFormatType::AUTO)
{
fileFormatType = FileFormatType::PNG;
}
switch(fileFormatType)
{
case FileFormatType::TGA:
if (SaveTGA(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Save() fail to save image as TGA");
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PNG:
if (SavePNG(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Save() fail to save image as PNG");
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PPM:
if (SavePPM(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Save() fail to save image as PPM");
return RETURN_VALUE_KO;
}
break;
}
return RETURN_VALUE_OK;
}
void Image::Unload()
{
if (m_imageBuffer)
{
m_width = 0;
m_height = 0;
m_internalFormatType = InternalFormatType::NONE;
m_GLFormatType = 0;
m_bytesPerPixel = 0;
delete[] m_imageBuffer;
m_imageBuffer = 0;
}
}
void Image::InitColor(const int &width, const int &height, const Color &c)
{
Init(width, height);
FillColor(Rect(0, 0, m_width, m_height), c);
}
void Image::FillColor(const Rect &rect, const Color &c)
{
for(int i = 0; i < m_height; ++i)
{
for(int j = 0; j < m_width; ++j)
{
SetPixel(rect.x + i, rect.y + j, c);
}
}
}
void Image::Blit(Image *image, const GLushort &x, const GLushort &y)
{
BlitSafe(image, Point(x,y), Rect(0,0,image->GetWidth(),image->GetHeight()));
}
void Image::Blit(Image *image, const Point &point)
{
BlitSafe(image, point, Rect(0,0,image->GetWidth(),image->GetHeight()));
}
void Image::Blit(Image *image, const Point &point, const Rect &rect)
{
BlitSafe(image, point, rect);
}
void Image::FlipVertical()
{
for(int i = 0; i < (m_width >> 1); ++i)
{
for(int j = 0; j < m_height; ++j)
{
int offset1 = i * m_width + j;
offset1 *= m_bytesPerPixel;
int vi = m_width - i - 1;
int vj = j;
int offset2 = vi * m_width + vj;
offset2 *= m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
}
}
}
void Image::FlipHorizontal()
{
for(int i = 0; i < m_width; ++i)
{
for(int j = 0; j < (m_height >> 1); ++j)
{
int offset1 = i * m_width + j;
offset1 *= m_bytesPerPixel;
int vi = i;
int vj = m_height - j + 1;
int offset2 = vi * m_width + vj;
offset2 *= m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
}
}
}
GLushort Image::GetWidth() const
{
return m_width;
}
GLushort Image::GetHeight() const
{
return m_height;
}
GLushort Image::GetBytesPerPixel() const
{
return m_bytesPerPixel;
}
GLint Image::GetGLFormat() const
{
return m_GLFormatType;
}
Image::InternalFormatType Image::GetFormat() const
{
return m_internalFormatType;
}
bool Image::HaveAlphaChannel() const
{
return m_internalFormatType == Image::InternalFormatType::GRAY_ALPHA ||
m_internalFormatType == Image::InternalFormatType::RGBA;
}
const BYTE* Image::GetImageData() const
{
return m_imageBuffer;
}
const BYTE* Image::GetPixelPointer(const GLushort &x, const GLushort &y) const
{
int index=x * m_width + y;
index *= m_bytesPerPixel;
return m_imageBuffer + index;
}
Color Image::GetPixel(const GLushort &x, const GLushort &y) const
{
int index=x * m_width + y;
index *= m_bytesPerPixel;
if (m_bytesPerPixel == 4)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], m_imageBuffer[index+3]);
}
else if(m_bytesPerPixel == 3)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], 255);
}
else if(m_bytesPerPixel == 2)
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], m_imageBuffer[index+1]);
}
else
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], 255);
}
}
void Image::SetPixel(const GLushort &x, const GLushort &y, const Color &c)
{
int index=x * m_width + y;
index *= m_bytesPerPixel;
if (m_bytesPerPixel == 4)
{
m_imageBuffer[index] = c.r;
m_imageBuffer[index+1] = c.g;
m_imageBuffer[index+2] = c.b;
m_imageBuffer[index+3] = c.a;
}
else if(m_bytesPerPixel == 3)
{
m_imageBuffer[index] = c.r;
m_imageBuffer[index+1] = c.g;
m_imageBuffer[index+2] = c.b;
}
else if(m_bytesPerPixel == 2)
{
unsigned char gray = (c.r + c.g + c.b) / 3;
m_imageBuffer[index] = gray;
m_imageBuffer[index+1] = c.a;
}
else
{
unsigned char gray = (c.r + c.g + c.b) / 3;
m_imageBuffer[index] = gray;
}
}
void Image::BlitSafe(Image *image, Point point, Rect rect)
{
GLushort width = image->GetWidth();
GLushort height = image->GetHeight();
if (point.x >= m_width || point.y >= m_height)
{
return;
}
if (rect.width <= 0 || rect.height <= 0)
{
return;
}
if (rect.x >= width || rect.y >= height)
{
return;
}
if (point.x < 0)
{
point.x = 0;
}
if (point.y < 0)
{
point.y = 0;
}
GLushort maxWidth = m_width - point.x;
if (rect.width > maxWidth)
{
rect.width = maxWidth;
}
GLushort maxHeight = m_height - point.y;
if (rect.height > maxHeight)
{
rect.height = maxHeight - point.y;
}
for (int i = 0; i < rect.height; ++i)
{
for (int j = 0; j < rect.width; ++j)
{
SetPixel(point.x + i, point.y + j, image->GetPixel(i + rect.x, j + rect.y));
}
}
}
GLushort GetBPP(GLint format)
{
switch(format)
{
case GL_RGB:
return 3;
break;
case GL_RGBA:
return 4;
break;
case GL_LUMINANCE:
return 1;
break;
case GL_LUMINANCE_ALPHA:
return 2;
break;
}
return 0;
}
}
}
<commit_msg>Fix Image.cpp<commit_after>#include "Image.hpp"
#include "StringEx.hpp"
#include "TargaImage.hpp"
#include "PNGImage.hpp"
using namespace std;
using namespace MPACK::Core;
namespace MPACK
{
namespace Graphics
{
Image::Image()
: m_width(0), m_height(0), m_GLFormatType(0), m_bytesPerPixel(0),
m_imageBuffer(NULL), m_internalFormatType(Image::InternalFormatType::NONE)
{
}
Image::~Image()
{
Unload();
}
void Image::Init(const int &width, const int &height)
{
Unload();
if (width < 0)
{
LOGW("PNGImage::Init() invalid width!");
m_width = 1;
}
else
{
m_width = width;
}
if (height < 0)
{
LOGW("PNGImage::Init() invalid height!");
m_height = 1;
}
else
{
m_height = height;
}
m_bytesPerPixel = 4;
m_GLFormatType = GL_RGBA;
m_imageBuffer = new BYTE[m_width * m_height * m_bytesPerPixel];
}
ReturnValue Image::Load(const std::string& path, FileFormatType fileFormatType)
{
Unload();
if (fileFormatType == FileFormatType::AUTO)
{
string ext;
Core::StringEx::GetExtension(path.c_str(), ext);
Core::StringEx::Upper(ext);
if(ext == "TGA")
{
fileFormatType = FileFormatType::TGA;
}
else if(ext == "PNG")
{
fileFormatType = FileFormatType::PNG;
}
else if(ext == "PPM")
{
fileFormatType = FileFormatType::PPM;
}
else
{
LOGE("Image::Load() format auto-detect fail: invalid extension: %s", path.c_str());
return RETURN_VALUE_KO;
}
}
switch(fileFormatType)
{
case FileFormatType::TGA:
if (LoadTGA(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Load() fail to load TGA image: %s", path.c_str());
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PNG:
if (LoadPNG(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Load() fail to load PNG image: %s", path.c_str());
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PPM:
if (LoadPPM(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Load() fail to load PPM image: %s", path.c_str());
return RETURN_VALUE_KO;
}
break;
}
return RETURN_VALUE_OK;
}
ReturnValue Image::Save(const std::string& path, FileFormatType fileFormatType)
{
if (fileFormatType == FileFormatType::AUTO)
{
fileFormatType = FileFormatType::PNG;
}
switch(fileFormatType)
{
case FileFormatType::TGA:
if (SaveTGA(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Save() fail to save image as TGA");
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PNG:
if (SavePNG(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Save() fail to save image as PNG");
return RETURN_VALUE_KO;
}
break;
case FileFormatType::PPM:
if (SavePPM(this, path) == RETURN_VALUE_KO)
{
LOGE("Image::Save() fail to save image as PPM");
return RETURN_VALUE_KO;
}
break;
}
return RETURN_VALUE_OK;
}
void Image::Unload()
{
if (m_imageBuffer)
{
m_width = 0;
m_height = 0;
m_internalFormatType = InternalFormatType::NONE;
m_GLFormatType = 0;
m_bytesPerPixel = 0;
delete[] m_imageBuffer;
m_imageBuffer = 0;
}
}
void Image::InitColor(const int &width, const int &height, const Color &c)
{
Init(width, height);
FillColor(Rect(0, 0, m_width, m_height), c);
}
void Image::FillColor(const Rect &rect, const Color &c)
{
for(int i = 0; i < m_height; ++i)
{
for(int j = 0; j < m_width; ++j)
{
SetPixel(rect.x + i, rect.y + j, c);
}
}
}
void Image::Blit(Image *image, const GLushort &x, const GLushort &y)
{
BlitSafe(image, Point(x,y), Rect(0,0,image->GetWidth(),image->GetHeight()));
}
void Image::Blit(Image *image, const Point &point)
{
BlitSafe(image, point, Rect(0,0,image->GetWidth(),image->GetHeight()));
}
void Image::Blit(Image *image, const Point &point, const Rect &rect)
{
BlitSafe(image, point, rect);
}
void Image::FlipVertical()
{
for(int i = 0; i < (m_width >> 1); ++i)
{
for(int j = 0; j < m_height; ++j)
{
int offset1 = i * m_width + j;
offset1 *= m_bytesPerPixel;
int vi = m_width - i - 1;
int vj = j;
int offset2 = vi * m_width + vj;
offset2 *= m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
}
}
}
void Image::FlipHorizontal()
{
for(int i = 0; i < m_width; ++i)
{
for(int j = 0; j < (m_height >> 1); ++j)
{
int offset1 = i * m_width + j;
offset1 *= m_bytesPerPixel;
int vi = i;
int vj = m_height - j + 1;
int offset2 = vi * m_width + vj;
offset2 *= m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer + offset1),(char*)(m_imageBuffer + offset2),m_bytesPerPixel);
}
}
}
GLushort Image::GetWidth() const
{
return m_width;
}
GLushort Image::GetHeight() const
{
return m_height;
}
GLushort Image::GetBytesPerPixel() const
{
return m_bytesPerPixel;
}
GLint Image::GetGLFormat() const
{
return m_GLFormatType;
}
Image::InternalFormatType Image::GetFormat() const
{
return m_internalFormatType;
}
bool Image::HaveAlphaChannel() const
{
return m_internalFormatType == Image::InternalFormatType::GRAY_ALPHA ||
m_internalFormatType == Image::InternalFormatType::RGBA;
}
const BYTE* Image::GetImageData() const
{
return m_imageBuffer;
}
const BYTE* Image::GetPixelPointer(const GLushort &x, const GLushort &y) const
{
int index=x * m_width + y;
index *= m_bytesPerPixel;
return m_imageBuffer + index;
}
Color Image::GetPixel(const GLushort &x, const GLushort &y) const
{
int index=x * m_width + y;
index *= m_bytesPerPixel;
if (m_bytesPerPixel == 4)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], m_imageBuffer[index+3]);
}
else if(m_bytesPerPixel == 3)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], 255);
}
else if(m_bytesPerPixel == 2)
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], m_imageBuffer[index+1]);
}
else
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], 255);
}
}
void Image::SetPixel(const GLushort &x, const GLushort &y, const Color &c)
{
int index=x * m_width + y;
index *= m_bytesPerPixel;
if (m_bytesPerPixel == 4)
{
m_imageBuffer[index] = c.r;
m_imageBuffer[index+1] = c.g;
m_imageBuffer[index+2] = c.b;
m_imageBuffer[index+3] = c.a;
}
else if(m_bytesPerPixel == 3)
{
m_imageBuffer[index] = c.r;
m_imageBuffer[index+1] = c.g;
m_imageBuffer[index+2] = c.b;
}
else if(m_bytesPerPixel == 2)
{
unsigned char gray = (c.r + c.g + c.b) / 3;
m_imageBuffer[index] = gray;
m_imageBuffer[index+1] = c.a;
}
else
{
unsigned char gray = (c.r + c.g + c.b) / 3;
m_imageBuffer[index] = gray;
}
}
void Image::BlitSafe(Image *image, Point point, Rect rect)
{
GLushort width = image->GetWidth();
GLushort height = image->GetHeight();
if (point.x >= m_width || point.y >= m_height)
{
return;
}
if (rect.width <= 0 || rect.height <= 0)
{
return;
}
if (rect.x >= width || rect.y >= height)
{
return;
}
if (point.x < 0)
{
point.x = 0;
}
if (point.y < 0)
{
point.y = 0;
}
GLushort maxWidth = m_width - point.x;
if (rect.width > maxWidth)
{
rect.width = maxWidth;
}
GLushort maxHeight = m_height - point.y;
if (rect.height > maxHeight)
{
rect.height = maxHeight - point.y;
}
for (int i = 0; i < rect.height; ++i)
{
for (int j = 0; j < rect.width; ++j)
{
SetPixel(point.y + i,point.x + j, image->GetPixel(i + rect.y, j + rect.x));
}
}
}
GLushort GetBPP(GLint format)
{
switch(format)
{
case GL_RGB:
return 3;
break;
case GL_RGBA:
return 4;
break;
case GL_LUMINANCE:
return 1;
break;
case GL_LUMINANCE_ALPHA:
return 2;
break;
}
return 0;
}
}
}
<|endoftext|> |
<commit_before>//===- GenerateCode.cpp - Functions for generating executable files ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains functions for generating executable files once linking
// has finished. This includes generating a shell script to run the JIT or
// a native executable derived from the bytecode.
//
//===----------------------------------------------------------------------===//
#include "gccld.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/SystemUtils.h"
#include "Support/CommandLine.h"
using namespace llvm;
namespace {
cl::opt<bool>
DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
cl::opt<bool>
Verify("verify", cl::desc("Verify intermediate results of all passes"));
cl::opt<bool>
DisableOptimizations("disable-opt",
cl::desc("Do not run any optimization passes"));
}
static inline void addPass(PassManager &PM, Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
// If we are verifying all of the intermediate steps, add the verifier...
if (Verify) PM.add(createVerifierPass());
}
/// GenerateBytecode - generates a bytecode file from the specified module.
///
/// Inputs:
/// M - The module for which bytecode should be generated.
/// Strip - Flags whether symbols should be stripped from the output.
/// Internalize - Flags whether all symbols should be marked internal.
/// Out - Pointer to file stream to which to write the output.
///
/// Returns non-zero value on error.
///
int llvm::GenerateBytecode(Module *M, bool Strip, bool Internalize,
std::ostream *Out) {
// In addition to just linking the input from GCC, we also want to spiff it up
// a little bit. Do this now.
PassManager Passes;
if (Verify) Passes.add(createVerifierPass());
// Add an appropriate TargetData instance for this module...
addPass(Passes, new TargetData("gccld", M));
// Often if the programmer does not specify proper prototypes for the
// functions they are calling, they end up calling a vararg version of the
// function that does not get a body filled in (the real function has typed
// arguments). This pass merges the two functions.
addPass(Passes, createFunctionResolvingPass());
if (!DisableOptimizations) {
if (Internalize) {
// Now that composite has been compiled, scan through the module, looking
// for a main function. If main is defined, mark all other functions
// internal.
addPass(Passes, createInternalizePass());
}
// Now that we internalized some globals, see if we can mark any globals as
// being constant!
addPass(Passes, createGlobalConstifierPass());
// Linking modules together can lead to duplicated global constants, only
// keep one copy of each constant...
addPass(Passes, createConstantMergePass());
// If the -s command line option was specified, strip the symbols out of the
// resulting program to make it smaller. -s is a GCC option that we are
// supporting.
if (Strip)
addPass(Passes, createSymbolStrippingPass());
// Propagate constants at call sites into the functions they call.
addPass(Passes, createIPConstantPropagationPass());
// Remove unused arguments from functions...
addPass(Passes, createDeadArgEliminationPass());
if (!DisableInline)
addPass(Passes, createFunctionInliningPass()); // Inline small functions
// If we didn't decide to inline a function, check to see if we can
// transform it to pass arguments by value instead of by reference.
addPass(Passes, createArgumentPromotionPass());
// The IPO passes may leave cruft around. Clean up after them.
addPass(Passes, createInstructionCombiningPass());
addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
// Run a few AA driven optimizations here and now, to cleanup the code.
// Eventually we should put an IP AA in place here.
addPass(Passes, createLICMPass()); // Hoist loop invariants
addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
addPass(Passes, createGCSEPass()); // Remove common subexprs
// Cleanup and simplify the code after the scalar optimizations.
addPass(Passes, createInstructionCombiningPass());
// Delete basic blocks, which optimization passes may have killed...
addPass(Passes, createCFGSimplificationPass());
// Now that we have optimized the program, discard unreachable functions...
addPass(Passes, createGlobalDCEPass());
}
// Make sure everything is still good.
Passes.add(createVerifierPass());
// Add the pass that writes bytecode to the output file...
addPass(Passes, new WriteBytecodePass(Out));
// Run our queue of passes all at once now, efficiently.
Passes.run(*M);
return 0;
}
/// GenerateAssembly - generates a native assembly language source file from the
/// specified bytecode file.
///
/// Inputs:
/// InputFilename - The name of the output bytecode file.
/// OutputFilename - The name of the file to generate.
/// llc - The pathname to use for LLC.
/// envp - The environment to use when running LLC.
///
/// Return non-zero value on error.
///
int llvm::GenerateAssembly(const std::string &OutputFilename,
const std::string &InputFilename,
const std::string &llc,
char ** const envp) {
// Run LLC to convert the bytecode file into assembly code.
const char *cmd[6];
cmd[0] = llc.c_str();
cmd[1] = "-f";
cmd[2] = "-o";
cmd[3] = OutputFilename.c_str();
cmd[4] = InputFilename.c_str();
cmd[5] = 0;
return ExecWait(cmd, envp);
}
/// GenerateAssembly - generates a native assembly language source file from the
/// specified bytecode file.
int llvm::GenerateCFile(const std::string &OutputFile,
const std::string &InputFile,
const std::string &llc, char ** const envp) {
// Run LLC to convert the bytecode file into C.
const char *cmd[7];
cmd[0] = llc.c_str();
cmd[1] = "-march=c";
cmd[2] = "-f";
cmd[3] = "-o";
cmd[4] = OutputFile.c_str();
cmd[5] = InputFile.c_str();
cmd[6] = 0;
return ExecWait(cmd, envp);
}
/// GenerateNative - generates a native assembly language source file from the
/// specified assembly source file.
///
/// Inputs:
/// InputFilename - The name of the output bytecode file.
/// OutputFilename - The name of the file to generate.
/// Libraries - The list of libraries with which to link.
/// LibPaths - The list of directories in which to find libraries.
/// gcc - The pathname to use for GGC.
/// envp - A copy of the process's current environment.
///
/// Outputs:
/// None.
///
/// Returns non-zero value on error.
///
int llvm::GenerateNative(const std::string &OutputFilename,
const std::string &InputFilename,
const std::vector<std::string> &Libraries,
const std::vector<std::string> &LibPaths,
const std::string &gcc, char ** const envp) {
// Remove these environment variables from the environment of the
// programs that we will execute. It appears that GCC sets these
// environment variables so that the programs it uses can configure
// themselves identically.
//
// However, when we invoke GCC below, we want it to use its normal
// configuration. Hence, we must sanitize its environment.
char ** clean_env = CopyEnv(envp);
if (clean_env == NULL)
return 1;
RemoveEnv("LIBRARY_PATH", clean_env);
RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
RemoveEnv("GCC_EXEC_PREFIX", clean_env);
RemoveEnv("COMPILER_PATH", clean_env);
RemoveEnv("COLLECT_GCC", clean_env);
std::vector<const char *> cmd;
// Run GCC to assemble and link the program into native code.
//
// Note:
// We can't just assemble and link the file with the system assembler
// and linker because we don't know where to put the _start symbol.
// GCC mysteriously knows how to do it.
cmd.push_back(gcc.c_str());
cmd.push_back("-O3");
cmd.push_back("-o");
cmd.push_back(OutputFilename.c_str());
cmd.push_back(InputFilename.c_str());
// Adding the library paths creates a problem for native generation. If we
// include the search paths from llvmgcc, then we'll be telling normal gcc
// to look inside of llvmgcc's library directories for libraries. This is
// bad because those libraries hold only bytecode files (not native object
// files). In the end, we attempt to link the bytecode libgcc into a native
// program.
#if 0
// Add in the library path options.
for (unsigned index=0; index < LibPaths.size(); index++) {
cmd.push_back("-L");
cmd.push_back(LibPaths[index].c_str());
}
#endif
// Add in the libraries to link.
std::vector<std::string> Libs(Libraries);
for (unsigned index = 0; index < Libs.size(); index++) {
if (Libs[index] != "crtend") {
Libs[index] = "-l" + Libs[index];
cmd.push_back(Libs[index].c_str());
}
}
cmd.push_back(NULL);
// Run the compiler to assembly and link together the program.
return ExecWait(&(cmd[0]), clean_env);
}
<commit_msg>Right, we break strict aliasing requirements. Make sure to disable strict aliasing in the C compiler.<commit_after>//===- GenerateCode.cpp - Functions for generating executable files ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains functions for generating executable files once linking
// has finished. This includes generating a shell script to run the JIT or
// a native executable derived from the bytecode.
//
//===----------------------------------------------------------------------===//
#include "gccld.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/SystemUtils.h"
#include "Support/CommandLine.h"
using namespace llvm;
namespace {
cl::opt<bool>
DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
cl::opt<bool>
Verify("verify", cl::desc("Verify intermediate results of all passes"));
cl::opt<bool>
DisableOptimizations("disable-opt",
cl::desc("Do not run any optimization passes"));
}
static inline void addPass(PassManager &PM, Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
// If we are verifying all of the intermediate steps, add the verifier...
if (Verify) PM.add(createVerifierPass());
}
/// GenerateBytecode - generates a bytecode file from the specified module.
///
/// Inputs:
/// M - The module for which bytecode should be generated.
/// Strip - Flags whether symbols should be stripped from the output.
/// Internalize - Flags whether all symbols should be marked internal.
/// Out - Pointer to file stream to which to write the output.
///
/// Returns non-zero value on error.
///
int llvm::GenerateBytecode(Module *M, bool Strip, bool Internalize,
std::ostream *Out) {
// In addition to just linking the input from GCC, we also want to spiff it up
// a little bit. Do this now.
PassManager Passes;
if (Verify) Passes.add(createVerifierPass());
// Add an appropriate TargetData instance for this module...
addPass(Passes, new TargetData("gccld", M));
// Often if the programmer does not specify proper prototypes for the
// functions they are calling, they end up calling a vararg version of the
// function that does not get a body filled in (the real function has typed
// arguments). This pass merges the two functions.
addPass(Passes, createFunctionResolvingPass());
if (!DisableOptimizations) {
if (Internalize) {
// Now that composite has been compiled, scan through the module, looking
// for a main function. If main is defined, mark all other functions
// internal.
addPass(Passes, createInternalizePass());
}
// Now that we internalized some globals, see if we can mark any globals as
// being constant!
addPass(Passes, createGlobalConstifierPass());
// Linking modules together can lead to duplicated global constants, only
// keep one copy of each constant...
addPass(Passes, createConstantMergePass());
// If the -s command line option was specified, strip the symbols out of the
// resulting program to make it smaller. -s is a GCC option that we are
// supporting.
if (Strip)
addPass(Passes, createSymbolStrippingPass());
// Propagate constants at call sites into the functions they call.
addPass(Passes, createIPConstantPropagationPass());
// Remove unused arguments from functions...
addPass(Passes, createDeadArgEliminationPass());
if (!DisableInline)
addPass(Passes, createFunctionInliningPass()); // Inline small functions
// If we didn't decide to inline a function, check to see if we can
// transform it to pass arguments by value instead of by reference.
addPass(Passes, createArgumentPromotionPass());
// The IPO passes may leave cruft around. Clean up after them.
addPass(Passes, createInstructionCombiningPass());
addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
// Run a few AA driven optimizations here and now, to cleanup the code.
// Eventually we should put an IP AA in place here.
addPass(Passes, createLICMPass()); // Hoist loop invariants
addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
addPass(Passes, createGCSEPass()); // Remove common subexprs
// Cleanup and simplify the code after the scalar optimizations.
addPass(Passes, createInstructionCombiningPass());
// Delete basic blocks, which optimization passes may have killed...
addPass(Passes, createCFGSimplificationPass());
// Now that we have optimized the program, discard unreachable functions...
addPass(Passes, createGlobalDCEPass());
}
// Make sure everything is still good.
Passes.add(createVerifierPass());
// Add the pass that writes bytecode to the output file...
addPass(Passes, new WriteBytecodePass(Out));
// Run our queue of passes all at once now, efficiently.
Passes.run(*M);
return 0;
}
/// GenerateAssembly - generates a native assembly language source file from the
/// specified bytecode file.
///
/// Inputs:
/// InputFilename - The name of the output bytecode file.
/// OutputFilename - The name of the file to generate.
/// llc - The pathname to use for LLC.
/// envp - The environment to use when running LLC.
///
/// Return non-zero value on error.
///
int llvm::GenerateAssembly(const std::string &OutputFilename,
const std::string &InputFilename,
const std::string &llc,
char ** const envp) {
// Run LLC to convert the bytecode file into assembly code.
const char *cmd[6];
cmd[0] = llc.c_str();
cmd[1] = "-f";
cmd[2] = "-o";
cmd[3] = OutputFilename.c_str();
cmd[4] = InputFilename.c_str();
cmd[5] = 0;
return ExecWait(cmd, envp);
}
/// GenerateAssembly - generates a native assembly language source file from the
/// specified bytecode file.
int llvm::GenerateCFile(const std::string &OutputFile,
const std::string &InputFile,
const std::string &llc, char ** const envp) {
// Run LLC to convert the bytecode file into C.
const char *cmd[8];
cmd[0] = llc.c_str();
cmd[1] = "-march=c";
cmd[2] = "-f";
cmd[3] = "-fno-strict-aliasing";
cmd[4] = "-o";
cmd[5] = OutputFile.c_str();
cmd[6] = InputFile.c_str();
cmd[7] = 0;
return ExecWait(cmd, envp);
}
/// GenerateNative - generates a native assembly language source file from the
/// specified assembly source file.
///
/// Inputs:
/// InputFilename - The name of the output bytecode file.
/// OutputFilename - The name of the file to generate.
/// Libraries - The list of libraries with which to link.
/// LibPaths - The list of directories in which to find libraries.
/// gcc - The pathname to use for GGC.
/// envp - A copy of the process's current environment.
///
/// Outputs:
/// None.
///
/// Returns non-zero value on error.
///
int llvm::GenerateNative(const std::string &OutputFilename,
const std::string &InputFilename,
const std::vector<std::string> &Libraries,
const std::vector<std::string> &LibPaths,
const std::string &gcc, char ** const envp) {
// Remove these environment variables from the environment of the
// programs that we will execute. It appears that GCC sets these
// environment variables so that the programs it uses can configure
// themselves identically.
//
// However, when we invoke GCC below, we want it to use its normal
// configuration. Hence, we must sanitize its environment.
char ** clean_env = CopyEnv(envp);
if (clean_env == NULL)
return 1;
RemoveEnv("LIBRARY_PATH", clean_env);
RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
RemoveEnv("GCC_EXEC_PREFIX", clean_env);
RemoveEnv("COMPILER_PATH", clean_env);
RemoveEnv("COLLECT_GCC", clean_env);
std::vector<const char *> cmd;
// Run GCC to assemble and link the program into native code.
//
// Note:
// We can't just assemble and link the file with the system assembler
// and linker because we don't know where to put the _start symbol.
// GCC mysteriously knows how to do it.
cmd.push_back(gcc.c_str());
cmd.push_back("-O3");
cmd.push_back("-o");
cmd.push_back(OutputFilename.c_str());
cmd.push_back(InputFilename.c_str());
// Adding the library paths creates a problem for native generation. If we
// include the search paths from llvmgcc, then we'll be telling normal gcc
// to look inside of llvmgcc's library directories for libraries. This is
// bad because those libraries hold only bytecode files (not native object
// files). In the end, we attempt to link the bytecode libgcc into a native
// program.
#if 0
// Add in the library path options.
for (unsigned index=0; index < LibPaths.size(); index++) {
cmd.push_back("-L");
cmd.push_back(LibPaths[index].c_str());
}
#endif
// Add in the libraries to link.
std::vector<std::string> Libs(Libraries);
for (unsigned index = 0; index < Libs.size(); index++) {
if (Libs[index] != "crtend") {
Libs[index] = "-l" + Libs[index];
cmd.push_back(Libs[index].c_str());
}
}
cmd.push_back(NULL);
// Run the compiler to assembly and link together the program.
return ExecWait(&(cmd[0]), clean_env);
}
<|endoftext|> |
<commit_before>#include "LinearTransformation.hpp"
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
namespace fast {
/**
* Initializes linear transformation object to identity matrix
*/
LinearTransformation::LinearTransformation() : boost::numeric::ublas::matrix<float>(4,4) {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
this->operator()(i,j) = i == j ? 1 : 0;
}
}
}
LinearTransformation LinearTransformation::getInverse() {
typedef permutation_matrix<std::size_t> pmatrix;
// create a working copy
matrix<float> A = getMatrix();
// create a permutation matrix for the LU-factorization
pmatrix pm(A.size1());
// perform LU-factorization
int res = lu_factorize(A, pm);
if (res != 0)
throw Exception("Unable to invert matrix");
// create identity matrix of "inverse"
LinearTransformation inverse;
inverse.assign(identity_matrix<float> (A.size1()));
// backsubstitute to get the inverse
lu_substitute(A, pm, inverse);
return inverse;
}
LinearTransformation LinearTransformation::operator *(
const LinearTransformation& other) {
LinearTransformation T(boost::numeric::ublas::prod(*this, other));
return T;
}
boost::numeric::ublas::matrix<float> LinearTransformation::getMatrix() const {
return matrix<float>(*this);
}
Float3 operator*(const Float3& vertex, const LinearTransformation& transform) {
vector<float> boostVertex(4);
boostVertex(0) = vertex[0];
boostVertex(1) = vertex[1];
boostVertex(2) = vertex[2];
boostVertex(3) = 1;
noalias(boostVertex) = prod(transform, boostVertex);
Float3 result;
result[0] = boostVertex(0);
result[1] = boostVertex(1);
result[2] = boostVertex(2);
return result;
}
Float3 LinearTransformation::operator*(Float3 vertex) const {
vector<float> boostVertex(4);
boostVertex(0) = vertex[0];
boostVertex(1) = vertex[1];
boostVertex(2) = vertex[2];
boostVertex(3) = 1;
noalias(boostVertex) = prod(*this, boostVertex);
Float3 result;
result[0] = boostVertex(0);
result[1] = boostVertex(1);
result[2] = boostVertex(2);
return result;
}
}
<commit_msg>fixed a transformation bug<commit_after>#include "LinearTransformation.hpp"
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
namespace fast {
/**
* Initializes linear transformation object to identity matrix
*/
LinearTransformation::LinearTransformation() : boost::numeric::ublas::matrix<float>(4,4) {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
this->operator()(i,j) = i == j ? 1 : 0;
}
}
}
LinearTransformation LinearTransformation::getInverse() {
typedef permutation_matrix<std::size_t> pmatrix;
// create a working copy
matrix<float> A = getMatrix();
// create a permutation matrix for the LU-factorization
pmatrix pm(A.size1());
// perform LU-factorization
int res = lu_factorize(A, pm);
if (res != 0)
throw Exception("Unable to invert matrix");
// create identity matrix of "inverse"
LinearTransformation inverse;
inverse.assign(identity_matrix<float> (A.size1()));
// backsubstitute to get the inverse
lu_substitute(A, pm, inverse);
return inverse;
}
LinearTransformation LinearTransformation::operator *(
const LinearTransformation& other) {
LinearTransformation T(boost::numeric::ublas::prod(*this, other));
return T;
}
boost::numeric::ublas::matrix<float> LinearTransformation::getMatrix() const {
return matrix<float>(*this);
}
Float3 operator*(const Float3& vertex, const LinearTransformation& transform) {
vector<float> boostVertex(4);
boostVertex(0) = vertex[0];
boostVertex(1) = vertex[1];
boostVertex(2) = vertex[2];
boostVertex(3) = 1;
boostVertex = prod(transform, boostVertex);
Float3 result;
result[0] = boostVertex(0);
result[1] = boostVertex(1);
result[2] = boostVertex(2);
return result;
}
Float3 LinearTransformation::operator*(Float3 vertex) const {
vector<float> boostVertex(4);
boostVertex(0) = vertex[0];
boostVertex(1) = vertex[1];
boostVertex(2) = vertex[2];
boostVertex(3) = 1;
boostVertex = prod(*this, boostVertex);
Float3 result;
result[0] = boostVertex(0);
result[1] = boostVertex(1);
result[2] = boostVertex(2);
return result;
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// General FIR digital filter routines with MMX optimization.
///
/// Note : MMX optimized functions reside in a separate, platform-specific file,
/// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////
#include <memory.h>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdexcept>
#include "FIRFilter.h"
#include "cpu_detect.h"
using namespace soundtouch;
/*****************************************************************************
*
* Implementation of the class 'FIRFilter'
*
*****************************************************************************/
FIRFilter::FIRFilter()
{
resultDivFactor = 0;
resultDivider = 0;
length = 0;
lengthDiv8 = 0;
filterCoeffs = NULL;
}
FIRFilter::~FIRFilter()
{
delete[] filterCoeffs;
}
// Usual C-version of the filter routine for stereo sound
uint FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples) const
{
uint i, j, end;
LONG_SAMPLETYPE suml, sumr;
#ifdef FLOAT_SAMPLES
// when using floating point samples, use a scaler instead of a divider
// because division is much slower operation than multiplying.
double dScaler = 1.0 / (double)resultDivider;
#endif
assert(length != 0);
assert(src != NULL);
assert(dest != NULL);
assert(filterCoeffs != NULL);
end = 2 * (numSamples - length);
for (j = 0; j < end; j += 2)
{
const SAMPLETYPE *ptr;
suml = sumr = 0;
ptr = src + j;
for (i = 0; i < length; i += 4)
{
// loop is unrolled by factor of 4 here for efficiency
suml += ptr[2 * i + 0] * filterCoeffs[i + 0] +
ptr[2 * i + 2] * filterCoeffs[i + 1] +
ptr[2 * i + 4] * filterCoeffs[i + 2] +
ptr[2 * i + 6] * filterCoeffs[i + 3];
sumr += ptr[2 * i + 1] * filterCoeffs[i + 0] +
ptr[2 * i + 3] * filterCoeffs[i + 1] +
ptr[2 * i + 5] * filterCoeffs[i + 2] +
ptr[2 * i + 7] * filterCoeffs[i + 3];
}
#ifdef INTEGER_SAMPLES
suml >>= resultDivFactor;
sumr >>= resultDivFactor;
// saturate to 16 bit integer limits
suml = (suml < -32768) ? -32768 : (suml > 32767) ? 32767 : suml;
// saturate to 16 bit integer limits
sumr = (sumr < -32768) ? -32768 : (sumr > 32767) ? 32767 : sumr;
#else
suml *= dScaler;
sumr *= dScaler;
#endif // INTEGER_SAMPLES
dest[j] = (SAMPLETYPE)suml;
dest[j + 1] = (SAMPLETYPE)sumr;
}
return numSamples - length;
}
// Usual C-version of the filter routine for mono sound
uint FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples) const
{
uint i, j, end;
LONG_SAMPLETYPE sum;
#ifdef FLOAT_SAMPLES
// when using floating point samples, use a scaler instead of a divider
// because division is much slower operation than multiplying.
double dScaler = 1.0 / (double)resultDivider;
#endif
assert(length != 0);
end = numSamples - length;
for (j = 0; j < end; j ++)
{
sum = 0;
for (i = 0; i < length; i += 4)
{
// loop is unrolled by factor of 4 here for efficiency
sum += src[i + 0] * filterCoeffs[i + 0] +
src[i + 1] * filterCoeffs[i + 1] +
src[i + 2] * filterCoeffs[i + 2] +
src[i + 3] * filterCoeffs[i + 3];
}
#ifdef INTEGER_SAMPLES
sum >>= resultDivFactor;
// saturate to 16 bit integer limits
sum = (sum < -32768) ? -32768 : (sum > 32767) ? 32767 : sum;
#else
sum *= dScaler;
#endif // INTEGER_SAMPLES
dest[j] = (SAMPLETYPE)sum;
src ++;
}
return end;
}
// Set filter coeffiecients and length.
//
// Throws an exception if filter length isn't divisible by 8
void FIRFilter::setCoefficients(const SAMPLETYPE *coeffs, uint newLength, uint uResultDivFactor)
{
assert(newLength > 0);
if (newLength % 8) throw std::runtime_error("FIR filter length not divisible by 8");
lengthDiv8 = newLength / 8;
length = lengthDiv8 * 8;
assert(length == newLength);
resultDivFactor = uResultDivFactor;
resultDivider = (SAMPLETYPE)pow(2, resultDivFactor);
delete[] filterCoeffs;
filterCoeffs = new SAMPLETYPE[length];
memcpy(filterCoeffs, coeffs, length * sizeof(SAMPLETYPE));
}
uint FIRFilter::getLength() const
{
return length;
}
// Applies the filter to the given sequence of samples.
//
// Note : The amount of outputted samples is by value of 'filter_length'
// smaller than the amount of input samples.
uint FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples, uint numChannels) const
{
assert(numChannels == 1 || numChannels == 2);
assert(length > 0);
assert(lengthDiv8 * 8 == length);
if (numSamples < length) return 0;
if (numChannels == 2)
{
return evaluateFilterStereo(dest, src, numSamples);
} else {
return evaluateFilterMono(dest, src, numSamples);
}
}
// Operator 'new' is overloaded so that it automatically creates a suitable instance
// depending on if we've a MMX-capable CPU available or not.
void * FIRFilter::operator new(size_t s)
{
// Notice! don't use "new FIRFilter" directly, use "newInstance" to create a new instance instead!
throw std::runtime_error("Error in FIRFilter::new: Don't use 'new FIRFilter', use 'newInstance' member instead!");
return NULL;
}
FIRFilter * FIRFilter::newInstance()
{
uint uExtensions;
uExtensions = detectCPUextensions();
// Check if MMX/SSE/3DNow! instruction set extensions supported by CPU
#ifdef ALLOW_MMX
// MMX routines available only with integer sample types
if (uExtensions & SUPPORT_MMX)
{
return ::new FIRFilterMMX;
}
else
#endif // ALLOW_MMX
#ifdef ALLOW_SSE
if (uExtensions & SUPPORT_SSE)
{
// SSE support
return ::new FIRFilterSSE;
}
else
#endif // ALLOW_SSE
#ifdef ALLOW_3DNOW
if (uExtensions & SUPPORT_3DNOW)
{
// 3DNow! support
return ::new FIRFilter3DNow;
}
else
#endif // ALLOW_3DNOW
{
// ISA optimizations not supported, use plain C version
return ::new FIRFilter;
}
}
<commit_msg>Added :: before pow to resolve namespace ambiguity<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// General FIR digital filter routines with MMX optimization.
///
/// Note : MMX optimized functions reside in a separate, platform-specific file,
/// e.g. 'mmx_win.cpp' or 'mmx_gcc.cpp'
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////
#include <memory.h>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdexcept>
#include "FIRFilter.h"
#include "cpu_detect.h"
using namespace soundtouch;
/*****************************************************************************
*
* Implementation of the class 'FIRFilter'
*
*****************************************************************************/
FIRFilter::FIRFilter()
{
resultDivFactor = 0;
resultDivider = 0;
length = 0;
lengthDiv8 = 0;
filterCoeffs = NULL;
}
FIRFilter::~FIRFilter()
{
delete[] filterCoeffs;
}
// Usual C-version of the filter routine for stereo sound
uint FIRFilter::evaluateFilterStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples) const
{
uint i, j, end;
LONG_SAMPLETYPE suml, sumr;
#ifdef FLOAT_SAMPLES
// when using floating point samples, use a scaler instead of a divider
// because division is much slower operation than multiplying.
double dScaler = 1.0 / (double)resultDivider;
#endif
assert(length != 0);
assert(src != NULL);
assert(dest != NULL);
assert(filterCoeffs != NULL);
end = 2 * (numSamples - length);
for (j = 0; j < end; j += 2)
{
const SAMPLETYPE *ptr;
suml = sumr = 0;
ptr = src + j;
for (i = 0; i < length; i += 4)
{
// loop is unrolled by factor of 4 here for efficiency
suml += ptr[2 * i + 0] * filterCoeffs[i + 0] +
ptr[2 * i + 2] * filterCoeffs[i + 1] +
ptr[2 * i + 4] * filterCoeffs[i + 2] +
ptr[2 * i + 6] * filterCoeffs[i + 3];
sumr += ptr[2 * i + 1] * filterCoeffs[i + 0] +
ptr[2 * i + 3] * filterCoeffs[i + 1] +
ptr[2 * i + 5] * filterCoeffs[i + 2] +
ptr[2 * i + 7] * filterCoeffs[i + 3];
}
#ifdef INTEGER_SAMPLES
suml >>= resultDivFactor;
sumr >>= resultDivFactor;
// saturate to 16 bit integer limits
suml = (suml < -32768) ? -32768 : (suml > 32767) ? 32767 : suml;
// saturate to 16 bit integer limits
sumr = (sumr < -32768) ? -32768 : (sumr > 32767) ? 32767 : sumr;
#else
suml *= dScaler;
sumr *= dScaler;
#endif // INTEGER_SAMPLES
dest[j] = (SAMPLETYPE)suml;
dest[j + 1] = (SAMPLETYPE)sumr;
}
return numSamples - length;
}
// Usual C-version of the filter routine for mono sound
uint FIRFilter::evaluateFilterMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples) const
{
uint i, j, end;
LONG_SAMPLETYPE sum;
#ifdef FLOAT_SAMPLES
// when using floating point samples, use a scaler instead of a divider
// because division is much slower operation than multiplying.
double dScaler = 1.0 / (double)resultDivider;
#endif
assert(length != 0);
end = numSamples - length;
for (j = 0; j < end; j ++)
{
sum = 0;
for (i = 0; i < length; i += 4)
{
// loop is unrolled by factor of 4 here for efficiency
sum += src[i + 0] * filterCoeffs[i + 0] +
src[i + 1] * filterCoeffs[i + 1] +
src[i + 2] * filterCoeffs[i + 2] +
src[i + 3] * filterCoeffs[i + 3];
}
#ifdef INTEGER_SAMPLES
sum >>= resultDivFactor;
// saturate to 16 bit integer limits
sum = (sum < -32768) ? -32768 : (sum > 32767) ? 32767 : sum;
#else
sum *= dScaler;
#endif // INTEGER_SAMPLES
dest[j] = (SAMPLETYPE)sum;
src ++;
}
return end;
}
// Set filter coeffiecients and length.
//
// Throws an exception if filter length isn't divisible by 8
void FIRFilter::setCoefficients(const SAMPLETYPE *coeffs, uint newLength, uint uResultDivFactor)
{
assert(newLength > 0);
if (newLength % 8) throw std::runtime_error("FIR filter length not divisible by 8");
lengthDiv8 = newLength / 8;
length = lengthDiv8 * 8;
assert(length == newLength);
resultDivFactor = uResultDivFactor;
resultDivider = (SAMPLETYPE)::pow(2, resultDivFactor);
delete[] filterCoeffs;
filterCoeffs = new SAMPLETYPE[length];
memcpy(filterCoeffs, coeffs, length * sizeof(SAMPLETYPE));
}
uint FIRFilter::getLength() const
{
return length;
}
// Applies the filter to the given sequence of samples.
//
// Note : The amount of outputted samples is by value of 'filter_length'
// smaller than the amount of input samples.
uint FIRFilter::evaluate(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples, uint numChannels) const
{
assert(numChannels == 1 || numChannels == 2);
assert(length > 0);
assert(lengthDiv8 * 8 == length);
if (numSamples < length) return 0;
if (numChannels == 2)
{
return evaluateFilterStereo(dest, src, numSamples);
} else {
return evaluateFilterMono(dest, src, numSamples);
}
}
// Operator 'new' is overloaded so that it automatically creates a suitable instance
// depending on if we've a MMX-capable CPU available or not.
void * FIRFilter::operator new(size_t s)
{
// Notice! don't use "new FIRFilter" directly, use "newInstance" to create a new instance instead!
throw std::runtime_error("Error in FIRFilter::new: Don't use 'new FIRFilter', use 'newInstance' member instead!");
return NULL;
}
FIRFilter * FIRFilter::newInstance()
{
uint uExtensions;
uExtensions = detectCPUextensions();
// Check if MMX/SSE/3DNow! instruction set extensions supported by CPU
#ifdef ALLOW_MMX
// MMX routines available only with integer sample types
if (uExtensions & SUPPORT_MMX)
{
return ::new FIRFilterMMX;
}
else
#endif // ALLOW_MMX
#ifdef ALLOW_SSE
if (uExtensions & SUPPORT_SSE)
{
// SSE support
return ::new FIRFilterSSE;
}
else
#endif // ALLOW_SSE
#ifdef ALLOW_3DNOW
if (uExtensions & SUPPORT_3DNOW)
{
// 3DNow! support
return ::new FIRFilter3DNow;
}
else
#endif // ALLOW_3DNOW
{
// ISA optimizations not supported, use plain C version
return ::new FIRFilter;
}
}
<|endoftext|> |
<commit_before>
#include "libtorrent/rss.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/bencode.hpp"
using namespace libtorrent;
void print_feed(feed_status const& f)
{
printf("FEED: %s\n",f.url.c_str());
if (f.error)
printf("ERROR: %s\n", f.error.message().c_str());
printf(" %s\n %s\n", f.title.c_str(), f.description.c_str());
printf(" ttl: %d minutes\n", f.ttl);
for (std::vector<feed_item>::const_iterator i = f.items.begin()
, end(f.items.end()); i != end; ++i)
{
printf("\033[32m%s\033[0m\n------------------------------------------------------\n"
" url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n"
" comment: %s\n category: %s\n"
, i->title.c_str(), i->url.c_str(), i->size
, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
}
}
std::string const& progress_bar(int progress, int width)
{
static std::string bar;
bar.clear();
bar.reserve(width + 10);
int progress_chars = (progress * width + 500) / 1000;
std::fill_n(std::back_inserter(bar), progress_chars, '#');
std::fill_n(std::back_inserter(bar), width - progress_chars, '-');
return bar;
}
int save_file(std::string const& filename, std::vector<char>& v)
{
using namespace libtorrent;
file f;
error_code ec;
if (!f.open(filename, file::write_only, ec)) return -1;
if (ec) return -1;
file::iovec_t b = {&v[0], v.size()};
size_type written = f.writev(0, &b, 1, ec);
if (written != v.size()) return -3;
if (ec) return -3;
return 0;
}
volatile bool quit = false;
void sig(int num)
{
quit = true;
}
int main(int argc, char* argv[])
{
if ((argc == 2 && strcmp(argv[1], "--help") == 0) || argc > 2)
{
std::cerr << "usage: rss_reader [rss-url]\n";
return 0;
}
session ses;
session_settings sett;
sett.active_downloads = 2;
sett.active_seeds = 1;
sett.active_limit = 3;
ses.set_settings(sett);
std::vector<char> in;
if (load_file(".ses_state", in) == 0)
{
lazy_entry e;
error_code ec;
if (lazy_bdecode(&in[0], &in[0] + in.size(), e, ec) == 0)
ses.load_state(e);
}
feed_handle fh;
if (argc == 2)
{
feed_settings feed;
feed.url = argv[1];
feed.add_args.save_path = ".";
fh = ses.add_feed(feed);
fh.update_feed();
}
else
{
std::vector<feed_handle> handles;
ses.get_feeds(handles);
if (handles.empty())
{
printf("usage: rss_reader rss-url\n");
return 1;
}
fh = handles[0];
}
feed_status fs = fh.get_feed_status();
int i = 0;
char spinner[] = {'|', '/', '-', '\\'};
fprintf(stderr, "fetching feed ... %c", spinner[i]);
while (fs.updating)
{
sleep(100);
i = (i + 1) % 4;
fprintf(stderr, "\b%c", spinner[i]);
fs = fh.get_feed_status();
}
fprintf(stderr, "\bDONE\n");
print_feed(fs);
signal(SIGTERM, &sig);
signal(SIGINT, &sig);
while (!quit)
{
std::vector<torrent_handle> t = ses.get_torrents();
for (std::vector<torrent_handle>::iterator i = t.begin()
, end(t.end()); i != end; ++i)
{
torrent_status st = i->status();
std::string const& progress = progress_bar(st.progress_ppm / 1000, 40);
std::string name = i->name();
if (name.size() > 70) name.resize(70);
std::string error = st.error;
if (error.size() > 40) error.resize(40);
static char const* state_str[] =
{"checking (q)", "checking", "dl metadata"
, "downloading", "finished", "seeding", "allocating", "checking (r)"};
std::string status = st.paused ? "queued" : state_str[st.state];
int attribute = 0;
if (st.paused) attribute = 33;
else if (st.state == torrent_status::downloading) attribute = 1;
printf("\033[%dm%2d %-70s d:%-4d u:%-4d %-40s %4d(%4d) %-12s\033[0m\n"
, attribute, st.queue_position
, name.c_str(), st.download_rate / 1000
, st.upload_rate / 1000, !error.empty() ? error.c_str() : progress.c_str()
, st.num_peers, st.num_seeds, status.c_str());
}
sleep(500);
if (quit) break;
printf("\033[%dA", int(t.size()));
}
printf("saving session state\n");
{
entry session_state;
ses.save_state(session_state);
std::vector<char> out;
bencode(std::back_inserter(out), session_state);
save_file(".ses_state", out);
}
printf("closing session");
return 0;
}
<commit_msg>linux build fix<commit_after>
#include "libtorrent/rss.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/bencode.hpp"
#include <signal.h>
using namespace libtorrent;
void print_feed(feed_status const& f)
{
printf("FEED: %s\n",f.url.c_str());
if (f.error)
printf("ERROR: %s\n", f.error.message().c_str());
printf(" %s\n %s\n", f.title.c_str(), f.description.c_str());
printf(" ttl: %d minutes\n", f.ttl);
for (std::vector<feed_item>::const_iterator i = f.items.begin()
, end(f.items.end()); i != end; ++i)
{
printf("\033[32m%s\033[0m\n------------------------------------------------------\n"
" url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n"
" comment: %s\n category: %s\n"
, i->title.c_str(), i->url.c_str(), i->size
, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
}
}
std::string const& progress_bar(int progress, int width)
{
static std::string bar;
bar.clear();
bar.reserve(width + 10);
int progress_chars = (progress * width + 500) / 1000;
std::fill_n(std::back_inserter(bar), progress_chars, '#');
std::fill_n(std::back_inserter(bar), width - progress_chars, '-');
return bar;
}
int save_file(std::string const& filename, std::vector<char>& v)
{
using namespace libtorrent;
file f;
error_code ec;
if (!f.open(filename, file::write_only, ec)) return -1;
if (ec) return -1;
file::iovec_t b = {&v[0], v.size()};
size_type written = f.writev(0, &b, 1, ec);
if (written != v.size()) return -3;
if (ec) return -3;
return 0;
}
volatile bool quit = false;
void sig(int num)
{
quit = true;
}
int main(int argc, char* argv[])
{
if ((argc == 2 && strcmp(argv[1], "--help") == 0) || argc > 2)
{
std::cerr << "usage: rss_reader [rss-url]\n";
return 0;
}
session ses;
session_settings sett;
sett.active_downloads = 2;
sett.active_seeds = 1;
sett.active_limit = 3;
ses.set_settings(sett);
std::vector<char> in;
if (load_file(".ses_state", in) == 0)
{
lazy_entry e;
error_code ec;
if (lazy_bdecode(&in[0], &in[0] + in.size(), e, ec) == 0)
ses.load_state(e);
}
feed_handle fh;
if (argc == 2)
{
feed_settings feed;
feed.url = argv[1];
feed.add_args.save_path = ".";
fh = ses.add_feed(feed);
fh.update_feed();
}
else
{
std::vector<feed_handle> handles;
ses.get_feeds(handles);
if (handles.empty())
{
printf("usage: rss_reader rss-url\n");
return 1;
}
fh = handles[0];
}
feed_status fs = fh.get_feed_status();
int i = 0;
char spinner[] = {'|', '/', '-', '\\'};
fprintf(stderr, "fetching feed ... %c", spinner[i]);
while (fs.updating)
{
sleep(100);
i = (i + 1) % 4;
fprintf(stderr, "\b%c", spinner[i]);
fs = fh.get_feed_status();
}
fprintf(stderr, "\bDONE\n");
print_feed(fs);
signal(SIGTERM, &sig);
signal(SIGINT, &sig);
while (!quit)
{
std::vector<torrent_handle> t = ses.get_torrents();
for (std::vector<torrent_handle>::iterator i = t.begin()
, end(t.end()); i != end; ++i)
{
torrent_status st = i->status();
std::string const& progress = progress_bar(st.progress_ppm / 1000, 40);
std::string name = i->name();
if (name.size() > 70) name.resize(70);
std::string error = st.error;
if (error.size() > 40) error.resize(40);
static char const* state_str[] =
{"checking (q)", "checking", "dl metadata"
, "downloading", "finished", "seeding", "allocating", "checking (r)"};
std::string status = st.paused ? "queued" : state_str[st.state];
int attribute = 0;
if (st.paused) attribute = 33;
else if (st.state == torrent_status::downloading) attribute = 1;
printf("\033[%dm%2d %-70s d:%-4d u:%-4d %-40s %4d(%4d) %-12s\033[0m\n"
, attribute, st.queue_position
, name.c_str(), st.download_rate / 1000
, st.upload_rate / 1000, !error.empty() ? error.c_str() : progress.c_str()
, st.num_peers, st.num_seeds, status.c_str());
}
sleep(500);
if (quit) break;
printf("\033[%dA", int(t.size()));
}
printf("saving session state\n");
{
entry session_state;
ses.save_state(session_state);
std::vector<char> out;
bencode(std::back_inserter(out), session_state);
save_file(".ses_state", out);
}
printf("closing session");
return 0;
}
<|endoftext|> |
<commit_before>#include "offset_estimator.h"
#include <Eigen/Dense>
#include "eigen_wrappers.h"
namespace InSituFTCalibration {
struct ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimatorPrivateAttributes
{
Eigen::Matrix<double,6,1> offset; //< Offset value estimated by the algorithm
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimator():
ForceTorqueAccelerometerDataset(),
ftoe_pimpl(new ForceTorqueOffsetEstimatorPrivateAttributes)
{
}
ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimator(const ForceTorqueOffsetEstimator& other):
ForceTorqueAccelerometerDataset(other),
ftoe_pimpl(new ForceTorqueOffsetEstimatorPrivateAttributes(*other.ftoe_pimpl))
{
}
/*
ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimator(ForceTorqueOffsetEstimator&& other)
: pimpl(0)
{
std::swap(pimpl, other.pimpl);
}*/
ForceTorqueOffsetEstimator& ForceTorqueOffsetEstimator::operator=(const ForceTorqueOffsetEstimator &other)
{
if(this != &other) {
*ftoe_pimpl = *(other.ftoe_pimpl);
}
return *this;
}
ForceTorqueOffsetEstimator::~ForceTorqueOffsetEstimator()
{
delete ftoe_pimpl;
ftoe_pimpl = 0;
}
Eigen::Matrix<double,9,1> vec_operator(const Eigen::Matrix3d & mat)
{
Eigen::Matrix<double,9,1> ret;
ret.segment<3>(0) = mat.block<3,1>(0,0);
ret.segment<3>(3) = mat.block<3,1>(0,1);
ret.segment<3>(6) = mat.block<3,1>(0,2);
return ret;
}
Eigen::Matrix<double,3,12> offset_regressor(const Eigen::Vector3d & g)
{
Eigen::Matrix<double,3,12> regr;
regr.setZero();
regr.block<3,3>(0,0) = g(0)*Eigen::Matrix3d::Identity();
regr.block<3,3>(0,3) = g(1)*Eigen::Matrix3d::Identity();
regr.block<3,3>(0,6) = g(2)*Eigen::Matrix3d::Identity();
regr.block<3,3>(0,9) = Eigen::Matrix3d::Identity();
return regr;
}
bool ForceTorqueOffsetEstimator::computeOffsetEstimation()
{
if( this->getNrOfSamples() == 0 )
{
return false;
}
//Compute the mean of the ft measurements (\f[ r_m \f])
Eigen::Matrix<double,6,1> r_m;
r_m.setZero();
for(int i=0; i < this->getNrOfSamples(); i++)
{
Eigen::Matrix<double,6,1> ft_sample;
Eigen::Vector3d acc_sample;
this->getMeasurements(i,wrapVec(ft_sample),wrapVec(acc_sample));
Eigen::Matrix<double,6,1> delta = ft_sample-r_m;
r_m += delta/(i+1);
}
//Compute the 3D subspace in which the measurement lie
//\todo this implementation is probably numerically unstable
// substitute it with welford algorithm
Eigen::Matrix<double,6,6> RTR;
RTR.setZero();
for(int i=0; i < this->getNrOfSamples(); i++)
{
Eigen::Matrix<double,6,1> ft_sample;
Eigen::Vector3d acc_sample;
this->getMeasurements(i,wrapVec(ft_sample),wrapVec(acc_sample));
Eigen::Matrix<double,6,1> ft_sample_without_mean = ft_sample-r_m;
RTR += (ft_sample_without_mean)*(ft_sample_without_mean).transpose();
}
//Compute the SVD (or eigenvalue decomposition) of RTR
//For getting the estimate of the subspace
Eigen::JacobiSVD<Eigen::Matrix<double,6,6>, Eigen::HouseholderQRPreconditioner>
svd(RTR, Eigen::ComputeFullU | Eigen::ComputeFullV);
svd.computeU();
svd.computeV();
Eigen::Matrix<double,6,3> U1 = svd.matrixU().block<6,3>(0,0);
//Solve offset least square problem
Eigen::Matrix<double,12,12> GammaTransposeGamma = Eigen::Matrix<double,12,12>::Zero();
Eigen::Matrix<double,12,1> GammaTranspose_r = Eigen::Matrix<double,12,1>::Zero();
for(int i=0; i < this->getNrOfSamples(); i++)
{
Eigen::Matrix<double,6,1> ft_sample;
Eigen::Vector3d acc_sample;
this->getMeasurements(i,wrapVec(ft_sample),wrapVec(acc_sample));
Eigen::Matrix<double,3,12> regr_matrix = offset_regressor(acc_sample);
Eigen::Vector3d ft_sample_without_mean_projected = U1.transpose()*(ft_sample-r_m);
GammaTransposeGamma += regr_matrix.transpose()*regr_matrix;
GammaTranspose_r += regr_matrix.transpose()*ft_sample_without_mean_projected;
}
Eigen::JacobiSVD<Eigen::Matrix<double,12,12>, Eigen::HouseholderQRPreconditioner>
svd_GTG(GammaTransposeGamma, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::Matrix<double,12,1> x = svd_GTG.solve(GammaTranspose_r);
//Get o_first
Eigen::Vector3d o_first = x.segment<3>(9);
//Get final offset
//FIXME the paper has a plus in this formula, probably we need to fix it in the paper
std::cout << "r_m : " << r_m.transpose() << std::endl;
this->ftoe_pimpl->offset = r_m + U1*o_first;
return true;
}
bool ForceTorqueOffsetEstimator::getEstimatedOffset(const VecWrapper offset) const
{
if( offset.size != 6 )
{
return false;
}
toEigen(offset) = this->ftoe_pimpl->offset;
return true;
}
bool ForceTorqueOffsetEstimator::getMeasurementsWithoutFTOffset(const int sample,
const VecWrapper ft_measure,
const VecWrapper acc_measure) const
{
if( !(sample >= 0 && sample < this->getNrOfSamples()) )
{
return false;
}
this->getMeasurements(sample,ft_measure,acc_measure);
toEigen(ft_measure) = toEigen(ft_measure)-this->ftoe_pimpl->offset;
return true;
}
}<commit_msg>Fix insitu ft<commit_after>#include "offset_estimator.h"
#include <Eigen/Dense>
#include "eigen_wrappers.h"
namespace InSituFTCalibration {
struct ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimatorPrivateAttributes
{
Eigen::Matrix<double,6,1> offset; //< Offset value estimated by the algorithm
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimator():
ForceTorqueAccelerometerDataset(),
ftoe_pimpl(new ForceTorqueOffsetEstimatorPrivateAttributes)
{
}
ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimator(const ForceTorqueOffsetEstimator& other):
ForceTorqueAccelerometerDataset(other),
ftoe_pimpl(new ForceTorqueOffsetEstimatorPrivateAttributes(*other.ftoe_pimpl))
{
}
/*
ForceTorqueOffsetEstimator::ForceTorqueOffsetEstimator(ForceTorqueOffsetEstimator&& other)
: pimpl(0)
{
std::swap(pimpl, other.pimpl);
}*/
ForceTorqueOffsetEstimator& ForceTorqueOffsetEstimator::operator=(const ForceTorqueOffsetEstimator &other)
{
if(this != &other) {
*ftoe_pimpl = *(other.ftoe_pimpl);
}
return *this;
}
ForceTorqueOffsetEstimator::~ForceTorqueOffsetEstimator()
{
delete ftoe_pimpl;
ftoe_pimpl = 0;
}
Eigen::Matrix<double,9,1> vec_operator(const Eigen::Matrix3d & mat)
{
Eigen::Matrix<double,9,1> ret;
ret.segment<3>(0) = mat.block<3,1>(0,0);
ret.segment<3>(3) = mat.block<3,1>(0,1);
ret.segment<3>(6) = mat.block<3,1>(0,2);
return ret;
}
Eigen::Matrix<double,3,12> offset_regressor(const Eigen::Vector3d & g)
{
Eigen::Matrix<double,3,12> regr;
regr.setZero();
regr.block<3,3>(0,0) = g(0)*Eigen::Matrix3d::Identity();
regr.block<3,3>(0,3) = g(1)*Eigen::Matrix3d::Identity();
regr.block<3,3>(0,6) = g(2)*Eigen::Matrix3d::Identity();
regr.block<3,3>(0,9) = Eigen::Matrix3d::Identity();
return regr;
}
bool ForceTorqueOffsetEstimator::computeOffsetEstimation()
{
if( this->getNrOfSamples() == 0 )
{
return false;
}
//Compute the mean of the ft measurements (\f[ r_m \f])
Eigen::Matrix<double,6,1> r_m;
r_m.setZero();
for(int i=0; i < this->getNrOfSamples(); i++)
{
Eigen::Matrix<double,6,1> ft_sample;
Eigen::Vector3d acc_sample;
this->getMeasurements(i,wrapVec(ft_sample),wrapVec(acc_sample));
Eigen::Matrix<double,6,1> delta = ft_sample-r_m;
r_m += delta/(i+1);
}
//Compute the 3D subspace in which the measurement lie
//\todo this implementation is probably numerically unstable
// substitute it with welford algorithm
Eigen::Matrix<double,6,6> RTR;
RTR.setZero();
for(int i=0; i < this->getNrOfSamples(); i++)
{
Eigen::Matrix<double,6,1> ft_sample;
Eigen::Vector3d acc_sample;
this->getMeasurements(i,wrapVec(ft_sample),wrapVec(acc_sample));
Eigen::Matrix<double,6,1> ft_sample_without_mean = ft_sample-r_m;
RTR += (ft_sample_without_mean)*(ft_sample_without_mean).transpose();
}
//Compute the SVD (or eigenvalue decomposition) of RTR
//For getting the estimate of the subspace
Eigen::JacobiSVD<Eigen::Matrix<double,6,6>, Eigen::HouseholderQRPreconditioner>
svd(RTR, Eigen::ComputeFullU | Eigen::ComputeFullV);
svd.computeU();
svd.computeV();
Eigen::Matrix<double,6,3> U1 = svd.matrixU().block<6,3>(0,0);
//Solve offset least square problem
Eigen::Matrix<double,12,12> GammaTransposeGamma = Eigen::Matrix<double,12,12>::Zero();
Eigen::Matrix<double,12,1> GammaTranspose_r = Eigen::Matrix<double,12,1>::Zero();
for(int i=0; i < this->getNrOfSamples(); i++)
{
Eigen::Matrix<double,6,1> ft_sample;
Eigen::Vector3d acc_sample;
this->getMeasurements(i,wrapVec(ft_sample),wrapVec(acc_sample));
Eigen::Matrix<double,3,12> regr_matrix = offset_regressor(acc_sample);
Eigen::Vector3d ft_sample_without_mean_projected = U1.transpose()*(ft_sample-r_m);
GammaTransposeGamma += regr_matrix.transpose()*regr_matrix;
GammaTranspose_r += regr_matrix.transpose()*ft_sample_without_mean_projected;
}
Eigen::JacobiSVD<Eigen::Matrix<double,12,12>, Eigen::HouseholderQRPreconditioner>
svd_GTG(GammaTransposeGamma, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::Matrix<double,12,1> x = svd_GTG.solve(GammaTranspose_r);
//Get o_first
Eigen::Vector3d o_first = x.segment<3>(9);
//Get final offset
this->ftoe_pimpl->offset = r_m + U1*o_first;
return true;
}
bool ForceTorqueOffsetEstimator::getEstimatedOffset(const VecWrapper offset) const
{
if( offset.size != 6 )
{
return false;
}
toEigen(offset) = this->ftoe_pimpl->offset;
return true;
}
bool ForceTorqueOffsetEstimator::getMeasurementsWithoutFTOffset(const int sample,
const VecWrapper ft_measure,
const VecWrapper acc_measure) const
{
if( !(sample >= 0 && sample < this->getNrOfSamples()) )
{
return false;
}
this->getMeasurements(sample,ft_measure,acc_measure);
toEigen(ft_measure) = toEigen(ft_measure)-this->ftoe_pimpl->offset;
return true;
}
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkNeighborhoodIterator.h"
#include "itkFastMarchingImageFilter.h"
#include "itkNumericTraits.h"
#include "itkRandomImageSource.h"
#include "itkAddImageFilter.h"
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6a.png}
// 100 100
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6b.png}
// 50 150
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6c.png}
// 150 50
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// Some image processing routines do not need to visit every pixel in an
// image. Flood-fill and connected-component algorithms, for example, only
// visit pixels that are locally connected to one another. Algorithms
// such as these can be efficiently written using the random access
// capabilities of the neighborhood iterator.
//
// The following example finds local minima. Given a seed point, we can search
// the neighborhood of that point and pick the smallest value $m$. While $m$
// is not at the center of our current neighborhood, we move in the direction
// of $m$ and repeat the analysis. Eventually we discover a local minimum and
// stop. This algorithm is made trivially simple in ND using an ITK
// neighborhood iterator.
//
// To illustrate the process, we create an image that descends everywhere to a
// single minimum: a positive distance transform to a point. The details of
// creating the distance transform are not relevant to the discussion of
// neighborhood iterators, but can be found in the source code of this
// example. Some noise has been added to the distance transform image for
// additional interest.
//
// Software Guide : EndLatex
int main( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " outputImageFile startX startY"
<< std::endl;
return -1;
}
typedef float PixelType;
typedef otb::Image< PixelType, 2 > ImageType;
typedef itk::NeighborhoodIterator< ImageType > NeighborhoodIteratorType;
typedef itk::FastMarchingImageFilter<ImageType, ImageType> FastMarchingFilterType;
FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New();
typedef FastMarchingFilterType::NodeContainer NodeContainer;
typedef FastMarchingFilterType::NodeType NodeType;
NodeContainer::Pointer seeds = NodeContainer::New();
ImageType::IndexType seedPosition;
seedPosition[0] = 128;
seedPosition[1] = 128;
const double initialDistance = 1.0;
NodeType node;
const double seedValue = - initialDistance;
ImageType::SizeType size = {{256, 256}};
node.SetValue( seedValue );
node.SetIndex( seedPosition );
seeds->Initialize();
seeds->InsertElement( 0, node );
fastMarching->SetTrialPoints( seeds );
fastMarching->SetSpeedConstant( 1.0 );
itk::AddImageFilter<ImageType, ImageType, ImageType>::Pointer adder
= itk::AddImageFilter<ImageType, ImageType, ImageType>::New();
itk::RandomImageSource<ImageType>::Pointer noise
= itk::RandomImageSource<ImageType>::New();
noise->SetSize(size.m_Size);
noise->SetMin(-.7);
noise->SetMax(.8);
adder->SetInput1(noise->GetOutput());
adder->SetInput2(fastMarching->GetOutput());
try
{
fastMarching->SetOutputSize( size );
fastMarching->Update();
adder->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
ImageType::Pointer input = adder->GetOutput();
// Software Guide : BeginLatex
//
// The variable \code{input} is the pointer to the distance transform image.
// The local minimum algorithm is initialized with a seed point read from the
// command line.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::IndexType index;
index[0] = ::atoi(argv[2]);
index[1] = ::atoi(argv[3]);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Next we create the neighborhood iterator and position it at the seed point.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighborhoodIteratorType::RadiusType radius;
radius.Fill(1);
NeighborhoodIteratorType it(radius, input, input->GetRequestedRegion());
it.SetLocation(index);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Searching for the local minimum involves finding the minimum in the current
// neighborhood, then shifting the neighborhood in the direction of that
// minimum. The \code{for} loop below records the \doxygen{itk}{Offset} of the
// minimum neighborhood pixel. The neighborhood iterator is then moved using
// that offset. When a local minimum is detected, \code{flag} will remain
// false and the \code{while} loop will exit. Note that this code is
// valid for an image of any dimensionality.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
bool flag = true;
while ( flag == true )
{
NeighborhoodIteratorType::OffsetType nextMove;
nextMove.Fill(0);
flag = false;
PixelType min = it.GetCenterPixel();
for (unsigned i = 0; i < it.Size(); i++)
{
if ( it.GetPixel(i) < min )
{
min = it.GetPixel(i);
nextMove = it.GetOffset(i);
flag = true;
}
}
it.SetCenterPixel( 255.0 );
it += nextMove;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:NeighborhoodExample6} shows the results of the algorithm
// for several seed points. The white line is the path of the iterator from
// the seed point to the minimum in the center of the image. The effect of the
// additive noise is visible as the small perturbations in the paths.
//
// \begin{figure} \centering
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6a.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6b.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6c.eps}
// \itkcaption[Finding local minima]{Paths traversed by the neighborhood
// iterator from different seed points to the local minimum.
// The true minimum is at the center
// of the image. The path of the iterator is shown in white. The effect of
// noise in the image is seen as small perturbations in each path. }
// \protect\label{fig:NeighborhoodExample6} \end{figure}
//
// Software Guide : EndLatex
typedef unsigned char WritePixelType;
typedef otb::Image< WritePixelType, 2 > WriteImageType;
typedef otb::ImageFileWriter< WriteImageType > WriterType;
typedef itk::RescaleIntensityImageFilter< ImageType,
WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput( input );
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[1] );
writer->SetInput( rescaler->GetOutput() );
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH Deterministic behaviour for ImageSourceRandom<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkNeighborhoodIterator.h"
#include "itkFastMarchingImageFilter.h"
#include "itkNumericTraits.h"
#include "itkRandomImageSource.h"
#include "itkAddImageFilter.h"
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6a.png}
// 100 100
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6b.png}
// 50 150
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// OUTPUTS: {NeighborhoodIterators6c.png}
// 150 50
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// Some image processing routines do not need to visit every pixel in an
// image. Flood-fill and connected-component algorithms, for example, only
// visit pixels that are locally connected to one another. Algorithms
// such as these can be efficiently written using the random access
// capabilities of the neighborhood iterator.
//
// The following example finds local minima. Given a seed point, we can search
// the neighborhood of that point and pick the smallest value $m$. While $m$
// is not at the center of our current neighborhood, we move in the direction
// of $m$ and repeat the analysis. Eventually we discover a local minimum and
// stop. This algorithm is made trivially simple in ND using an ITK
// neighborhood iterator.
//
// To illustrate the process, we create an image that descends everywhere to a
// single minimum: a positive distance transform to a point. The details of
// creating the distance transform are not relevant to the discussion of
// neighborhood iterators, but can be found in the source code of this
// example. Some noise has been added to the distance transform image for
// additional interest.
//
// Software Guide : EndLatex
int main( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " outputImageFile startX startY"
<< std::endl;
return -1;
}
typedef float PixelType;
typedef otb::Image< PixelType, 2 > ImageType;
typedef itk::NeighborhoodIterator< ImageType > NeighborhoodIteratorType;
typedef itk::FastMarchingImageFilter<ImageType, ImageType> FastMarchingFilterType;
FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New();
typedef FastMarchingFilterType::NodeContainer NodeContainer;
typedef FastMarchingFilterType::NodeType NodeType;
NodeContainer::Pointer seeds = NodeContainer::New();
ImageType::IndexType seedPosition;
seedPosition[0] = 128;
seedPosition[1] = 128;
const double initialDistance = 1.0;
NodeType node;
const double seedValue = - initialDistance;
ImageType::SizeType size = {{256, 256}};
node.SetValue( seedValue );
node.SetIndex( seedPosition );
seeds->Initialize();
seeds->InsertElement( 0, node );
fastMarching->SetTrialPoints( seeds );
fastMarching->SetSpeedConstant( 1.0 );
itk::AddImageFilter<ImageType, ImageType, ImageType>::Pointer adder
= itk::AddImageFilter<ImageType, ImageType, ImageType>::New();
itk::RandomImageSource<ImageType>::Pointer noise
= itk::RandomImageSource<ImageType>::New();
noise->SetSize(size.m_Size);
noise->SetMin(-.7);
noise->SetMax(.8);
noise->SetNumberOfThreads(1);
adder->SetInput1(noise->GetOutput());
adder->SetInput2(fastMarching->GetOutput());
try
{
fastMarching->SetOutputSize( size );
fastMarching->Update();
adder->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
ImageType::Pointer input = adder->GetOutput();
// Software Guide : BeginLatex
//
// The variable \code{input} is the pointer to the distance transform image.
// The local minimum algorithm is initialized with a seed point read from the
// command line.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::IndexType index;
index[0] = ::atoi(argv[2]);
index[1] = ::atoi(argv[3]);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Next we create the neighborhood iterator and position it at the seed point.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
NeighborhoodIteratorType::RadiusType radius;
radius.Fill(1);
NeighborhoodIteratorType it(radius, input, input->GetRequestedRegion());
it.SetLocation(index);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Searching for the local minimum involves finding the minimum in the current
// neighborhood, then shifting the neighborhood in the direction of that
// minimum. The \code{for} loop below records the \doxygen{itk}{Offset} of the
// minimum neighborhood pixel. The neighborhood iterator is then moved using
// that offset. When a local minimum is detected, \code{flag} will remain
// false and the \code{while} loop will exit. Note that this code is
// valid for an image of any dimensionality.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
bool flag = true;
while ( flag == true )
{
NeighborhoodIteratorType::OffsetType nextMove;
nextMove.Fill(0);
flag = false;
PixelType min = it.GetCenterPixel();
for (unsigned i = 0; i < it.Size(); i++)
{
if ( it.GetPixel(i) < min )
{
min = it.GetPixel(i);
nextMove = it.GetOffset(i);
flag = true;
}
}
it.SetCenterPixel( 255.0 );
it += nextMove;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:NeighborhoodExample6} shows the results of the algorithm
// for several seed points. The white line is the path of the iterator from
// the seed point to the minimum in the center of the image. The effect of the
// additive noise is visible as the small perturbations in the paths.
//
// \begin{figure} \centering
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6a.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6b.eps}
// \includegraphics[width=0.3\textwidth]{NeighborhoodIterators6c.eps}
// \itkcaption[Finding local minima]{Paths traversed by the neighborhood
// iterator from different seed points to the local minimum.
// The true minimum is at the center
// of the image. The path of the iterator is shown in white. The effect of
// noise in the image is seen as small perturbations in each path. }
// \protect\label{fig:NeighborhoodExample6} \end{figure}
//
// Software Guide : EndLatex
typedef unsigned char WritePixelType;
typedef otb::Image< WritePixelType, 2 > WriteImageType;
typedef otb::ImageFileWriter< WriteImageType > WriterType;
typedef itk::RescaleIntensityImageFilter< ImageType,
WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput( input );
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[1] );
writer->SetInput( rescaler->GetOutput() );
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* 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: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* For LWP filter architecture prototype
************************************************************************/
#include "lwplaypiece.hxx"
#include "lwpfilehdr.hxx"
LwpRotor::LwpRotor()
: m_nRotation(0)
{}
LwpRotor::~LwpRotor()
{}
void LwpRotor:: Read(LwpObjectStream *pStrm)
{
m_nRotation = pStrm->QuickReadInt16();
}
LwpLayoutGeometry::LwpLayoutGeometry(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
, m_nWidth(0)
, m_nHeight(0)
, m_ContentOrientation(0)
{}
LwpLayoutGeometry::~LwpLayoutGeometry()
{}
void LwpLayoutGeometry::Read()
{
LwpVirtualPiece::Read();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_nWidth = m_pObjStrm->QuickReadInt32();
m_nHeight = m_pObjStrm->QuickReadInt32();
m_Origin.Read(m_pObjStrm);
m_AbsoluteOrigin.Read(m_pObjStrm);
m_ContainerRotor.Read(m_pObjStrm);
m_ContentOrientation = m_pObjStrm->QuickReaduInt8();
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutGeometry::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutScale::LwpLayoutScale(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
, m_nScaleMode(0)
, m_nScalePercentage(0)
, m_nScaleWidth(0)
, m_nScaleHeight(0)
, m_nContentRotation(0)
, m_nPlacement(0)
{}
LwpLayoutScale::~LwpLayoutScale()
{}
void LwpLayoutScale::Read()
{
LwpVirtualPiece::Read();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_nScaleMode = m_pObjStrm->QuickReaduInt16();
m_nScalePercentage = m_pObjStrm->QuickReaduInt32();
m_nScaleWidth = m_pObjStrm->QuickReadInt32();
m_nScaleHeight = m_pObjStrm->QuickReadInt32();
m_nContentRotation = m_pObjStrm->QuickReaduInt16();
m_Offset.Read(m_pObjStrm);
m_nPlacement = m_pObjStrm->QuickReaduInt16();
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutScale::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutMargins::LwpLayoutMargins(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutMargins::~LwpLayoutMargins()
{}
void LwpLayoutMargins::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_Margins.Read(m_pObjStrm);
m_ExtMargins.Read(m_pObjStrm);
m_ExtraMargins.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutMargins::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutBorder::LwpLayoutBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutBorder::~LwpLayoutBorder()
{}
void LwpLayoutBorder::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_BorderStuff.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutBorder::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutBackground::LwpLayoutBackground(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutBackground::~LwpLayoutBackground()
{}
void LwpLayoutBackground::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_BackgroundStuff.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutBackground::Parse(IXFStream* /*pOutputStream*/)
{}
LwpExternalBorder::LwpExternalBorder()
{}
LwpExternalBorder::~LwpExternalBorder()
{}
void LwpExternalBorder:: Read(LwpObjectStream *pStrm)
{
if( LwpFileHeader::m_nFileRevision >= 0x000F )
{
//enum {BORDER,JOIN};
m_LeftName.Read(pStrm);
m_TopName.Read(pStrm);
m_RightName.Read(pStrm);
m_BottomName.Read(pStrm);
// TODO: Do not know what it is for
/*cLeftName = CStyleMgr::GetUniqueMetaFileName(cLeftName,BORDER);
cRightName = CStyleMgr::GetUniqueMetaFileName(cRightName,BORDER);
cTopName = CStyleMgr::GetUniqueMetaFileName(cTopName,BORDER);
cBottomName = CStyleMgr::GetUniqueMetaFileName(cBottomName,BORDER);*/
pStrm->SkipExtra();
}
}
LwpLayoutExternalBorder::LwpLayoutExternalBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutExternalBorder::~LwpLayoutExternalBorder()
{}
void LwpLayoutExternalBorder::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_ExtranalBorder.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutExternalBorder::Parse(IXFStream* /*pOutputStream*/)
{}
LwpColumnInfo::LwpColumnInfo()
: m_nWidth(0)
, m_nGap(0)
{}
LwpColumnInfo::~LwpColumnInfo()
{}
void LwpColumnInfo:: Read(LwpObjectStream *pStrm)
{
m_nWidth = pStrm->QuickReadInt32();
m_nGap = pStrm->QuickReadInt32();
}
LwpLayoutColumns::LwpLayoutColumns(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm),m_pColumns(NULL)
{}
LwpLayoutColumns::~LwpLayoutColumns()
{
if(m_pColumns)
{
delete[] m_pColumns;
m_pColumns = NULL;
}
}
void LwpLayoutColumns::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_nNumCols = m_pObjStrm->QuickReaduInt16();
m_pColumns = new LwpColumnInfo[m_nNumCols];
for(int i=0; i<m_nNumCols; i++)
{
m_pColumns[i].Read(m_pObjStrm);
}
m_pObjStrm->SkipExtra();
}
}
double LwpLayoutColumns::GetColWidth(sal_uInt16 nIndex)
{
if(nIndex >= m_nNumCols)
{
return 0;
}
return m_pColumns[nIndex].GetWidth();
}
double LwpLayoutColumns::GetColGap(sal_uInt16 nIndex)
{
if(nIndex >= m_nNumCols)
{
return 0;
}
return m_pColumns[nIndex].GetGap();
}
void LwpLayoutColumns::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutGutters::LwpLayoutGutters(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutGutters::~LwpLayoutGutters()
{}
void LwpLayoutGutters::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_BorderBuffer.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutGutters::Parse(IXFStream* /*pOutputStream*/)
{}
LwpJoinStuff::LwpJoinStuff()
{}
LwpJoinStuff::~LwpJoinStuff()
{}
#include "lwpstyledef.hxx"
void LwpJoinStuff:: Read(LwpObjectStream *pStrm)
{
m_nWidth = pStrm->QuickReadInt32();
m_nHeight = pStrm->QuickReadInt32();
m_nPercentage = pStrm->QuickReaduInt16();
m_nID = pStrm->QuickReaduInt16();
m_nCorners = pStrm->QuickReaduInt16();
m_nScaling = pStrm->QuickReaduInt16();
m_Color.Read(pStrm);
pStrm->SkipExtra();
// Bug fix: if reading in from something older than Release 9
// then check for the external ID and change it to solid.
if (LwpFileHeader::m_nFileRevision < 0x0010)
{
if (m_nID & EXTERNAL_ID)
m_nID = MITRE;
}
}
LwpLayoutJoins::LwpLayoutJoins(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutJoins::~LwpLayoutJoins()
{}
void LwpLayoutJoins::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_JoinStuff.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutJoins::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutShadow::LwpLayoutShadow(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutShadow::~LwpLayoutShadow()
{}
void LwpLayoutShadow::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_Shadow.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutShadow::Parse(IXFStream* /*pOutputStream*/)
{}
/**************************************************************************
* @descr: Constructor
* @param:
* @param:
* @return:
**************************************************************************/
LwpLayoutRelativityGuts::LwpLayoutRelativityGuts()
{
m_nRelType = LAY_PARENT_RELATIVE;
m_nRelFromWhere = LAY_UPPERLEFT;
m_RelDistance.SetX(0);
m_RelDistance.SetY(0);
m_nTether = LAY_UPPERLEFT;
m_nTetherWhere = LAY_BORDER;
m_nFlags = 0;
}
/**************************************************************************
* @descr: Read LayoutRelativityGuts' information.
* @param:
* @param:
* @return:
**************************************************************************/
void LwpLayoutRelativityGuts::Read(LwpObjectStream *pStrm)
{
m_nRelType = pStrm->QuickReaduInt8();
m_nRelFromWhere = pStrm->QuickReaduInt8();
m_RelDistance.Read(pStrm);
m_nTether = pStrm->QuickReaduInt8();
m_nTetherWhere = pStrm->QuickReaduInt8();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_nFlags = pStrm->QuickReaduInt8();
}
else
{
m_nFlags = 0;
}
}
/**************************************************************************
* @descr: Constructor
* @param:
* @param:
* @return:
**************************************************************************/
LwpLayoutRelativity::LwpLayoutRelativity(LwpObjectHeader &objHdr, LwpSvStream *pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{
}
/**************************************************************************
* @descr: destructor
* @param:
* @param:
* @return:
**************************************************************************/
LwpLayoutRelativity::~LwpLayoutRelativity()
{
}
void LwpLayoutRelativity::Read()
{
LwpVirtualPiece::Read();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_RelGuts.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutRelativity::Parse(IXFStream * /*pOutputStream*/)
{
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738727: Unitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* 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: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* For LWP filter architecture prototype
************************************************************************/
#include "lwplaypiece.hxx"
#include "lwpfilehdr.hxx"
LwpRotor::LwpRotor()
: m_nRotation(0)
{}
LwpRotor::~LwpRotor()
{}
void LwpRotor:: Read(LwpObjectStream *pStrm)
{
m_nRotation = pStrm->QuickReadInt16();
}
LwpLayoutGeometry::LwpLayoutGeometry(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
, m_nWidth(0)
, m_nHeight(0)
, m_ContentOrientation(0)
{}
LwpLayoutGeometry::~LwpLayoutGeometry()
{}
void LwpLayoutGeometry::Read()
{
LwpVirtualPiece::Read();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_nWidth = m_pObjStrm->QuickReadInt32();
m_nHeight = m_pObjStrm->QuickReadInt32();
m_Origin.Read(m_pObjStrm);
m_AbsoluteOrigin.Read(m_pObjStrm);
m_ContainerRotor.Read(m_pObjStrm);
m_ContentOrientation = m_pObjStrm->QuickReaduInt8();
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutGeometry::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutScale::LwpLayoutScale(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
, m_nScaleMode(0)
, m_nScalePercentage(0)
, m_nScaleWidth(0)
, m_nScaleHeight(0)
, m_nContentRotation(0)
, m_nPlacement(0)
{}
LwpLayoutScale::~LwpLayoutScale()
{}
void LwpLayoutScale::Read()
{
LwpVirtualPiece::Read();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_nScaleMode = m_pObjStrm->QuickReaduInt16();
m_nScalePercentage = m_pObjStrm->QuickReaduInt32();
m_nScaleWidth = m_pObjStrm->QuickReadInt32();
m_nScaleHeight = m_pObjStrm->QuickReadInt32();
m_nContentRotation = m_pObjStrm->QuickReaduInt16();
m_Offset.Read(m_pObjStrm);
m_nPlacement = m_pObjStrm->QuickReaduInt16();
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutScale::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutMargins::LwpLayoutMargins(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutMargins::~LwpLayoutMargins()
{}
void LwpLayoutMargins::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_Margins.Read(m_pObjStrm);
m_ExtMargins.Read(m_pObjStrm);
m_ExtraMargins.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutMargins::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutBorder::LwpLayoutBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutBorder::~LwpLayoutBorder()
{}
void LwpLayoutBorder::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_BorderStuff.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutBorder::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutBackground::LwpLayoutBackground(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutBackground::~LwpLayoutBackground()
{}
void LwpLayoutBackground::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_BackgroundStuff.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutBackground::Parse(IXFStream* /*pOutputStream*/)
{}
LwpExternalBorder::LwpExternalBorder()
{}
LwpExternalBorder::~LwpExternalBorder()
{}
void LwpExternalBorder:: Read(LwpObjectStream *pStrm)
{
if( LwpFileHeader::m_nFileRevision >= 0x000F )
{
//enum {BORDER,JOIN};
m_LeftName.Read(pStrm);
m_TopName.Read(pStrm);
m_RightName.Read(pStrm);
m_BottomName.Read(pStrm);
// TODO: Do not know what it is for
/*cLeftName = CStyleMgr::GetUniqueMetaFileName(cLeftName,BORDER);
cRightName = CStyleMgr::GetUniqueMetaFileName(cRightName,BORDER);
cTopName = CStyleMgr::GetUniqueMetaFileName(cTopName,BORDER);
cBottomName = CStyleMgr::GetUniqueMetaFileName(cBottomName,BORDER);*/
pStrm->SkipExtra();
}
}
LwpLayoutExternalBorder::LwpLayoutExternalBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutExternalBorder::~LwpLayoutExternalBorder()
{}
void LwpLayoutExternalBorder::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_ExtranalBorder.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutExternalBorder::Parse(IXFStream* /*pOutputStream*/)
{}
LwpColumnInfo::LwpColumnInfo()
: m_nWidth(0)
, m_nGap(0)
{}
LwpColumnInfo::~LwpColumnInfo()
{}
void LwpColumnInfo:: Read(LwpObjectStream *pStrm)
{
m_nWidth = pStrm->QuickReadInt32();
m_nGap = pStrm->QuickReadInt32();
}
LwpLayoutColumns::LwpLayoutColumns(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
, m_nNumCols(0)
, m_pColumns(NULL)
{}
LwpLayoutColumns::~LwpLayoutColumns()
{
if(m_pColumns)
{
delete[] m_pColumns;
m_pColumns = NULL;
}
}
void LwpLayoutColumns::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_nNumCols = m_pObjStrm->QuickReaduInt16();
m_pColumns = new LwpColumnInfo[m_nNumCols];
for(int i=0; i<m_nNumCols; i++)
{
m_pColumns[i].Read(m_pObjStrm);
}
m_pObjStrm->SkipExtra();
}
}
double LwpLayoutColumns::GetColWidth(sal_uInt16 nIndex)
{
if(nIndex >= m_nNumCols)
{
return 0;
}
return m_pColumns[nIndex].GetWidth();
}
double LwpLayoutColumns::GetColGap(sal_uInt16 nIndex)
{
if(nIndex >= m_nNumCols)
{
return 0;
}
return m_pColumns[nIndex].GetGap();
}
void LwpLayoutColumns::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutGutters::LwpLayoutGutters(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutGutters::~LwpLayoutGutters()
{}
void LwpLayoutGutters::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_BorderBuffer.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutGutters::Parse(IXFStream* /*pOutputStream*/)
{}
LwpJoinStuff::LwpJoinStuff()
{}
LwpJoinStuff::~LwpJoinStuff()
{}
#include "lwpstyledef.hxx"
void LwpJoinStuff:: Read(LwpObjectStream *pStrm)
{
m_nWidth = pStrm->QuickReadInt32();
m_nHeight = pStrm->QuickReadInt32();
m_nPercentage = pStrm->QuickReaduInt16();
m_nID = pStrm->QuickReaduInt16();
m_nCorners = pStrm->QuickReaduInt16();
m_nScaling = pStrm->QuickReaduInt16();
m_Color.Read(pStrm);
pStrm->SkipExtra();
// Bug fix: if reading in from something older than Release 9
// then check for the external ID and change it to solid.
if (LwpFileHeader::m_nFileRevision < 0x0010)
{
if (m_nID & EXTERNAL_ID)
m_nID = MITRE;
}
}
LwpLayoutJoins::LwpLayoutJoins(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutJoins::~LwpLayoutJoins()
{}
void LwpLayoutJoins::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_JoinStuff.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutJoins::Parse(IXFStream* /*pOutputStream*/)
{}
LwpLayoutShadow::LwpLayoutShadow(LwpObjectHeader& objHdr, LwpSvStream* pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{}
LwpLayoutShadow::~LwpLayoutShadow()
{}
void LwpLayoutShadow::Read()
{
LwpVirtualPiece::Read();
if( LwpFileHeader::m_nFileRevision >= 0x000B )
{
m_Shadow.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutShadow::Parse(IXFStream* /*pOutputStream*/)
{}
/**************************************************************************
* @descr: Constructor
* @param:
* @param:
* @return:
**************************************************************************/
LwpLayoutRelativityGuts::LwpLayoutRelativityGuts()
{
m_nRelType = LAY_PARENT_RELATIVE;
m_nRelFromWhere = LAY_UPPERLEFT;
m_RelDistance.SetX(0);
m_RelDistance.SetY(0);
m_nTether = LAY_UPPERLEFT;
m_nTetherWhere = LAY_BORDER;
m_nFlags = 0;
}
/**************************************************************************
* @descr: Read LayoutRelativityGuts' information.
* @param:
* @param:
* @return:
**************************************************************************/
void LwpLayoutRelativityGuts::Read(LwpObjectStream *pStrm)
{
m_nRelType = pStrm->QuickReaduInt8();
m_nRelFromWhere = pStrm->QuickReaduInt8();
m_RelDistance.Read(pStrm);
m_nTether = pStrm->QuickReaduInt8();
m_nTetherWhere = pStrm->QuickReaduInt8();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_nFlags = pStrm->QuickReaduInt8();
}
else
{
m_nFlags = 0;
}
}
/**************************************************************************
* @descr: Constructor
* @param:
* @param:
* @return:
**************************************************************************/
LwpLayoutRelativity::LwpLayoutRelativity(LwpObjectHeader &objHdr, LwpSvStream *pStrm)
: LwpVirtualPiece(objHdr, pStrm)
{
}
/**************************************************************************
* @descr: destructor
* @param:
* @param:
* @return:
**************************************************************************/
LwpLayoutRelativity::~LwpLayoutRelativity()
{
}
void LwpLayoutRelativity::Read()
{
LwpVirtualPiece::Read();
if(LwpFileHeader::m_nFileRevision >= 0x000B)
{
m_RelGuts.Read(m_pObjStrm);
m_pObjStrm->SkipExtra();
}
}
void LwpLayoutRelativity::Parse(IXFStream * /*pOutputStream*/)
{
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* main.cpp
* Copyright (C) 2012 xent
* Project is distributed under the terms of the GNU General Public License v3.0
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <vector>
#include "commands.hpp"
#include "crypto.hpp"
#include "shell.hpp"
#include "threading.hpp"
//------------------------------------------------------------------------------
extern "C"
{
#include <libyaf/fat32.h>
#include "mmi.h"
}
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
if (argc < 2)
return 0;
Interface *mmaped;
FsHandle *handle;
mmaped = reinterpret_cast<Interface *>(init(Mmi, argv[1]));
if (!mmaped)
{
printf("Error opening file\n");
return 0;
}
MbrDescriptor mbrRecord;
if (mmiReadTable(mmaped, 0, 0, &mbrRecord) == E_OK)
{
if (mmiSetPartition(mmaped, &mbrRecord) != E_OK)
printf("Error setup partition\n");
}
else
printf("No partitions found, selected raw partition at 0\n");
Fat32Config fsConf;
fsConf.interface = mmaped;
#ifdef CONFIG_FAT_POOLS
fsConf.nodes = 4;
fsConf.directories = 2;
fsConf.files = 2;
#endif
#ifdef CONFIG_FAT_THREADS
fsConf.threads = 2;
#endif
handle = reinterpret_cast<FsHandle *>(init(FatHandle, &fsConf));
if (!handle)
{
printf("Error creating FAT32 handle\n");
return 0;
}
Shell shell(0, handle);
shell.append(CommandBuilder<ChangeDirectory>());
shell.append(CommandBuilder<CopyEntry>());
shell.append(CommandBuilder<ExitShell>());
shell.append(CommandBuilder<ListCommands>());
shell.append(CommandBuilder<ListEntries>());
shell.append(CommandBuilder<MakeDirectory>());
shell.append(CommandBuilder<MeasureTime>());
shell.append(CommandBuilder<RemoveDirectory>());
shell.append(CommandBuilder<RemoveEntry>());
shell.append(CommandBuilder<ComputeHash>());
shell.append(CommandBuilder<ThreadSwarm>());
bool terminate = false;
while (!terminate)
{
cout << shell.path() << "> ";
string command;
getline(cin, command);
enum result res = shell.execute(command.c_str());
switch (res)
{
case E_OK:
break;
case E_ACCESS:
case E_BUSY:
case E_ENTRY:
case E_VALUE:
break;
default:
terminate = true;
break;
}
}
printf("Unloading\n");
deinit(handle);
deinit(mmaped);
return 0;
}
<commit_msg>Updated commands registration.<commit_after>/*
* main.cpp
* Copyright (C) 2012 xent
* Project is distributed under the terms of the GNU General Public License v3.0
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <vector>
#include "commands.hpp"
#include "crypto.hpp"
#include "shell.hpp"
#include "threading.hpp"
//------------------------------------------------------------------------------
extern "C"
{
#include <libyaf/fat32.h>
#include "mmi.h"
}
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
if (argc < 2)
return 0;
Interface *mmaped;
FsHandle *handle;
mmaped = reinterpret_cast<Interface *>(init(Mmi, argv[1]));
if (!mmaped)
{
printf("Error opening file\n");
return 0;
}
MbrDescriptor mbrRecord;
if (mmiReadTable(mmaped, 0, 0, &mbrRecord) == E_OK)
{
if (mmiSetPartition(mmaped, &mbrRecord) != E_OK)
printf("Error setup partition\n");
}
else
printf("No partitions found, selected raw partition at 0\n");
Fat32Config fsConf;
fsConf.interface = mmaped;
#ifdef CONFIG_FAT_POOLS
fsConf.nodes = 4;
fsConf.directories = 2;
fsConf.files = 2;
#endif
#ifdef CONFIG_FAT_THREADS
fsConf.threads = 2;
#endif
handle = reinterpret_cast<FsHandle *>(init(FatHandle, &fsConf));
if (!handle)
{
printf("Error creating FAT32 handle\n");
return 0;
}
Shell shell(0, handle);
shell.append(CommandBuilder<ChangeDirectory>());
shell.append(CommandBuilder<CopyEntry>());
shell.append(CommandBuilder<DirectData>());
shell.append(CommandBuilder<ExitShell>());
shell.append(CommandBuilder<ListCommands>());
shell.append(CommandBuilder<ListEntries>());
shell.append(CommandBuilder<MakeDirectory>());
shell.append(CommandBuilder<MeasureTime>());
shell.append(CommandBuilder<RemoveDirectory>());
shell.append(CommandBuilder<RemoveEntry>());
shell.append(CommandBuilder<ThreadSwarm>());
#ifdef CONFIG_CRYPTO
shell.append(CommandBuilder<ComputeHash>());
#endif
bool terminate = false;
while (!terminate)
{
cout << shell.path() << "> ";
string command;
getline(cin, command);
enum result res = shell.execute(command.c_str());
switch (res)
{
case E_OK:
break;
case E_ACCESS:
case E_BUSY:
case E_ENTRY:
case E_VALUE:
break;
default:
terminate = true;
break;
}
}
printf("Unloading\n");
deinit(handle);
deinit(mmaped);
return 0;
}
<|endoftext|> |
<commit_before>//-*- Mode: C++ -*-
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Svein Lindal *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/**
* @file AliHLTCaloHistoInvMass
* @author Svein Lindal <slindal@fys.uio.no>
* @date
* @brief Produces plots of invariant mass of two clusters
*/
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
#include "AliHLTCaloHistoInvMass.h"
#include "AliHLTCaloClusterDataStruct.h"
#include "TObjArray.h"
#include "AliESDEvent.h"
#include "TRefArray.h"
#include "TH1F.h"
#include "TString.h"
#include "AliESDCaloCluster.h"
AliHLTCaloHistoInvMass::AliHLTCaloHistoInvMass(TString det) :
fHistTwoClusterInvMass(NULL)
{
// See header file for documentation
fHistTwoClusterInvMass = new TH1F(Form("%s fHistTwoClusterInvMass", det.Data()), Form("%s Invariant mass of two clusters PHOS", det.Data()), 200, 0, 1);
fHistTwoClusterInvMass->GetXaxis()->SetTitle("m_{#gamma#gamma} GeV");
fHistTwoClusterInvMass->GetYaxis()->SetTitle("Number of counts");
fHistTwoClusterInvMass->SetMarkerStyle(21);
fHistArray->AddLast(fHistTwoClusterInvMass);
}
AliHLTCaloHistoInvMass::~AliHLTCaloHistoInvMass()
{
if(fHistTwoClusterInvMass)
delete fHistTwoClusterInvMass;
fHistTwoClusterInvMass = NULL;
}
Int_t AliHLTCaloHistoInvMass::FillHistograms(Int_t nc, vector<AliHLTCaloClusterDataStruct*> &cVec) {
//See header file for documentation
Float_t cPos[nc][3];
Float_t cEnergy[nc];
for(int ic = 0; ic < nc; ic++) {
AliHLTCaloClusterDataStruct * cluster = cVec.at(ic);
cluster->GetPosition(cPos[ic]);
cEnergy[ic] = cluster->E();
}
for(Int_t ipho = 0; ipho<(nc-1); ipho++) {
for(Int_t jpho = ipho+1; jpho<nc; jpho++) {
// Calculate the theta angle between two photons
Double_t theta = (2* asin(0.5*TMath::Sqrt((cPos[ipho][0]-cPos[jpho][0])*(cPos[ipho][0]-cPos[jpho][0]) +(cPos[ipho][1]-cPos[jpho][1])*(cPos[ipho][1]-cPos[jpho][1]))/460));
// Calculate the mass m of the pion candidate
Double_t m =(TMath::Sqrt(2 * cEnergy[ipho]* cEnergy[jpho]*(1-TMath::Cos(theta))));
fHistTwoClusterInvMass->Fill(m);
}
}
return 0;
}
Int_t AliHLTCaloHistoInvMass::FillHistograms(Int_t nc, TRefArray * clusterArray) {
//See header file for documentation
Float_t cPos[nc][3];
Float_t cEnergy[nc];
for(int ic = 0; ic < nc; ic++) {
AliESDCaloCluster * cluster = static_cast<AliESDCaloCluster*>(clusterArray->At(ic));
cluster->GetPosition(cPos[ic]);
cEnergy[ic] = cluster->E();
}
for(Int_t ipho = 0; ipho<(nc-1); ipho++) {
for(Int_t jpho = ipho+1; jpho<nc; jpho++) {
// Calculate the theta angle between two photons
Double_t theta = (2* asin(0.5*TMath::Sqrt((cPos[ipho][0]-cPos[jpho][0])*(cPos[ipho][0]-cPos[jpho][0]) +(cPos[ipho][1]-cPos[jpho][1])*(cPos[ipho][1]-cPos[jpho][1]))/460));
// Calculate the mass m of the pion candidate
Double_t m =(TMath::Sqrt(2 * cEnergy[ipho]* cEnergy[jpho]*(1-TMath::Cos(theta))));
fHistTwoClusterInvMass->Fill(m);
}
}
return 0;
}
<commit_msg>cosmetics<commit_after>//-*- Mode: C++ -*-
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Svein Lindal *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/**
* @file AliHLTCaloHistoInvMass
* @author Svein Lindal <slindal@fys.uio.no>
* @date
* @brief Produces plots of invariant mass of two clusters.
*/
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
#include "AliHLTCaloHistoInvMass.h"
#include "AliHLTCaloClusterDataStruct.h"
#include "TObjArray.h"
#include "AliESDEvent.h"
#include "TRefArray.h"
#include "TH1F.h"
#include "TString.h"
#include "AliESDCaloCluster.h"
AliHLTCaloHistoInvMass::AliHLTCaloHistoInvMass(TString det) :
fHistTwoClusterInvMass(NULL)
{
// See header file for documentation
fHistTwoClusterInvMass = new TH1F(Form("%s fHistTwoClusterInvMass", det.Data()), Form("%s Invariant mass of two clusters PHOS", det.Data()), 200, 0, 1);
fHistTwoClusterInvMass->GetXaxis()->SetTitle("m_{#gamma#gamma} GeV");
fHistTwoClusterInvMass->GetYaxis()->SetTitle("Number of counts");
fHistTwoClusterInvMass->SetMarkerStyle(21);
fHistArray->AddLast(fHistTwoClusterInvMass);
}
AliHLTCaloHistoInvMass::~AliHLTCaloHistoInvMass()
{
if(fHistTwoClusterInvMass)
delete fHistTwoClusterInvMass;
fHistTwoClusterInvMass = NULL;
}
Int_t AliHLTCaloHistoInvMass::FillHistograms(Int_t nc, vector<AliHLTCaloClusterDataStruct*> &cVec) {
//See header file for documentation
Float_t cPos[nc][3];
Float_t cEnergy[nc];
for(int ic = 0; ic < nc; ic++) {
AliHLTCaloClusterDataStruct * cluster = cVec.at(ic);
cluster->GetPosition(cPos[ic]);
cEnergy[ic] = cluster->E();
}
for(Int_t ipho = 0; ipho<(nc-1); ipho++) {
for(Int_t jpho = ipho+1; jpho<nc; jpho++) {
// Calculate the theta angle between two photons
Double_t theta = (2* asin(0.5*TMath::Sqrt((cPos[ipho][0]-cPos[jpho][0])*(cPos[ipho][0]-cPos[jpho][0]) +(cPos[ipho][1]-cPos[jpho][1])*(cPos[ipho][1]-cPos[jpho][1]))/460));
// Calculate the mass m of the pion candidate
Double_t m =(TMath::Sqrt(2 * cEnergy[ipho]* cEnergy[jpho]*(1-TMath::Cos(theta))));
fHistTwoClusterInvMass->Fill(m);
}
}
return 0;
}
Int_t AliHLTCaloHistoInvMass::FillHistograms(Int_t nc, TRefArray * clusterArray) {
//See header file for documentation
Float_t cPos[nc][3];
Float_t cEnergy[nc];
for(int ic = 0; ic < nc; ic++) {
AliESDCaloCluster * cluster = static_cast<AliESDCaloCluster*>(clusterArray->At(ic));
cluster->GetPosition(cPos[ic]);
cEnergy[ic] = cluster->E();
}
for(Int_t ipho = 0; ipho<(nc-1); ipho++) {
for(Int_t jpho = ipho+1; jpho<nc; jpho++) {
// Calculate the theta angle between two photons
Double_t theta = (2* asin(0.5*TMath::Sqrt((cPos[ipho][0]-cPos[jpho][0])*(cPos[ipho][0]-cPos[jpho][0]) +(cPos[ipho][1]-cPos[jpho][1])*(cPos[ipho][1]-cPos[jpho][1]))/460));
// Calculate the mass m of the pion candidate
Double_t m =(TMath::Sqrt(2 * cEnergy[ipho]* cEnergy[jpho]*(1-TMath::Cos(theta))));
fHistTwoClusterInvMass->Fill(m);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <boost/filesystem.hpp>
#include <nanikanizer/nanikanizer.hpp>
#include "game.hpp"
#include "enumerate_action.hpp"
#include "apply_state.hpp"
#include "random_state_generator.hpp"
namespace shogi
{
void pretrain(
nnk::linear_layer<float>& l1,
nnk::linear_layer<float>& l2,
nnk::linear_layer<float>& l3,
nnk::linear_layer<float>& l4,
nnk::linear_layer<float>& l5)
{
namespace fs = boost::filesystem;
shogi::random_state_generator gen;
nnk::variable<float> input;
auto pretrain_layer = [&](
nnk::linear_layer<float>& layer,
nnk::expression<float>& prev,
nnk::expression<float>& next,
std::size_t batch_size,
std::size_t repeat,
const fs::path& cache)
{
fs::ofstream log(fs::change_extension(cache, ".log"));
if (fs::exists(cache))
{
fs::ifstream is(cache, std::ios_base::binary);
nnk::binary_reader reader(is);
layer.load(reader);
}
else
{
nnk::linear_layer<float> layer_backward(layer.output_dimension(), layer.input_dimension());
auto prev_ = nnk::sigmoid(layer_backward.forward(next));
auto loss = nnk::cross_entropy(prev_ - prev);
nnk::adam_optimizer optimizer;
optimizer.add_parameter(layer);
optimizer.add_parameter(layer_backward);
nnk::evaluator<float> ev(loss);
input.value().resize(shogi::input_size * batch_size);
for (std::size_t i = 0; i < repeat; ++i)
{
optimizer.zero_grads();
gen.generate(&input.value()[0], batch_size);
log << ev.forward()[0] << std::endl;
ev.backward();
optimizer.update();
}
fs::ofstream os(cache, std::ios_base::binary);
nnk::binary_writer writer(os);
layer.save(writer);
}
};
auto x1 = input.expr();
auto x2 = nnk::sigmoid(l1.forward(x1));
auto x3 = nnk::sigmoid(l2.forward(x2));
auto x4 = nnk::sigmoid(l3.forward(x3));
auto x5 = nnk::sigmoid(l4.forward(x4));
auto x6 = nnk::sigmoid(l5.forward(x5));
pretrain_layer(l1, x1, x2, 100, 10000, "layer1.nan");
pretrain_layer(l2, x2, x3, 100, 10000, "layer2.nan");
pretrain_layer(l3, x3, x4, 100, 10000, "layer3.nan");
pretrain_layer(l4, x4, x5, 100, 10000, "layer4.nan");
pretrain_layer(l5, x5, x6, 100, 10000, "layer5.nan");
}
}
int main(int /*argc*/, char* /*argv*/[])
{
namespace fs = boost::filesystem;
try
{
nnk::linear_layer<float> l1(shogi::input_size, 1500);
nnk::linear_layer<float> l2(1500, 1000);
nnk::linear_layer<float> l3(1000, 750);
nnk::linear_layer<float> l4(750, 500);
nnk::linear_layer<float> l5(500, 250);
shogi::pretrain(l1, l2, l3, l4, l5);
nnk::linear_layer<float> l6(250, 1);
auto forward_all = [&](const nnk::expression<float>& x1)
{
auto x2 = nnk::sigmoid(l1.forward(x1));
auto x3 = nnk::sigmoid(l2.forward(x2));
auto x4 = nnk::sigmoid(l3.forward(x3));
auto x5 = nnk::sigmoid(l4.forward(x4));
auto x6 = nnk::sigmoid(l5.forward(x5));
auto x7 = l6.forward(x6);
return x7;
};
nnk::variable<float> input;
nnk::variable<float> input_next;
auto output = forward_all(input.expr());
auto output_next = nnk::min(forward_all(input_next.expr()));
auto loss_normal = nnk::abs(output + output_next);
auto loss_win = nnk::abs(output - nnk::expression<float>{ 1.0 });
nnk::evaluator<float> ev_normal(loss_normal);
nnk::evaluator<float> ev_win(loss_win);
nnk::adam_optimizer optimizer;
optimizer.add_parameter(l1);
optimizer.add_parameter(l2);
optimizer.add_parameter(l3);
optimizer.add_parameter(l4);
optimizer.add_parameter(l5);
optimizer.add_parameter(l6);
shogi::random_state_generator gen;
std::vector<shogi::action> actions;
while (true)
{
gen.randomize();
const shogi::game& g = gen.get();
input.value().resize(shogi::input_size);
shogi::apply_state(&input.value()[0], g.state(), g.turn());
actions.clear();
shogi::enumerate_action(g, std::back_inserter(actions));
input_next.value().resize(shogi::input_size * actions.size());
bool win = false;
for (std::size_t j = 0; j < actions.size(); ++j)
{
const shogi::action& action = actions[j];
shogi::game next_game = g;
next_game.apply(action);
if (next_game.state().is_finished())
{
win = true;
break;
}
float* p = &input_next.value()[shogi::input_size * j];
shogi::apply_state(p, next_game.state(), next_game.turn());
}
//std::cout << g.state() << std::endl;
nnk::evaluator<float>& ev = win ? ev_win : ev_normal;
std::size_t count = win ? 100 : 1;
for (std::size_t i = 0; i < count; ++i)
{
optimizer.zero_grads();
std::cout << win << ":" << ev.forward()[0] << std::endl;
ev.backward();
optimizer.update();
}
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
<commit_msg>CPU vs CPU<commit_after>#include <iostream>
#include <iomanip>
#include <boost/filesystem.hpp>
#include <nanikanizer/nanikanizer.hpp>
#include "game.hpp"
#include "enumerate_action.hpp"
#include "apply_state.hpp"
#include "random_state_generator.hpp"
namespace shogi
{
namespace fs = boost::filesystem;
class shogi_layers : boost::noncopyable
{
public:
shogi_layers()
: l1_(input_size, 1500)
, l2_(1500, 1000)
, l3_(1000, 750)
, l4_(750, 500)
, l5_(500, 250)
, l6_(250, 1)
{
}
void pre_train()
{
nnk::variable<float> input;
auto x1 = input.expr();
auto x2 = nnk::sigmoid(l1_.forward(x1));
auto x3 = nnk::sigmoid(l2_.forward(x2));
auto x4 = nnk::sigmoid(l3_.forward(x3));
auto x5 = nnk::sigmoid(l4_.forward(x4));
auto x6 = nnk::sigmoid(l5_.forward(x5));
pre_train_layer(input, l1_, x1, x2, 100, 10000, "layer1.nan");
pre_train_layer(input, l2_, x2, x3, 100, 10000, "layer2.nan");
pre_train_layer(input, l3_, x3, x4, 100, 10000, "layer3.nan");
pre_train_layer(input, l4_, x4, x5, 100, 10000, "layer4.nan");
pre_train_layer(input, l5_, x5, x6, 100, 10000, "layer5.nan");
}
void fine_tune()
{
fs::path cache = "all.nnk";
if (fs::exists(cache))
{
fs::ifstream is(cache, std::ios_base::binary);
nnk::binary_reader reader(is);
l1_.load(reader);
l2_.load(reader);
l3_.load(reader);
l4_.load(reader);
l5_.load(reader);
l6_.load(reader);
}
else
{
nnk::variable<float> input;
nnk::variable<float> input_next;
auto output = forward_all(input.expr());
auto output_next = nnk::min(forward_all(input_next.expr()));
auto loss_normal = nnk::abs(output + output_next);
auto scale = nnk::expression<float>({ 5.0f });
auto loss_win = scale * nnk::abs(output - nnk::expression<float>{ 1.0f });
nnk::evaluator<float> ev_normal(loss_normal);
nnk::evaluator<float> ev_win(loss_win);
nnk::adam_optimizer optimizer(0.0001);
optimizer.add_parameter(l1_);
optimizer.add_parameter(l2_);
optimizer.add_parameter(l3_);
optimizer.add_parameter(l4_);
optimizer.add_parameter(l5_);
optimizer.add_parameter(l6_);
random_state_generator gen;
std::vector<action> actions;
while (true)
{
optimizer.zero_grads();
for (std::size_t i = 0; i < 100; ++i)
{
gen.randomize();
const game& g = gen.get();
input.value().resize(input_size);
apply_state(&input.value()[0], g.state(), g.turn());
actions.clear();
enumerate_action(g, std::back_inserter(actions));
input_next.value().resize(input_size * actions.size());
bool win = false;
for (std::size_t j = 0; j < actions.size(); ++j)
{
const action& action = actions[j];
game next_game = g;
next_game.apply(action);
if (next_game.state().is_finished())
win = true;
float* p = &input_next.value()[input_size * j];
apply_state(p, next_game.state(), next_game.turn());
}
//std::cout << g.state() << std::endl;
nnk::evaluator<float>& ev = win ? ev_win : ev_normal;
std::cout << win << ":" << ev.forward()[0] << std::endl;
ev.backward();
}
optimizer.update();
{
fs::ofstream os(cache, std::ios_base::binary);
nnk::binary_writer writer(os);
l1_.save(writer);
l2_.save(writer);
l3_.save(writer);
l4_.save(writer);
l5_.save(writer);
l6_.save(writer);
}
std::cout << "----------" << std::endl;
}
}
}
float evaluate(const shogi::game& g)
{
nnk::variable<float> input;
auto output = forward_all(input.expr());
input.value().resize(input_size);
apply_state(&input.value()[0], g.state(), g.turn());
nnk::evaluator<float> ev(output);
ev.forward();
return output.root()->output()[0];
}
private:
void pre_train_layer(
nnk::variable<float>& input,
nnk::linear_layer<float>& layer,
nnk::expression<float>& prev,
nnk::expression<float>& next,
std::size_t batch_size,
std::size_t repeat,
const fs::path& cache)
{
fs::ofstream log(fs::change_extension(cache, ".log"));
if (fs::exists(cache))
{
fs::ifstream is(cache, std::ios_base::binary);
nnk::binary_reader reader(is);
layer.load(reader);
}
else
{
nnk::linear_layer<float> layer_backward(layer.output_dimension(), layer.input_dimension());
auto prev_ = nnk::sigmoid(layer_backward.forward(next));
auto loss = nnk::cross_entropy(prev_ - prev);
nnk::adam_optimizer optimizer;
optimizer.add_parameter(layer);
optimizer.add_parameter(layer_backward);
nnk::evaluator<float> ev(loss);
input.value().resize(input_size * batch_size);
for (std::size_t i = 0; i < repeat; ++i)
{
optimizer.zero_grads();
gen_.generate(&input.value()[0], batch_size);
log << ev.forward()[0] << std::endl;
ev.backward();
optimizer.update();
}
fs::ofstream os(cache, std::ios_base::binary);
nnk::binary_writer writer(os);
layer.save(writer);
}
}
nnk::expression<float> forward_all(const nnk::expression<float>& x1)
{
auto x2 = nnk::sigmoid(l1_.forward(x1));
auto x3 = nnk::sigmoid(l2_.forward(x2));
auto x4 = nnk::sigmoid(l3_.forward(x3));
auto x5 = nnk::sigmoid(l4_.forward(x4));
auto x6 = nnk::sigmoid(l5_.forward(x5));
auto x7 = nnk::tanh(l6_.forward(x6));
return x7;
}
nnk::linear_layer<float> l1_;
nnk::linear_layer<float> l2_;
nnk::linear_layer<float> l3_;
nnk::linear_layer<float> l4_;
nnk::linear_layer<float> l5_;
nnk::linear_layer<float> l6_;
random_state_generator gen_;
};
}
int main(int /*argc*/, char* /*argv*/[])
{
try
{
shogi::shogi_layers layers;
layers.pre_train();
layers.fine_tune();
shogi::game g;
std::vector<shogi::action> actions;
std::vector<float> action_values;
while (!g.state().is_finished())
{
std::cout << g.state() << std::endl;
actions.clear();
enumerate_action(g, std::back_inserter(actions));
action_values.resize(actions.size());
std::transform(actions.begin(), actions.end(), action_values.begin(),
[&](const shogi::action& action)
{
shogi::game next_game = g;
next_game.apply(action);
if (next_game.state().is_finished())
return FLT_MAX;
return -layers.evaluate(next_game);
});
auto it = std::max_element(action_values.begin(), action_values.end());
std::size_t index = it - action_values.begin();
g.apply(actions[index]);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a set of path-sensitive checks for idempotent and/or
// tautological operations. Each potential operation is checked along all paths
// to see if every path results in a pointless operation.
// +-------------------------------------------+
// |Table of idempotent/tautological operations|
// +-------------------------------------------+
//+--------------------------------------------------------------------------+
//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
//+--------------------------------------------------------------------------+
// +, += | | | | x | x | |
// -, -= | | | | x | -x | |
// *, *= | | x | x | 0 | 0 | |
// /, /= | 1 | x | | N/A | 0 | |
// &, &= | x | | | 0 | 0 | x | x
// |, |= | x | | | x | x | ~0 | ~0
// ^, ^= | 0 | | | x | x | |
// <<, <<= | | | | x | 0 | |
// >>, >>= | | | | x | 0 | |
// || | 1 | 1 | 1 | x | x | 1 | 1
// && | 1 | x | x | 0 | 0 | x | x
// = | x | | | | | |
// == | 1 | | | | | |
// >= | 1 | | | | | |
// <= | 1 | | | | | |
// > | 0 | | | | | |
// < | 0 | | | | | |
// != | 0 | | | | | |
//===----------------------------------------------------------------------===//
//
// Ways to reduce false positives (that need to be implemented):
// - Don't flag downsizing casts
// - Improved handling of static/global variables
// - Per-block marking of incomplete analysis
// - Handling ~0 values
// - False positives involving silencing unused variable warnings
//
// Other things TODO:
// - Improved error messages
// - Handle mixed assumptions (which assumptions can belong together?)
// - Finer grained false positive control (levels)
#include "GRExprEngineInternalChecks.h"
#include "clang/Checker/BugReporter/BugType.h"
#include "clang/Checker/PathSensitive/CheckerHelpers.h"
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/SVals.h"
#include "clang/AST/Stmt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
namespace {
class IdempotentOperationChecker
: public CheckerVisitor<IdempotentOperationChecker> {
public:
static void *getTag();
void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B,
bool hasWorkRemaining);
private:
// Our assumption about a particular operation.
enum Assumption { Possible, Impossible, Equal, LHSis1, RHSis1, LHSis0,
RHSis0 };
void UpdateAssumption(Assumption &A, const Assumption &New);
/// contains* - Useful recursive methods to see if a statement contains an
/// element somewhere. Used in static analysis to reduce false positives.
static bool isParameterSelfAssign(const Expr *LHS, const Expr *RHS);
static bool isTruncationExtensionAssignment(const Expr *LHS,
const Expr *RHS);
static bool containsZeroConstant(const Stmt *S);
static bool containsOneConstant(const Stmt *S);
// Hash table
typedef llvm::DenseMap<const BinaryOperator *, Assumption> AssumptionMap;
AssumptionMap hash;
};
}
void *IdempotentOperationChecker::getTag() {
static int x = 0;
return &x;
}
void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
Eng.registerCheck(new IdempotentOperationChecker());
}
void IdempotentOperationChecker::PreVisitBinaryOperator(
CheckerContext &C,
const BinaryOperator *B) {
// Find or create an entry in the hash for this BinaryOperator instance
AssumptionMap::iterator i = hash.find(B);
Assumption &A = i == hash.end() ? hash[B] : i->second;
// If we had to create an entry, initialise the value to Possible
if (i == hash.end())
A = Possible;
// If we already have visited this node on a path that does not contain an
// idempotent operation, return immediately.
if (A == Impossible)
return;
// Skip binary operators containing common false positives
if (containsMacro(B) || containsEnum(B) || containsStmt<SizeOfAlignOfExpr>(B)
|| containsZeroConstant(B) || containsOneConstant(B)
|| containsBuiltinOffsetOf(B) || containsStaticLocal(B)) {
A = Impossible;
return;
}
const Expr *LHS = B->getLHS();
const Expr *RHS = B->getRHS();
const GRState *state = C.getState();
SVal LHSVal = state->getSVal(LHS);
SVal RHSVal = state->getSVal(RHS);
// If either value is unknown, we can't be 100% sure of all paths.
if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
A = Impossible;
return;
}
BinaryOperator::Opcode Op = B->getOpcode();
// Dereference the LHS SVal if this is an assign operation
switch (Op) {
default:
break;
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Assign:
// Assign statements have one extra level of indirection
if (!isa<Loc>(LHSVal)) {
A = Impossible;
return;
}
LHSVal = state->getSVal(cast<Loc>(LHSVal));
}
// We now check for various cases which result in an idempotent operation.
// x op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::Assign:
// x Assign x has a few more false positives we can check for
if (isParameterSelfAssign(RHS, LHS)
|| isTruncationExtensionAssignment(RHS, LHS)) {
A = Impossible;
return;
}
case BinaryOperator::SubAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Sub:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (LHSVal != RHSVal)
break;
UpdateAssumption(A, Equal);
return;
}
// x op 1
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(1))
break;
UpdateAssumption(A, RHSis1);
return;
}
// 1 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::Mul:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(1))
break;
UpdateAssumption(A, LHSis1);
return;
}
// x op 0
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(0))
break;
UpdateAssumption(A, RHSis0);
return;
}
// 0 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
//case BinaryOperator::AddAssign: // Common false positive
case BinaryOperator::SubAssign: // Check only if unsigned
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
//case BinaryOperator::OrAssign: // Common false positive
//case BinaryOperator::XorAssign: // Common false positive
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(0))
break;
UpdateAssumption(A, LHSis0);
return;
}
// If we get to this point, there has been a valid use of this operation.
A = Impossible;
}
void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
BugReporter &BR,
bool hasWorkRemaining) {
// If there is any work remaining we cannot be 100% sure about our warnings
if (hasWorkRemaining)
return;
// Iterate over the hash to see if we have any paths with definite
// idempotent operations.
for (AssumptionMap::const_iterator i =
hash.begin(); i != hash.end(); ++i) {
if (i->second != Impossible) {
// Select the error message.
const BinaryOperator *B = i->first;
llvm::SmallString<128> buf;
llvm::raw_svector_ostream os(buf);
switch (i->second) {
case Equal:
if (B->getOpcode() == BinaryOperator::Assign)
os << "Assigned value is always the same as the existing value";
else
os << "Both operands to '" << B->getOpcodeStr()
<< "' always have the same value";
break;
case LHSis1:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case RHSis1:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case LHSis0:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case RHSis0:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case Possible:
llvm_unreachable("Operation was never marked with an assumption");
case Impossible:
llvm_unreachable(0);
}
// Create the SourceRange Arrays
SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
i->first->getRHS()->getSourceRange() };
BR.EmitBasicReport("Idempotent operation", "Dead code",
os.str(), i->first->getOperatorLoc(), S, 2);
}
}
}
// Updates the current assumption given the new assumption
inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
const Assumption &New) {
switch (A) {
// If we don't currently have an assumption, set it
case Possible:
A = New;
return;
// If we have determined that a valid state happened, ignore the new
// assumption.
case Impossible:
return;
// Any other case means that we had a different assumption last time. We don't
// currently support mixing assumptions for diagnostic reasons, so we set
// our assumption to be impossible.
default:
A = Impossible;
return;
}
}
// Check for a statement were a parameter is self assigned (to avoid an unused
// variable warning)
bool IdempotentOperationChecker::isParameterSelfAssign(const Expr *LHS,
const Expr *RHS) {
LHS = LHS->IgnoreParenCasts();
RHS = RHS->IgnoreParenCasts();
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
if (!LHS_DR)
return false;
const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(LHS_DR->getDecl());
if (!PD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
if (!RHS_DR)
return false;
return PD == RHS_DR->getDecl();
}
// Check for self casts truncating/extending a variable
bool IdempotentOperationChecker::isTruncationExtensionAssignment(
const Expr *LHS,
const Expr *RHS) {
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
if (!LHS_DR)
return false;
const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
if (!VD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
if (!RHS_DR)
return false;
if (VD != RHS_DR->getDecl())
return false;
return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
}
// Check for a integer or float constant of 0
bool IdempotentOperationChecker::containsZeroConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 0)
return true;
const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S);
if (FL && FL->getValue().isZero())
return true;
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsZeroConstant(child))
return true;
return false;
}
// Check for an integer or float constant of 1
bool IdempotentOperationChecker::containsOneConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 1)
return true;
if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S)) {
const llvm::APFloat &val = FL->getValue();
const llvm::APFloat one(val.getSemantics(), 1);
if (val.compare(one) == llvm::APFloat::cmpEqual)
return true;
}
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsOneConstant(child))
return true;
return false;
}
<commit_msg>'Assumption &A' gets default initialized to 'Possible' if it doesn't exist; no need to two lookups in the hashtable.<commit_after>//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a set of path-sensitive checks for idempotent and/or
// tautological operations. Each potential operation is checked along all paths
// to see if every path results in a pointless operation.
// +-------------------------------------------+
// |Table of idempotent/tautological operations|
// +-------------------------------------------+
//+--------------------------------------------------------------------------+
//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
//+--------------------------------------------------------------------------+
// +, += | | | | x | x | |
// -, -= | | | | x | -x | |
// *, *= | | x | x | 0 | 0 | |
// /, /= | 1 | x | | N/A | 0 | |
// &, &= | x | | | 0 | 0 | x | x
// |, |= | x | | | x | x | ~0 | ~0
// ^, ^= | 0 | | | x | x | |
// <<, <<= | | | | x | 0 | |
// >>, >>= | | | | x | 0 | |
// || | 1 | 1 | 1 | x | x | 1 | 1
// && | 1 | x | x | 0 | 0 | x | x
// = | x | | | | | |
// == | 1 | | | | | |
// >= | 1 | | | | | |
// <= | 1 | | | | | |
// > | 0 | | | | | |
// < | 0 | | | | | |
// != | 0 | | | | | |
//===----------------------------------------------------------------------===//
//
// Ways to reduce false positives (that need to be implemented):
// - Don't flag downsizing casts
// - Improved handling of static/global variables
// - Per-block marking of incomplete analysis
// - Handling ~0 values
// - False positives involving silencing unused variable warnings
//
// Other things TODO:
// - Improved error messages
// - Handle mixed assumptions (which assumptions can belong together?)
// - Finer grained false positive control (levels)
#include "GRExprEngineInternalChecks.h"
#include "clang/Checker/BugReporter/BugType.h"
#include "clang/Checker/PathSensitive/CheckerHelpers.h"
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/SVals.h"
#include "clang/AST/Stmt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
namespace {
class IdempotentOperationChecker
: public CheckerVisitor<IdempotentOperationChecker> {
public:
static void *getTag();
void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B,
bool hasWorkRemaining);
private:
// Our assumption about a particular operation.
enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
RHSis0 };
void UpdateAssumption(Assumption &A, const Assumption &New);
/// contains* - Useful recursive methods to see if a statement contains an
/// element somewhere. Used in static analysis to reduce false positives.
static bool isParameterSelfAssign(const Expr *LHS, const Expr *RHS);
static bool isTruncationExtensionAssignment(const Expr *LHS,
const Expr *RHS);
static bool containsZeroConstant(const Stmt *S);
static bool containsOneConstant(const Stmt *S);
// Hash table
typedef llvm::DenseMap<const BinaryOperator *, Assumption> AssumptionMap;
AssumptionMap hash;
};
}
void *IdempotentOperationChecker::getTag() {
static int x = 0;
return &x;
}
void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
Eng.registerCheck(new IdempotentOperationChecker());
}
void IdempotentOperationChecker::PreVisitBinaryOperator(
CheckerContext &C,
const BinaryOperator *B) {
// Find or create an entry in the hash for this BinaryOperator instance.
// If we haven't done a lookup before, it will get default initialized to
// 'Possible'.
Assumption &A = hash[B];
// If we already have visited this node on a path that does not contain an
// idempotent operation, return immediately.
if (A == Impossible)
return;
// Skip binary operators containing common false positives
if (containsMacro(B) || containsEnum(B) || containsStmt<SizeOfAlignOfExpr>(B)
|| containsZeroConstant(B) || containsOneConstant(B)
|| containsBuiltinOffsetOf(B) || containsStaticLocal(B)) {
A = Impossible;
return;
}
const Expr *LHS = B->getLHS();
const Expr *RHS = B->getRHS();
const GRState *state = C.getState();
SVal LHSVal = state->getSVal(LHS);
SVal RHSVal = state->getSVal(RHS);
// If either value is unknown, we can't be 100% sure of all paths.
if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
A = Impossible;
return;
}
BinaryOperator::Opcode Op = B->getOpcode();
// Dereference the LHS SVal if this is an assign operation
switch (Op) {
default:
break;
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Assign:
// Assign statements have one extra level of indirection
if (!isa<Loc>(LHSVal)) {
A = Impossible;
return;
}
LHSVal = state->getSVal(cast<Loc>(LHSVal));
}
// We now check for various cases which result in an idempotent operation.
// x op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::Assign:
// x Assign x has a few more false positives we can check for
if (isParameterSelfAssign(RHS, LHS)
|| isTruncationExtensionAssignment(RHS, LHS)) {
A = Impossible;
return;
}
case BinaryOperator::SubAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Sub:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (LHSVal != RHSVal)
break;
UpdateAssumption(A, Equal);
return;
}
// x op 1
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(1))
break;
UpdateAssumption(A, RHSis1);
return;
}
// 1 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::MulAssign:
case BinaryOperator::Mul:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(1))
break;
UpdateAssumption(A, LHSis1);
return;
}
// x op 0
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
case BinaryOperator::AddAssign:
case BinaryOperator::SubAssign:
case BinaryOperator::MulAssign:
case BinaryOperator::AndAssign:
case BinaryOperator::OrAssign:
case BinaryOperator::XorAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!RHSVal.isConstant(0))
break;
UpdateAssumption(A, RHSis0);
return;
}
// 0 op x
switch (Op) {
default:
break; // We don't care about any other operators.
// Fall through intentional
//case BinaryOperator::AddAssign: // Common false positive
case BinaryOperator::SubAssign: // Check only if unsigned
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign:
case BinaryOperator::AndAssign:
//case BinaryOperator::OrAssign: // Common false positive
//case BinaryOperator::XorAssign: // Common false positive
case BinaryOperator::ShlAssign:
case BinaryOperator::ShrAssign:
case BinaryOperator::Add:
case BinaryOperator::Sub:
case BinaryOperator::Mul:
case BinaryOperator::Div:
case BinaryOperator::And:
case BinaryOperator::Or:
case BinaryOperator::Xor:
case BinaryOperator::Shl:
case BinaryOperator::Shr:
case BinaryOperator::LOr:
case BinaryOperator::LAnd:
if (!LHSVal.isConstant(0))
break;
UpdateAssumption(A, LHSis0);
return;
}
// If we get to this point, there has been a valid use of this operation.
A = Impossible;
}
void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
BugReporter &BR,
bool hasWorkRemaining) {
// If there is any work remaining we cannot be 100% sure about our warnings
if (hasWorkRemaining)
return;
// Iterate over the hash to see if we have any paths with definite
// idempotent operations.
for (AssumptionMap::const_iterator i =
hash.begin(); i != hash.end(); ++i) {
if (i->second != Impossible) {
// Select the error message.
const BinaryOperator *B = i->first;
llvm::SmallString<128> buf;
llvm::raw_svector_ostream os(buf);
switch (i->second) {
case Equal:
if (B->getOpcode() == BinaryOperator::Assign)
os << "Assigned value is always the same as the existing value";
else
os << "Both operands to '" << B->getOpcodeStr()
<< "' always have the same value";
break;
case LHSis1:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case RHSis1:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
break;
case LHSis0:
os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case RHSis0:
os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
break;
case Possible:
llvm_unreachable("Operation was never marked with an assumption");
case Impossible:
llvm_unreachable(0);
}
// Create the SourceRange Arrays
SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
i->first->getRHS()->getSourceRange() };
BR.EmitBasicReport("Idempotent operation", "Dead code",
os.str(), i->first->getOperatorLoc(), S, 2);
}
}
}
// Updates the current assumption given the new assumption
inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
const Assumption &New) {
switch (A) {
// If we don't currently have an assumption, set it
case Possible:
A = New;
return;
// If we have determined that a valid state happened, ignore the new
// assumption.
case Impossible:
return;
// Any other case means that we had a different assumption last time. We don't
// currently support mixing assumptions for diagnostic reasons, so we set
// our assumption to be impossible.
default:
A = Impossible;
return;
}
}
// Check for a statement were a parameter is self assigned (to avoid an unused
// variable warning)
bool IdempotentOperationChecker::isParameterSelfAssign(const Expr *LHS,
const Expr *RHS) {
LHS = LHS->IgnoreParenCasts();
RHS = RHS->IgnoreParenCasts();
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
if (!LHS_DR)
return false;
const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(LHS_DR->getDecl());
if (!PD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
if (!RHS_DR)
return false;
return PD == RHS_DR->getDecl();
}
// Check for self casts truncating/extending a variable
bool IdempotentOperationChecker::isTruncationExtensionAssignment(
const Expr *LHS,
const Expr *RHS) {
const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
if (!LHS_DR)
return false;
const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
if (!VD)
return false;
const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
if (!RHS_DR)
return false;
if (VD != RHS_DR->getDecl())
return false;
return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
}
// Check for a integer or float constant of 0
bool IdempotentOperationChecker::containsZeroConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 0)
return true;
const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S);
if (FL && FL->getValue().isZero())
return true;
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsZeroConstant(child))
return true;
return false;
}
// Check for an integer or float constant of 1
bool IdempotentOperationChecker::containsOneConstant(const Stmt *S) {
const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
if (IL && IL->getValue() == 1)
return true;
if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S)) {
const llvm::APFloat &val = FL->getValue();
const llvm::APFloat one(val.getSemantics(), 1);
if (val.compare(one) == llvm::APFloat::cmpEqual)
return true;
}
for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
++I)
if (const Stmt *child = *I)
if (containsOneConstant(child))
return true;
return false;
}
<|endoftext|> |
<commit_before>// Time: O(logn), n is the value of the integer
// Space: O(1)
class Solution {
public:
string numberToWords(int num) {
if (num == 0) {
return "Zero";
}
const unordered_map<int, string> lookup = {{0, "Zero"}, {1, "One"}, {2, "Two"},
{3, "Three"}, {4, "Four"}, {5, "Five"},
{6, "Six"}, {7, "Seven"}, {8, "Eight"},
{9, "Nine"}, {10, "Ten"}, {11, "Eleven"},
{12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"},
{15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"},
{18, "Eighteen"}, {19, "Nineteen"}, {20, "Twenty"},
{30, "Thirty"}, {40, "Forty"}, {50, "Fifty"},
{60, "Sixty"}, {70, "Seventy"}, {80, "Eighty"},
{90, "Ninety"}};
const vector<string> unit{"", "Thousand", "Million", "Billion"};
vector<string> res;
int i = 0;
while (num) {
const int cur = num % 1000;
if (num % 1000) {
res.emplace_back(threeDigits(cur, lookup, unit[i]));
}
num /= 1000;
++i;
}
reverse(res.begin(), res.end());
return join(res, " ");
}
string join(const vector<string>& strings, const string& delim) {
if (strings.empty()) {
return "";
}
ostringstream imploded;
copy(strings.begin(), prev(strings.end()), ostream_iterator<string>(imploded, delim.c_str()));
return imploded.str() + *prev(strings.end());
}
string threeDigits(const int& num, const unordered_map<int, string>& lookup, const string& unit) {
vector<string> res;
if (num / 100) {
res.emplace_back(lookup.find(num / 100)->second + " " + "Hundred");
}
if (num % 100) {
res.emplace_back(twoDigits(num % 100, lookup));
}
if (!unit.empty()) {
res.emplace_back(unit);
}
return join(res, " ");
}
string twoDigits(const int& num, const unordered_map<int, string>& lookup) {
if (lookup.find(num) != lookup.end()) {
return lookup.find(num)->second;
}
return lookup.find((num / 10) * 10)->second + " " + lookup.find(num % 10)->second;
}
};
<commit_msg>Update integer-to-english-words.cpp<commit_after>// Time: O(logn) = O(1), n is the value of the integer, which is less than 2^31 - 1
// Space: O(1)
class Solution {
public:
string numberToWords(int num) {
if (num == 0) {
return "Zero";
}
const unordered_map<int, string> lookup = {{0, "Zero"}, {1, "One"}, {2, "Two"},
{3, "Three"}, {4, "Four"}, {5, "Five"},
{6, "Six"}, {7, "Seven"}, {8, "Eight"},
{9, "Nine"}, {10, "Ten"}, {11, "Eleven"},
{12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"},
{15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"},
{18, "Eighteen"}, {19, "Nineteen"}, {20, "Twenty"},
{30, "Thirty"}, {40, "Forty"}, {50, "Fifty"},
{60, "Sixty"}, {70, "Seventy"}, {80, "Eighty"},
{90, "Ninety"}};
const vector<string> unit{"", "Thousand", "Million", "Billion"};
vector<string> res;
int i = 0;
while (num) {
const int cur = num % 1000;
if (num % 1000) {
res.emplace_back(threeDigits(cur, lookup, unit[i]));
}
num /= 1000;
++i;
}
reverse(res.begin(), res.end());
return join(res, " ");
}
string join(const vector<string>& strings, const string& delim) {
if (strings.empty()) {
return "";
}
ostringstream imploded;
copy(strings.begin(), prev(strings.end()), ostream_iterator<string>(imploded, delim.c_str()));
return imploded.str() + *prev(strings.end());
}
string threeDigits(const int& num, const unordered_map<int, string>& lookup, const string& unit) {
vector<string> res;
if (num / 100) {
res.emplace_back(lookup.find(num / 100)->second + " " + "Hundred");
}
if (num % 100) {
res.emplace_back(twoDigits(num % 100, lookup));
}
if (!unit.empty()) {
res.emplace_back(unit);
}
return join(res, " ");
}
string twoDigits(const int& num, const unordered_map<int, string>& lookup) {
if (lookup.find(num) != lookup.end()) {
return lookup.find(num)->second;
}
return lookup.find((num / 10) * 10)->second + " " + lookup.find(num % 10)->second;
}
};
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file generate_d_operator_matrix.hpp
*
* \brief Contains implementation of sirius::Potential::generate_D_operator_matrix method.
*/
#ifdef __GPU
extern "C" void mul_veff_with_phase_factors_gpu(int num_atoms__,
int num_gvec_loc__,
double_complex const* veff__,
int const* gvec__,
double const* atom_pos__,
double* veff_a__,
int stream_id__);
#endif
inline void Potential::generate_D_operator_matrix()
{
PROFILE("sirius::Potential::generate_D_operator_matrix");
/* store effective potential and magnetic field in a vector */
std::vector<Periodic_function<double>*> veff_vec(ctx_.num_mag_dims() + 1);
veff_vec[0] = effective_potential_.get();
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
veff_vec[1 + j] = effective_magnetic_field_[j];
}
#ifdef __GPU
mdarray<double_complex, 1> veff_tmp(nullptr, ctx_.gvec().count());
if (ctx_.processing_unit() == GPU) {
veff_tmp.allocate(memory_t::device);
}
#endif
ctx_.augmentation_op(0).prepare(0);
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
auto& atom_type = unit_cell_.atom_type(iat);
int nbf = atom_type.mt_basis_size();
/* start copy of Q(G) for the next atom type */
#ifdef __GPU
if (ctx_.processing_unit() == GPU) {
acc::sync_stream(0);
if (iat + 1 != unit_cell_.num_atom_types()) {
ctx_.augmentation_op(iat + 1).prepare(0);
}
}
#endif
/* trivial case */
if (!atom_type.pp_desc().augment) {
for (int iv = 0; iv < ctx_.num_mag_dims() + 1; iv++) {
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
auto& atom = unit_cell_.atom(ia);
for (int xi2 = 0; xi2 < nbf; xi2++) {
for (int xi1 = 0; xi1 < nbf; xi1++) {
atom.d_mtrx(xi1, xi2, iv) = 0;
}
}
}
}
continue;
}
matrix<double> d_tmp(nbf * (nbf + 1) / 2, atom_type.num_atoms());
for (int iv = 0; iv < ctx_.num_mag_dims() + 1; iv++) {
switch (ctx_.processing_unit()) {
case CPU: {
matrix<double> veff_a(2 * ctx_.gvec().count(), atom_type.num_atoms());
#pragma omp parallel for schedule(static)
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
for (int igloc = 0; igloc < ctx_.gvec().count(); igloc++) {
int ig = ctx_.gvec().offset() + igloc;
/* V(G) * exp(i * G * r_{alpha}) */
auto z = veff_vec[iv]->f_pw_local(igloc) * ctx_.gvec_phase_factor(ig, ia);
veff_a(2 * igloc, i) = z.real();
veff_a(2 * igloc + 1, i) = z.imag();
}
}
linalg<CPU>::gemm(0, 0, nbf * (nbf + 1) / 2, atom_type.num_atoms(), 2 * ctx_.gvec().count(),
ctx_.augmentation_op(iat).q_pw(), veff_a, d_tmp);
break;
}
case GPU: {
#ifdef __GPU
/* copy plane wave coefficients of effective potential to GPU */
mdarray<double_complex, 1> veff(&veff_vec[iv]->f_pw_local(0), veff_tmp.at<GPU>(),
ctx_.gvec().count());
veff.copy<memory_t::host, memory_t::device>();
matrix<double> veff_a(2 * ctx_.gvec().count(), atom_type.num_atoms(), memory_t::device);
d_tmp.allocate(memory_t::device);
mul_veff_with_phase_factors_gpu(atom_type.num_atoms(),
ctx_.gvec().count(),
veff.at<GPU>(),
ctx_.gvec_coord().at<GPU>(),
ctx_.atom_coord(iat).at<GPU>(),
veff_a.at<GPU>(), 1);
linalg<GPU>::gemm(0, 0, nbf * (nbf + 1) / 2, atom_type.num_atoms(), 2 * ctx_.gvec().count(),
ctx_.augmentation_op(iat).q_pw(), veff_a, d_tmp, 1);
d_tmp.copy<memory_t::device, memory_t::host>();
#endif
break;
}
}
if (ctx_.gvec().reduced()) {
if (comm_.rank() == 0) {
for (int i = 0; i < atom_type.num_atoms(); i++) {
for (int j = 0; j < nbf * (nbf + 1) / 2; j++) {
d_tmp(j, i) = 2 * d_tmp(j, i) - veff_vec[iv]->f_pw_local(0).real() * ctx_.augmentation_op(iat).q_pw(j, 0);
}
}
} else {
for (int i = 0; i < atom_type.num_atoms(); i++) {
for (int j = 0; j < nbf * (nbf + 1) / 2; j++) {
d_tmp(j, i) *= 2;
}
}
}
}
comm_.allreduce(d_tmp.at<CPU>(), static_cast<int>(d_tmp.size()));
if (ctx_.control().print_checksum_) {
auto cs = d_tmp.checksum();
DUMP("checksum(d_mtrx): %18.10f", cs);
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
auto& atom = unit_cell_.atom(ia);
for (int xi2 = 0; xi2 < nbf; xi2++) {
for (int xi1 = 0; xi1 <= xi2; xi1++) {
int idx12 = xi2 * (xi2 + 1) / 2 + xi1;
/* D-matix is symmetric */
atom.d_mtrx(xi1, xi2, iv) = atom.d_mtrx(xi2, xi1, iv) = d_tmp(idx12, i) * unit_cell_.omega();
}
}
}
}
ctx_.augmentation_op(iat).dismiss();
if (atom_type.pp_desc().SpinOrbit_Coupling) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
auto& atom = unit_cell_.atom(ia);
for (int xi2 = 0; xi2 < nbf; xi2++) {
for (int xi1 = 0; xi1 <= xi2; xi1++) {
// first compute \f[A^_\alpha I^{I,\alpha}_{xi,xi}\f]
// cf Eq.19 PRB 71 115106
// note that the I integrals are already calculated and
// stored in atom.d_mtrx
for (int sigma = 0; sigma < 2; sigma++) {
for (int sigmap = 0; sigmap < 2; sigmap++) {
const double_complex Pauli_vector[4][2][2] = {
{{{1.0,0.0}, {0.0,0.0}},
{{0.0, 0.0}, {1.0, 0.0}}}, // Id
{{{1.0, 0.0}, {0.0, 0.0}},
{{0.0, 0.0}, {0.0,-1.0}}}, // sigma_z
{{{0.0, 0.0},{0.0,1.0}},
{{1.0, 0.0},{0.0,0.0}}}, // sigma_x
{{{0.0, 0.0},{0.0,-1.0}},
{{0.0,1.0}, {0.0,0.0}}} // sigma_y
};
double_complex result = {0.0, 0.0};
for (auto xi2p = 0; xi2p < nbf; xi2p++) {
if (atom_type.compare_index_beta_functions(xi2, xi2p)) {
for (auto xi1p = 0; xi1p < nbf; xi1p++) {
if (atom_type.compare_index_beta_functions(xi1, xi1p)) {
for (int alpha = 0; alpha < 4; alpha++) { // loop over the 0, z,x,y coordinates
for (int sigma1 = 0; sigma1 < 2; sigma1++) {
for (int sigma2 = 0; sigma2 < 2; sigma2++) {
result +=
atom.d_mtrx(xi1p, xi2p, alpha) *
Pauli_vector[alpha][sigma1][sigma2] *
atom.type().f_coefficients(xi1, xi1p, sigma, sigma1) *
atom.type().f_coefficients(xi2, xi2p, sigma2, sigmap);
}
}
}
}
}
}
atom.d_mtrx_so(xi2, xi1, 2 * sigma + sigmap) = result;
}
}
}
}
}
// then add the bare D
for (int xi2 = 0; xi2 < nbf; xi2++) {
int lm2 = atom.type().indexb(xi2).lm;
int idxrf2 = atom.type().indexb(xi2).idxrf;
int l2 = atom.type().indexb(xi2).l;
double j2 = atom.type().indexb(xi2).j;
int m2 = atom.type().indexb(xi2).m;
for (int xi1 = 0; xi1 < nbf; xi1++) {
int lm1 = atom.type().indexb(xi1).lm;
int l1 = atom.type().indexb(xi1).l;
int idxrf1 = atom.type().indexb(xi1).idxrf;
double j1 = atom.type().indexb(xi1).j;
int m1 = atom.type().indexb(xi1).m;
if ((l1 == l2) && (fabs(j1 - j2) < 1e-8)) {
atom.d_mtrx_so(xi1, xi2, 0) += atom.type().pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom.type().f_coefficients(xi2, xi1, 0, 0);
atom.d_mtrx_so(xi1, xi2, 1) += atom.type().pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom.type().f_coefficients(xi2, xi1, 0, 1);
atom.d_mtrx_so(xi1, xi2, 2) += atom.type().pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom.type().f_coefficients(xi2, xi1, 1, 0);
atom.d_mtrx_so(xi1, xi2, 3) += atom.type().pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom.type().f_coefficients(xi2, xi1, 1, 1);
}
}
}
}
// need to clear d_mtrx_so
} else {
/* add d_ion to the effective potential component of D-operator */
#pragma omp parallel for schedule(static)
for (int ia = 0; ia < unit_cell_.num_atoms(); ia++) {
auto& atom_type = unit_cell_.atom(ia).type();
int nbf = unit_cell_.atom(ia).mt_basis_size();
for (int xi2 = 0; xi2 < nbf; xi2++) {
int lm2 = atom_type.indexb(xi2).lm;
int idxrf2 = atom_type.indexb(xi2).idxrf;
for (int xi1 = 0; xi1 < nbf; xi1++) {
int lm1 = atom_type.indexb(xi1).lm;
int idxrf1 = atom_type.indexb(xi1).idxrf;
if (lm1 == lm2) {
unit_cell_.atom(ia).d_mtrx(xi1, xi2, 0) += atom_type.pp_desc().d_mtrx_ion(idxrf1, idxrf2);
}
}
}
}
}
}
}
<commit_msg>Corrected a bug in the calculation of so interactions<commit_after>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file generate_d_operator_matrix.hpp
*
* \brief Contains implementation of sirius::Potential::generate_D_operator_matrix method.
*/
#ifdef __GPU
extern "C" void mul_veff_with_phase_factors_gpu(int num_atoms__,
int num_gvec_loc__,
double_complex const* veff__,
int const* gvec__,
double const* atom_pos__,
double* veff_a__,
int stream_id__);
#endif
inline void Potential::generate_D_operator_matrix()
{
PROFILE("sirius::Potential::generate_D_operator_matrix");
/* store effective potential and magnetic field in a vector */
std::vector<Periodic_function<double>*> veff_vec(ctx_.num_mag_dims() + 1);
veff_vec[0] = effective_potential_.get();
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
veff_vec[1 + j] = effective_magnetic_field_[j];
}
#ifdef __GPU
mdarray<double_complex, 1> veff_tmp(nullptr, ctx_.gvec().count());
if (ctx_.processing_unit() == GPU) {
veff_tmp.allocate(memory_t::device);
}
#endif
ctx_.augmentation_op(0).prepare(0);
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
auto& atom_type = unit_cell_.atom_type(iat);
int nbf = atom_type.mt_basis_size();
/* start copy of Q(G) for the next atom type */
#ifdef __GPU
if (ctx_.processing_unit() == GPU) {
acc::sync_stream(0);
if (iat + 1 != unit_cell_.num_atom_types()) {
ctx_.augmentation_op(iat + 1).prepare(0);
}
}
#endif
/* trivial case */
if (!atom_type.pp_desc().augment) {
for (int iv = 0; iv < ctx_.num_mag_dims() + 1; iv++) {
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
auto& atom = unit_cell_.atom(ia);
for (int xi2 = 0; xi2 < nbf; xi2++) {
for (int xi1 = 0; xi1 < nbf; xi1++) {
atom.d_mtrx(xi1, xi2, iv) = 0;
}
}
}
}
continue;
}
matrix<double> d_tmp(nbf * (nbf + 1) / 2, atom_type.num_atoms());
for (int iv = 0; iv < ctx_.num_mag_dims() + 1; iv++) {
switch (ctx_.processing_unit()) {
case CPU: {
matrix<double> veff_a(2 * ctx_.gvec().count(), atom_type.num_atoms());
#pragma omp parallel for schedule(static)
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
for (int igloc = 0; igloc < ctx_.gvec().count(); igloc++) {
int ig = ctx_.gvec().offset() + igloc;
/* V(G) * exp(i * G * r_{alpha}) */
auto z = veff_vec[iv]->f_pw_local(igloc) * ctx_.gvec_phase_factor(ig, ia);
veff_a(2 * igloc, i) = z.real();
veff_a(2 * igloc + 1, i) = z.imag();
}
}
linalg<CPU>::gemm(0, 0, nbf * (nbf + 1) / 2, atom_type.num_atoms(), 2 * ctx_.gvec().count(),
ctx_.augmentation_op(iat).q_pw(), veff_a, d_tmp);
break;
}
case GPU: {
#ifdef __GPU
/* copy plane wave coefficients of effective potential to GPU */
mdarray<double_complex, 1> veff(&veff_vec[iv]->f_pw_local(0), veff_tmp.at<GPU>(),
ctx_.gvec().count());
veff.copy<memory_t::host, memory_t::device>();
matrix<double> veff_a(2 * ctx_.gvec().count(), atom_type.num_atoms(), memory_t::device);
d_tmp.allocate(memory_t::device);
mul_veff_with_phase_factors_gpu(atom_type.num_atoms(),
ctx_.gvec().count(),
veff.at<GPU>(),
ctx_.gvec_coord().at<GPU>(),
ctx_.atom_coord(iat).at<GPU>(),
veff_a.at<GPU>(), 1);
linalg<GPU>::gemm(0, 0, nbf * (nbf + 1) / 2, atom_type.num_atoms(), 2 * ctx_.gvec().count(),
ctx_.augmentation_op(iat).q_pw(), veff_a, d_tmp, 1);
d_tmp.copy<memory_t::device, memory_t::host>();
#endif
break;
}
}
if (ctx_.gvec().reduced()) {
if (comm_.rank() == 0) {
for (int i = 0; i < atom_type.num_atoms(); i++) {
for (int j = 0; j < nbf * (nbf + 1) / 2; j++) {
d_tmp(j, i) = 2 * d_tmp(j, i) - veff_vec[iv]->f_pw_local(0).real() * ctx_.augmentation_op(iat).q_pw(j, 0);
}
}
} else {
for (int i = 0; i < atom_type.num_atoms(); i++) {
for (int j = 0; j < nbf * (nbf + 1) / 2; j++) {
d_tmp(j, i) *= 2;
}
}
}
}
comm_.allreduce(d_tmp.at<CPU>(), static_cast<int>(d_tmp.size()));
if (ctx_.control().print_checksum_) {
auto cs = d_tmp.checksum();
DUMP("checksum(d_mtrx): %18.10f", cs);
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
auto& atom = unit_cell_.atom(ia);
for (int xi2 = 0; xi2 < nbf; xi2++) {
for (int xi1 = 0; xi1 <= xi2; xi1++) {
int idx12 = xi2 * (xi2 + 1) / 2 + xi1;
/* D-matix is symmetric */
atom.d_mtrx(xi1, xi2, iv) = atom.d_mtrx(xi2, xi1, iv) = d_tmp(idx12, i) * unit_cell_.omega();
}
}
}
}
// Now compute the d operator for atoms with so interactions
if (atom_type.pp_desc().SpinOrbit_Coupling) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < atom_type.num_atoms(); i++) {
int ia = atom_type.atom_id(i);
auto& atom = unit_cell_.atom(ia);
for (int xi2 = 0; xi2 < nbf; xi2++) {
for (int xi1 = 0; xi1 <= xi2; xi1++) {
// first compute \f[A^_\alpha I^{I,\alpha}_{xi,xi}\f]
// cf Eq.19 PRB 71 115106
// note that the I integrals are already calculated and
// stored in atom.d_mtrx
for (int sigma = 0; sigma < 2; sigma++) {
for (int sigmap = 0; sigmap < 2; sigmap++) {
const double_complex Pauli_vector[4][2][2] = {
{{{1.0,0.0}, {0.0,0.0}},
{{0.0, 0.0}, {1.0, 0.0}}}, // Id
{{{1.0, 0.0}, {0.0, 0.0}},
{{0.0, 0.0}, {0.0,-1.0}}}, // sigma_z
{{{0.0, 0.0},{0.0,1.0}},
{{1.0, 0.0},{0.0,0.0}}}, // sigma_x
{{{0.0, 0.0},{0.0,-1.0}},
{{0.0,1.0}, {0.0,0.0}}} // sigma_y
};
double_complex result = {0.0, 0.0};
for (auto xi2p = 0; xi2p < nbf; xi2p++) {
if (atom_type.compare_index_beta_functions(xi2, xi2p)) {
for (auto xi1p = 0; xi1p < nbf; xi1p++) {
if (atom_type.compare_index_beta_functions(xi1, xi1p)) {
for (int alpha = 0; alpha < 4; alpha++) { // loop over the 0, z,x,y coordinates
for (int sigma1 = 0; sigma1 < 2; sigma1++) {
for (int sigma2 = 0; sigma2 < 2; sigma2++) {
result +=
atom.d_mtrx(xi1p, xi2p, alpha) *
Pauli_vector[alpha][sigma1][sigma2] *
atom.type().f_coefficients(xi1, xi1p, sigma, sigma1) *
atom.type().f_coefficients(xi2, xi2p, sigma2, sigmap);
}
}
}
}
}
}
atom.d_mtrx_so(xi2, xi1, 2 * sigma + sigmap) = result;
}
}
}
}
}
}
}
ctx_.augmentation_op(iat).dismiss();
// need to clear d_mtrx_so
}
/* add d_ion to the effective potential component of D-operator */
#pragma omp parallel for schedule(static)
for (int ia = 0; ia < unit_cell_.num_atoms(); ia++) {
auto& atom_type = unit_cell_.atom(ia).type();
int nbf = unit_cell_.atom(ia).mt_basis_size();
if (atom_type.pp_desc().SpinOrbit_Coupling) {
// then add the bare D
for (int xi2 = 0; xi2 < nbf; xi2++) {
int lm2 = atom_type.indexb(xi2).lm;
int idxrf2 = atom_type.indexb(xi2).idxrf;
int l2 = atom_type.indexb(xi2).l;
double j2 = atom_type.indexb(xi2).j;
int m2 = atom_type.indexb(xi2).m;
for (int xi1 = 0; xi1 < nbf; xi1++) {
int lm1 = atom_type.indexb(xi1).lm;
int l1 = atom_type.indexb(xi1).l;
int idxrf1 = atom_type.indexb(xi1).idxrf;
double j1 = atom_type.indexb(xi1).j;
int m1 = atom_type.indexb(xi1).m;
if ((l1 == l2) && (fabs(j1 - j2) < 1e-8)) {
unit_cell_.atom(ia).d_mtrx_so(xi1, xi2, 0) += atom_type.pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom_type.f_coefficients(xi2, xi1, 0, 0);
unit_cell_.atom(ia).d_mtrx_so(xi1, xi2, 1) += atom_type.pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom_type.f_coefficients(xi2, xi1, 0, 1);
unit_cell_.atom(ia).d_mtrx_so(xi1, xi2, 2) += atom_type.pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom_type.f_coefficients(xi2, xi1, 1, 0);
unit_cell_.atom(ia).d_mtrx_so(xi1, xi2, 3) += atom_type.pp_desc().d_mtrx_ion(idxrf1, idxrf2) *
atom_type.f_coefficients(xi2, xi1, 1, 1);
}
}
}
} else {
for (int xi2 = 0; xi2 < nbf; xi2++) {
int lm2 = atom_type.indexb(xi2).lm;
int idxrf2 = atom_type.indexb(xi2).idxrf;
for (int xi1 = 0; xi1 < nbf; xi1++) {
int lm1 = atom_type.indexb(xi1).lm;
int idxrf1 = atom_type.indexb(xi1).idxrf;
if (lm1 == lm2) {
unit_cell_.atom(ia).d_mtrx(xi1, xi2, 0) += atom_type.pp_desc().d_mtrx_ion(idxrf1, idxrf2);
}
}
}
}
}
}
<|endoftext|> |
<commit_before>//===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level dead-code-elimination pass.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "codegen-dce"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
STATISTIC(NumDeletes, "Number of dead instructions deleted");
namespace {
class DeadMachineInstructionElim : public MachineFunctionPass {
virtual bool runOnMachineFunction(MachineFunction &MF);
const TargetRegisterInfo *TRI;
const MachineRegisterInfo *MRI;
const TargetInstrInfo *TII;
BitVector LivePhysRegs;
public:
static char ID; // Pass identification, replacement for typeid
DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}
private:
bool isDead(const MachineInstr *MI) const;
};
}
char DeadMachineInstructionElim::ID = 0;
static RegisterPass<DeadMachineInstructionElim>
Y("dead-mi-elimination",
"Remove dead machine instructions");
FunctionPass *llvm::createDeadMachineInstructionElimPass() {
return new DeadMachineInstructionElim();
}
bool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {
// Don't delete instructions with side effects.
bool SawStore = false;
if (!MI->isSafeToMove(TII, SawStore, 0) && !MI->isPHI())
return false;
// Examine each operand.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (TargetRegisterInfo::isPhysicalRegister(Reg) ?
LivePhysRegs[Reg] : !MRI->use_empty(Reg)) {
// This def has a use. Don't delete the instruction!
return false;
}
}
}
// If there are no defs with uses, the instruction is dead.
return true;
}
bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
bool AnyChanges = false;
MRI = &MF.getRegInfo();
TRI = MF.getTarget().getRegisterInfo();
TII = MF.getTarget().getInstrInfo();
// Compute a bitvector to represent all non-allocatable physregs.
BitVector NonAllocatableRegs = TRI->getAllocatableSet(MF);
NonAllocatableRegs.flip();
// Loop over all instructions in all blocks, from bottom to top, so that it's
// more likely that chains of dependent but ultimately dead instructions will
// be cleaned up.
for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
I != E; ++I) {
MachineBasicBlock *MBB = &*I;
// Start out assuming that all non-allocatable registers are live
// out of this block.
LivePhysRegs = NonAllocatableRegs;
// Also add any explicit live-out physregs for this block.
if (!MBB->empty() && MBB->back().getDesc().isReturn())
for (MachineRegisterInfo::liveout_iterator LOI = MRI->liveout_begin(),
LOE = MRI->liveout_end(); LOI != LOE; ++LOI) {
unsigned Reg = *LOI;
if (TargetRegisterInfo::isPhysicalRegister(Reg))
LivePhysRegs.set(Reg);
}
// Now scan the instructions and delete dead ones, tracking physreg
// liveness as we go.
for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),
MIE = MBB->rend(); MII != MIE; ) {
MachineInstr *MI = &*MII;
if (MI->isDebugValue()) {
// Don't delete the DBG_VALUE itself, but if its Value operand is
// a vreg and this is the only use, substitute an undef operand;
// the former operand will then be deleted normally.
if (MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
unsigned Reg = MI->getOperand(0).getReg();
MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg);
assert(I != MRI->use_end());
if (++I == MRI->use_end())
// only one use, which must be this DBG_VALUE.
MI->getOperand(0).setReg(0U);
}
}
// If the instruction is dead, delete it!
if (isDead(MI)) {
DEBUG(dbgs() << "DeadMachineInstructionElim: DELETING: " << *MI);
AnyChanges = true;
MI->eraseFromParent();
++NumDeletes;
MIE = MBB->rend();
// MII is now pointing to the next instruction to process,
// so don't increment it.
continue;
}
// Record the physreg defs.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.reset(Reg);
// Check the subreg set, not the alias set, because a def
// of a super-register may still be partially live after
// this def.
for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
*SubRegs; ++SubRegs)
LivePhysRegs.reset(*SubRegs);
}
}
}
// Record the physreg uses, after the defs, in case a physreg is
// both defined and used in the same instruction.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isUse()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.set(Reg);
for (const unsigned *AliasSet = TRI->getAliasSet(Reg);
*AliasSet; ++AliasSet)
LivePhysRegs.set(*AliasSet);
}
}
}
// We didn't delete the current instruction, so increment MII to
// the next one.
++MII;
}
}
LivePhysRegs.clear();
return AnyChanges;
}
<commit_msg>Allow for more than one DBG_VALUE targeting the same dead instruction.<commit_after>//===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level dead-code-elimination pass.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "codegen-dce"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
STATISTIC(NumDeletes, "Number of dead instructions deleted");
namespace {
class DeadMachineInstructionElim : public MachineFunctionPass {
virtual bool runOnMachineFunction(MachineFunction &MF);
const TargetRegisterInfo *TRI;
const MachineRegisterInfo *MRI;
const TargetInstrInfo *TII;
BitVector LivePhysRegs;
public:
static char ID; // Pass identification, replacement for typeid
DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}
private:
bool isDead(const MachineInstr *MI) const;
};
}
char DeadMachineInstructionElim::ID = 0;
static RegisterPass<DeadMachineInstructionElim>
Y("dead-mi-elimination",
"Remove dead machine instructions");
FunctionPass *llvm::createDeadMachineInstructionElimPass() {
return new DeadMachineInstructionElim();
}
bool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {
// Don't delete instructions with side effects.
bool SawStore = false;
if (!MI->isSafeToMove(TII, SawStore, 0) && !MI->isPHI())
return false;
// Examine each operand.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (TargetRegisterInfo::isPhysicalRegister(Reg) ?
LivePhysRegs[Reg] : !MRI->use_empty(Reg)) {
// This def has a use. Don't delete the instruction!
return false;
}
}
}
// If there are no defs with uses, the instruction is dead.
return true;
}
bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
bool AnyChanges = false;
MRI = &MF.getRegInfo();
TRI = MF.getTarget().getRegisterInfo();
TII = MF.getTarget().getInstrInfo();
// Compute a bitvector to represent all non-allocatable physregs.
BitVector NonAllocatableRegs = TRI->getAllocatableSet(MF);
NonAllocatableRegs.flip();
// Loop over all instructions in all blocks, from bottom to top, so that it's
// more likely that chains of dependent but ultimately dead instructions will
// be cleaned up.
for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
I != E; ++I) {
MachineBasicBlock *MBB = &*I;
// Start out assuming that all non-allocatable registers are live
// out of this block.
LivePhysRegs = NonAllocatableRegs;
// Also add any explicit live-out physregs for this block.
if (!MBB->empty() && MBB->back().getDesc().isReturn())
for (MachineRegisterInfo::liveout_iterator LOI = MRI->liveout_begin(),
LOE = MRI->liveout_end(); LOI != LOE; ++LOI) {
unsigned Reg = *LOI;
if (TargetRegisterInfo::isPhysicalRegister(Reg))
LivePhysRegs.set(Reg);
}
// Now scan the instructions and delete dead ones, tracking physreg
// liveness as we go.
for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),
MIE = MBB->rend(); MII != MIE; ) {
MachineInstr *MI = &*MII;
if (MI->isDebugValue()) {
// Don't delete the DBG_VALUE itself, but if its Value operand is
// a vreg and this is the only use, substitute an undef operand;
// the former operand will then be deleted normally.
if (MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
unsigned Reg = MI->getOperand(0).getReg();
MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
if (I == MRI->use_nodbg_end())
// All uses are DBG_VALUEs. Nullify this one; if we find
// others later we will nullify them then.
MI->getOperand(0).setReg(0U);
}
}
// If the instruction is dead, delete it!
if (isDead(MI)) {
DEBUG(dbgs() << "DeadMachineInstructionElim: DELETING: " << *MI);
AnyChanges = true;
MI->eraseFromParent();
++NumDeletes;
MIE = MBB->rend();
// MII is now pointing to the next instruction to process,
// so don't increment it.
continue;
}
// Record the physreg defs.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.reset(Reg);
// Check the subreg set, not the alias set, because a def
// of a super-register may still be partially live after
// this def.
for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
*SubRegs; ++SubRegs)
LivePhysRegs.reset(*SubRegs);
}
}
}
// Record the physreg uses, after the defs, in case a physreg is
// both defined and used in the same instruction.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isUse()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.set(Reg);
for (const unsigned *AliasSet = TRI->getAliasSet(Reg);
*AliasSet; ++AliasSet)
LivePhysRegs.set(*AliasSet);
}
}
}
// We didn't delete the current instruction, so increment MII to
// the next one.
++MII;
}
}
LivePhysRegs.clear();
return AnyChanges;
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
if (source.empty() || source.length() < target.length()) {
return "";
}
const int ASCII_MAX = 256;
vector<int> expCnt(ASCII_MAX, 0);
vector<int> curCnt(ASCII_MAX, 0);
int cnt = 0;
int start = 0;
int min_width = INT_MAX;
int min_start = 0;
for (const auto& c : T) {
++expCnt[c];
}
for (int i = 0; i < source.length(); ++i) {
if(expCnt[S[i]] > 0) {
++curCnt[S[i]];
if (curCnt[S[i]] <= expCnt[S[i]]) { // Counting expected elements.
++cnt;
}
}
if(cnt == target.size()) { // If window meets the requirement
while (expCnt[S[start]] == 0 || curCnt[S[start]] > expCnt[S[start]]) { // Adjust left bound of window
--curCnt[S[start]];
++start;
}
if(min_width > i - start + 1) { // Update minimum window
min_width = i - start + 1;
min_start = start;
}
}
}
if (min_width == INT_MAX) {
return "";
}
return source.substr(min_start, min_width);
}
};
<commit_msg>Update minimum-window-substring.cpp<commit_after>// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
if (source.empty() || source.length() < target.length()) {
return "";
}
const int ASCII_MAX = 256;
vector<int> expCnt(ASCII_MAX, 0);
vector<int> curCnt(ASCII_MAX, 0);
int cnt = 0;
int start = 0;
int min_width = INT_MAX;
int min_start = 0;
for (const auto& c : T) {
++expCnt[c];
}
for (int i = 0; i < source.length(); ++i) {
if (expCnt[S[i]] > 0) {
++curCnt[S[i]];
if (curCnt[S[i]] <= expCnt[S[i]]) { // Counting expected elements.
++cnt;
}
}
if (cnt == target.size()) { // If window meets the requirement
while (expCnt[S[start]] == 0 || curCnt[S[start]] > expCnt[S[start]]) { // Adjust left bound of window
--curCnt[S[start]];
++start;
}
if (min_width > i - start + 1) { // Update minimum window
min_width = i - start + 1;
min_start = start;
}
}
}
if (min_width == INT_MAX) {
return "";
}
return source.substr(min_start, min_width);
}
};
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of FlashGraph.
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kmeans.h"
using namespace fg;
bool updated = false;
static vsize_t NEV;
static size_t K;
static vsize_t NUM_ROWS;
static struct timeval start, end;
/**
* \brief Print an arry of some length `len`.
* \param len The length of the array.
*/
template <typename T>
static void print_arr(T* arr, vsize_t len) {
printf("[ ");
for (vsize_t i = 0; i < len; i++) {
std::cout << arr[i] << " ";
}
printf("]\n");
}
/*
* \Internal
* \brief Simple helper used to print a vector.
* \param v The vector to print.
*/
template <typename T>
static void print_vector(typename std::vector<T>& v)
{
std::cout << "[";
typename std::vector<T>::iterator itr = v.begin();
for (; itr != v.end(); itr++) {
std::cout << " "<< *itr;
}
std::cout << " ]\n";
}
/**
* \brief Get the squared distance given two values.
* \param arg1 the first value.
* \param arg2 the second value.
* \return the squared distance.
*/
static double dist_sq(double arg1, double arg2)
{
double diff = arg1 - arg2;
return diff*diff;
}
/**
* \brief This initializes clusters by randomly choosing sample
* membership in a cluster.
* See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods
* \param cluster_assignments Which cluster each sample falls into.
*/
static void random_partition_init(vsize_t* cluster_assignments)
{
BOOST_LOG_TRIVIAL(info) << "Random init start";
// #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments)
for (vsize_t vid = 0; vid < NUM_ROWS; vid++) {
size_t assigned_cluster = random() % K; // 0...K
cluster_assignments[vid] = assigned_cluster;
}
// NOTE: M-Step is called in compute func to update cluster counts & centers
#if 0
printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS);
#endif
BOOST_LOG_TRIVIAL(info) << "Random init end\n";
}
/**
* \brief Forgy init takes `K` random samples from the matrix
* and uses them as cluster centers.
* \param matrix the flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
*/
static void forgy_init(const double* matrix, double* clusters) {
BOOST_LOG_TRIVIAL(info) << "Forgy init start";
// #pragma omp parallel for firstprivate(matrix) shared (clusters)
for (vsize_t clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K
vsize_t rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1)
memcpy(&clusters[clust_idx*NEV], &matrix[rand_idx*NEV], sizeof(clusters[0])*NEV);
}
BOOST_LOG_TRIVIAL(info) << "Forgy init end";
}
/**
* \brief A parallel version of the kmeans++ initialization alg.
*/
static void kmeanspp_init()
{
BOOST_LOG_TRIVIAL(fatal) << "kmeanspp not yet implemented";
exit(-1);
}
/*\Internal
* \brief print a col wise matrix of type double / double.
* Used for testing only.
* \param matrix The col wise matrix.
* \param rows The number of rows in the mat
* \param cols The number of cols in the mat
*/
template <typename T>
static void print_mat(T* matrix, const vsize_t rows, const vsize_t cols) {
for (vsize_t row = 0; row < rows; row++) {
std::cout << "[";
for (vsize_t col = 0; col < cols; col++) {
std::cout << " " << matrix[row*cols + col];
}
std::cout << " ]\n";
}
}
/**
* \brief Update the cluster assignments while recomputing distance matrix.
* \param matrix The flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void E_step(const double* matrix, double* clusters, vsize_t* cluster_assignments)
{
#pragma omp parallel for firstprivate(matrix, clusters) shared(cluster_assignments)
for (vsize_t row=0; row < NUM_ROWS; row++) {
size_t asgnd_clust = std::numeric_limits<size_t>::max();
double best = std::numeric_limits<double>::max();
for (size_t clust_idx = 0; clust_idx < K; clust_idx++) {
double sum = 0;
for (vsize_t col = 0; col < NEV; col++) {
sum += dist_sq(matrix[(row*NEV) + col], clusters[clust_idx*NEV + col]);
}
if (sum < best) {
best = sum;
asgnd_clust = clust_idx;
}
}
if (asgnd_clust != cluster_assignments[row]) {
if (!updated) updated = true;
}
cluster_assignments[row] = asgnd_clust;
}
#if 0
printf("Cluster assignments:\n"); print_arr(cluster_assignments, NUM_ROWS);
#endif
}
/**
* \brief Update the cluster means
* \param matrix The matrix who's rows are being clustered.
* \param clusters The cluster centers (means).
* \param cluster_assignment_counts How many members each cluster has.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void M_step(const double* matrix, double* clusters,
vsize_t* cluster_assignment_counts, const vsize_t* cluster_assignments)
{
BOOST_LOG_TRIVIAL(info) << "M_step start";
gettimeofday(&start, NULL);
BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ...";
memset(clusters, 0, sizeof(clusters[0])*K*NEV);
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignments";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
// TODO: Parallelize me somehow
for (vsize_t vid = 0; vid < NUM_ROWS; vid++) {
// Update cluster counts
vsize_t asgnd_clust = cluster_assignments[vid];
cluster_assignment_counts[asgnd_clust]++;
for (vsize_t col = 0; col < NEV; col++) {
clusters[asgnd_clust*NEV + col] = clusters[asgnd_clust*NEV + col] + matrix[vid*NEV + col];
}
}
#if 0
printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K);
printf("Cluster centers: \n"); print_mat(clusters, K, NEV);
#endif
// Take the mean of all added means
BOOST_LOG_TRIVIAL(info) << " Div by in place ...";
//#pragma omp parallel for firstprivate(cluster_assignment_counts, K, NEV) shared(clusters)
for (vsize_t clust_idx = 0; clust_idx < K; clust_idx++) {
if (cluster_assignment_counts[clust_idx] > 0) { // Avoid div by 0
#pragma omp parallel for firstprivate(cluster_assignment_counts, NEV) shared(clusters)
for (vsize_t col = 0; col < NEV; col++) {
clusters[clust_idx*NEV + col] =
clusters[clust_idx*NEV + col] / cluster_assignment_counts[clust_idx];
}
}
}
gettimeofday(&end, NULL);
BOOST_LOG_TRIVIAL(info) << "M-step time taken = %.3f\n", time_diff(start, end);
# if 0
printf("Cluster centers: \n"); print_mat(clusters, K, NEV);
#endif
}
vsize_t compute_kmeans(const double* matrix, double* clusters,
vsize_t* cluster_assignments, vsize_t* cluster_assignment_counts,
const vsize_t num_rows, const vsize_t nev, const size_t k, const vsize_t MAX_ITERS,
const std::string init)
{
NEV = nev;
K = k;
NUM_ROWS = num_rows;
if (K > NUM_ROWS || K < 2) {
BOOST_LOG_TRIVIAL(fatal)
<< "'k' must be between 2 and the number of rows in the matrix";
exit(-1);
}
if (init.compare("random") != 0 && init.compare("kmeanspp") != 0 &&
init.compare("forgy") != 0) {
BOOST_LOG_TRIVIAL(fatal)
<< "[ERROR]: param init must be one of: 'random', 'kmeanspp'.It is '"
<< init << "'";
exit(-1);
}
#ifdef PROFILER
ProfilerStart(PROF_FILE_LOC);
#endif
/*** Begin VarInit of data structures ***/
memset(cluster_assignments, INVALID_VERTEX_ID,
sizeof(cluster_assignments[0])*NUM_ROWS);
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
/*** End VarInit ***/
if (init == "random") {
BOOST_LOG_TRIVIAL(info) << "Init is random_partition \n";
random_partition_init(cluster_assignments);
// We must now update cluster centers before we begin
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments);
}
if (init == "forgy") {
BOOST_LOG_TRIVIAL(info) << "Init is forgy";
forgy_init(matrix, clusters);
}
else {
if (init == "kmeanspp") {
kmeanspp_init(); // TODO: kmeanspp
}
}
BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ...";
bool converged = false;
std::string str_iters = MAX_ITERS == std::numeric_limits<vsize_t>::max() ? "until convergence ...":
std::to_string(MAX_ITERS) + " iterations ...";
BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters;
vsize_t iter = 1;
while (iter < MAX_ITERS) {
// Hold cluster assignment counter
BOOST_LOG_TRIVIAL(info) << "E-step Iteration " << iter << " . Computing cluster assignments ...";
E_step(matrix, clusters, cluster_assignments);
if (!updated) {
converged = true;
break;
} else { updated = false; }
BOOST_LOG_TRIVIAL(info) << "M-step Updating cluster means ...";
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments);
iter++;
}
#ifdef PROFILER
ProfilerStop();
#endif
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
if (converged) {
BOOST_LOG_TRIVIAL(info) <<
"K-means converged in " << iter << " iterations";
} else {
BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in "
<< iter << " iterations";
}
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
BOOST_LOG_TRIVIAL(info) << "\nCluster counts: ";
return iter;
}
<commit_msg>[Matrix]: kmeans performing cluster center updates and counting in || but using significantly more memory<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of FlashGraph.
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kmeans.h"
#define OMP_MAX_THREADS 32
using namespace fg;
bool updated = false;
static vsize_t NEV;
static size_t K;
static vsize_t NUM_ROWS;
static struct timeval start, end;
/**
* \brief Print an arry of some length `len`.
* \param len The length of the array.
*/
template <typename T>
static void print_arr(T* arr, vsize_t len) {
printf("[ ");
for (vsize_t i = 0; i < len; i++) {
std::cout << arr[i] << " ";
}
printf("]\n");
}
/*
* \Internal
* \brief Simple helper used to print a vector.
* \param v The vector to print.
*/
template <typename T>
static void print_vector(typename std::vector<T>& v)
{
std::cout << "[";
typename std::vector<T>::iterator itr = v.begin();
for (; itr != v.end(); itr++) {
std::cout << " "<< *itr;
}
std::cout << " ]\n";
}
/**
* \brief Get the squared distance given two values.
* \param arg1 the first value.
* \param arg2 the second value.
* \return the squared distance.
*/
static double dist_sq(double arg1, double arg2)
{
double diff = arg1 - arg2;
return diff*diff;
}
/**
* \brief This initializes clusters by randomly choosing sample
* membership in a cluster.
* See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods
* \param cluster_assignments Which cluster each sample falls into.
*/
static void random_partition_init(vsize_t* cluster_assignments)
{
BOOST_LOG_TRIVIAL(info) << "Random init start";
// #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments)
for (vsize_t vid = 0; vid < NUM_ROWS; vid++) {
size_t assigned_cluster = random() % K; // 0...K
cluster_assignments[vid] = assigned_cluster;
}
// NOTE: M-Step is called in compute func to update cluster counts & centers
#if 0
printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS);
#endif
BOOST_LOG_TRIVIAL(info) << "Random init end\n";
}
/**
* \brief Forgy init takes `K` random samples from the matrix
* and uses them as cluster centers.
* \param matrix the flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
*/
static void forgy_init(const double* matrix, double* clusters) {
BOOST_LOG_TRIVIAL(info) << "Forgy init start";
// #pragma omp parallel for firstprivate(matrix) shared (clusters)
for (vsize_t clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K
vsize_t rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1)
memcpy(&clusters[clust_idx*NEV], &matrix[rand_idx*NEV], sizeof(clusters[0])*NEV);
}
BOOST_LOG_TRIVIAL(info) << "Forgy init end";
}
/**
* \brief A parallel version of the kmeans++ initialization alg.
*/
static void kmeanspp_init()
{
BOOST_LOG_TRIVIAL(fatal) << "kmeanspp not yet implemented";
exit(-1);
}
/*\Internal
* \brief print a col wise matrix of type double / double.
* Used for testing only.
* \param matrix The col wise matrix.
* \param rows The number of rows in the mat
* \param cols The number of cols in the mat
*/
template <typename T>
static void print_mat(T* matrix, const vsize_t rows, const vsize_t cols) {
for (vsize_t row = 0; row < rows; row++) {
std::cout << "[";
for (vsize_t col = 0; col < cols; col++) {
std::cout << " " << matrix[row*cols + col];
}
std::cout << " ]\n";
}
}
/**
* \brief Update the cluster assignments while recomputing distance matrix.
* \param matrix The flattened matrix who's rows are being clustered.
* \param clusters The cluster centers (means) flattened matrix.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void E_step(const double* matrix, double* clusters,
vsize_t* cluster_assignments, vsize_t* cluster_assignment_counts)
{
gettimeofday(&start, NULL);
#if 1
// Create per thread vectors
std::vector<std::vector<vsize_t>> pt_cl_as_cnt; // K * OMP_MAX_THREADS
std::vector<std::vector<double>> pt_cl; // K * nev * OMP_MAX_THREADS
pt_cl_as_cnt.resize(OMP_MAX_THREADS);
pt_cl.resize(OMP_MAX_THREADS);
for (int i = 0; i < OMP_MAX_THREADS; i++) {
pt_cl_as_cnt[i].resize(K); // C++ default is 0 value in all
pt_cl[i].resize(K*NEV);
}
#endif
#pragma omp parallel for firstprivate(matrix, clusters) shared(pt_cl_as_cnt, cluster_assignments)
for (vsize_t row = 0; row < NUM_ROWS; row++) {
size_t asgnd_clust = std::numeric_limits<size_t>::max();
double best = std::numeric_limits<double>::max();
for (size_t clust_idx = 0; clust_idx < K; clust_idx++) {
double sum = 0;
for (vsize_t col = 0; col < NEV; col++) {
sum += dist_sq(matrix[(row*NEV) + col], clusters[clust_idx*NEV + col]);
}
if (sum < best) {
best = sum;
asgnd_clust = clust_idx;
}
}
if (asgnd_clust != cluster_assignments[row]) {
if (!updated) updated = true;
}
cluster_assignments[row] = asgnd_clust;
#if 1
pt_cl_as_cnt[omp_get_thread_num()][asgnd_clust]++; // Add to local copy
// Accumulate for local copies
for (vsize_t col = 0; col < NEV; col++) {
pt_cl[omp_get_thread_num()][asgnd_clust*NEV + col] =
pt_cl[omp_get_thread_num()][asgnd_clust*NEV + col] + matrix[row*NEV + col];
}
#endif
}
#if 1
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
// Serial aggreate of OMP_MAX_THREADS vectors
for (int i = 0; i < OMP_MAX_THREADS; i++) {
// Counts
for (vsize_t j = 0; j < K; j++) {
cluster_assignment_counts[j] += pt_cl_as_cnt[i][j];
}
// Summation for cluster centers
#pragma omp parallel for firstprivate(pt_cl) shared(clusters)
for (vsize_t row = 0; row < K; row++) { /* ClusterID */
for (vsize_t col = 0; col < NEV; col++) { /* Features */
clusters[row*NEV+col] = pt_cl[i][row*NEV + col] + clusters[row*NEV + col];
}
}
}
#endif
gettimeofday(&end, NULL);
BOOST_LOG_TRIVIAL(info) << "E-step time taken = " << time_diff(start, end) << "sec";
#if 1
printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K);
//printf("Cluster assignments:\n"); print_arr(cluster_assignments, NUM_ROWS);
#endif
}
/**
* \brief Update the cluster means
* \param matrix The matrix who's rows are being clustered.
* \param clusters The cluster centers (means).
* \param cluster_assignment_counts How many members each cluster has.
* \param cluster_assignments Which cluster each sample falls into.
*/
static void M_step(const double* matrix, double* clusters,
vsize_t* cluster_assignment_counts, const vsize_t* cluster_assignments, bool init=false)
{
BOOST_LOG_TRIVIAL(info) << "M_step start";
gettimeofday(&start, NULL);
if (init) {
BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ...";
memset(clusters, 0, sizeof(clusters[0])*K*NEV);
BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts";
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
for (vsize_t vid = 0; vid < NUM_ROWS; vid++) {
vsize_t asgnd_clust = cluster_assignments[vid];
cluster_assignment_counts[asgnd_clust]++;
for (vsize_t col = 0; col < NEV; col++) {
clusters[asgnd_clust*NEV + col] = clusters[asgnd_clust*NEV + col] + matrix[vid*NEV + col];
}
}
}
#if 0
printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K);
printf("Cluster centers: \n"); print_mat(clusters, K, NEV);
#endif
// Take the mean of all added means
BOOST_LOG_TRIVIAL(info) << " Div by in place ...";
for (vsize_t clust_idx = 0; clust_idx < K; clust_idx++) {
if (cluster_assignment_counts[clust_idx] > 0) { // Avoid div by 0
#pragma omp parallel for firstprivate(cluster_assignment_counts, NEV) shared(clusters)
for (vsize_t col = 0; col < NEV; col++) {
clusters[clust_idx*NEV + col] =
clusters[clust_idx*NEV + col] / cluster_assignment_counts[clust_idx];
}
}
}
gettimeofday(&end, NULL);
BOOST_LOG_TRIVIAL(info) << "M-step time taken = " << time_diff(start, end) << "sec";
# if 0
printf("Cluster centers: \n"); print_mat(clusters, K, NEV);
#endif
}
vsize_t compute_kmeans(const double* matrix, double* clusters,
vsize_t* cluster_assignments, vsize_t* cluster_assignment_counts,
const vsize_t num_rows, const vsize_t nev, const size_t k, const vsize_t MAX_ITERS,
const std::string init)
{
NEV = nev;
K = k;
NUM_ROWS = num_rows;
if (K > NUM_ROWS || K < 2) {
BOOST_LOG_TRIVIAL(fatal)
<< "'k' must be between 2 and the number of rows in the matrix";
exit(-1);
}
if (init.compare("random") != 0 && init.compare("kmeanspp") != 0 &&
init.compare("forgy") != 0) {
BOOST_LOG_TRIVIAL(fatal)
<< "[ERROR]: param init must be one of: 'random', 'kmeanspp'.It is '"
<< init << "'";
exit(-1);
}
#ifdef PROFILER
ProfilerStart(PROF_FILE_LOC);
#endif
/*** Begin VarInit of data structures ***/
memset(cluster_assignments, INVALID_VERTEX_ID,
sizeof(cluster_assignments[0])*NUM_ROWS);
memset(cluster_assignment_counts, 0, sizeof(cluster_assignment_counts[0])*K);
/*** End VarInit ***/
if (init == "random") {
BOOST_LOG_TRIVIAL(info) << "Init is random_partition \n";
random_partition_init(cluster_assignments);
// We must now update cluster centers before we begin
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments, true);
}
if (init == "forgy") {
BOOST_LOG_TRIVIAL(info) << "Init is forgy";
forgy_init(matrix, clusters);
}
else {
if (init == "kmeanspp") {
kmeanspp_init(); // TODO: kmeanspp
}
}
BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ...";
bool converged = false;
std::string str_iters = MAX_ITERS == std::numeric_limits<vsize_t>::max() ? "until convergence ...":
std::to_string(MAX_ITERS) + " iterations ...";
BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters;
vsize_t iter = 1;
while (iter < MAX_ITERS) {
// Hold cluster assignment counter
BOOST_LOG_TRIVIAL(info) << "E-step Iteration " << iter << " . Computing cluster assignments ...";
E_step(matrix, clusters, cluster_assignments, cluster_assignment_counts);
if (!updated) {
converged = true;
break;
} else { updated = false; }
BOOST_LOG_TRIVIAL(info) << "M-step Updating cluster means ...";
M_step(matrix, clusters, cluster_assignment_counts, cluster_assignments);
iter++;
}
#ifdef PROFILER
ProfilerStop();
#endif
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
if (converged) {
BOOST_LOG_TRIVIAL(info) <<
"K-means converged in " << iter << " iterations";
} else {
BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in "
<< iter << " iterations";
}
BOOST_LOG_TRIVIAL(info) << "\n******************************************\n";
BOOST_LOG_TRIVIAL(info) << "\nCluster counts: ";
return iter;
}
<|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 "chrome/renderer/page_click_tracker.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/page_click_listener.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMMouseEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
using WebKit::WebDOMEvent;
using WebKit::WebDOMMouseEvent;
using WebKit::WebElement;
using WebKit::WebFormControlElement;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebNode;
using WebKit::WebString;
using WebKit::WebView;
PageClickTracker::PageClickTracker(RenderView* render_view)
: RenderViewObserver(render_view),
was_focused_(false) {
}
PageClickTracker::~PageClickTracker() {
// Note that even though RenderView calls FrameDetached when notified that
// a frame was closed, it might not always get that notification from WebKit
// for all frames.
// By the time we get here, the frame could have been destroyed so we cannot
// unregister listeners in frames remaining in tracked_frames_ as they might
// be invalid.
}
void PageClickTracker::DidHandleMouseEvent(const WebMouseEvent& event) {
if (event.type != WebInputEvent::MouseDown ||
last_node_clicked_.isNull()) {
return;
}
// We are only interested in text field clicks.
if (!last_node_clicked_.isElementNode())
return;
const WebElement& element = last_node_clicked_.toConst<WebElement>();
if (!element.isFormControlElement())
return;
const WebFormControlElement& control =
element.toConst<WebFormControlElement>();
if (control.formControlType() != WebString::fromUTF8("text"))
return;
const WebInputElement& input_element = element.toConst<WebInputElement>();
bool is_focused = (last_node_clicked_ == GetFocusedNode());
ObserverListBase<PageClickListener>::Iterator it(listeners_);
PageClickListener* listener;
while ((listener = it.GetNext()) != NULL) {
if (listener->InputElementClicked(input_element, was_focused_, is_focused))
break;
}
last_node_clicked_.reset();
}
void PageClickTracker::AddListener(PageClickListener* listener) {
listeners_.AddObserver(listener);
}
void PageClickTracker::RemoveListener(PageClickListener* listener) {
listeners_.RemoveObserver(listener);
}
bool PageClickTracker::OnMessageReceived(const IPC::Message& message) {
if (message.type() == ViewMsg_HandleInputEvent::ID) {
void* iter = NULL;
const char* data;
int data_length;
if (message.ReadData(&iter, &data, &data_length)) {
const WebInputEvent* input_event =
reinterpret_cast<const WebInputEvent*>(data);
if (WebInputEvent::isMouseEventType(input_event->type))
DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
}
}
return false;
}
void PageClickTracker::DidFinishDocumentLoad(WebKit::WebFrame* frame) {
tracked_frames_.push_back(frame);
frame->document().addEventListener("mousedown", this, false);
}
void PageClickTracker::FrameDetached(WebKit::WebFrame* frame) {
FrameList::iterator iter =
std::find(tracked_frames_.begin(), tracked_frames_.end(), frame);
if (iter == tracked_frames_.end()) {
// Some frames might never load contents so we may not have a listener on
// them. Calling removeEventListener() on them would trigger an assert, so
// we need to keep track of which frames we are listening to.
return;
}
tracked_frames_.erase(iter);
}
void PageClickTracker::handleEvent(const WebDOMEvent& event) {
last_node_clicked_.reset();
if (!event.isMouseEvent())
return;
const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>();
DCHECK(mouse_event.buttonDown());
if (mouse_event.button() != 0)
return; // We are only interested in left clicks.
// Remember which node has focus before the click is processed.
// We'll get a notification once the mouse event has been processed
// (DidHandleMouseEvent), we'll notify the listener at that point.
last_node_clicked_ = mouse_event.target();
was_focused_ = (GetFocusedNode() == last_node_clicked_);
}
WebNode PageClickTracker::GetFocusedNode() {
WebView* web_view = render_view()->webview();
if (!web_view)
return WebNode();
WebFrame* web_frame = web_view->focusedFrame();
if (!web_frame)
return WebNode();
return web_frame->document().focusedNode();
}
<commit_msg>In PageClickTracker: As soon as we start to handle an event, filter against the type of nodes we care about (only text fields), rather than waiting to filter in DidHandleMouseEvent().<commit_after>// Copyright (c) 2011 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 "chrome/renderer/page_click_tracker.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/page_click_listener.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMMouseEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
using WebKit::WebDOMEvent;
using WebKit::WebDOMMouseEvent;
using WebKit::WebElement;
using WebKit::WebFormControlElement;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebNode;
using WebKit::WebString;
using WebKit::WebView;
namespace {
// Casts |node| to a WebInputElement.
// Returns an empty (isNull()) WebInputElement if |node| is not a text
// WebInputElement.
const WebInputElement GetTextWebInputElement(const WebNode& node) {
if (!node.isElementNode())
return WebInputElement();
const WebElement element = node.toConst<WebElement>();
if (!element.isFormControlElement())
return WebInputElement();
const WebFormControlElement control =
element.toConst<WebFormControlElement>();
if (control.formControlType() != WebString::fromUTF8("text"))
return WebInputElement();
return element.toConst<WebInputElement>();
}
} // namespace
PageClickTracker::PageClickTracker(RenderView* render_view)
: RenderViewObserver(render_view),
was_focused_(false) {
}
PageClickTracker::~PageClickTracker() {
// Note that even though RenderView calls FrameDetached when notified that
// a frame was closed, it might not always get that notification from WebKit
// for all frames.
// By the time we get here, the frame could have been destroyed so we cannot
// unregister listeners in frames remaining in tracked_frames_ as they might
// be invalid.
}
void PageClickTracker::DidHandleMouseEvent(const WebMouseEvent& event) {
if (event.type != WebInputEvent::MouseDown ||
last_node_clicked_.isNull()) {
return;
}
// We are only interested in text field clicks.
const WebInputElement input_element =
GetTextWebInputElement(last_node_clicked_);
if (input_element.isNull())
return;
bool is_focused = (last_node_clicked_ == GetFocusedNode());
ObserverListBase<PageClickListener>::Iterator it(listeners_);
PageClickListener* listener;
while ((listener = it.GetNext()) != NULL) {
if (listener->InputElementClicked(input_element, was_focused_, is_focused))
break;
}
last_node_clicked_.reset();
}
void PageClickTracker::AddListener(PageClickListener* listener) {
listeners_.AddObserver(listener);
}
void PageClickTracker::RemoveListener(PageClickListener* listener) {
listeners_.RemoveObserver(listener);
}
bool PageClickTracker::OnMessageReceived(const IPC::Message& message) {
if (message.type() == ViewMsg_HandleInputEvent::ID) {
void* iter = NULL;
const char* data;
int data_length;
if (message.ReadData(&iter, &data, &data_length)) {
const WebInputEvent* input_event =
reinterpret_cast<const WebInputEvent*>(data);
if (WebInputEvent::isMouseEventType(input_event->type))
DidHandleMouseEvent(*(static_cast<const WebMouseEvent*>(input_event)));
}
}
return false;
}
void PageClickTracker::DidFinishDocumentLoad(WebKit::WebFrame* frame) {
tracked_frames_.push_back(frame);
frame->document().addEventListener("mousedown", this, false);
}
void PageClickTracker::FrameDetached(WebKit::WebFrame* frame) {
FrameList::iterator iter =
std::find(tracked_frames_.begin(), tracked_frames_.end(), frame);
if (iter == tracked_frames_.end()) {
// Some frames might never load contents so we may not have a listener on
// them. Calling removeEventListener() on them would trigger an assert, so
// we need to keep track of which frames we are listening to.
return;
}
tracked_frames_.erase(iter);
}
void PageClickTracker::handleEvent(const WebDOMEvent& event) {
last_node_clicked_.reset();
if (!event.isMouseEvent())
return;
const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>();
DCHECK(mouse_event.buttonDown());
if (mouse_event.button() != 0)
return; // We are only interested in left clicks.
// Remember which node has focus before the click is processed.
// We'll get a notification once the mouse event has been processed
// (DidHandleMouseEvent), we'll notify the listener at that point.
WebNode node = mouse_event.target();
// We are only interested in text field clicks.
if (GetTextWebInputElement(node).isNull())
return;
last_node_clicked_ = node;
was_focused_ = (GetFocusedNode() == last_node_clicked_);
}
WebNode PageClickTracker::GetFocusedNode() {
WebView* web_view = render_view()->webview();
if (!web_view)
return WebNode();
WebFrame* web_frame = web_view->focusedFrame();
if (!web_frame)
return WebNode();
return web_frame->document().focusedNode();
}
<|endoftext|> |
<commit_before>#include "layouter.h"
#include "utf-8.h"
#include <harfbuzz/hb.h>
#include <harfbuzz/hb-ft.h>
#include <fribidi/fribidi.h>
#include <linebreak.h>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
typedef struct
{
std::vector<textLayout_c::commandData> run;
int dx, dy;
FriBidiLevel embeddingLevel;
char linebreak;
std::shared_ptr<fontFace_c> font;
} runInfo;
// TODO create a sharing structure, where we only
// define structures for each configuration once
// and link to it
// but for now it is good as it is
typedef struct
{
uint8_t r, g, b;
std::shared_ptr<fontFace_c> font;
std::string lang;
} codepointAttributes;
FriBidiLevel getBidiEmbeddingLevels(const std::u32string & txt32, std::vector<FriBidiLevel> & embedding_levels)
{
std::vector<FriBidiCharType> bidiTypes(txt32.length());
fribidi_get_bidi_types((uint32_t*)txt32.c_str(), txt32.length(), bidiTypes.data());
FriBidiParType base_dir = FRIBIDI_TYPE_LTR_VAL; // TODO depends on main script of text
embedding_levels.resize(txt32.length());
FriBidiLevel max_level = fribidi_get_par_embedding_levels(bidiTypes.data(), txt32.length(),
&base_dir, embedding_levels.data());
return max_level;
}
textLayout_c layoutParagraph(const std::u32string & txt32, const std::vector<codepointAttributes> & attr, const shape_c & shape)
{
// calculate embedding types for the text
std::vector<FriBidiLevel> embedding_levels;
FriBidiLevel max_level = getBidiEmbeddingLevels(txt32, embedding_levels);
// calculate the possible linebreak positions
std::vector<char> linebreaks(txt32.length());
set_linebreaks_utf32((utf32_t*)txt32.c_str(), txt32.length(), "", linebreaks.data());
// Get our harfbuzz font structs, TODO we need to do that for all the fonts
std::map<const std::shared_ptr<fontFace_c>, hb_font_t *> hb_ft_fonts;
for (const auto & a : attr)
{
if (hb_ft_fonts.find(a.font) == hb_ft_fonts.end())
{
hb_ft_fonts[a.font] = hb_ft_font_create(a.font->getFace(), NULL);
}
}
// Create a buffer for harfbuzz to use
hb_buffer_t *buf = hb_buffer_create();
std::string lan = attr[0].lang.substr(0, 2);
std::string s = attr[0].lang.substr(3, 4);
hb_script_t scr = hb_script_from_iso15924_tag(HB_TAG(s[0], s[1], s[2], s[3]));
hb_buffer_set_script(buf, scr);
// TODO must come either from text or from rules
hb_buffer_set_language(buf, hb_language_from_string(lan.c_str(), lan.length()));
size_t runstart = 0;
std::vector<runInfo> runs;
while (runstart < txt32.length())
{
size_t spos = runstart+1;
// find end of current run
while ( (spos < txt32.length())
&& (embedding_levels[runstart] == embedding_levels[spos])
&& (attr[runstart].font == attr[spos].font)
&& ( (linebreaks[spos-1] == LINEBREAK_NOBREAK)
|| (linebreaks[spos-1] == LINEBREAK_INSIDEACHAR)
)
)
{
spos++;
}
hb_buffer_add_utf32(buf, ((uint32_t*)txt32.c_str())+runstart, spos-runstart, 0, spos-runstart);
if (embedding_levels[runstart] % 2 == 0)
{
hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
}
else
{
hb_buffer_set_direction(buf, HB_DIRECTION_RTL);
}
hb_shape(hb_ft_fonts[attr[runstart].font], buf, NULL, 0);
unsigned int glyph_count;
hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count);
hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count);
runInfo run;
run.dx = run.dy = 0;
run.embeddingLevel = embedding_levels[runstart];
run.linebreak = linebreaks[spos-1];
run.font = attr[runstart].font;
for (size_t j=0; j < glyph_count; ++j)
{
textLayout_c::commandData g;
g.glyphIndex = glyph_info[j].codepoint;
g.font = attr[runstart].font;
// TODO the other parameters
g.x = run.dx + (glyph_pos[j].x_offset/64);
g.y = run.dy - (glyph_pos[j].y_offset/64);
run.dx += glyph_pos[j].x_advance/64;
run.dy -= glyph_pos[j].y_advance/64;
g.r = attr[glyph_info[j].cluster + runstart].r;
g.g = attr[glyph_info[j].cluster + runstart].g;
g.b = attr[glyph_info[j].cluster + runstart].b;
g.command = textLayout_c::commandData::CMD_GLYPH;
run.run.push_back(g);
}
runs.push_back(run);
runstart = spos;
hb_buffer_reset(buf);
}
hb_buffer_destroy(buf);
for (auto & a : hb_ft_fonts)
hb_font_destroy(a.second);
std::vector<size_t> runorder(runs.size());
int n(0);
std::generate(runorder.begin(), runorder.end(), [&]{ return n++; });
// layout a run
// TODO take care of different font sizes of the different runs
runstart = 0;
int32_t ypos = runs[0].font->getAscender()/64;
textLayout_c l;
while (runstart < runs.size())
{
// todo use actual font line height
int32_t left = shape.getLeft(ypos-runs[runstart].font->getAscender()/64, ypos-runs[runstart].font->getDescender()/64) + runs[runstart].dx;
int32_t right = shape.getRight(ypos-runs[runstart].font->getAscender()/64, ypos-runs[runstart].font->getDescender()/64);
size_t spos = runstart + 1;
while (spos < runs.size() && left+runs[spos].dx < right)
{
left += runs[spos].dx;
spos++;
}
// reorder runs for current line
for (int i = max_level-1; i >= 0; i--)
{
// find starts of regions to reverse
for (size_t j = runstart; j < spos; j++)
{
if (runs[runorder[j]].embeddingLevel > i)
{
// find the end of the current regions
size_t k = j+1;
while (k < spos && runs[runorder[k]].embeddingLevel > i)
{
k++;
}
std::reverse(runorder.begin()+j, runorder.begin()+k);
j = k;
}
}
}
int32_t xpos = shape.getLeft(ypos-runs[runstart].font->getAscender(), ypos-runs[runstart].font->getDescender());
for (size_t i = runstart; i < spos; i++)
{
l.addCommandVector(runs[runorder[i]].run, xpos, ypos);
xpos += runs[runorder[i]].dx;
}
ypos += runs[runstart].font->getHeigt()/64;
runstart = spos;
}
// TODO proper font handling for multiple fonts in a line
l.setHeight(ypos-runs[0].font->getAscender()/64);
return l;
}
void layoutXML_text(const pugi::xml_node & xml, const textStyleSheet_c & rules, std::u32string & txt,
std::vector<codepointAttributes> & attr)
{
for (const auto & i : xml)
{
if (i.type() == pugi::node_pcdata)
{
txt += u8_convertToU32(i.value());
codepointAttributes a;
evalColor(rules.getValue(xml, "color"), a.r, a.g, a.b);
std::string fontFamily = rules.getValue(xml, "font-family");
std::string fontStyle = rules.getValue(xml, "font-style");
double fontSize = evalSize(rules.getValue(xml, "font-size"));
a.font = rules.findFamily(fontFamily)->getFont(64*fontSize, fontStyle);
a.lang = "en-eng";
while (attr.size() < txt.length())
attr.push_back(a);
}
else if (i.type() == pugi::node_element && std::string("i") == i.name())
{
layoutXML_text(i, rules, txt, attr);
}
}
}
// this whole stuff is a recursive descending parser of the XHTML stuff
textLayout_c layoutXML_P(const pugi::xml_node & xml, const textStyleSheet_c & rules, const shape_c & shape)
{
std::u32string txt;
std::vector<codepointAttributes> attr;
layoutXML_text(xml, rules, txt, attr);
return layoutParagraph(txt, attr, shape);
}
textLayout_c layoutXML_BODY(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
for (const auto & i : txt)
{
if (i.type() == pugi::node_element && std::string("p") == i.name())
{
l.append(layoutXML_P(i, rules, shape), 0, l.getHeight());
}
else if (i.type() == pugi::node_element && std::string("table") == i.name())
{
}
else
{
// TODO exception nothing else supported
}
}
return l;
}
textLayout_c layoutXML_HTML(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
bool headfound = false;
bool bodyfound = false;
for (const auto & i : txt)
{
if (std::string("head") == i.name() && !headfound)
{
headfound = true;
}
else if (std::string("body") == i.name() && !bodyfound)
{
bodyfound = true;
l = layoutXML_BODY(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXML(const pugi::xml_document & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
// we must have a HTML root node
for (const auto & i : txt)
{
if (std::string("html") == i.name())
{
l = layoutXML_HTML(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXHTML(const std::string & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
pugi::xml_document doc;
// TODO handle parser errors
doc.load_buffer(txt.c_str(), txt.length());
return layoutXML(doc, rules, shape);
}
textLayout_c layoutRaw(const std::string & txt, const std::shared_ptr<fontFace_c> font, const shape_c & shape, const std::string & language)
{
// when we layout raw text we
// only have to convert the text to utf-32
// and assign the given font and language to all the codepoints of that text
std::u32string txt32 = u8_convertToU32(txt);
std::vector<codepointAttributes> attr(txt32.size());
for (auto & i : attr)
{
i.r = i.g = i.b = 255;
i.font = font;
i.lang = language;
}
return layoutParagraph(txt32, attr, shape);
}
<commit_msg>div sections withint paragraph sections<commit_after>#include "layouter.h"
#include "utf-8.h"
#include <harfbuzz/hb.h>
#include <harfbuzz/hb-ft.h>
#include <fribidi/fribidi.h>
#include <linebreak.h>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
typedef struct
{
std::vector<textLayout_c::commandData> run;
int dx, dy;
FriBidiLevel embeddingLevel;
char linebreak;
std::shared_ptr<fontFace_c> font;
} runInfo;
// TODO create a sharing structure, where we only
// define structures for each configuration once
// and link to it
// but for now it is good as it is
typedef struct
{
uint8_t r, g, b;
std::shared_ptr<fontFace_c> font;
std::string lang;
} codepointAttributes;
FriBidiLevel getBidiEmbeddingLevels(const std::u32string & txt32, std::vector<FriBidiLevel> & embedding_levels)
{
std::vector<FriBidiCharType> bidiTypes(txt32.length());
fribidi_get_bidi_types((uint32_t*)txt32.c_str(), txt32.length(), bidiTypes.data());
FriBidiParType base_dir = FRIBIDI_TYPE_LTR_VAL; // TODO depends on main script of text
embedding_levels.resize(txt32.length());
FriBidiLevel max_level = fribidi_get_par_embedding_levels(bidiTypes.data(), txt32.length(),
&base_dir, embedding_levels.data());
return max_level;
}
textLayout_c layoutParagraph(const std::u32string & txt32, const std::vector<codepointAttributes> & attr, const shape_c & shape)
{
// calculate embedding types for the text
std::vector<FriBidiLevel> embedding_levels;
FriBidiLevel max_level = getBidiEmbeddingLevels(txt32, embedding_levels);
// calculate the possible linebreak positions
std::vector<char> linebreaks(txt32.length());
set_linebreaks_utf32((utf32_t*)txt32.c_str(), txt32.length(), "", linebreaks.data());
// Get our harfbuzz font structs, TODO we need to do that for all the fonts
std::map<const std::shared_ptr<fontFace_c>, hb_font_t *> hb_ft_fonts;
for (const auto & a : attr)
{
if (hb_ft_fonts.find(a.font) == hb_ft_fonts.end())
{
hb_ft_fonts[a.font] = hb_ft_font_create(a.font->getFace(), NULL);
}
}
// Create a buffer for harfbuzz to use
hb_buffer_t *buf = hb_buffer_create();
std::string lan = attr[0].lang.substr(0, 2);
std::string s = attr[0].lang.substr(3, 4);
hb_script_t scr = hb_script_from_iso15924_tag(HB_TAG(s[0], s[1], s[2], s[3]));
hb_buffer_set_script(buf, scr);
// TODO must come either from text or from rules
hb_buffer_set_language(buf, hb_language_from_string(lan.c_str(), lan.length()));
size_t runstart = 0;
std::vector<runInfo> runs;
while (runstart < txt32.length())
{
size_t spos = runstart+1;
// find end of current run
while ( (spos < txt32.length())
&& (embedding_levels[runstart] == embedding_levels[spos])
&& (attr[runstart].font == attr[spos].font)
&& ( (linebreaks[spos-1] == LINEBREAK_NOBREAK)
|| (linebreaks[spos-1] == LINEBREAK_INSIDEACHAR)
)
)
{
spos++;
}
hb_buffer_add_utf32(buf, ((uint32_t*)txt32.c_str())+runstart, spos-runstart, 0, spos-runstart);
if (embedding_levels[runstart] % 2 == 0)
{
hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
}
else
{
hb_buffer_set_direction(buf, HB_DIRECTION_RTL);
}
hb_shape(hb_ft_fonts[attr[runstart].font], buf, NULL, 0);
unsigned int glyph_count;
hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count);
hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count);
runInfo run;
run.dx = run.dy = 0;
run.embeddingLevel = embedding_levels[runstart];
run.linebreak = linebreaks[spos-1];
run.font = attr[runstart].font;
for (size_t j=0; j < glyph_count; ++j)
{
textLayout_c::commandData g;
g.glyphIndex = glyph_info[j].codepoint;
g.font = attr[runstart].font;
// TODO the other parameters
g.x = run.dx + (glyph_pos[j].x_offset/64);
g.y = run.dy - (glyph_pos[j].y_offset/64);
run.dx += glyph_pos[j].x_advance/64;
run.dy -= glyph_pos[j].y_advance/64;
g.r = attr[glyph_info[j].cluster + runstart].r;
g.g = attr[glyph_info[j].cluster + runstart].g;
g.b = attr[glyph_info[j].cluster + runstart].b;
g.command = textLayout_c::commandData::CMD_GLYPH;
run.run.push_back(g);
}
runs.push_back(run);
runstart = spos;
hb_buffer_reset(buf);
}
hb_buffer_destroy(buf);
for (auto & a : hb_ft_fonts)
hb_font_destroy(a.second);
std::vector<size_t> runorder(runs.size());
int n(0);
std::generate(runorder.begin(), runorder.end(), [&]{ return n++; });
// layout a run
// TODO take care of different font sizes of the different runs
runstart = 0;
int32_t ypos = runs[0].font->getAscender()/64;
textLayout_c l;
while (runstart < runs.size())
{
// todo use actual font line height
int32_t left = shape.getLeft(ypos-runs[runstart].font->getAscender()/64, ypos-runs[runstart].font->getDescender()/64) + runs[runstart].dx;
int32_t right = shape.getRight(ypos-runs[runstart].font->getAscender()/64, ypos-runs[runstart].font->getDescender()/64);
size_t spos = runstart + 1;
while (spos < runs.size() && left+runs[spos].dx < right)
{
left += runs[spos].dx;
spos++;
}
// reorder runs for current line
for (int i = max_level-1; i >= 0; i--)
{
// find starts of regions to reverse
for (size_t j = runstart; j < spos; j++)
{
if (runs[runorder[j]].embeddingLevel > i)
{
// find the end of the current regions
size_t k = j+1;
while (k < spos && runs[runorder[k]].embeddingLevel > i)
{
k++;
}
std::reverse(runorder.begin()+j, runorder.begin()+k);
j = k;
}
}
}
int32_t xpos = shape.getLeft(ypos-runs[runstart].font->getAscender(), ypos-runs[runstart].font->getDescender());
for (size_t i = runstart; i < spos; i++)
{
l.addCommandVector(runs[runorder[i]].run, xpos, ypos);
xpos += runs[runorder[i]].dx;
}
ypos += runs[runstart].font->getHeigt()/64;
runstart = spos;
}
// TODO proper font handling for multiple fonts in a line
l.setHeight(ypos-runs[0].font->getAscender()/64);
return l;
}
void layoutXML_text(const pugi::xml_node & xml, const textStyleSheet_c & rules, std::u32string & txt,
std::vector<codepointAttributes> & attr)
{
for (const auto & i : xml)
{
if (i.type() == pugi::node_pcdata)
{
txt += u8_convertToU32(i.value());
codepointAttributes a;
evalColor(rules.getValue(xml, "color"), a.r, a.g, a.b);
std::string fontFamily = rules.getValue(xml, "font-family");
std::string fontStyle = rules.getValue(xml, "font-style");
double fontSize = evalSize(rules.getValue(xml, "font-size"));
a.font = rules.findFamily(fontFamily)->getFont(64*fontSize, fontStyle);
a.lang = "en-eng";
while (attr.size() < txt.length())
attr.push_back(a);
}
else if (i.type() == pugi::node_element && std::string("i") == i.name())
{
layoutXML_text(i, rules, txt, attr);
}
else if (i.type() == pugi::node_element && std::string("div") == i.name())
{
layoutXML_text(i, rules, txt, attr);
}
}
}
// this whole stuff is a recursive descending parser of the XHTML stuff
textLayout_c layoutXML_P(const pugi::xml_node & xml, const textStyleSheet_c & rules, const shape_c & shape)
{
std::u32string txt;
std::vector<codepointAttributes> attr;
layoutXML_text(xml, rules, txt, attr);
return layoutParagraph(txt, attr, shape);
}
textLayout_c layoutXML_BODY(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
for (const auto & i : txt)
{
if (i.type() == pugi::node_element && std::string("p") == i.name())
{
l.append(layoutXML_P(i, rules, shape), 0, l.getHeight());
}
else if (i.type() == pugi::node_element && std::string("table") == i.name())
{
}
else
{
// TODO exception nothing else supported
}
}
return l;
}
textLayout_c layoutXML_HTML(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
bool headfound = false;
bool bodyfound = false;
for (const auto & i : txt)
{
if (std::string("head") == i.name() && !headfound)
{
headfound = true;
}
else if (std::string("body") == i.name() && !bodyfound)
{
bodyfound = true;
l = layoutXML_BODY(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXML(const pugi::xml_document & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
// we must have a HTML root node
for (const auto & i : txt)
{
if (std::string("html") == i.name())
{
l = layoutXML_HTML(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXHTML(const std::string & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
pugi::xml_document doc;
// TODO handle parser errors
doc.load_buffer(txt.c_str(), txt.length());
return layoutXML(doc, rules, shape);
}
textLayout_c layoutRaw(const std::string & txt, const std::shared_ptr<fontFace_c> font, const shape_c & shape, const std::string & language)
{
// when we layout raw text we
// only have to convert the text to utf-32
// and assign the given font and language to all the codepoints of that text
std::u32string txt32 = u8_convertToU32(txt);
std::vector<codepointAttributes> attr(txt32.size());
for (auto & i : attr)
{
i.r = i.g = i.b = 255;
i.font = font;
i.lang = language;
}
return layoutParagraph(txt32, attr, shape);
}
<|endoftext|> |
<commit_before>//===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level dead-code-elimination pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN DeadMachineInstructionElim :
public MachineFunctionPass {
virtual bool runOnMachineFunction(MachineFunction &MF);
public:
static char ID; // Pass identification, replacement for typeid
DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}
};
}
char DeadMachineInstructionElim::ID = 0;
static RegisterPass<DeadMachineInstructionElim>
Y("dead-mi-elimination",
"Remove dead machine instructions");
FunctionPass *llvm::createDeadMachineInstructionElimPass() {
return new DeadMachineInstructionElim();
}
bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
bool AnyChanges = false;
const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo();
const MachineRegisterInfo &MRI = MF.getRegInfo();
const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
BitVector LivePhysRegs;
bool SawStore;
// Compute a bitvector to represent all non-allocatable physregs.
BitVector NonAllocatableRegs = TRI.getAllocatableSet(MF);
NonAllocatableRegs.flip();
// Loop over all instructions in all blocks, from bottom to top, so that it's
// more likely that chains of dependent but ultimately dead instructions will
// be cleaned up.
for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
I != E; ++I) {
MachineBasicBlock *MBB = &*I;
// Start out assuming that all non-allocatable registers are live
// out of this block.
LivePhysRegs = NonAllocatableRegs;
// Also add any explicit live-out physregs for this block.
if (!MBB->empty() && MBB->back().getDesc().isReturn())
for (MachineRegisterInfo::liveout_iterator LOI = MRI.liveout_begin(),
LOE = MRI.liveout_end(); LOI != LOE; ++LOI) {
unsigned Reg = *LOI;
if (TargetRegisterInfo::isPhysicalRegister(Reg))
LivePhysRegs.set(Reg);
}
// Now scan the instructions and delete dead ones, tracking physreg
// liveness as we go.
for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),
MIE = MBB->rend(); MII != MIE; ) {
MachineInstr *MI = &*MII;
// Don't delete instructions with side effects.
SawStore = false;
if (MI->isSafeToMove(&TII, SawStore)) {
// Examine each operand.
bool AllDefsDead = true;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isRegister() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (TargetRegisterInfo::isPhysicalRegister(Reg) ?
LivePhysRegs[Reg] : !MRI.use_empty(Reg)) {
// This def has a use. Don't delete the instruction!
AllDefsDead = false;
break;
}
}
}
// If there are no defs with uses, the instruction is dead.
if (AllDefsDead) {
AnyChanges = true;
MI->eraseFromParent();
MIE = MBB->rend();
// MII is now pointing to the next instruction to process,
// so don't increment it.
continue;
}
}
// Record the physreg defs.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isRegister() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.reset(Reg);
for (const unsigned *AliasSet = TRI.getAliasSet(Reg);
*AliasSet; ++AliasSet)
LivePhysRegs.reset(*AliasSet);
}
}
}
// Record the physreg uses, after the defs, in case a physreg is
// both defined and used in the same instruction.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isRegister() && MO.isUse()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.set(Reg);
for (const unsigned *AliasSet = TRI.getAliasSet(Reg);
*AliasSet; ++AliasSet)
LivePhysRegs.set(*AliasSet);
}
}
}
// We didn't delete the current instruction, so increment MII to
// the next one.
++MII;
}
}
return AnyChanges;
}
<commit_msg>Refactor the logic for testing if an instruction is dead into a separate method.<commit_after>//===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level dead-code-elimination pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/Pass.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN DeadMachineInstructionElim :
public MachineFunctionPass {
virtual bool runOnMachineFunction(MachineFunction &MF);
const TargetRegisterInfo *TRI;
const MachineRegisterInfo *MRI;
const TargetInstrInfo *TII;
BitVector LivePhysRegs;
public:
static char ID; // Pass identification, replacement for typeid
DeadMachineInstructionElim() : MachineFunctionPass(&ID) {}
private:
bool isDead(MachineInstr *MI) const;
};
}
char DeadMachineInstructionElim::ID = 0;
static RegisterPass<DeadMachineInstructionElim>
Y("dead-mi-elimination",
"Remove dead machine instructions");
FunctionPass *llvm::createDeadMachineInstructionElimPass() {
return new DeadMachineInstructionElim();
}
bool DeadMachineInstructionElim::isDead(MachineInstr *MI) const {
// Don't delete instructions with side effects.
bool SawStore = false;
if (!MI->isSafeToMove(TII, SawStore))
return false;
// Examine each operand.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isRegister() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (TargetRegisterInfo::isPhysicalRegister(Reg) ?
LivePhysRegs[Reg] : !MRI->use_empty(Reg)) {
// This def has a use. Don't delete the instruction!
return false;
}
}
}
// If there are no defs with uses, the instruction is dead.
return true;
}
bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
bool AnyChanges = false;
MRI = &MF.getRegInfo();
TRI = MF.getTarget().getRegisterInfo();
TII = MF.getTarget().getInstrInfo();
// Compute a bitvector to represent all non-allocatable physregs.
BitVector NonAllocatableRegs = TRI->getAllocatableSet(MF);
NonAllocatableRegs.flip();
// Loop over all instructions in all blocks, from bottom to top, so that it's
// more likely that chains of dependent but ultimately dead instructions will
// be cleaned up.
for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
I != E; ++I) {
MachineBasicBlock *MBB = &*I;
// Start out assuming that all non-allocatable registers are live
// out of this block.
LivePhysRegs = NonAllocatableRegs;
// Also add any explicit live-out physregs for this block.
if (!MBB->empty() && MBB->back().getDesc().isReturn())
for (MachineRegisterInfo::liveout_iterator LOI = MRI->liveout_begin(),
LOE = MRI->liveout_end(); LOI != LOE; ++LOI) {
unsigned Reg = *LOI;
if (TargetRegisterInfo::isPhysicalRegister(Reg))
LivePhysRegs.set(Reg);
}
// Now scan the instructions and delete dead ones, tracking physreg
// liveness as we go.
for (MachineBasicBlock::reverse_iterator MII = MBB->rbegin(),
MIE = MBB->rend(); MII != MIE; ) {
MachineInstr *MI = &*MII;
// If the instruction is dead, delete it!
if (isDead(MI)) {
AnyChanges = true;
MI->eraseFromParent();
MIE = MBB->rend();
// MII is now pointing to the next instruction to process,
// so don't increment it.
continue;
}
// Record the physreg defs.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isRegister() && MO.isDef()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.reset(Reg);
for (const unsigned *AliasSet = TRI->getAliasSet(Reg);
*AliasSet; ++AliasSet)
LivePhysRegs.reset(*AliasSet);
}
}
}
// Record the physreg uses, after the defs, in case a physreg is
// both defined and used in the same instruction.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isRegister() && MO.isUse()) {
unsigned Reg = MO.getReg();
if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
LivePhysRegs.set(Reg);
for (const unsigned *AliasSet = TRI->getAliasSet(Reg);
*AliasSet; ++AliasSet)
LivePhysRegs.set(*AliasSet);
}
}
}
// We didn't delete the current instruction, so increment MII to
// the next one.
++MII;
}
}
LivePhysRegs.clear();
return AnyChanges;
}
<|endoftext|> |
<commit_before>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#include <iomanip>
#ifdef _ELASTIX_USE_MEVISDICOMTIFF
#include "itkUseMevisDicomTiff.h"
#endif
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOBase.h"
#include <string>
#include "itkMath.h"
#include "itkTestingComparisonImageFilter.h"
//-------------------------------------------------------------------------------------
// This test tests the itkMevisDicomTiffImageIO library. The test is performed
// in 2D, 3D, and 4D, for a unsigned char image. An artificial image is generated,
// written to disk, read from disk, and compared to the original.
template< unsigned int Dimension >
int testMevis( void )
{
std::cerr << "Testing write/read of " << Dimension << "D image..." << std::endl;
/** Some basic type definitions. */
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageFileWriter< ImageType > WriterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::Testing::ComparisonImageFilter<
ImageType, ImageType > ComparisonFilterType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef typename ImageType::PointType OriginType;
typedef typename ImageType::DirectionType DirectionType;
typedef itk::ImageRegionIterator< ImageType > IteratorType;
typename WriterType::Pointer writer = WriterType::New();
typename ReaderType::Pointer reader = ReaderType::New();
typename ImageType::Pointer inputImage = ImageType::New();
SizeType size;
SpacingType spacing;
OriginType origin;
DirectionType direction;
direction.Fill( 0.0 );
for( unsigned int i = 0; i < Dimension; ++i )
{
size[i] = 20+i;
spacing[i] = 0.5 + 0.1*i;
origin[i] = 5 + 3*i;
direction[i][i] = 1.0; // default, will be changed below
}
// 4th dimension origin/spacing are lost using dcm/tiff format!
if (Dimension == 4)
{
// default values
spacing[3] = 1.0;
origin[3] = 0.0;
}
// Difficult direction cosines:
if ( Dimension == 2 )
{
// Test flips
direction[0][0] = 1; direction[0][1] = 0;
direction[1][0] = 0; direction[1][1] = -1;
}
else if ( Dimension == 3 )
{
// Test axis permutations
// RM: won't work, because dicom always assume right hand
// coordinate system when reconstructing the third direction
/*
direction[0][0] = 1; direction[0][1] = 0; direction[0][2] = 0;
direction[1][0] = 0; direction[1][1] = 0; direction[1][2] = 1;
direction[2][0] = 0; direction[2][1] = 1; direction[2][2] = 0;
*/
// this works:
direction[0][0] = 1; direction[0][1] = 0; direction[0][2] = 0;
direction[1][0] = 0; direction[1][1] = 0; direction[1][2] = -1;
direction[2][0] = 0; direction[2][1] = 1; direction[2][2] = 0;
}
else if ( Dimension == 4 )
{
// Test 4D. RM: also make sure it is a right hand coordinate system
direction[0][0] = 1; direction[0][1] = 0; direction[0][2] = 0; direction[0][3] = 0;
direction[1][0] = 0; direction[1][1] = 0; direction[1][2] = -1; direction[1][3] = 0;
direction[2][0] = 0; direction[2][1] = 1; direction[2][2] = 0; direction[2][3] = 0;
direction[3][0] = 0; direction[3][1] = 0; direction[3][2] = 0; direction[3][3] = 1;
}
/** Generate image with gradually increasing pixel values. */
inputImage->SetRegions( size );
inputImage->SetSpacing( spacing );
inputImage->SetOrigin( origin );
inputImage->SetDirection( direction );
try
{
inputImage->Allocate();
}
catch ( itk::ExceptionObject & err )
{
std::cerr << "ERROR: Failed to allocate test image" << std::endl;
std::cerr << err << std::endl;
return 1;
}
IteratorType it( inputImage, inputImage->GetLargestPossibleRegion() );
unsigned long nrPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();
double factor = itk::NumericTraits<PixelType>::max() / static_cast<double>(nrPixels);
PixelType pixval = 0;
unsigned long pixnr = 0;
for ( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
pixval = static_cast<PixelType>(
itk::Math::Floor<double>( pixnr * factor ) );
it.Set( pixval );
}
std::string testfile( "testimageMevisDicomTiff.dcm" );
writer->SetFileName( testfile );
writer->SetInput( inputImage );
reader->SetFileName( testfile );
std::string task( "" );
try
{
task = "Writing";
writer->Update();
task = "Reading";
reader->Update();
}
catch ( itk::ExceptionObject & err )
{
std::cerr << "ERROR: " << task << " mevis dicomtiff failed in . " << std::endl;
std::cerr << err << std::endl;
return 1;
}
std::cerr << "\nPrintSelf():\n" << std::endl;
typename itk::ImageIOBase::Pointer mevisIO = reader->GetImageIO();
mevisIO->Print( std::cerr, 2 );
typename ImageType::Pointer outputImage = reader->GetOutput();
bool same = true;
same &= size == outputImage->GetLargestPossibleRegion().GetSize();
same &= spacing == outputImage->GetSpacing();
same &= origin == outputImage->GetOrigin();
same &= direction == outputImage->GetDirection();
if ( !same )
{
std::cerr << "ERROR: image properties are not preserved" << std::endl;
std::cerr << "Original properties:" << std::endl;
inputImage->Print( std::cerr, 0 );
std::cerr << "After write/read:" << std::endl;
outputImage->Print( std::cerr, 0 );
return 1;
}
typename ComparisonFilterType::Pointer comparisonFilter = ComparisonFilterType::New();
comparisonFilter->SetTestInput( outputImage );
comparisonFilter->SetValidInput( inputImage );
comparisonFilter->Update();
unsigned long nrDiffPixels = comparisonFilter->GetNumberOfPixelsWithDifferences();
if ( nrDiffPixels > 0 )
{
std::cerr << "ERROR: the pixel values are not correct after write/read" << std::endl;
return 1;
}
return 0;
} // end templated function
int main( int argc, char *argv[] )
{
#ifdef _ELASTIX_USE_MEVISDICOMTIFF
/** Test for 2d, 3d, and 4d images */
int ret2d = testMevis<2>();
int ret3d = testMevis<3>();
int ret4d = testMevis<4>();
/** Return a value. */
return (ret2d | ret3d | ret4d);
#else
std::cerr << "Elastix was not built with Mevis DicomTiff support, so this test is not relevant." << std::endl;
return 0;
#endif
} // end main
<commit_msg>-BUG: I didn't update the MevisDicomTiff test to use .tif as filename...<commit_after>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#include <iomanip>
#ifdef _ELASTIX_USE_MEVISDICOMTIFF
#include "itkUseMevisDicomTiff.h"
#endif
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOBase.h"
#include <string>
#include "itkMath.h"
#include "itkTestingComparisonImageFilter.h"
//-------------------------------------------------------------------------------------
// This test tests the itkMevisDicomTiffImageIO library. The test is performed
// in 2D, 3D, and 4D, for a unsigned char image. An artificial image is generated,
// written to disk, read from disk, and compared to the original.
template< unsigned int Dimension >
int testMevis( void )
{
std::cerr << "Testing write/read of " << Dimension << "D image..." << std::endl;
/** Some basic type definitions. */
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageFileWriter< ImageType > WriterType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::Testing::ComparisonImageFilter<
ImageType, ImageType > ComparisonFilterType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef typename ImageType::PointType OriginType;
typedef typename ImageType::DirectionType DirectionType;
typedef itk::ImageRegionIterator< ImageType > IteratorType;
typename WriterType::Pointer writer = WriterType::New();
typename ReaderType::Pointer reader = ReaderType::New();
typename ImageType::Pointer inputImage = ImageType::New();
SizeType size;
SpacingType spacing;
OriginType origin;
DirectionType direction;
direction.Fill( 0.0 );
for( unsigned int i = 0; i < Dimension; ++i )
{
size[i] = 20+i;
spacing[i] = 0.5 + 0.1*i;
origin[i] = 5 + 3*i;
direction[i][i] = 1.0; // default, will be changed below
}
// 4th dimension origin/spacing are lost using dcm/tiff format!
if (Dimension == 4)
{
// default values
spacing[3] = 1.0;
origin[3] = 0.0;
}
// Difficult direction cosines:
if ( Dimension == 2 )
{
// Test flips
direction[0][0] = 1; direction[0][1] = 0;
direction[1][0] = 0; direction[1][1] = -1;
}
else if ( Dimension == 3 )
{
// Test axis permutations
// RM: won't work, because dicom always assume right hand
// coordinate system when reconstructing the third direction
/*
direction[0][0] = 1; direction[0][1] = 0; direction[0][2] = 0;
direction[1][0] = 0; direction[1][1] = 0; direction[1][2] = 1;
direction[2][0] = 0; direction[2][1] = 1; direction[2][2] = 0;
*/
// this works:
direction[0][0] = 1; direction[0][1] = 0; direction[0][2] = 0;
direction[1][0] = 0; direction[1][1] = 0; direction[1][2] = -1;
direction[2][0] = 0; direction[2][1] = 1; direction[2][2] = 0;
}
else if ( Dimension == 4 )
{
// Test 4D. RM: also make sure it is a right hand coordinate system
direction[0][0] = 1; direction[0][1] = 0; direction[0][2] = 0; direction[0][3] = 0;
direction[1][0] = 0; direction[1][1] = 0; direction[1][2] = -1; direction[1][3] = 0;
direction[2][0] = 0; direction[2][1] = 1; direction[2][2] = 0; direction[2][3] = 0;
direction[3][0] = 0; direction[3][1] = 0; direction[3][2] = 0; direction[3][3] = 1;
}
/** Generate image with gradually increasing pixel values. */
inputImage->SetRegions( size );
inputImage->SetSpacing( spacing );
inputImage->SetOrigin( origin );
inputImage->SetDirection( direction );
try
{
inputImage->Allocate();
}
catch ( itk::ExceptionObject & err )
{
std::cerr << "ERROR: Failed to allocate test image" << std::endl;
std::cerr << err << std::endl;
return 1;
}
IteratorType it( inputImage, inputImage->GetLargestPossibleRegion() );
unsigned long nrPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();
double factor = itk::NumericTraits<PixelType>::max() / static_cast<double>(nrPixels);
PixelType pixval = 0;
unsigned long pixnr = 0;
for ( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
pixval = static_cast<PixelType>(
itk::Math::Floor<double>( pixnr * factor ) );
it.Set( pixval );
}
std::string testfile( "testimageMevisDicomTiff.tif" );
writer->SetFileName( testfile );
writer->SetInput( inputImage );
reader->SetFileName( testfile );
std::string task( "" );
try
{
task = "Writing";
writer->Update();
task = "Reading";
reader->Update();
}
catch ( itk::ExceptionObject & err )
{
std::cerr << "ERROR: " << task << " mevis dicomtiff failed in . " << std::endl;
std::cerr << err << std::endl;
return 1;
}
std::cerr << "\nPrintSelf():\n" << std::endl;
typename itk::ImageIOBase::Pointer mevisIO = reader->GetImageIO();
mevisIO->Print( std::cerr, 2 );
typename ImageType::Pointer outputImage = reader->GetOutput();
bool same = true;
same &= size == outputImage->GetLargestPossibleRegion().GetSize();
same &= spacing == outputImage->GetSpacing();
same &= origin == outputImage->GetOrigin();
same &= direction == outputImage->GetDirection();
if ( !same )
{
std::cerr << "ERROR: image properties are not preserved" << std::endl;
std::cerr << "Original properties:" << std::endl;
inputImage->Print( std::cerr, 0 );
std::cerr << "After write/read:" << std::endl;
outputImage->Print( std::cerr, 0 );
return 1;
}
typename ComparisonFilterType::Pointer comparisonFilter = ComparisonFilterType::New();
comparisonFilter->SetTestInput( outputImage );
comparisonFilter->SetValidInput( inputImage );
comparisonFilter->Update();
unsigned long nrDiffPixels = comparisonFilter->GetNumberOfPixelsWithDifferences();
if ( nrDiffPixels > 0 )
{
std::cerr << "ERROR: the pixel values are not correct after write/read" << std::endl;
return 1;
}
return 0;
} // end templated function
int main( int argc, char *argv[] )
{
#ifdef _ELASTIX_USE_MEVISDICOMTIFF
/** Test for 2d, 3d, and 4d images */
int ret2d = testMevis<2>();
int ret3d = testMevis<3>();
int ret4d = testMevis<4>();
/** Return a value. */
return (ret2d | ret3d | ret4d);
#else
std::cerr << "Elastix was not built with Mevis DicomTiff support, so this test is not relevant." << std::endl;
return 0;
#endif
} // end main
<|endoftext|> |
<commit_before>// For stat, getcwd
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <libport/file-system.hh>
// For bad_alloc
#include <exception>
#include <boost/format.hpp>
#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
#include <runner/raise.hh>
namespace object
{
using boost::format;
/*------------.
| C++ methods |
`------------*/
const Path::value_type& Path::value_get() const
{
return path_;
}
/*-------------.
| Urbi methods |
`-------------*/
// Construction
Path::Path()
: path_("/")
{
proto_add(proto);
}
Path::Path(rPath model)
: path_(model->value_get())
{
proto_add(model);
}
Path::Path(const std::string& value)
: path_(value)
{
proto_add(proto ? proto : object_class);
}
void Path::init(const std::string& path)
{
path_ = path;
}
// Global informations
rPath Path::cwd()
{
return new Path(libport::get_current_directory());
}
// Stats
bool Path::absolute()
{
return path_.absolute_get();
}
bool Path::exists()
{
if (!::access(path_.to_string().c_str(), F_OK))
return true;
if (errno == ENOENT)
return false;
handle_any_error();
}
struct stat Path::stat()
{
struct stat res;
if (::stat(path_.to_string().c_str(), &res))
handle_any_error();
return res;
}
bool Path::is_dir()
{
return stat().st_mode & S_IFDIR;
}
bool Path::is_reg()
{
return stat().st_mode & S_IFREG;
}
bool Path::readable()
{
if (!::access(path_.to_string().c_str(), R_OK))
return true;
if (errno == EACCES)
return false;
handle_any_error();
}
bool Path::writable()
{
if (!::access(path_.to_string().c_str(), W_OK))
return true;
if (errno == EACCES || errno == EROFS)
return false;
handle_any_error();
}
// Operations
std::string Path::basename()
{
return path_.basename();
}
rPath Path::cd()
{
if (chdir(as_string().c_str()))
handle_any_error();
return cwd();
}
rPath Path::path_concat(rPath other)
{
return new Path(path_ / other->path_);
}
rPath Path::string_concat(rString other)
{
return path_concat(new Path(other->value_get()));
}
OVERLOAD_TYPE(concat_bouncer, 1, 1,
Path, &Path::path_concat,
String, &Path::string_concat);
rPath Path::dirname()
{
return new Path(path_.dirname());
}
rObject Path::open()
{
if (is_dir())
return new Directory(path_);
if (is_reg())
return new File(path_);
runner::raise_primitive_error(str(format("Unsupported file type: %s.") %
path_));
}
// Conversions
std::string Path::as_string()
{
return path_.to_string();
}
std::string Path::as_printable()
{
return str(format("Path(\"%s\")") % as_string());
}
rList Path::as_list()
{
List::value_type res;
foreach (const std::string& c, path_.components())
res << new String(c);
return new List(res);
}
/*--------.
| Details |
`--------*/
void Path::handle_any_error()
{
runner::raise_primitive_error(str(format("%1%: %2%") %
strerror(errno) % path_));
}
/*---------------.
| Binding system |
`---------------*/
void Path::initialize(CxxObject::Binder<Path>& bind)
{
bind(SYMBOL(absolute), &Path::absolute);
bind(SYMBOL(asList), &Path::as_list);
bind(SYMBOL(asPrintable), &Path::as_printable);
bind(SYMBOL(asString), &Path::as_string);
bind(SYMBOL(basename), &Path::basename);
bind(SYMBOL(cd), &Path::cd);
bind(SYMBOL(cwd), &Path::cwd);
bind(SYMBOL(dirname), &Path::dirname);
bind(SYMBOL(exists), &Path::exists);
bind(SYMBOL(init), &Path::init);
bind(SYMBOL(isDir), &Path::is_dir);
bind(SYMBOL(isReg), &Path::is_reg);
bind(SYMBOL(open), &Path::open);
bind(SYMBOL(readable), &Path::readable);
bind(SYMBOL(SLASH), concat_bouncer);
bind(SYMBOL(writable), &Path::writable);
}
rObject
Path::proto_make()
{
#ifdef WIN32
return new Path("C:\\");
#else
return new Path("/");
#endif
}
URBI_CXX_OBJECT_REGISTER(Path);
}
<commit_msg>Catch errors from "libport::path".<commit_after>// For stat, getcwd
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <libport/file-system.hh>
// For bad_alloc
#include <exception>
#include <boost/format.hpp>
#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
#include <runner/raise.hh>
namespace object
{
using boost::format;
/*------------.
| C++ methods |
`------------*/
const Path::value_type& Path::value_get() const
{
return path_;
}
/*-------------.
| Urbi methods |
`-------------*/
// Construction
Path::Path()
: path_("/")
{
proto_add(proto);
}
Path::Path(rPath model)
: path_(model->value_get())
{
proto_add(model);
}
Path::Path(const std::string& value)
: path_(value)
{
proto_add(proto ? proto : object_class);
}
void Path::init(const std::string& path)
{
path_ = path;
}
// Global informations
rPath Path::cwd()
{
return new Path(libport::get_current_directory());
}
// Stats
bool Path::absolute()
{
return path_.absolute_get();
}
bool Path::exists()
{
if (!::access(path_.to_string().c_str(), F_OK))
return true;
if (errno == ENOENT)
return false;
handle_any_error();
}
struct stat Path::stat()
{
struct stat res;
if (::stat(path_.to_string().c_str(), &res))
handle_any_error();
return res;
}
bool Path::is_dir()
{
return stat().st_mode & S_IFDIR;
}
bool Path::is_reg()
{
return stat().st_mode & S_IFREG;
}
bool Path::readable()
{
if (!::access(path_.to_string().c_str(), R_OK))
return true;
if (errno == EACCES)
return false;
handle_any_error();
}
bool Path::writable()
{
if (!::access(path_.to_string().c_str(), W_OK))
return true;
if (errno == EACCES || errno == EROFS)
return false;
handle_any_error();
}
// Operations
std::string Path::basename()
{
return path_.basename();
}
rPath Path::cd()
{
if (chdir(as_string().c_str()))
handle_any_error();
return cwd();
}
rPath Path::path_concat(rPath other)
{
try
{
return new Path(path_ / other->path_);
}
catch (const libport::path::invalid_path& e)
{
runner::raise_primitive_error(e.what());
}
}
rPath Path::string_concat(rString other)
{
return path_concat(new Path(other->value_get()));
}
OVERLOAD_TYPE(concat_bouncer, 1, 1,
Path, &Path::path_concat,
String, &Path::string_concat);
rPath Path::dirname()
{
return new Path(path_.dirname());
}
rObject Path::open()
{
if (is_dir())
return new Directory(path_);
if (is_reg())
return new File(path_);
runner::raise_primitive_error(str(format("Unsupported file type: %s.") %
path_));
}
// Conversions
std::string Path::as_string()
{
return path_.to_string();
}
std::string Path::as_printable()
{
return str(format("Path(\"%s\")") % as_string());
}
rList Path::as_list()
{
List::value_type res;
foreach (const std::string& c, path_.components())
res << new String(c);
return new List(res);
}
/*--------.
| Details |
`--------*/
void Path::handle_any_error()
{
runner::raise_primitive_error(str(format("%1%: %2%") %
strerror(errno) % path_));
}
/*---------------.
| Binding system |
`---------------*/
void Path::initialize(CxxObject::Binder<Path>& bind)
{
bind(SYMBOL(absolute), &Path::absolute);
bind(SYMBOL(asList), &Path::as_list);
bind(SYMBOL(asPrintable), &Path::as_printable);
bind(SYMBOL(asString), &Path::as_string);
bind(SYMBOL(basename), &Path::basename);
bind(SYMBOL(cd), &Path::cd);
bind(SYMBOL(cwd), &Path::cwd);
bind(SYMBOL(dirname), &Path::dirname);
bind(SYMBOL(exists), &Path::exists);
bind(SYMBOL(init), &Path::init);
bind(SYMBOL(isDir), &Path::is_dir);
bind(SYMBOL(isReg), &Path::is_reg);
bind(SYMBOL(open), &Path::open);
bind(SYMBOL(readable), &Path::readable);
bind(SYMBOL(SLASH), concat_bouncer);
bind(SYMBOL(writable), &Path::writable);
}
rObject
Path::proto_make()
{
#ifdef WIN32
return new Path("C:\\");
#else
return new Path("/");
#endif
}
URBI_CXX_OBJECT_REGISTER(Path);
}
<|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 "chrome/test/nacl/nacl_sandbox_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_switches.h"
namespace {
// Base url is specified in nacl_test.
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
} // anonymous namespace
NaClSandboxTest::NaClSandboxTest() : NaClTest() {
// Append the --test-nacl-sandbox=$TESTDLL flag before launching.
FilePath dylibDir;
PathService::Get(base::DIR_EXE, &dylibDir);
#if defined(OS_MACOSX)
dylibDir = dylibDir.AppendASCII("libnacl_security_tests.dylib");
launch_arguments_.AppendSwitchWithValue(switches::kTestNaClSandbox,
dylibDir.value());
#elif defined(OS_WIN)
// Let the NaCl process detect if it is 64-bit or not and hack on
// the appropriate suffix to this dll.
dylibDir = dylibDir.AppendASCII("nacl_security_tests");
launch_arguments_.AppendSwitchWithValue(switches::kTestNaClSandbox,
dylibDir.value());
#elif defined(OS_LINUX)
// We currently do not test the Chrome Linux SUID or seccomp sandboxes.
#endif
}
NaClSandboxTest::~NaClSandboxTest() {}
TEST_F(NaClSandboxTest, NaClOuterSBTest) {
// Load a helloworld .nexe to trigger the nacl loader test.
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
<commit_msg>Mark NaClSandboxTest.NaClOuterSBTest as flaky.<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 "chrome/test/nacl/nacl_sandbox_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_switches.h"
namespace {
// Base url is specified in nacl_test.
const FilePath::CharType kSrpcHwHtmlFileName[] =
FILE_PATH_LITERAL("srpc_hw.html");
} // anonymous namespace
NaClSandboxTest::NaClSandboxTest() : NaClTest() {
// Append the --test-nacl-sandbox=$TESTDLL flag before launching.
FilePath dylibDir;
PathService::Get(base::DIR_EXE, &dylibDir);
#if defined(OS_MACOSX)
dylibDir = dylibDir.AppendASCII("libnacl_security_tests.dylib");
launch_arguments_.AppendSwitchWithValue(switches::kTestNaClSandbox,
dylibDir.value());
#elif defined(OS_WIN)
// Let the NaCl process detect if it is 64-bit or not and hack on
// the appropriate suffix to this dll.
dylibDir = dylibDir.AppendASCII("nacl_security_tests");
launch_arguments_.AppendSwitchWithValue(switches::kTestNaClSandbox,
dylibDir.value());
#elif defined(OS_LINUX)
// We currently do not test the Chrome Linux SUID or seccomp sandboxes.
#endif
}
NaClSandboxTest::~NaClSandboxTest() {}
// http://crbug.com/50121
TEST_F(NaClSandboxTest, FLAKY_NaClOuterSBTest) {
// Load a helloworld .nexe to trigger the nacl loader test.
FilePath test_file(kSrpcHwHtmlFileName);
RunTest(test_file, action_max_timeout_ms());
}
<|endoftext|> |
<commit_before>/**
* C S O U N D V S T
*
* A VST plugin version of Csound, with Python scripting.
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CsoundFile.hpp"
#include "CppSound.hpp"
#include "System.hpp"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
extern "C"
{
extern MYFLT timtot;
extern void csoundDefaultMidiOpen(void *csound);
};
CppSound::CppSound() : isCompiled(false),
isPerforming(false),
csound(0),
spoutSize(0),
go(false)
{
csound = (ENVIRON *)csoundCreate(this);
}
CppSound::~CppSound()
{
if(csound)
{
csoundDestroy(csound);
csound = 0;
}
}
int CppSound::perform()
{
int argc = 0;
char **argv = 0;
scatterArgs(getCommand(), &argc, &argv);
int returnValue = perform(argc, argv);
deleteArgs(argc, argv);
return returnValue;
}
int CppSound::perform(int argc, char **argv)
{
double beganAt = double(clock()) / double(CLOCKS_PER_SEC);
isCompiled = false;
isPerforming = false;
go = false;
message("BEGAN CppSound::perform(%d, %x)...\n", argc, argv);
if(argc <= 0)
{
message("ENDED CppSound::perform without compiling or performing.\n");
return 0;
}
int returnValue = compile(argc, argv);
if(returnValue == -1)
{
return returnValue;
}
for(isPerforming = true; isPerforming && go; )
{
isPerforming = !performKsmps();
}
csoundCleanup(csound);
double endedAt = double(clock()) / double(CLOCKS_PER_SEC);
double elapsed = endedAt - beganAt;
message("Elapsed time = %f seconds.\n", elapsed);
message("ENDED CppSound::perform.\n");
isCompiled = false;
isPerforming = false;
return 1;
}
void CppSound::stop()
{
message("RECEIVED CppSound::stop...\n");
isCompiled = false;
isPerforming = false;
go = false;
}
void CppSound::reset()
{
csoundReset(csound);
}
int CppSound::compile(int argc, char **argv)
{
message("BEGAN CppSound::compile(%d, %x)...\n", argc, argv);
go = false;
int returnValue = csoundCompile(csound, argc, argv);
spoutSize = ksmps * nchnls * sizeof(MYFLT);
if(returnValue)
{
isCompiled = false;
}
else
{
isCompiled = true;
go = true;
}
message("ENDED CppSound::compile.\n");
return returnValue;
}
int CppSound::compile()
{
message("BEGAN CppSound::compile()...\n");
int argc = 0;
char **argv = 0;
if(getCommand().length() <= 0)
{
message("No Csound command.\n");
return -1;
}
scatterArgs(getCommand(), &argc, &argv);
int returnValue = compile(argc, argv);
deleteArgs(argc, argv);
message("ENDED CppSound::compile.\n");
return returnValue;
}
int CppSound::performKsmps()
{
return csoundPerformKsmps(csound);
}
void CppSound::cleanup()
{
csoundCleanup(csound);
}
MYFLT *CppSound::getSpin()
{
return csoundGetSpin(csound);
}
MYFLT *CppSound::getSpout()
{
return csoundGetSpout(csound);
}
void CppSound::setMessageCallback(void (*messageCallback)(void *hostData, const char *format, va_list args))
{
csoundSetMessageCallback(csound, messageCallback);
}
int CppSound::getKsmps()
{
return csoundGetKsmps(csound);
}
int CppSound::getNchnls()
{
return csoundGetNchnls(csound);
}
int CppSound::getMessageLevel()
{
return csoundGetMessageLevel(csound);
}
void CppSound::setMessageLevel(int messageLevel)
{
csoundSetMessageLevel(csound, messageLevel);
}
void CppSound::throwMessage(const char *format,...)
{
va_list args;
va_start(args, format);
csoundThrowMessageV(csound, format, args);
va_end(args);
}
void CppSound::throwMessageV(const char *format, va_list args)
{
csoundThrowMessageV(csound, format, args);
}
void CppSound::setThrowMessageCallback(void (*throwCallback)(void *csound_, const char *format, va_list args))
{
csoundSetThrowMessageCallback(csound, throwCallback);
}
int CppSound::isExternalMidiEnabled()
{
return csoundIsExternalMidiEnabled(csound);
}
void CppSound::setExternalMidiEnabled(int enabled)
{
csoundSetExternalMidiEnabled(csound, enabled);
}
void CppSound::setExternalMidiOpenCallback(void (*midiOpen)(void *csound))
{
csoundSetExternalMidiOpenCallback(csound, midiOpen);
}
void CppSound::setExternalMidiReadCallback(int (*midiReadCallback)(void *ownerData, unsigned char *midiData, int size))
{
csoundSetExternalMidiReadCallback(csound, midiReadCallback);
}
void CppSound::setExternalMidiCloseCallback(void (*midiClose)(void *csound))
{
csoundSetExternalMidiCloseCallback(csound, midiClose);
}
void CppSound::defaultMidiOpen()
{
csoundDefaultMidiOpen(csound);
}
int CppSound::isScorePending()
{
return csoundIsScorePending(csound);
}
void CppSound::setScorePending(int pending)
{
csoundSetScorePending(csound, pending);
}
void CppSound::setScoreOffsetSeconds(MYFLT offset)
{
csoundSetScoreOffsetSeconds(csound, offset);
}
MYFLT CppSound::getScoreOffsetSeconds()
{
return csoundGetScoreOffsetSeconds(csound);
}
void CppSound::rewindScore()
{
csoundRewindScore(csound);
}
MYFLT CppSound::getSr()
{
return csoundGetSr(csound);
}
MYFLT CppSound::getKr()
{
return csoundGetKr(csound);
}
int CppSound::appendOpcode(char *opname, int dsblksiz, int thread, char *outypes, char *intypes, SUBR iopadr, SUBR kopadr, SUBR aopadr, SUBR dopadr)
{
return csoundAppendOpcode(csound, opname, dsblksiz, thread, outypes, intypes, iopadr, kopadr, aopadr, dopadr);
}
void CppSound::message(const char *format,...)
{
va_list args;
va_start(args, format);
csoundMessageV(csound, format, args);
va_end(args);
}
void CppSound::messageV(const char *format, va_list args)
{
csoundMessageV(csound, format, args);
}
int CppSound::loadExternals()
{
return csoundLoadExternals(csound);
}
size_t CppSound::getSpoutSize() const
{
return spoutSize;
}
void CppSound::inputMessage(std::string istatement)
{
csound->InputMessage(csound, istatement.c_str());
}
void *CppSound::getCsound()
{
return csound;
}
void CppSound::write(const char *text)
{
csoundMessage(getCsound(), text);
}
long CppSound::getThis()
{
return (long) this;
}
bool CppSound::getIsCompiled() const
{
return isCompiled;
}
void CppSound::setIsPerforming(bool isPerforming)
{
this->isPerforming = isPerforming;
}
bool CppSound::getIsPerforming() const
{
return isPerforming;
}
bool CppSound::getIsGo() const
{
return go;
}
/**
* Glue for incomplete Csound API.
*/
extern "C"
{
#ifdef WIN32
int XOpenDisplay(char *)
{
return 1;
}
#endif
};
<commit_msg>Attempt to run as csd if command line is csd style.<commit_after>/**
* C S O U N D V S T
*
* A VST plugin version of Csound, with Python scripting.
*
* L I C E N S E
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CsoundFile.hpp"
#include "CppSound.hpp"
#include "System.hpp"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
extern "C"
{
extern MYFLT timtot;
extern void csoundDefaultMidiOpen(void *csound);
};
CppSound::CppSound() : isCompiled(false),
isPerforming(false),
csound(0),
spoutSize(0),
go(false)
{
csound = (ENVIRON *)csoundCreate(this);
}
CppSound::~CppSound()
{
if(csound)
{
csoundDestroy(csound);
csound = 0;
}
}
int CppSound::perform()
{
int returnValue = 0;
int argc = 0;
char **argv = 0;
std::string command = getCommand();
if(command.find("-") == 0)
{
const char *args[] = {"csound", getFilename().c_str(), 0};
returnValue = perform(2, (char **)args);
}
else
{
scatterArgs(getCommand(), &argc, &argv);
returnValue = perform(argc, argv);
}
deleteArgs(argc, argv);
return returnValue;
}
int CppSound::perform(int argc, char **argv)
{
double beganAt = double(clock()) / double(CLOCKS_PER_SEC);
isCompiled = false;
isPerforming = false;
go = false;
message("BEGAN CppSound::perform(%d, %x)...\n", argc, argv);
if(argc <= 0)
{
message("ENDED CppSound::perform without compiling or performing.\n");
return 0;
}
int returnValue = compile(argc, argv);
if(returnValue == -1)
{
return returnValue;
}
for(isPerforming = true; isPerforming && go; )
{
isPerforming = !performKsmps();
}
csoundCleanup(csound);
double endedAt = double(clock()) / double(CLOCKS_PER_SEC);
double elapsed = endedAt - beganAt;
message("Elapsed time = %f seconds.\n", elapsed);
message("ENDED CppSound::perform.\n");
isCompiled = false;
isPerforming = false;
return 1;
}
void CppSound::stop()
{
message("RECEIVED CppSound::stop...\n");
isCompiled = false;
isPerforming = false;
go = false;
}
void CppSound::reset()
{
csoundReset(csound);
}
int CppSound::compile(int argc, char **argv)
{
message("BEGAN CppSound::compile(%d, %x)...\n", argc, argv);
go = false;
int returnValue = csoundCompile(csound, argc, argv);
spoutSize = ksmps * nchnls * sizeof(MYFLT);
if(returnValue)
{
isCompiled = false;
}
else
{
isCompiled = true;
go = true;
}
message("ENDED CppSound::compile.\n");
return returnValue;
}
int CppSound::compile()
{
message("BEGAN CppSound::compile()...\n");
int argc = 0;
char **argv = 0;
if(getCommand().length() <= 0)
{
message("No Csound command.\n");
return -1;
}
scatterArgs(getCommand(), &argc, &argv);
int returnValue = compile(argc, argv);
deleteArgs(argc, argv);
message("ENDED CppSound::compile.\n");
return returnValue;
}
int CppSound::performKsmps()
{
return csoundPerformKsmps(csound);
}
void CppSound::cleanup()
{
csoundCleanup(csound);
}
MYFLT *CppSound::getSpin()
{
return csoundGetSpin(csound);
}
MYFLT *CppSound::getSpout()
{
return csoundGetSpout(csound);
}
void CppSound::setMessageCallback(void (*messageCallback)(void *hostData, const char *format, va_list args))
{
csoundSetMessageCallback(csound, messageCallback);
}
int CppSound::getKsmps()
{
return csoundGetKsmps(csound);
}
int CppSound::getNchnls()
{
return csoundGetNchnls(csound);
}
int CppSound::getMessageLevel()
{
return csoundGetMessageLevel(csound);
}
void CppSound::setMessageLevel(int messageLevel)
{
csoundSetMessageLevel(csound, messageLevel);
}
void CppSound::throwMessage(const char *format,...)
{
va_list args;
va_start(args, format);
csoundThrowMessageV(csound, format, args);
va_end(args);
}
void CppSound::throwMessageV(const char *format, va_list args)
{
csoundThrowMessageV(csound, format, args);
}
void CppSound::setThrowMessageCallback(void (*throwCallback)(void *csound_, const char *format, va_list args))
{
csoundSetThrowMessageCallback(csound, throwCallback);
}
int CppSound::isExternalMidiEnabled()
{
return csoundIsExternalMidiEnabled(csound);
}
void CppSound::setExternalMidiEnabled(int enabled)
{
csoundSetExternalMidiEnabled(csound, enabled);
}
void CppSound::setExternalMidiOpenCallback(void (*midiOpen)(void *csound))
{
csoundSetExternalMidiOpenCallback(csound, midiOpen);
}
void CppSound::setExternalMidiReadCallback(int (*midiReadCallback)(void *ownerData, unsigned char *midiData, int size))
{
csoundSetExternalMidiReadCallback(csound, midiReadCallback);
}
void CppSound::setExternalMidiCloseCallback(void (*midiClose)(void *csound))
{
csoundSetExternalMidiCloseCallback(csound, midiClose);
}
void CppSound::defaultMidiOpen()
{
csoundDefaultMidiOpen(csound);
}
int CppSound::isScorePending()
{
return csoundIsScorePending(csound);
}
void CppSound::setScorePending(int pending)
{
csoundSetScorePending(csound, pending);
}
void CppSound::setScoreOffsetSeconds(MYFLT offset)
{
csoundSetScoreOffsetSeconds(csound, offset);
}
MYFLT CppSound::getScoreOffsetSeconds()
{
return csoundGetScoreOffsetSeconds(csound);
}
void CppSound::rewindScore()
{
csoundRewindScore(csound);
}
MYFLT CppSound::getSr()
{
return csoundGetSr(csound);
}
MYFLT CppSound::getKr()
{
return csoundGetKr(csound);
}
int CppSound::appendOpcode(char *opname, int dsblksiz, int thread, char *outypes, char *intypes, SUBR iopadr, SUBR kopadr, SUBR aopadr, SUBR dopadr)
{
return csoundAppendOpcode(csound, opname, dsblksiz, thread, outypes, intypes, iopadr, kopadr, aopadr, dopadr);
}
void CppSound::message(const char *format,...)
{
va_list args;
va_start(args, format);
csoundMessageV(csound, format, args);
va_end(args);
}
void CppSound::messageV(const char *format, va_list args)
{
csoundMessageV(csound, format, args);
}
int CppSound::loadExternals()
{
return csoundLoadExternals(csound);
}
size_t CppSound::getSpoutSize() const
{
return spoutSize;
}
void CppSound::inputMessage(std::string istatement)
{
csound->InputMessage(csound, istatement.c_str());
}
void *CppSound::getCsound()
{
return csound;
}
void CppSound::write(const char *text)
{
csoundMessage(getCsound(), text);
}
long CppSound::getThis()
{
return (long) this;
}
bool CppSound::getIsCompiled() const
{
return isCompiled;
}
void CppSound::setIsPerforming(bool isPerforming)
{
this->isPerforming = isPerforming;
}
bool CppSound::getIsPerforming() const
{
return isPerforming;
}
bool CppSound::getIsGo() const
{
return go;
}
/**
* Glue for incomplete Csound API.
*/
extern "C"
{
#ifdef WIN32
int XOpenDisplay(char *)
{
return 1;
}
#endif
};
<|endoftext|> |
<commit_before>//
// MIT License
//
// Copyright 2017-2019
//
// 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 <boost/core/ignore_unused.hpp>
#include "cpu.hh"
#include "instruction.hh"
#include "interrupts.hh"
#include "memory.hh"
#include "opcode.hh"
#include "registers.hh"
#include "status_register.hh"
using namespace jones;
class cpu::impl final {
public:
explicit impl(const memory &memory) : memory_(memory), ram_(), status_register_(), registers_() {}
void initialize() {
std::fill(ram_, ram_ + ram_size, 0);
status_register_.set(status_flag::D);
status_register_.set(status_flag::B1);
status_register_.set(status_flag::B2);
registers_.set(register_type::AC, 0x00);
registers_.set(register_type::X, 0x00);
registers_.set(register_type::Y, 0x00);
registers_.set(register_type::SP, 0xFD);
interrupts_.set_state(interrupt_type::IRQ, false);
interrupts_.set_state(interrupt_type::NMI, false);
// frame irq is enabled
memory_.write(0x4017, 0x00);
// all channels disabled
memory_.write(0x4015, 0x00);
// setting to initial pc address
const auto reset_vector = interrupts_.get_vector(interrupt_type::RESET);
const auto initial_pc = memory_.read(reset_vector);
registers_.set(register_type::PC, initial_pc);
}
void step() {}
void reset() {
initialize();
}
void run() {
}
uint8_t read(uint16_t address) {
boost::ignore_unused(address);
return 0;
}
void write(uint16_t address, uint8_t data) {
boost::ignore_unused(address);
boost::ignore_unused(data);
}
cpu_state get_state() {
return cpu_state();
}
private:
static constexpr int ram_size = 2048;
const memory &memory_;
uint8_t ram_[ram_size];
status_register status_register_;
registers registers_;
interrupts interrupts_;
};
cpu::cpu(const memory &memory) : impl_(new impl(memory)) {}
cpu::~cpu() = default;
void cpu::step() { impl_->step(); }
void cpu::reset() { impl_->reset(); }
void cpu::run() { impl_->run(); }
uint8_t cpu::read(uint16_t address) {
return impl_->read(address);
}
void cpu::write(uint16_t address, uint8_t data) {
impl_->write(address, data);
}
cpu_state cpu::get_state() {
return impl_->get_state();
}
void cpu::initialize() {
impl_->initialize();
}
<commit_msg>fixing tidy warning<commit_after>//
// MIT License
//
// Copyright 2017-2019
//
// 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 <boost/core/ignore_unused.hpp>
#include "cpu.hh"
#include "instruction.hh"
#include "interrupts.hh"
#include "memory.hh"
#include "opcode.hh"
#include "registers.hh"
#include "status_register.hh"
using namespace jones;
class cpu::impl final {
public:
explicit impl(const memory &memory) : memory_(memory), ram_(), status_register_(), registers_(), interrupts_() {}
void initialize() {
std::fill(ram_, ram_ + ram_size, 0);
status_register_.set(status_flag::D);
status_register_.set(status_flag::B1);
status_register_.set(status_flag::B2);
registers_.set(register_type::AC, 0x00);
registers_.set(register_type::X, 0x00);
registers_.set(register_type::Y, 0x00);
registers_.set(register_type::SP, 0xFD);
interrupts_.set_state(interrupt_type::IRQ, false);
interrupts_.set_state(interrupt_type::NMI, false);
// frame irq is enabled
memory_.write(0x4017, 0x00);
// all channels disabled
memory_.write(0x4015, 0x00);
// setting to initial pc address
const auto reset_vector = interrupts_.get_vector(interrupt_type::RESET);
const auto initial_pc = memory_.read(reset_vector);
registers_.set(register_type::PC, initial_pc);
}
void step() {}
void reset() {
initialize();
}
void run() {
}
uint8_t read(uint16_t address) {
boost::ignore_unused(address);
return 0;
}
void write(uint16_t address, uint8_t data) {
boost::ignore_unused(address);
boost::ignore_unused(data);
}
cpu_state get_state() {
return cpu_state();
}
private:
static constexpr int ram_size = 2048;
const memory &memory_;
uint8_t ram_[ram_size];
status_register status_register_;
registers registers_;
interrupts interrupts_;
};
cpu::cpu(const memory &memory) : impl_(new impl(memory)) {}
cpu::~cpu() = default;
void cpu::step() { impl_->step(); }
void cpu::reset() { impl_->reset(); }
void cpu::run() { impl_->run(); }
uint8_t cpu::read(uint16_t address) {
return impl_->read(address);
}
void cpu::write(uint16_t address, uint8_t data) {
impl_->write(address, data);
}
cpu_state cpu::get_state() {
return impl_->get_state();
}
void cpu::initialize() {
impl_->initialize();
}
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2014 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "FSImageFactory.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "fs/ntfs.h"
#ifdef _WIN32
#include "fs/ntfs_win.h"
#define FSNTFS FSNTFSWIN
#endif
#include "fs/unknown.h"
#include "vhdfile.h"
#include "../stringtools.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <errno.h>
#endif
void PrintInfo(IFilesystem *fs)
{
Server->Log("FSINFO: blocksize="+nconvert(fs->getBlocksize())+" size="+nconvert(fs->getSize())+" has_error="+nconvert(fs->hasError())+" used_space="+nconvert(fs->calculateUsedSpace()), LL_DEBUG);
}
IFilesystem *FSImageFactory::createFilesystem(const std::wstring &pDev, bool read_ahead, bool background_priority, bool exclude_shadow_storage)
{
IFile *dev=Server->openFile(pDev, MODE_READ_DEVICE);
if(dev==NULL)
{
int last_error;
#ifdef _WIN32
last_error=GetLastError();
#else
last_error=errno;
#endif
Server->Log(L"Error opening device file ("+pDev+L") Errorcode: "+convert(last_error), LL_ERROR);
return NULL;
}
char buffer[1024];
_u32 rc=dev->Read(buffer, 1024);
if(rc!=1024)
{
Server->Log(L"Error reading data from device ("+pDev+L")", LL_ERROR);
return NULL;
}
Server->destroy(dev);
if(isNTFS(buffer) )
{
Server->Log(L"Filesystem type is ntfs ("+pDev+L")", LL_DEBUG);
FSNTFS *fs=new FSNTFS(pDev, read_ahead, background_priority);
#ifdef _WIN32
if(exclude_shadow_storage && pDev.find(L"HarddiskVolumeShadowCopy")!=std::string::npos)
{
fs->excludeFiles(pDev+L"\\System Volume Information", L"{3808876b-c176-4e48-b7ae-04046e6cc752}");
fs->excludeFile(pDev+L"\\pagefile.sys");
}
#endif
/*
int64 idx=0;
while(idx<fs->getSize()/fs->getBlocksize())
{
std::string b1;
std::string b2;
int64 idx_start=idx;
for(size_t i=0;i<100;++i)
{
b1+=nconvert((int)fs->readBlock(idx, NULL));
b2+=nconvert((int)fs2->readBlock(idx, NULL));
++idx;
}
if(b1!=b2)
{
Server->Log(nconvert(idx_start)+" fs1: "+b1, LL_DEBUG);
Server->Log(nconvert(idx_start)+" fs2: "+b2, LL_DEBUG);
}
}*/
if(fs->hasError())
{
Server->Log("NTFS has error", LL_WARNING);
delete fs;
Server->Log("Unknown filesystem type", LL_DEBUG);
FSUnknown *fs2=new FSUnknown(pDev, read_ahead, background_priority);
if(fs2->hasError())
{
delete fs2;
return NULL;
}
PrintInfo(fs2);
return fs2;
}
PrintInfo(fs);
return fs;
}
else
{
Server->Log("Unknown filesystem type", LL_DEBUG);
FSUnknown *fs=new FSUnknown(pDev, read_ahead, background_priority);
if(fs->hasError())
{
delete fs;
return NULL;
}
PrintInfo(fs);
return fs;
}
}
bool FSImageFactory::isNTFS(char *buffer)
{
if(buffer[3]=='N' && buffer[4]=='T' && buffer[5]=='F' && buffer[6]=='S')
{
return true;
}
else
{
return false;
}
}
IVHDFile *FSImageFactory::createVHDFile(const std::wstring &fn, bool pRead_only, uint64 pDstsize,
unsigned int pBlocksize, bool fast_mode, CompressionSetting compress)
{
return new VHDFile(fn, pRead_only, pDstsize, pBlocksize, fast_mode, compress!=CompressionSetting_None);
}
IVHDFile *FSImageFactory::createVHDFile(const std::wstring &fn, const std::wstring &parent_fn,
bool pRead_only, bool fast_mode, CompressionSetting compress)
{
return new VHDFile(fn, parent_fn, pRead_only, fast_mode, compress!=CompressionSetting_None);
}
void FSImageFactory::destroyVHDFile(IVHDFile *vhd)
{
delete ((VHDFile*)vhd);
}
<commit_msg>Don't use pagefile exclusion code<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2014 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "FSImageFactory.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "fs/ntfs.h"
#ifdef _WIN32
#include "fs/ntfs_win.h"
#define FSNTFS FSNTFSWIN
#endif
#include "fs/unknown.h"
#include "vhdfile.h"
#include "../stringtools.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <errno.h>
#endif
void PrintInfo(IFilesystem *fs)
{
Server->Log("FSINFO: blocksize="+nconvert(fs->getBlocksize())+" size="+nconvert(fs->getSize())+" has_error="+nconvert(fs->hasError())+" used_space="+nconvert(fs->calculateUsedSpace()), LL_DEBUG);
}
IFilesystem *FSImageFactory::createFilesystem(const std::wstring &pDev, bool read_ahead, bool background_priority, bool exclude_shadow_storage)
{
IFile *dev=Server->openFile(pDev, MODE_READ_DEVICE);
if(dev==NULL)
{
int last_error;
#ifdef _WIN32
last_error=GetLastError();
#else
last_error=errno;
#endif
Server->Log(L"Error opening device file ("+pDev+L") Errorcode: "+convert(last_error), LL_ERROR);
return NULL;
}
char buffer[1024];
_u32 rc=dev->Read(buffer, 1024);
if(rc!=1024)
{
Server->Log(L"Error reading data from device ("+pDev+L")", LL_ERROR);
return NULL;
}
Server->destroy(dev);
if(isNTFS(buffer) )
{
Server->Log(L"Filesystem type is ntfs ("+pDev+L")", LL_DEBUG);
FSNTFS *fs=new FSNTFS(pDev, read_ahead, background_priority);
/** NOT TESTED ENOUGH
if(exclude_shadow_storage && pDev.find(L"HarddiskVolumeShadowCopy")!=std::string::npos)
{
fs->excludeFiles(pDev+L"\\System Volume Information", L"{3808876b-c176-4e48-b7ae-04046e6cc752}");
fs->excludeFile(pDev+L"\\pagefile.sys");
}*/
/*
int64 idx=0;
while(idx<fs->getSize()/fs->getBlocksize())
{
std::string b1;
std::string b2;
int64 idx_start=idx;
for(size_t i=0;i<100;++i)
{
b1+=nconvert((int)fs->readBlock(idx, NULL));
b2+=nconvert((int)fs2->readBlock(idx, NULL));
++idx;
}
if(b1!=b2)
{
Server->Log(nconvert(idx_start)+" fs1: "+b1, LL_DEBUG);
Server->Log(nconvert(idx_start)+" fs2: "+b2, LL_DEBUG);
}
}*/
if(fs->hasError())
{
Server->Log("NTFS has error", LL_WARNING);
delete fs;
Server->Log("Unknown filesystem type", LL_DEBUG);
FSUnknown *fs2=new FSUnknown(pDev, read_ahead, background_priority);
if(fs2->hasError())
{
delete fs2;
return NULL;
}
PrintInfo(fs2);
return fs2;
}
PrintInfo(fs);
return fs;
}
else
{
Server->Log("Unknown filesystem type", LL_DEBUG);
FSUnknown *fs=new FSUnknown(pDev, read_ahead, background_priority);
if(fs->hasError())
{
delete fs;
return NULL;
}
PrintInfo(fs);
return fs;
}
}
bool FSImageFactory::isNTFS(char *buffer)
{
if(buffer[3]=='N' && buffer[4]=='T' && buffer[5]=='F' && buffer[6]=='S')
{
return true;
}
else
{
return false;
}
}
IVHDFile *FSImageFactory::createVHDFile(const std::wstring &fn, bool pRead_only, uint64 pDstsize,
unsigned int pBlocksize, bool fast_mode, CompressionSetting compress)
{
return new VHDFile(fn, pRead_only, pDstsize, pBlocksize, fast_mode, compress!=CompressionSetting_None);
}
IVHDFile *FSImageFactory::createVHDFile(const std::wstring &fn, const std::wstring &parent_fn,
bool pRead_only, bool fast_mode, CompressionSetting compress)
{
return new VHDFile(fn, parent_fn, pRead_only, fast_mode, compress!=CompressionSetting_None);
}
void FSImageFactory::destroyVHDFile(IVHDFile *vhd)
{
delete ((VHDFile*)vhd);
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "test_utils/test_utils.hpp"
#include "cpputil/math_utils.hpp"
#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/IndependentMvnVarSampler.hpp"
#include "Models/StateSpace/MultivariateStateSpaceRegressionModel.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/PosteriorSamplers/SharedLocalLevelPosteriorSampler.hpp"
#include "Models/StateSpace/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "distributions.hpp"
#include "LinAlg/Array.hpp"
namespace {
using namespace BOOM;
using std::endl;
using std::cout;
class MultivariateStateSpaceRegressionModelTest : public ::testing::Test {
protected:
MultivariateStateSpaceRegressionModelTest()
{
GlobalRng::rng.seed(8675310);
}
};
//===========================================================================
TEST_F(MultivariateStateSpaceRegressionModelTest, EmptyTest) {}
//===========================================================================
TEST_F(MultivariateStateSpaceRegressionModelTest, ConstructorTest) {
MultivariateStateSpaceRegressionModel model(3, 4);
}
} // namespace
<commit_msg>Add test cases for multivariate state space regression. Still need to finish MCMC.<commit_after>#include "gtest/gtest.h"
#include "test_utils/test_utils.hpp"
#include "cpputil/math_utils.hpp"
#include "Models/ChisqModel.hpp"
#include "Models/MvnModel.hpp"
#include "Models/PosteriorSamplers/IndependentMvnVarSampler.hpp"
#include "Models/Glm/PosteriorSamplers/RegressionSemiconjugateSampler.hpp"
#include "Models/StateSpace/MultivariateStateSpaceRegressionModel.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/PosteriorSamplers/SharedLocalLevelPosteriorSampler.hpp"
#include "Models/StateSpace/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "distributions.hpp"
#include "LinAlg/Array.hpp"
namespace {
using namespace BOOM;
using std::endl;
using std::cout;
class MultivariateStateSpaceRegressionModelTest : public ::testing::Test {
protected:
MultivariateStateSpaceRegressionModelTest()
{
GlobalRng::rng.seed(8675310);
}
};
//===========================================================================
TEST_F(MultivariateStateSpaceRegressionModelTest, EmptyTest) {}
//===========================================================================
TEST_F(MultivariateStateSpaceRegressionModelTest, ConstructorTest) {
MultivariateStateSpaceRegressionModel model(3, 4);
}
TEST_F(MultivariateStateSpaceRegressionModelTest, DataTest) {
TimeSeriesRegressionData data_point(3.2, Vector{1, 2, 3}, 0, 4);
EXPECT_DOUBLE_EQ(3.2, data_point.y());
EXPECT_TRUE(VectorEquals(Vector{1, 2, 3}, data_point.x()));
EXPECT_EQ(0, data_point.series());
EXPECT_EQ(4, data_point.timestamp());
}
TEST_F(MultivariateStateSpaceRegressionModelTest, ModelTest) {
int ydim = 4;
int xdim = 3;
MultivariateStateSpaceRegressionModel model(xdim, ydim);
EXPECT_EQ(0, model.state_dimension());
EXPECT_EQ(0, model.number_of_state_models());
EXPECT_EQ(nullptr, model.state_model(0));
EXPECT_EQ(nullptr, model.state_model(-1));
EXPECT_EQ(nullptr, model.state_model(2));
EXPECT_EQ(0, model.time_dimension());
EXPECT_EQ(ydim, model.nseries());
EXPECT_EQ(xdim, model.xdim());
std::vector<Ptr<TimeSeriesRegressionData>> data;
Matrix response_data(ydim, 12);
for (int time = 0; time < 12; ++time) {
for (int series = 0; series < ydim; ++series){
NEW(TimeSeriesRegressionData, data_point)(
rnorm(0, 1), rnorm_vector(xdim, 0, 1), series, time);
data.push_back(data_point);
model.add_data(data_point);
response_data(series, time) = data_point->y();
}
}
EXPECT_EQ(12, model.time_dimension());
for (int time = 0; time < 12; ++time) {
for (int series = 0; series < ydim; ++series) {
EXPECT_TRUE(model.is_observed(series, time));
EXPECT_DOUBLE_EQ(response_data(series, time),
model.observed_data(series, time));
}
}
}
TEST_F(MultivariateStateSpaceRegressionModelTest, McmcTest) {
// Simulate fake data from the model: shared local level and a regression
// effect.
int xdim = 3;
int ydim = 6;
int nfactors = 2;
int sample_size = 100;
double factor_sd = .3;
double residual_sd = .1;
//----------------------------------------------------------------------
// Simulate the state.
Matrix state(nfactors, sample_size);
for (int factor = 0; factor < nfactors; ++factor) {
state(factor, 0) = rnorm();
for (int time = 1; time < sample_size; ++time) {
state(factor, time) = state(factor, time - 1) + rnorm(0, factor_sd);
}
}
// Set up the observation coefficients, which are zero above the diagonal
// and 1 on the diagonal.
Matrix observation_coefficients(ydim, nfactors);
observation_coefficients.randomize();
for (int i = 0; i < nfactors; ++i) {
observation_coefficients(i, i) = 1.0;
for (int j = i + 1; j < nfactors; ++j) {
observation_coefficients(i, j) = 0.0;
}
}
// Set up the regression coefficients and the predictors.
Matrix regression_coefficients(ydim, xdim);
regression_coefficients.randomize();
Matrix predictors(sample_size, xdim);
predictors.randomize();
// Simulate the response.
Matrix response(sample_size, ydim);
for (int i = 0; i < sample_size; ++i) {
Vector yhat = observation_coefficients * state.col(i)
+ regression_coefficients * predictors.row(i);
for (int j = 0; j < ydim; ++j) {
response(i, j) = yhat[j] + rnorm(0, residual_sd);
}
}
//----------------------------------------------------------------------
// Define the model.
NEW(MultivariateStateSpaceRegressionModel, model)(xdim, ydim);
for (int time = 0; time < sample_size; ++time) {
for (int series = 0; series < ydim; ++series) {
NEW(TimeSeriesRegressionData, data_point)(
response(time, series), predictors.row(time), series, time);
model->add_data(data_point);
}
}
//---------------------------------------------------------------------------
// Define the state model.
NEW(SharedLocalLevelStateModel, state_model)(
nfactors, model.get(), ydim);
std::vector<Ptr<GammaModelBase>> innovation_precision_priors;
for (int factor = 0; factor < nfactors; ++factor) {
innovation_precision_priors.push_back(new ChisqModel(1.0, .10));
}
Matrix observation_coefficient_prior_mean(ydim, nfactors, 0.0);
NEW(SharedLocalLevelPosteriorSampler, state_model_sampler)(
state_model.get(),
innovation_precision_priors,
observation_coefficient_prior_mean,
.01);
state_model->set_method(state_model_sampler);
model->add_state(state_model);
//---------------------------------------------------------------------------
// Set the prior for the regression model.
for (int i = 0; i < ydim; ++i) {
Vector beta_prior_mean(xdim, 0.0);
SpdMatrix beta_precision(xdim, 1.0);
NEW(MvnModel, beta_prior)(beta_prior_mean, beta_precision, true);
NEW(ChisqModel, residual_precision_prior)(1.0, residual_sd);
NEW(RegressionSemiconjugateSampler, regression_sampler)(
model->observation_model()->model(i).get(),
beta_prior, residual_precision_prior);
model->observation_model()->model(i)->set_method(regression_sampler);
}
}
} // namespace
<|endoftext|> |
<commit_before>#include "Console.hpp"
#include "logger.hpp"
#define PUTC(c) pc.putc(c)
#define GETC pc.getc
#define PRINTF(...) pc.printf(__VA_ARGS__)
const std::string Console::RX_BUFFER_FULL_MSG = "RX BUFFER FULL";
const std::string Console::COMMAND_BREAK_MSG = "*BREAK*\033[K";
shared_ptr<Console> Console::instance;
bool Console::iter_break_req = false;
bool Console::command_handled = true;
bool Console::command_ready = false;
Console::Console() : pc(USBTX, USBRX) { }
shared_ptr<Console>& Console::Instance(void)
{
if (instance.get() == nullptr)
instance.reset(new Console);
return instance;
}
void Console::Init(void)
{
auto instance = Instance();
// Set default values for the header parameters
instance->CONSOLE_USER = "anon";
instance->CONSOLE_HOSTNAME = "robot";
instance->setHeader();
// set baud rate, store the value before
Baudrate(9600);
// clear buffers
instance->ClearRXBuffer();
instance->ClearTXBuffer();
// attach interrupt handlers
// instance->pc.attach(&Console::RXCallback_MODSERIAL, MODSERIAL::RxIrq);
// instance->pc.attach(&Console::TXCallback_MODSERIAL, MODSERIAL::TxIrq);
instance->pc.attach(instance.get(), &Console::RXCallback, Serial::RxIrq);
instance->pc.attach(instance.get(), &Console::TXCallback, Serial::TxIrq);
// reset indicces
instance->rxIndex = 0;
instance->txIndex = 0;
// Default for a host response escaped input terminating character
// instance->SetEscEnd('R');
LOG(INF3, "Hello from the 'common2015' library!");
}
void Console::PrintHeader(void)
{
// prints out a bash-like header
Flush();
instance->PRINTF("\r\n%s", instance->CONSOLE_HEADER.c_str());
Flush();
}
void Console::ClearRXBuffer(void)
{
memset(rxBuffer, '\0', BUFFER_LENGTH);
}
void Console::ClearTXBuffer(void)
{
memset(txBuffer, '\0', BUFFER_LENGTH);
}
void Console::Flush(void)
{
fflush(stdout);
}
void Console::RXCallback(void)
{
// If for some reason more than one character is in the buffer when the
// interrupt is called, handle them all.
while (pc.readable()) {
// If there is an command that hasn't finished yet, ignore the character for now
if (command_handled == false && command_ready == true) {
return;
} else {
// Otherwise, continue as normal
// read the char that caused the interrupt
char c = GETC();
// flag the start of an arrow key sequence
// if (c == ARROW_KEY_SEQUENCE_ONE) {
// flagOne = true;
// }
// check if we're in a sequence if flagOne is set - do things if necessary
// else if (flagOne) {
// if (flagTwo) {
// switch (c) {
// case ARROW_UP_KEY:
// PRINTF("\033M");
// break;
// case ARROW_DOWN_KEY:
// PRINTF("\033D");
// break;
// default:
// flagOne = false;
// flagTwo = false;
// }
// Flush();
// continue;
// } else { // flagTwo not set
// switch (c) {
// case ARROW_KEY_SEQUENCE_TWO:
// flagTwo = true;
// break;
// default:
// flagOne = false;
// break;
// }
// }
// }
// if the buffer is full, ignore the chracter and print a
// warning to the console
if (rxIndex >= (BUFFER_LENGTH - 5) && c != BACKSPACE_FLAG_CHAR) {
rxIndex = 0;
PRINTF("%s\r\n", RX_BUFFER_FULL_MSG.c_str());
Flush();
// Execute the function that sets up the console after a command's execution.
// This will ensure everything flushes corectly on a full buffer
CommandHandled(true);
}
// if a new line character is sent, process the current buffer
else if (c == NEW_LINE_CHAR) {
// print new line prior to executing
PRINTF("%c\n", NEW_LINE_CHAR);
Flush();
rxBuffer[rxIndex] = '\0';
command_ready = true;
command_handled = false;
}
// if a backspace is requested, handle it.
else if (c == BACKSPACE_FLAG_CHAR)
if (rxIndex > 0) {//instance->CONSOLE_HEADER.length()) {
//re-terminate the string
rxBuffer[--rxIndex] = '\0';
// 1) Move cursor back
// 2) Write a space to clear the character
// 3) Move back cursor again
PUTC(BACKSPACE_REPLY_CHAR);
PUTC(BACKSPACE_REPLACE_CHAR);
PUTC(BACKSPACE_REPLY_CHAR);
Flush();
} else {
/* do nothing if we can't back space any more */
}
// set that a command break was requested flag if we received a break character
else if (c == BREAK_CHAR) {
iter_break_req = true;
}
// No special character, add it to the buffer and return it to
// the terminal to be visible.
else {
if ( (c != ESC_START) && (esc_en == false) ) {
if (!(c == ARROW_UP_KEY || c == ARROW_DOWN_KEY)) {
rxBuffer[rxIndex++] = c;
}
esc_host_res = "";
PUTC(c);
Flush();
}
else {
if ( esc_seq_en == true ) {
esc_host_res += c;
}
if ( c == ESC_START ) {
esc_en = true;
} else if ( c == ESC_SEQ_START ) {
esc_seq_en = true;
} else if ( c == esc_host_end_char ) {
// Remove the terminating character
esc_host_res.pop_back();
// Set the flag for knowing we've received an expected response
esc_host_res_rdy = true;
// Reset everything back to normal
esc_en = false;
esc_seq_en = false;
}
}
}
}
}
}
void Console::TXCallback(void)
{
//NVIC_DisableIRQ(UART0_IRQn);
//handle transmission interrupts if necessary here
//NVIC_EnableIRQ(UART0_IRQn);
}
void Console::ConComCheck(void)
{
/*
* Currently no way to check if a vbus has been disconnected or
* reconnected. Will continue to keep track of a beta library located
* here: http://developer.mbed.org/handbook/USBHostSerial
* Source here: http://developer.mbed.org/users/mbed_official/code/USBHost/file/607951c26872/USBHostSerial/USBHostSerial.cpp
* It's not present in our currently library, and is not working
* for most people. It could however, greatly reduce what we have to
* implement while adding more functionality.
*/
/*
* Note for the above ^. The vbus can be monitored through ADC0, input 4.
* This is possible when bits 29..28 of the PINSEL3 register are set to 0b01.
*
* - Jon
*/
return;
}
void Console::RequestSystemStop(void)
{
Instance()->sysStopReq = true;
instance.reset();
}
bool Console::IsSystemStopRequested(void)
{
return Instance()->sysStopReq;
}
bool Console::IterCmdBreakReq(void)
{
return iter_break_req;
}
void Console::IterCmdBreakReq(bool newState)
{
iter_break_req = newState;
// Print out the header if an iterating command is stopped
if (newState == false) {
instance->PRINTF("%s", COMMAND_BREAK_MSG.c_str());
PrintHeader();
}
}
char* Console::rxBufferPtr(void)
{
return instance->rxBuffer;
}
bool Console::CommandReady(void)
{
return command_ready;
}
void Console::CommandHandled(bool cmdDoneState)
{
// update the class's flag for if a command was handled or not
command_handled = cmdDoneState;
// Clean up after command execution
instance->rxIndex = 0;
// reset our outgoing flag saying if there's a valid command sequence in the RX buffer or now
command_ready = false;
// print out the header without a newline first
if (iter_break_req == false) {
instance->PRINTF("%s", instance->CONSOLE_HEADER.c_str());
Flush();
}
}
void Console::changeHostname(const std::string & hostname)
{
instance->CONSOLE_HOSTNAME = hostname;
instance->setHeader();
}
void Console::changeUser(const std::string & user)
{
instance->CONSOLE_USER = user;
instance->setHeader();
}
void Console::setHeader(void)
{
instance->CONSOLE_HEADER = "\033[36m" + instance->CONSOLE_USER + "\033[34m@\033[33m" + instance->CONSOLE_HOSTNAME + " \033[36m$\033[0m \033[0J\033[5m";
//instance->CONSOLE_HEADER = instance->CONSOLE_USER + "@" + instance->CONSOLE_HOSTNAME + " $ ";
}
void Console::Baudrate(uint16_t baud)
{
instance->baudrate = baud;
instance->pc.baud(instance->baudrate);
}
uint16_t Console::Baudrate(void)
{
return instance->baudrate;
}
void Console::RXCallback_MODSERIAL(MODSERIAL_IRQ_INFO * info)
{
Console::RXCallback();
}
void Console::TXCallback_MODSERIAL(MODSERIAL_IRQ_INFO * info)
{
Console::TXCallback();
}
void Console::SetEscEnd(char c)
{
instance->esc_host_end_char = c;
}
const std::string& Console::GetHostResponse(void)
{
if ( instance->esc_host_res_rdy == true ) {
instance->esc_host_res_rdy = false;
return instance->esc_host_res;
} else {
return "";
}
}
void Console::ShowLogo(void)
{
Flush();
instance->PRINTF (
" _____ _ _ _ _\r\n"
" | __ \\ | | | | | | | | \r\n"
" | |__) |___ | |__ ___ | | __ _ ___| | _____| |_ ___ \r\n"
" | _ // _ \\| '_ \\ / _ \\ _ | |/ _` |/ __| |/ / _ \\ __/ __|\r\n"
" | | \\ \\ (_) | |_) | (_) | |__| | (_| | (__| < __/ |_\\__ \\\r\n"
" |_| \\_\\___/|_.__/ \\___/ \\____/ \\__,_|\\___|_|\\_\\___|\\__|___/\r\n"
);
Flush();
}
<commit_msg>fixing blinking issue<commit_after>#include "Console.hpp"
#include "logger.hpp"
#define PUTC(c) pc.putc(c)
#define GETC pc.getc
#define PRINTF(...) pc.printf(__VA_ARGS__)
const std::string Console::RX_BUFFER_FULL_MSG = "RX BUFFER FULL";
const std::string Console::COMMAND_BREAK_MSG = "*BREAK*\033[K";
shared_ptr<Console> Console::instance;
bool Console::iter_break_req = false;
bool Console::command_handled = true;
bool Console::command_ready = false;
Console::Console() : pc(USBTX, USBRX) { }
shared_ptr<Console>& Console::Instance(void)
{
if (instance.get() == nullptr)
instance.reset(new Console);
return instance;
}
void Console::Init(void)
{
auto instance = Instance();
// Set default values for the header parameters
instance->CONSOLE_USER = "anon";
instance->CONSOLE_HOSTNAME = "robot";
instance->setHeader();
// set baud rate, store the value before
Baudrate(9600);
// clear buffers
instance->ClearRXBuffer();
instance->ClearTXBuffer();
// attach interrupt handlers
// instance->pc.attach(&Console::RXCallback_MODSERIAL, MODSERIAL::RxIrq);
// instance->pc.attach(&Console::TXCallback_MODSERIAL, MODSERIAL::TxIrq);
instance->pc.attach(instance.get(), &Console::RXCallback, Serial::RxIrq);
instance->pc.attach(instance.get(), &Console::TXCallback, Serial::TxIrq);
// reset indicces
instance->rxIndex = 0;
instance->txIndex = 0;
// Default for a host response escaped input terminating character
// instance->SetEscEnd('R');
LOG(INF3, "Hello from the 'common2015' library!");
}
void Console::PrintHeader(void)
{
// prints out a bash-like header
Flush();
instance->PRINTF("\r\n%s", instance->CONSOLE_HEADER.c_str());
Flush();
}
void Console::ClearRXBuffer(void)
{
memset(rxBuffer, '\0', BUFFER_LENGTH);
}
void Console::ClearTXBuffer(void)
{
memset(txBuffer, '\0', BUFFER_LENGTH);
}
void Console::Flush(void)
{
fflush(stdout);
}
void Console::RXCallback(void)
{
// If for some reason more than one character is in the buffer when the
// interrupt is called, handle them all.
while (pc.readable()) {
// If there is an command that hasn't finished yet, ignore the character for now
if (command_handled == false && command_ready == true) {
return;
} else {
// Otherwise, continue as normal
// read the char that caused the interrupt
char c = GETC();
// flag the start of an arrow key sequence
// if (c == ARROW_KEY_SEQUENCE_ONE) {
// flagOne = true;
// }
// check if we're in a sequence if flagOne is set - do things if necessary
// else if (flagOne) {
// if (flagTwo) {
// switch (c) {
// case ARROW_UP_KEY:
// PRINTF("\033M");
// break;
// case ARROW_DOWN_KEY:
// PRINTF("\033D");
// break;
// default:
// flagOne = false;
// flagTwo = false;
// }
// Flush();
// continue;
// } else { // flagTwo not set
// switch (c) {
// case ARROW_KEY_SEQUENCE_TWO:
// flagTwo = true;
// break;
// default:
// flagOne = false;
// break;
// }
// }
// }
// if the buffer is full, ignore the chracter and print a
// warning to the console
if (rxIndex >= (BUFFER_LENGTH - 5) && c != BACKSPACE_FLAG_CHAR) {
rxIndex = 0;
PRINTF("%s\r\n", RX_BUFFER_FULL_MSG.c_str());
Flush();
// Execute the function that sets up the console after a command's execution.
// This will ensure everything flushes corectly on a full buffer
CommandHandled(true);
}
// if a new line character is sent, process the current buffer
else if (c == NEW_LINE_CHAR) {
// print new line prior to executing
PRINTF("%c\n", NEW_LINE_CHAR);
Flush();
rxBuffer[rxIndex] = '\0';
command_ready = true;
command_handled = false;
}
// if a backspace is requested, handle it.
else if (c == BACKSPACE_FLAG_CHAR)
if (rxIndex > 0) {//instance->CONSOLE_HEADER.length()) {
//re-terminate the string
rxBuffer[--rxIndex] = '\0';
// 1) Move cursor back
// 2) Write a space to clear the character
// 3) Move back cursor again
PUTC(BACKSPACE_REPLY_CHAR);
PUTC(BACKSPACE_REPLACE_CHAR);
PUTC(BACKSPACE_REPLY_CHAR);
Flush();
} else {
/* do nothing if we can't back space any more */
}
// set that a command break was requested flag if we received a break character
else if (c == BREAK_CHAR) {
iter_break_req = true;
}
// No special character, add it to the buffer and return it to
// the terminal to be visible.
else {
if ( (c != ESC_START) && (esc_en == false) ) {
if (!(c == ARROW_UP_KEY || c == ARROW_DOWN_KEY)) {
rxBuffer[rxIndex++] = c;
}
esc_host_res = "";
PUTC(c);
Flush();
}
else {
if ( esc_seq_en == true ) {
esc_host_res += c;
}
if ( c == ESC_START ) {
esc_en = true;
} else if ( c == ESC_SEQ_START ) {
esc_seq_en = true;
} else if ( c == esc_host_end_char ) {
// Remove the terminating character
esc_host_res.pop_back();
// Set the flag for knowing we've received an expected response
esc_host_res_rdy = true;
// Reset everything back to normal
esc_en = false;
esc_seq_en = false;
}
}
}
}
}
}
void Console::TXCallback(void)
{
//NVIC_DisableIRQ(UART0_IRQn);
//handle transmission interrupts if necessary here
//NVIC_EnableIRQ(UART0_IRQn);
}
void Console::ConComCheck(void)
{
/*
* Currently no way to check if a vbus has been disconnected or
* reconnected. Will continue to keep track of a beta library located
* here: http://developer.mbed.org/handbook/USBHostSerial
* Source here: http://developer.mbed.org/users/mbed_official/code/USBHost/file/607951c26872/USBHostSerial/USBHostSerial.cpp
* It's not present in our currently library, and is not working
* for most people. It could however, greatly reduce what we have to
* implement while adding more functionality.
*/
/*
* Note for the above ^. The vbus can be monitored through ADC0, input 4.
* This is possible when bits 29..28 of the PINSEL3 register are set to 0b01.
*
* - Jon
*/
return;
}
void Console::RequestSystemStop(void)
{
Instance()->sysStopReq = true;
instance.reset();
}
bool Console::IsSystemStopRequested(void)
{
return Instance()->sysStopReq;
}
bool Console::IterCmdBreakReq(void)
{
return iter_break_req;
}
void Console::IterCmdBreakReq(bool newState)
{
iter_break_req = newState;
// Print out the header if an iterating command is stopped
if (newState == false) {
instance->PRINTF("%s", COMMAND_BREAK_MSG.c_str());
PrintHeader();
}
}
char* Console::rxBufferPtr(void)
{
return instance->rxBuffer;
}
bool Console::CommandReady(void)
{
return command_ready;
}
void Console::CommandHandled(bool cmdDoneState)
{
// update the class's flag for if a command was handled or not
command_handled = cmdDoneState;
// Clean up after command execution
instance->rxIndex = 0;
// reset our outgoing flag saying if there's a valid command sequence in the RX buffer or now
command_ready = false;
// print out the header without a newline first
if (iter_break_req == false) {
instance->PRINTF("%s", instance->CONSOLE_HEADER.c_str());
Flush();
}
}
void Console::changeHostname(const std::string & hostname)
{
instance->CONSOLE_HOSTNAME = hostname;
instance->setHeader();
}
void Console::changeUser(const std::string & user)
{
instance->CONSOLE_USER = user;
instance->setHeader();
}
void Console::setHeader(void)
{
instance->CONSOLE_HEADER = "\033[36m" + instance->CONSOLE_USER + "\033[34m@\033[33m" + instance->CONSOLE_HOSTNAME + " \033[36m$\033[0m \033[0J\033[0m";
//instance->CONSOLE_HEADER = instance->CONSOLE_USER + "@" + instance->CONSOLE_HOSTNAME + " $ ";
}
void Console::Baudrate(uint16_t baud)
{
instance->baudrate = baud;
instance->pc.baud(instance->baudrate);
}
uint16_t Console::Baudrate(void)
{
return instance->baudrate;
}
void Console::RXCallback_MODSERIAL(MODSERIAL_IRQ_INFO * info)
{
Console::RXCallback();
}
void Console::TXCallback_MODSERIAL(MODSERIAL_IRQ_INFO * info)
{
Console::TXCallback();
}
void Console::SetEscEnd(char c)
{
instance->esc_host_end_char = c;
}
const std::string& Console::GetHostResponse(void)
{
if ( instance->esc_host_res_rdy == true ) {
instance->esc_host_res_rdy = false;
return instance->esc_host_res;
} else {
return "";
}
}
void Console::ShowLogo(void)
{
Flush();
instance->PRINTF (
" _____ _ _ _ _\r\n"
" | __ \\ | | | | | | | | \r\n"
" | |__) |___ | |__ ___ | | __ _ ___| | _____| |_ ___ \r\n"
" | _ // _ \\| '_ \\ / _ \\ _ | |/ _` |/ __| |/ / _ \\ __/ __|\r\n"
" | | \\ \\ (_) | |_) | (_) | |__| | (_| | (__| < __/ |_\\__ \\\r\n"
" |_| \\_\\___/|_.__/ \\___/ \\____/ \\__,_|\\___|_|\\_\\___|\\__|___/\r\n"
);
Flush();
}
<|endoftext|> |
<commit_before>//===-- HexagonCFGOptimizer.cpp - CFG optimizations -----------------------===//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Hexagon.h"
#include "HexagonMachineFunctionInfo.h"
#include "HexagonSubtarget.h"
#include "HexagonTargetMachine.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
#define DEBUG_TYPE "hexagon_cfg"
namespace llvm {
FunctionPass *createHexagonCFGOptimizer();
void initializeHexagonCFGOptimizerPass(PassRegistry&);
}
namespace {
class HexagonCFGOptimizer : public MachineFunctionPass {
private:
void InvertAndChangeJumpTarget(MachineInstr*, MachineBasicBlock*);
public:
static char ID;
HexagonCFGOptimizer() : MachineFunctionPass(ID) {
initializeHexagonCFGOptimizerPass(*PassRegistry::getPassRegistry());
}
const char *getPassName() const override {
return "Hexagon CFG Optimizer";
}
bool runOnMachineFunction(MachineFunction &Fn) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::AllVRegsAllocated);
}
};
char HexagonCFGOptimizer::ID = 0;
static bool IsConditionalBranch(int Opc) {
return (Opc == Hexagon::J2_jumpt) || (Opc == Hexagon::J2_jumpf)
|| (Opc == Hexagon::J2_jumptnewpt) || (Opc == Hexagon::J2_jumpfnewpt);
}
static bool IsUnconditionalJump(int Opc) {
return (Opc == Hexagon::J2_jump);
}
void
HexagonCFGOptimizer::InvertAndChangeJumpTarget(MachineInstr* MI,
MachineBasicBlock* NewTarget) {
const TargetInstrInfo *TII =
MI->getParent()->getParent()->getSubtarget().getInstrInfo();
int NewOpcode = 0;
switch(MI->getOpcode()) {
case Hexagon::J2_jumpt:
NewOpcode = Hexagon::J2_jumpf;
break;
case Hexagon::J2_jumpf:
NewOpcode = Hexagon::J2_jumpt;
break;
case Hexagon::J2_jumptnewpt:
NewOpcode = Hexagon::J2_jumpfnewpt;
break;
case Hexagon::J2_jumpfnewpt:
NewOpcode = Hexagon::J2_jumptnewpt;
break;
default:
llvm_unreachable("Cannot handle this case");
}
MI->setDesc(TII->get(NewOpcode));
MI->getOperand(1).setMBB(NewTarget);
}
bool HexagonCFGOptimizer::runOnMachineFunction(MachineFunction &Fn) {
if (skipFunction(*Fn.getFunction()))
return false;
// Loop over all of the basic blocks.
for (MachineFunction::iterator MBBb = Fn.begin(), MBBe = Fn.end();
MBBb != MBBe; ++MBBb) {
MachineBasicBlock *MBB = &*MBBb;
// Traverse the basic block.
MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
if (MII != MBB->end()) {
MachineInstr *MI = MII;
int Opc = MI->getOpcode();
if (IsConditionalBranch(Opc)) {
//
// (Case 1) Transform the code if the following condition occurs:
// BB1: if (p0) jump BB3
// ...falls-through to BB2 ...
// BB2: jump BB4
// ...next block in layout is BB3...
// BB3: ...
//
// Transform this to:
// BB1: if (!p0) jump BB4
// Remove BB2
// BB3: ...
//
// (Case 2) A variation occurs when BB3 contains a JMP to BB4:
// BB1: if (p0) jump BB3
// ...falls-through to BB2 ...
// BB2: jump BB4
// ...other basic blocks ...
// BB4:
// ...not a fall-thru
// BB3: ...
// jump BB4
//
// Transform this to:
// BB1: if (!p0) jump BB4
// Remove BB2
// BB3: ...
// BB4: ...
//
unsigned NumSuccs = MBB->succ_size();
MachineBasicBlock::succ_iterator SI = MBB->succ_begin();
MachineBasicBlock* FirstSucc = *SI;
MachineBasicBlock* SecondSucc = *(++SI);
MachineBasicBlock* LayoutSucc = nullptr;
MachineBasicBlock* JumpAroundTarget = nullptr;
if (MBB->isLayoutSuccessor(FirstSucc)) {
LayoutSucc = FirstSucc;
JumpAroundTarget = SecondSucc;
} else if (MBB->isLayoutSuccessor(SecondSucc)) {
LayoutSucc = SecondSucc;
JumpAroundTarget = FirstSucc;
} else {
// Odd case...cannot handle.
}
// The target of the unconditional branch must be JumpAroundTarget.
// TODO: If not, we should not invert the unconditional branch.
MachineBasicBlock* CondBranchTarget = nullptr;
if ((MI->getOpcode() == Hexagon::J2_jumpt) ||
(MI->getOpcode() == Hexagon::J2_jumpf)) {
CondBranchTarget = MI->getOperand(1).getMBB();
}
if (!LayoutSucc || (CondBranchTarget != JumpAroundTarget)) {
continue;
}
if ((NumSuccs == 2) && LayoutSucc && (LayoutSucc->pred_size() == 1)) {
// Ensure that BB2 has one instruction -- an unconditional jump.
if ((LayoutSucc->size() == 1) &&
IsUnconditionalJump(LayoutSucc->front().getOpcode())) {
assert(JumpAroundTarget && "jump target is needed to process second basic block");
MachineBasicBlock* UncondTarget =
LayoutSucc->front().getOperand(0).getMBB();
// Check if the layout successor of BB2 is BB3.
bool case1 = LayoutSucc->isLayoutSuccessor(JumpAroundTarget);
bool case2 = JumpAroundTarget->isSuccessor(UncondTarget) &&
JumpAroundTarget->size() >= 1 &&
IsUnconditionalJump(JumpAroundTarget->back().getOpcode()) &&
JumpAroundTarget->pred_size() == 1 &&
JumpAroundTarget->succ_size() == 1;
if (case1 || case2) {
InvertAndChangeJumpTarget(MI, UncondTarget);
MBB->replaceSuccessor(JumpAroundTarget, UncondTarget);
// Remove the unconditional branch in LayoutSucc.
LayoutSucc->erase(LayoutSucc->begin());
LayoutSucc->replaceSuccessor(UncondTarget, JumpAroundTarget);
// This code performs the conversion for case 2, which moves
// the block to the fall-thru case (BB3 in the code above).
if (case2 && !case1) {
JumpAroundTarget->moveAfter(LayoutSucc);
// only move a block if it doesn't have a fall-thru. otherwise
// the CFG will be incorrect.
if (!UncondTarget->canFallThrough()) {
UncondTarget->moveAfter(JumpAroundTarget);
}
}
//
// Correct live-in information. Is used by post-RA scheduler
// The live-in to LayoutSucc is now all values live-in to
// JumpAroundTarget.
//
std::vector<MachineBasicBlock::RegisterMaskPair> OrigLiveIn(
LayoutSucc->livein_begin(), LayoutSucc->livein_end());
std::vector<MachineBasicBlock::RegisterMaskPair> NewLiveIn(
JumpAroundTarget->livein_begin(),
JumpAroundTarget->livein_end());
for (const auto &OrigLI : OrigLiveIn)
LayoutSucc->removeLiveIn(OrigLI.PhysReg);
for (const auto &NewLI : NewLiveIn)
LayoutSucc->addLiveIn(NewLI);
}
}
}
}
}
}
return true;
}
}
//===----------------------------------------------------------------------===//
// Public Constructor Functions
//===----------------------------------------------------------------------===//
static void initializePassOnce(PassRegistry &Registry) {
PassInfo *PI = new PassInfo("Hexagon CFG Optimizer", "hexagon-cfg",
&HexagonCFGOptimizer::ID, nullptr, false, false);
Registry.registerPass(*PI, true);
}
void llvm::initializeHexagonCFGOptimizerPass(PassRegistry &Registry) {
CALL_ONCE_INITIALIZATION(initializePassOnce)
}
FunctionPass *llvm::createHexagonCFGOptimizer() {
return new HexagonCFGOptimizer();
}
<commit_msg>Use the standard INITIALIZE_PASS macro rather than hand rolling a (not entirely correct) version of its contents.<commit_after>//===-- HexagonCFGOptimizer.cpp - CFG optimizations -----------------------===//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Hexagon.h"
#include "HexagonMachineFunctionInfo.h"
#include "HexagonSubtarget.h"
#include "HexagonTargetMachine.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
#define DEBUG_TYPE "hexagon_cfg"
namespace llvm {
FunctionPass *createHexagonCFGOptimizer();
void initializeHexagonCFGOptimizerPass(PassRegistry&);
}
namespace {
class HexagonCFGOptimizer : public MachineFunctionPass {
private:
void InvertAndChangeJumpTarget(MachineInstr*, MachineBasicBlock*);
public:
static char ID;
HexagonCFGOptimizer() : MachineFunctionPass(ID) {
initializeHexagonCFGOptimizerPass(*PassRegistry::getPassRegistry());
}
const char *getPassName() const override {
return "Hexagon CFG Optimizer";
}
bool runOnMachineFunction(MachineFunction &Fn) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::AllVRegsAllocated);
}
};
char HexagonCFGOptimizer::ID = 0;
static bool IsConditionalBranch(int Opc) {
return (Opc == Hexagon::J2_jumpt) || (Opc == Hexagon::J2_jumpf)
|| (Opc == Hexagon::J2_jumptnewpt) || (Opc == Hexagon::J2_jumpfnewpt);
}
static bool IsUnconditionalJump(int Opc) {
return (Opc == Hexagon::J2_jump);
}
void
HexagonCFGOptimizer::InvertAndChangeJumpTarget(MachineInstr* MI,
MachineBasicBlock* NewTarget) {
const TargetInstrInfo *TII =
MI->getParent()->getParent()->getSubtarget().getInstrInfo();
int NewOpcode = 0;
switch(MI->getOpcode()) {
case Hexagon::J2_jumpt:
NewOpcode = Hexagon::J2_jumpf;
break;
case Hexagon::J2_jumpf:
NewOpcode = Hexagon::J2_jumpt;
break;
case Hexagon::J2_jumptnewpt:
NewOpcode = Hexagon::J2_jumpfnewpt;
break;
case Hexagon::J2_jumpfnewpt:
NewOpcode = Hexagon::J2_jumptnewpt;
break;
default:
llvm_unreachable("Cannot handle this case");
}
MI->setDesc(TII->get(NewOpcode));
MI->getOperand(1).setMBB(NewTarget);
}
bool HexagonCFGOptimizer::runOnMachineFunction(MachineFunction &Fn) {
if (skipFunction(*Fn.getFunction()))
return false;
// Loop over all of the basic blocks.
for (MachineFunction::iterator MBBb = Fn.begin(), MBBe = Fn.end();
MBBb != MBBe; ++MBBb) {
MachineBasicBlock *MBB = &*MBBb;
// Traverse the basic block.
MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
if (MII != MBB->end()) {
MachineInstr *MI = MII;
int Opc = MI->getOpcode();
if (IsConditionalBranch(Opc)) {
//
// (Case 1) Transform the code if the following condition occurs:
// BB1: if (p0) jump BB3
// ...falls-through to BB2 ...
// BB2: jump BB4
// ...next block in layout is BB3...
// BB3: ...
//
// Transform this to:
// BB1: if (!p0) jump BB4
// Remove BB2
// BB3: ...
//
// (Case 2) A variation occurs when BB3 contains a JMP to BB4:
// BB1: if (p0) jump BB3
// ...falls-through to BB2 ...
// BB2: jump BB4
// ...other basic blocks ...
// BB4:
// ...not a fall-thru
// BB3: ...
// jump BB4
//
// Transform this to:
// BB1: if (!p0) jump BB4
// Remove BB2
// BB3: ...
// BB4: ...
//
unsigned NumSuccs = MBB->succ_size();
MachineBasicBlock::succ_iterator SI = MBB->succ_begin();
MachineBasicBlock* FirstSucc = *SI;
MachineBasicBlock* SecondSucc = *(++SI);
MachineBasicBlock* LayoutSucc = nullptr;
MachineBasicBlock* JumpAroundTarget = nullptr;
if (MBB->isLayoutSuccessor(FirstSucc)) {
LayoutSucc = FirstSucc;
JumpAroundTarget = SecondSucc;
} else if (MBB->isLayoutSuccessor(SecondSucc)) {
LayoutSucc = SecondSucc;
JumpAroundTarget = FirstSucc;
} else {
// Odd case...cannot handle.
}
// The target of the unconditional branch must be JumpAroundTarget.
// TODO: If not, we should not invert the unconditional branch.
MachineBasicBlock* CondBranchTarget = nullptr;
if ((MI->getOpcode() == Hexagon::J2_jumpt) ||
(MI->getOpcode() == Hexagon::J2_jumpf)) {
CondBranchTarget = MI->getOperand(1).getMBB();
}
if (!LayoutSucc || (CondBranchTarget != JumpAroundTarget)) {
continue;
}
if ((NumSuccs == 2) && LayoutSucc && (LayoutSucc->pred_size() == 1)) {
// Ensure that BB2 has one instruction -- an unconditional jump.
if ((LayoutSucc->size() == 1) &&
IsUnconditionalJump(LayoutSucc->front().getOpcode())) {
assert(JumpAroundTarget && "jump target is needed to process second basic block");
MachineBasicBlock* UncondTarget =
LayoutSucc->front().getOperand(0).getMBB();
// Check if the layout successor of BB2 is BB3.
bool case1 = LayoutSucc->isLayoutSuccessor(JumpAroundTarget);
bool case2 = JumpAroundTarget->isSuccessor(UncondTarget) &&
JumpAroundTarget->size() >= 1 &&
IsUnconditionalJump(JumpAroundTarget->back().getOpcode()) &&
JumpAroundTarget->pred_size() == 1 &&
JumpAroundTarget->succ_size() == 1;
if (case1 || case2) {
InvertAndChangeJumpTarget(MI, UncondTarget);
MBB->replaceSuccessor(JumpAroundTarget, UncondTarget);
// Remove the unconditional branch in LayoutSucc.
LayoutSucc->erase(LayoutSucc->begin());
LayoutSucc->replaceSuccessor(UncondTarget, JumpAroundTarget);
// This code performs the conversion for case 2, which moves
// the block to the fall-thru case (BB3 in the code above).
if (case2 && !case1) {
JumpAroundTarget->moveAfter(LayoutSucc);
// only move a block if it doesn't have a fall-thru. otherwise
// the CFG will be incorrect.
if (!UncondTarget->canFallThrough()) {
UncondTarget->moveAfter(JumpAroundTarget);
}
}
//
// Correct live-in information. Is used by post-RA scheduler
// The live-in to LayoutSucc is now all values live-in to
// JumpAroundTarget.
//
std::vector<MachineBasicBlock::RegisterMaskPair> OrigLiveIn(
LayoutSucc->livein_begin(), LayoutSucc->livein_end());
std::vector<MachineBasicBlock::RegisterMaskPair> NewLiveIn(
JumpAroundTarget->livein_begin(),
JumpAroundTarget->livein_end());
for (const auto &OrigLI : OrigLiveIn)
LayoutSucc->removeLiveIn(OrigLI.PhysReg);
for (const auto &NewLI : NewLiveIn)
LayoutSucc->addLiveIn(NewLI);
}
}
}
}
}
}
return true;
}
}
//===----------------------------------------------------------------------===//
// Public Constructor Functions
//===----------------------------------------------------------------------===//
INITIALIZE_PASS(HexagonCFGOptimizer, "hexagon-cfg", "Hexagon CFG Optimizer",
false, false)
FunctionPass *llvm::createHexagonCFGOptimizer() {
return new HexagonCFGOptimizer();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.