text stringlengths 54 60.6k |
|---|
<commit_before>/*
* Copyright 2011 Esrille 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 "Box.h"
#include <jpeglib.h>
#include <png.h>
#include <stdio.h>
#include <GL/gl.h>
#include <boost/bind.hpp>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
// image/png - 89 50 4E 47 0D 0A 1A 0A
// image/gif - "GIF87a" or "GIF89a"
// image/jpeg - FF D8
// image/bmp - "BM"
// image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)
namespace {
unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
png_byte header[8];
if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 0;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 0;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 0;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);
unsigned color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_tRNS_to_alpha(png_ptr);
color_type = GL_RGBA;
}
if (bit_depth == 16)
png_set_strip_16(png_ptr);
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_GRAY:
case PNG_COLOR_TYPE_PALETTE:
format = GL_RGB;
break;
default:
format = GL_RGBA;
break;
}
png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_bytep data = (png_bytep) malloc(rowbytes * height);
png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (unsigned i = 0; i < height; i++)
row_pointers[i] = &data[rowbytes * i];
png_read_image(png_ptr, row_pointers);
free(row_pointers);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return data;
}
unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
unsigned char sig[2];
if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)
return 0;
rewind(file);
JSAMPARRAY img;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, true);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);
img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
for (unsigned i = 0; i < height; ++i)
img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];
while(cinfo.output_scanline < cinfo.output_height)
jpeg_read_scanlines(&cinfo,
img + cinfo.output_scanline,
cinfo.output_height - cinfo.output_scanline);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(img);
if (cinfo.out_color_components == 1)
format = GL_LUMINANCE;
else
format = GL_RGB;
return data;
}
} // namespace
BoxImage::BoxImage(Box* box) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */)
{
}
BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(repeat),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */),
request(base)
{
open(url);
}
BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(Clamp),
format(GL_RGBA),
img(img),
request(base)
{
open(img.getSrc());
}
void BoxImage::open(const std::u16string& url)
{
request.open(u"GET", url);
request.setHanndler(boost::bind(&BoxImage::notify, this));
request.send();
state = Sent;
if (request.getReadyState() != HttpRequest::DONE)
return;
if (request.getErrorFlag()) {
state = Broken;
return;
}
FILE* file = request.openFile();
if (!file) {
state = Broken;
return;
}
pixels = readAsPng(file, naturalWidth, naturalHeight, format);
if (!pixels) {
rewind(file);
pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);
}
if (pixels)
state = CompletelyAvailable;
else
state = Broken;
fclose(file);
}
void BoxImage::notify()
{
if (state == Sent) {
if (request.getStatus() == 200)
box->flags = 1; // for updating render tree.
else
state = Unavailable;
}
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(readAsPng) : Support grayscale images of less than 8 bit depths.<commit_after>/*
* Copyright 2011 Esrille 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 "Box.h"
#include <jpeglib.h>
#include <png.h>
#include <stdio.h>
#include <GL/gl.h>
#include <boost/bind.hpp>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
// image/png - 89 50 4E 47 0D 0A 1A 0A
// image/gif - "GIF87a" or "GIF89a"
// image/jpeg - FF D8
// image/bmp - "BM"
// image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)
namespace {
unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
png_byte header[8];
if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 0;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 0;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 0;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);
unsigned color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_gray_1_2_4_to_8(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_tRNS_to_alpha(png_ptr);
color_type = GL_RGBA;
}
if (bit_depth == 16)
png_set_strip_16(png_ptr);
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_GRAY:
case PNG_COLOR_TYPE_PALETTE:
format = GL_RGB;
break;
default:
format = GL_RGBA;
break;
}
png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_bytep data = (png_bytep) malloc(rowbytes * height);
png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (unsigned i = 0; i < height; i++)
row_pointers[i] = &data[rowbytes * i];
png_read_image(png_ptr, row_pointers);
free(row_pointers);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return data;
}
unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
unsigned char sig[2];
if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)
return 0;
rewind(file);
JSAMPARRAY img;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, true);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);
img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
for (unsigned i = 0; i < height; ++i)
img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];
while(cinfo.output_scanline < cinfo.output_height)
jpeg_read_scanlines(&cinfo,
img + cinfo.output_scanline,
cinfo.output_height - cinfo.output_scanline);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(img);
if (cinfo.out_color_components == 1)
format = GL_LUMINANCE;
else
format = GL_RGB;
return data;
}
} // namespace
BoxImage::BoxImage(Box* box) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */)
{
}
BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(repeat),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */),
request(base)
{
open(url);
}
BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(Clamp),
format(GL_RGBA),
img(img),
request(base)
{
open(img.getSrc());
}
void BoxImage::open(const std::u16string& url)
{
request.open(u"GET", url);
request.setHanndler(boost::bind(&BoxImage::notify, this));
request.send();
state = Sent;
if (request.getReadyState() != HttpRequest::DONE)
return;
if (request.getErrorFlag()) {
state = Broken;
return;
}
FILE* file = request.openFile();
if (!file) {
state = Broken;
return;
}
pixels = readAsPng(file, naturalWidth, naturalHeight, format);
if (!pixels) {
rewind(file);
pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);
}
if (pixels)
state = CompletelyAvailable;
else
state = Broken;
fclose(file);
}
void BoxImage::notify()
{
if (state == Sent) {
if (request.getStatus() == 200)
box->flags = 1; // for updating render tree.
else
state = Unavailable;
}
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Esrille 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 "Box.h"
#include <jpeglib.h>
#include <png.h>
#include <stdio.h>
#include <GL/gl.h>
#include <boost/bind.hpp>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
// image/png - 89 50 4E 47 0D 0A 1A 0A
// image/gif - "GIF87a" or "GIF89a"
// image/jpeg - FF D8
// image/bmp - "BM"
// image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)
namespace {
unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height)
{
png_byte header[8];
if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 0;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 0;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 0;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);
unsigned color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if (bit_depth == 16)
png_set_strip_16(png_ptr);
if (color_type == PNG_COLOR_TYPE_RGB)
png_set_filler(png_ptr, 0xff, PNG_FILLER_BEFORE);
png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_bytep data = (png_bytep) malloc(rowbytes * height);
png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (unsigned i = 0; i < height; i++)
row_pointers[i] = &data[rowbytes * i];
png_read_image(png_ptr, row_pointers);
free(row_pointers);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return data;
}
unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
unsigned char sig[2];
if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)
return 0;
rewind(file);
JSAMPARRAY img;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, true);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);
img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
for (unsigned i = 0; i < height; ++i)
img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];
while(cinfo.output_scanline < cinfo.output_height)
jpeg_read_scanlines(&cinfo,
img + cinfo.output_scanline,
cinfo.output_height - cinfo.output_scanline);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(img);
if (cinfo.out_color_components == 1)
format = GL_LUMINANCE;
else
format = GL_RGB;
return data;
}
} // namespace
BoxImage::BoxImage(Box* box) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */)
{
}
BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(repeat),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */),
request(base)
{
open(url);
}
BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(img),
request(base)
{
open(img.getSrc());
}
void BoxImage::open(const std::u16string& url)
{
request.open(u"GET", url);
request.setHanndler(boost::bind(&BoxImage::notify, this));
request.send();
state = Sent;
if (request.getReadyState() != HttpRequest::DONE)
return;
if (request.getErrorFlag()) {
state = Broken;
return;
}
FILE* file = request.openFile();
if (!file) {
state = Broken;
return;
}
pixels = readAsPng(file, naturalWidth, naturalHeight);
if (!pixels) {
rewind(file);
pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);
}
if (pixels)
state = CompletelyAvailable;
else
state = Broken;
fclose(file);
}
void BoxImage::notify()
{
if (state == Sent) {
// TODO: update render tree!!
box->flags = 1;
}
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(BoxImage::notify) : Fix not to send requests repeatedly.<commit_after>/*
* Copyright 2011 Esrille 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 "Box.h"
#include <jpeglib.h>
#include <png.h>
#include <stdio.h>
#include <GL/gl.h>
#include <boost/bind.hpp>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
// image/png - 89 50 4E 47 0D 0A 1A 0A
// image/gif - "GIF87a" or "GIF89a"
// image/jpeg - FF D8
// image/bmp - "BM"
// image/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)
namespace {
unsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height)
{
png_byte header[8];
if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 0;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 0;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 0;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return 0;
}
png_init_io(png_ptr, file);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);
unsigned color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if (bit_depth == 16)
png_set_strip_16(png_ptr);
if (color_type == PNG_COLOR_TYPE_RGB)
png_set_filler(png_ptr, 0xff, PNG_FILLER_BEFORE);
png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);
png_bytep data = (png_bytep) malloc(rowbytes * height);
png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (unsigned i = 0; i < height; i++)
row_pointers[i] = &data[rowbytes * i];
png_read_image(png_ptr, row_pointers);
free(row_pointers);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return data;
}
unsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)
{
unsigned char sig[2];
if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)
return 0;
rewind(file);
JSAMPARRAY img;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr); // TODO: set our own error handdler
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, true);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);
img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);
for (unsigned i = 0; i < height; ++i)
img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];
while(cinfo.output_scanline < cinfo.output_height)
jpeg_read_scanlines(&cinfo,
img + cinfo.output_scanline,
cinfo.output_height - cinfo.output_scanline);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(img);
if (cinfo.out_color_components == 1)
format = GL_LUMINANCE;
else
format = GL_RGB;
return data;
}
} // namespace
BoxImage::BoxImage(Box* box) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */)
{
}
BoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(repeat),
format(GL_RGBA),
img(static_cast<html::HTMLImageElement*>(0) /* nullptr */),
request(base)
{
open(url);
}
BoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :
box(box),
state(Unavailable),
pixels(0),
naturalWidth(0),
naturalHeight(0),
repeat(0),
format(GL_RGBA),
img(img),
request(base)
{
open(img.getSrc());
}
void BoxImage::open(const std::u16string& url)
{
request.open(u"GET", url);
request.setHanndler(boost::bind(&BoxImage::notify, this));
request.send();
state = Sent;
if (request.getReadyState() != HttpRequest::DONE)
return;
if (request.getErrorFlag()) {
state = Broken;
return;
}
FILE* file = request.openFile();
if (!file) {
state = Broken;
return;
}
pixels = readAsPng(file, naturalWidth, naturalHeight);
if (!pixels) {
rewind(file);
pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);
}
if (pixels)
state = CompletelyAvailable;
else
state = Broken;
fclose(file);
}
void BoxImage::notify()
{
if (state == Sent) {
if (request.getStatus() == 200)
box->flags = 1; // for updating render tree.
else
state = Unavailable;
}
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2022 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Base class for a vehicle visualization system
//
// =============================================================================
#include "chrono_vehicle/ChVehicleVisualSystem.h"
#include "chrono_vehicle/ChWorldFrame.h"
namespace chrono {
namespace vehicle {
ChVehicleVisualSystem::ChVehicleVisualSystem()
: m_vehicle(nullptr),
m_stepsize(1e-3),
m_camera_point(ChVector<>(1, 0, 0)),
m_camera_dist(5.0),
m_camera_height(0.5),
m_camera_state(utils::ChChaseCamera::State::Chase),
m_camera_pos(VNULL),
m_camera_angle(0),
m_camera_minMult(1),
m_camera_maxMult(1),
m_steering(0),
m_throttle(0),
m_braking(0) {}
ChVehicleVisualSystem ::~ChVehicleVisualSystem() {}
void ChVehicleVisualSystem::Synchronize(const std::string& msg, const ChDriver::Inputs& driver_inputs) {
m_driver_msg = msg;
m_steering = driver_inputs.m_steering;
m_throttle = driver_inputs.m_throttle;
m_braking = driver_inputs.m_braking;
}
void ChVehicleVisualSystem::OnAttachToVehicle() {
m_camera = chrono_types::make_unique<utils::ChChaseCamera>(m_vehicle->GetChassisBody());
// Attention: order of calls is important here!
m_camera->SetCameraPos(m_camera_pos);
m_camera->SetCameraAngle(m_camera_angle);
m_camera->SetState(m_camera_state);
m_camera->Initialize(m_camera_point, m_vehicle->GetChassis()->GetLocalDriverCoordsys(), m_camera_dist,
m_camera_height, ChWorldFrame::Vertical(), ChWorldFrame::Forward());
m_camera->SetMultLimits(m_camera_minMult, m_camera_maxMult);
}
void ChVehicleVisualSystem::SetChaseCamera(const ChVector<>& ptOnChassis, double chaseDist, double chaseHeight) {
m_camera_point = ptOnChassis;
m_camera_dist = chaseDist;
m_camera_height = chaseHeight;
if (m_camera) {
m_camera->SetTargetPoint(m_camera_point);
m_camera->SetChaseDistance(m_camera_dist);
m_camera->SetChaseHeight(m_camera_height);
}
}
void ChVehicleVisualSystem::SetStepsize(double val) {
m_stepsize = val;
}
void ChVehicleVisualSystem::SetChaseCameraState(utils::ChChaseCamera::State state) {
m_camera_state = state;
if (m_camera)
m_camera->SetState(m_camera_state);
}
void ChVehicleVisualSystem::SetChaseCameraPosition(const ChVector<>& pos) {
m_camera_pos = pos;
if (m_camera)
m_camera->SetCameraPos(m_camera_pos);
}
void ChVehicleVisualSystem::SetChaseCameraAngle(double angle) {
m_camera_angle = angle;
if (m_camera)
m_camera->SetCameraAngle(m_camera_angle);
}
void ChVehicleVisualSystem::SetChaseCameraMultipliers(double minMult, double maxMult) {
m_camera_minMult = minMult;
m_camera_maxMult = maxMult;
if (m_camera)
m_camera->SetMultLimits(m_camera_minMult, m_camera_maxMult);
}
} // namespace vehicle
} // namespace chrono
<commit_msg>Fix incorrect initialization of chase camera zoom multiplier limits<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2022 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Base class for a vehicle visualization system
//
// =============================================================================
#include "chrono_vehicle/ChVehicleVisualSystem.h"
#include "chrono_vehicle/ChWorldFrame.h"
namespace chrono {
namespace vehicle {
ChVehicleVisualSystem::ChVehicleVisualSystem()
: m_vehicle(nullptr),
m_stepsize(1e-3),
m_camera_point(ChVector<>(1, 0, 0)),
m_camera_dist(5.0),
m_camera_height(0.5),
m_camera_state(utils::ChChaseCamera::State::Chase),
m_camera_pos(VNULL),
m_camera_angle(0),
m_camera_minMult(0.5),
m_camera_maxMult(10),
m_steering(0),
m_throttle(0),
m_braking(0) {}
ChVehicleVisualSystem ::~ChVehicleVisualSystem() {}
void ChVehicleVisualSystem::Synchronize(const std::string& msg, const ChDriver::Inputs& driver_inputs) {
m_driver_msg = msg;
m_steering = driver_inputs.m_steering;
m_throttle = driver_inputs.m_throttle;
m_braking = driver_inputs.m_braking;
}
void ChVehicleVisualSystem::OnAttachToVehicle() {
m_camera = chrono_types::make_unique<utils::ChChaseCamera>(m_vehicle->GetChassisBody());
// Attention: order of calls is important here!
m_camera->SetCameraPos(m_camera_pos);
m_camera->SetCameraAngle(m_camera_angle);
m_camera->SetState(m_camera_state);
m_camera->Initialize(m_camera_point, m_vehicle->GetChassis()->GetLocalDriverCoordsys(), m_camera_dist,
m_camera_height, ChWorldFrame::Vertical(), ChWorldFrame::Forward());
m_camera->SetMultLimits(m_camera_minMult, m_camera_maxMult);
}
void ChVehicleVisualSystem::SetChaseCamera(const ChVector<>& ptOnChassis, double chaseDist, double chaseHeight) {
m_camera_point = ptOnChassis;
m_camera_dist = chaseDist;
m_camera_height = chaseHeight;
if (m_camera) {
m_camera->SetTargetPoint(m_camera_point);
m_camera->SetChaseDistance(m_camera_dist);
m_camera->SetChaseHeight(m_camera_height);
}
}
void ChVehicleVisualSystem::SetStepsize(double val) {
m_stepsize = val;
}
void ChVehicleVisualSystem::SetChaseCameraState(utils::ChChaseCamera::State state) {
m_camera_state = state;
if (m_camera)
m_camera->SetState(m_camera_state);
}
void ChVehicleVisualSystem::SetChaseCameraPosition(const ChVector<>& pos) {
m_camera_pos = pos;
if (m_camera)
m_camera->SetCameraPos(m_camera_pos);
}
void ChVehicleVisualSystem::SetChaseCameraAngle(double angle) {
m_camera_angle = angle;
if (m_camera)
m_camera->SetCameraAngle(m_camera_angle);
}
void ChVehicleVisualSystem::SetChaseCameraMultipliers(double minMult, double maxMult) {
m_camera_minMult = minMult;
m_camera_maxMult = maxMult;
if (m_camera)
m_camera->SetMultLimits(m_camera_minMult, m_camera_maxMult);
}
} // namespace vehicle
} // namespace chrono
<|endoftext|> |
<commit_before>/**
* \file
* \brief SemaphoreOperationsTestCase class implementation
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "SemaphoreOperationsTestCase.hpp"
#include "waitForNextTick.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/StaticSoftwareTimer.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// single duration used in tests
constexpr auto singleDuration = TickClock::duration{1};
/// long duration used in tests
constexpr auto longDuration = singleDuration * 10;
/// expected number of context switches in waitForNextTick(): main -> idle -> main
constexpr decltype(statistics::getContextSwitchCount()) waitForNextTickContextSwitchCount {2};
/// expected number of context switches in phase1 block involving tryWaitFor() or tryWaitUntil() (excluding
/// waitForNextTick()): 1 - main thread blocks on semaphore (main -> idle), 2 - main thread wakes up (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase1TryWaitForUntilContextSwitchCount {2};
/// expected number of context switches in phase3 block involving test thread (excluding waitForNextTick()): 1 - test
/// thread starts (main -> test), 2 - test thread goes to sleep (test -> main), 3 - main thread blocks on semaphore
/// (main -> idle), 4 - test thread wakes (idle -> test), 5 - test thread terminates (test -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase3ThreadContextSwitchCount {5};
/// expected number of context switches in phase4 block involving software timer (excluding waitForNextTick()): 1 - main
/// thread blocks on semaphore (main -> idle), 2 - main thread is unblocked by interrupt (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase4SoftwareTimerContextSwitchCount {2};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Tests Semaphore::post() - it must succeed immediately
*
* \param [in] semaphore is a reference to semaphore that will be posted
*
* \return true if test succeeded, false otherwise
*/
bool testPost(Semaphore& semaphore)
{
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.post();
return ret == 0 && start == TickClock::now() && semaphore.getValue() > 0;
}
/**
* \brief Tests Semaphore::tryWait() when semaphore is locked - it must fail immediately and return EAGAIN
*
* \param [in] semaphore is a reference to semaphore that will be tested
*
* \return true if test succeeded, false otherwise
*/
bool testTryWaitWhenLocked(Semaphore& semaphore)
{
// semaphore is locked, so tryWait() should fail immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWait();
return ret == EAGAIN && TickClock::now() == start && semaphore.getValue() == 0;
}
/**
* \brief Phase 1 of test case.
*
* Tests whether all tryWait*() functions properly return some error when dealing with locked semaphore.
*
* \return true if test succeeded, false otherwise
*/
bool phase1()
{
Semaphore semaphore {0};
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
// semaphore is locked, so tryWaitFor() should time-out at expected time
const auto start = TickClock::now();
const auto ret = semaphore.tryWaitFor(singleDuration);
const auto realDuration = TickClock::now() - start;
if (ret != ETIMEDOUT || realDuration != singleDuration + decltype(singleDuration){1} ||
semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase1TryWaitForUntilContextSwitchCount)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
// semaphore is locked, so tryWaitUntil() should time-out at exact expected time
const auto requestedTimePoint = TickClock::now() + singleDuration;
const auto ret = semaphore.tryWaitUntil(requestedTimePoint);
if (ret != ETIMEDOUT || requestedTimePoint != TickClock::now() || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase1TryWaitForUntilContextSwitchCount)
return false;
}
return true;
}
/**
* \brief Phase 2 of test case.
*
* Tests whether all tryWait*() functions properly lock unlocked semaphore.
*
* \return true if test succeeded, false otherwise
*/
bool phase2()
{
Semaphore semaphore {1};
{
// semaphore is unlocked, so tryWait() must succeed immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWait();
if (ret != 0 || start != TickClock::now() || semaphore.getValue() != 0)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
const auto ret = testPost(semaphore);
if (ret != true)
return ret;
}
{
// semaphore is unlocked, so tryWaitFor() should succeed immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWaitFor(singleDuration);
if (ret != 0 || start != TickClock::now() || semaphore.getValue() != 0)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
const auto ret = testPost(semaphore);
if (ret != true)
return ret;
}
{
// semaphore is unlocked, so tryWaitUntil() should succeed immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWaitUntil(start + singleDuration);
if (ret != 0 || start != TickClock::now() || semaphore.getValue() != 0)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
const auto ret = testPost(semaphore);
if (ret != true)
return ret;
}
return true;
}
/**
* \brief Phase 3 of test case.
*
* Tests thread-thread signaling scenario. Main (current) thread waits for a locked semaphore to become available. Test
* thread posts the semaphore at specified time point, main thread is expected to acquire ownership of this semaphore
* (with wait(), tryWaitFor() and tryWaitUntil()) in the same moment.
*
* \return true if test succeeded, false otherwise
*/
bool phase3()
{
constexpr size_t testThreadStackSize {384};
Semaphore semaphore {0};
const auto sleepUntilFunctor = [&semaphore](const TickClock::time_point timePoint)
{
ThisThread::sleepUntil(timePoint);
semaphore.post();
};
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeAndStartDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
ThisThread::yield();
// semaphore is currently locked, but wait() should succeed at expected time
const auto ret = semaphore.wait();
const auto wokenUpTimePoint = TickClock::now();
thread.join();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase3ThreadContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeAndStartDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
ThisThread::yield();
// semaphore is currently locked, but tryWaitFor() should succeed at expected time
const auto ret = semaphore.tryWaitFor(wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
thread.join();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase3ThreadContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeAndStartDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
ThisThread::yield();
// semaphore is locked, but tryWaitUntil() should succeed at expected time
const auto ret = semaphore.tryWaitUntil(wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
thread.join();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase3ThreadContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
return true;
}
/**
* \brief Phase 4 of test case.
*
* Tests interrupt-thread signaling scenario. Main (current) thread waits for a locked semaphore to become available.
* Software timer is used to posts the semaphore at specified time point from interrupt context, main thread is expected
* to acquire ownership of this semaphore (with wait(), tryWaitFor() and tryWaitUntil()) in the same moment.
*
* \return true if test succeeded, false otherwise
*/
bool phase4()
{
Semaphore semaphore {0};
auto softwareTimer = makeStaticSoftwareTimer(&Semaphore::post, std::ref(semaphore));
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// semaphore is currently locked, but wait() should succeed at expected time
const auto ret = semaphore.wait();
const auto wokenUpTimePoint = TickClock::now();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase4SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// semaphore is currently locked, but tryWaitFor() should succeed at expected time
const auto ret = semaphore.tryWaitFor(wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase4SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// semaphore is locked, but tryWaitUntil() should succeed at expected time
const auto ret = semaphore.tryWaitUntil(wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase4SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
return true;
}
/**
* \brief Phase 5 of test case.
*
* Tests correction of invalid initialization and overflow detection of semaphore with explicit max value. Semaphore's
* initial value cannot be higher than given max value - value must be truncated in the constructor. Semaphore's value
* must never be higher than the max value - any call to Semaphore::post() after the value reached max value must result
* in EOVERFLOW error.
*
* \return true if test succeeded, false otherwise
*/
bool phase5()
{
constexpr auto initialValue = std::numeric_limits<Semaphore::Value>::max();
constexpr auto maxValue = initialValue / 2;
Semaphore semaphore {initialValue, maxValue};
if (semaphore.getValue() != maxValue)
return false;
{
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.post();
if (ret != EOVERFLOW || start != TickClock::now() || semaphore.getValue() != maxValue)
return false;
}
return true;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SemaphoreOperationsTestCase::run_() const
{
constexpr auto phase1ExpectedContextSwitchCount = 3 * waitForNextTickContextSwitchCount +
2 * phase1TryWaitForUntilContextSwitchCount;
constexpr auto phase2ExpectedContextSwitchCount = 9 * waitForNextTickContextSwitchCount;
constexpr auto phase3ExpectedContextSwitchCount = 6 * waitForNextTickContextSwitchCount +
3 * phase3ThreadContextSwitchCount;
constexpr auto phase4ExpectedContextSwitchCount = 6 * waitForNextTickContextSwitchCount +
3 * phase4SoftwareTimerContextSwitchCount;
constexpr auto phase5ExpectedContextSwitchCount = 1 * waitForNextTickContextSwitchCount;
constexpr auto expectedContextSwitchCount = phase1ExpectedContextSwitchCount + phase2ExpectedContextSwitchCount +
phase3ExpectedContextSwitchCount + phase4ExpectedContextSwitchCount + phase5ExpectedContextSwitchCount;
const auto contextSwitchCount = statistics::getContextSwitchCount();
for (const auto& function : {phase1, phase2, phase3, phase4, phase5})
{
const auto ret = function();
if (ret != true)
return ret;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: include <cerrno> in SemaphoreOperationsTestCase.cpp<commit_after>/**
* \file
* \brief SemaphoreOperationsTestCase class implementation
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "SemaphoreOperationsTestCase.hpp"
#include "waitForNextTick.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/StaticSoftwareTimer.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
#include <cerrno>
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// single duration used in tests
constexpr auto singleDuration = TickClock::duration{1};
/// long duration used in tests
constexpr auto longDuration = singleDuration * 10;
/// expected number of context switches in waitForNextTick(): main -> idle -> main
constexpr decltype(statistics::getContextSwitchCount()) waitForNextTickContextSwitchCount {2};
/// expected number of context switches in phase1 block involving tryWaitFor() or tryWaitUntil() (excluding
/// waitForNextTick()): 1 - main thread blocks on semaphore (main -> idle), 2 - main thread wakes up (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase1TryWaitForUntilContextSwitchCount {2};
/// expected number of context switches in phase3 block involving test thread (excluding waitForNextTick()): 1 - test
/// thread starts (main -> test), 2 - test thread goes to sleep (test -> main), 3 - main thread blocks on semaphore
/// (main -> idle), 4 - test thread wakes (idle -> test), 5 - test thread terminates (test -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase3ThreadContextSwitchCount {5};
/// expected number of context switches in phase4 block involving software timer (excluding waitForNextTick()): 1 - main
/// thread blocks on semaphore (main -> idle), 2 - main thread is unblocked by interrupt (idle -> main)
constexpr decltype(statistics::getContextSwitchCount()) phase4SoftwareTimerContextSwitchCount {2};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Tests Semaphore::post() - it must succeed immediately
*
* \param [in] semaphore is a reference to semaphore that will be posted
*
* \return true if test succeeded, false otherwise
*/
bool testPost(Semaphore& semaphore)
{
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.post();
return ret == 0 && start == TickClock::now() && semaphore.getValue() > 0;
}
/**
* \brief Tests Semaphore::tryWait() when semaphore is locked - it must fail immediately and return EAGAIN
*
* \param [in] semaphore is a reference to semaphore that will be tested
*
* \return true if test succeeded, false otherwise
*/
bool testTryWaitWhenLocked(Semaphore& semaphore)
{
// semaphore is locked, so tryWait() should fail immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWait();
return ret == EAGAIN && TickClock::now() == start && semaphore.getValue() == 0;
}
/**
* \brief Phase 1 of test case.
*
* Tests whether all tryWait*() functions properly return some error when dealing with locked semaphore.
*
* \return true if test succeeded, false otherwise
*/
bool phase1()
{
Semaphore semaphore {0};
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
// semaphore is locked, so tryWaitFor() should time-out at expected time
const auto start = TickClock::now();
const auto ret = semaphore.tryWaitFor(singleDuration);
const auto realDuration = TickClock::now() - start;
if (ret != ETIMEDOUT || realDuration != singleDuration + decltype(singleDuration){1} ||
semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase1TryWaitForUntilContextSwitchCount)
return false;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
// semaphore is locked, so tryWaitUntil() should time-out at exact expected time
const auto requestedTimePoint = TickClock::now() + singleDuration;
const auto ret = semaphore.tryWaitUntil(requestedTimePoint);
if (ret != ETIMEDOUT || requestedTimePoint != TickClock::now() || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase1TryWaitForUntilContextSwitchCount)
return false;
}
return true;
}
/**
* \brief Phase 2 of test case.
*
* Tests whether all tryWait*() functions properly lock unlocked semaphore.
*
* \return true if test succeeded, false otherwise
*/
bool phase2()
{
Semaphore semaphore {1};
{
// semaphore is unlocked, so tryWait() must succeed immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWait();
if (ret != 0 || start != TickClock::now() || semaphore.getValue() != 0)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
const auto ret = testPost(semaphore);
if (ret != true)
return ret;
}
{
// semaphore is unlocked, so tryWaitFor() should succeed immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWaitFor(singleDuration);
if (ret != 0 || start != TickClock::now() || semaphore.getValue() != 0)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
const auto ret = testPost(semaphore);
if (ret != true)
return ret;
}
{
// semaphore is unlocked, so tryWaitUntil() should succeed immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.tryWaitUntil(start + singleDuration);
if (ret != 0 || start != TickClock::now() || semaphore.getValue() != 0)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
const auto ret = testPost(semaphore);
if (ret != true)
return ret;
}
return true;
}
/**
* \brief Phase 3 of test case.
*
* Tests thread-thread signaling scenario. Main (current) thread waits for a locked semaphore to become available. Test
* thread posts the semaphore at specified time point, main thread is expected to acquire ownership of this semaphore
* (with wait(), tryWaitFor() and tryWaitUntil()) in the same moment.
*
* \return true if test succeeded, false otherwise
*/
bool phase3()
{
constexpr size_t testThreadStackSize {384};
Semaphore semaphore {0};
const auto sleepUntilFunctor = [&semaphore](const TickClock::time_point timePoint)
{
ThisThread::sleepUntil(timePoint);
semaphore.post();
};
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeAndStartDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
ThisThread::yield();
// semaphore is currently locked, but wait() should succeed at expected time
const auto ret = semaphore.wait();
const auto wokenUpTimePoint = TickClock::now();
thread.join();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase3ThreadContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeAndStartDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
ThisThread::yield();
// semaphore is currently locked, but tryWaitFor() should succeed at expected time
const auto ret = semaphore.tryWaitFor(wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
thread.join();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase3ThreadContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
auto thread = makeAndStartDynamicThread({testThreadStackSize, UINT8_MAX}, sleepUntilFunctor, wakeUpTimePoint);
ThisThread::yield();
// semaphore is locked, but tryWaitUntil() should succeed at expected time
const auto ret = semaphore.tryWaitUntil(wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
thread.join();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase3ThreadContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
return true;
}
/**
* \brief Phase 4 of test case.
*
* Tests interrupt-thread signaling scenario. Main (current) thread waits for a locked semaphore to become available.
* Software timer is used to posts the semaphore at specified time point from interrupt context, main thread is expected
* to acquire ownership of this semaphore (with wait(), tryWaitFor() and tryWaitUntil()) in the same moment.
*
* \return true if test succeeded, false otherwise
*/
bool phase4()
{
Semaphore semaphore {0};
auto softwareTimer = makeStaticSoftwareTimer(&Semaphore::post, std::ref(semaphore));
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// semaphore is currently locked, but wait() should succeed at expected time
const auto ret = semaphore.wait();
const auto wokenUpTimePoint = TickClock::now();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase4SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// semaphore is currently locked, but tryWaitFor() should succeed at expected time
const auto ret = semaphore.tryWaitFor(wakeUpTimePoint - TickClock::now() + longDuration);
const auto wokenUpTimePoint = TickClock::now();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase4SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
{
waitForNextTick();
const auto contextSwitchCount = statistics::getContextSwitchCount();
const auto wakeUpTimePoint = TickClock::now() + longDuration;
softwareTimer.start(wakeUpTimePoint);
// semaphore is locked, but tryWaitUntil() should succeed at expected time
const auto ret = semaphore.tryWaitUntil(wakeUpTimePoint + longDuration);
const auto wokenUpTimePoint = TickClock::now();
if (ret != 0 || wakeUpTimePoint != wokenUpTimePoint || semaphore.getValue() != 0 ||
statistics::getContextSwitchCount() - contextSwitchCount != phase4SoftwareTimerContextSwitchCount)
return false;
}
{
const auto ret = testTryWaitWhenLocked(semaphore);
if (ret != true)
return ret;
}
return true;
}
/**
* \brief Phase 5 of test case.
*
* Tests correction of invalid initialization and overflow detection of semaphore with explicit max value. Semaphore's
* initial value cannot be higher than given max value - value must be truncated in the constructor. Semaphore's value
* must never be higher than the max value - any call to Semaphore::post() after the value reached max value must result
* in EOVERFLOW error.
*
* \return true if test succeeded, false otherwise
*/
bool phase5()
{
constexpr auto initialValue = std::numeric_limits<Semaphore::Value>::max();
constexpr auto maxValue = initialValue / 2;
Semaphore semaphore {initialValue, maxValue};
if (semaphore.getValue() != maxValue)
return false;
{
waitForNextTick();
const auto start = TickClock::now();
const auto ret = semaphore.post();
if (ret != EOVERFLOW || start != TickClock::now() || semaphore.getValue() != maxValue)
return false;
}
return true;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SemaphoreOperationsTestCase::run_() const
{
constexpr auto phase1ExpectedContextSwitchCount = 3 * waitForNextTickContextSwitchCount +
2 * phase1TryWaitForUntilContextSwitchCount;
constexpr auto phase2ExpectedContextSwitchCount = 9 * waitForNextTickContextSwitchCount;
constexpr auto phase3ExpectedContextSwitchCount = 6 * waitForNextTickContextSwitchCount +
3 * phase3ThreadContextSwitchCount;
constexpr auto phase4ExpectedContextSwitchCount = 6 * waitForNextTickContextSwitchCount +
3 * phase4SoftwareTimerContextSwitchCount;
constexpr auto phase5ExpectedContextSwitchCount = 1 * waitForNextTickContextSwitchCount;
constexpr auto expectedContextSwitchCount = phase1ExpectedContextSwitchCount + phase2ExpectedContextSwitchCount +
phase3ExpectedContextSwitchCount + phase4ExpectedContextSwitchCount + phase5ExpectedContextSwitchCount;
const auto contextSwitchCount = statistics::getContextSwitchCount();
for (const auto& function : {phase1, phase2, phase3, phase4, phase5})
{
const auto ret = function();
if (ret != true)
return ret;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>#include <TestSupport.h>
#include <string>
#include <DataStructures/StringKeyTable.h>
using namespace Passenger;
using namespace std;
namespace tut {
struct DataStructures_StringKeyTableTest {
StringKeyTable<string> table;
string *value;
DataStructures_StringKeyTableTest() {
value = NULL;
}
};
DEFINE_TEST_GROUP(DataStructures_StringKeyTableTest);
TEST_METHOD(1) {
set_test_name("Initial state");
ensure_equals(table.size(), 0u);
ensure_equals(table.arraySize(), (unsigned int) StringKeyTable<string>::DEFAULT_SIZE);
}
TEST_METHOD(2) {
set_test_name("On an empty StringKeyTable, iterators reach the end immediately");
StringKeyTable<string>::Iterator it(table);
ensure_equals<void *>(*it, NULL);
}
TEST_METHOD(3) {
set_test_name("On an empty StringKeyTable, lookups return NULL");
ensure(!table.lookup("hello", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookup("?", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookupRandom(NULL, &value));
ensure_equals<void *>(value, NULL);
}
TEST_METHOD(4) {
set_test_name("Insertions work");
table.insert("Content-Length", "5");
ensure_equals(table.size(), 1u);
ensure(!table.lookup("hello", &value));
ensure_equals<void *>("(1)", value, NULL);
ensure(!table.lookup("Host", &value));
ensure_equals<void *>("(2)", value, NULL);
ensure(table.lookup("Content-Length", &value));
ensure_equals("(3)", *value, "5");
table.insert("Host", "foo.com");
ensure_equals(table.size(), 2u);
ensure(!table.lookup("hello", &value));
ensure_equals<void *>("(5)", value, NULL);
ensure(table.lookup("Host", &value));
ensure_equals("(6)", *value, "foo.com");
ensure(table.lookup("Content-Length", &value));
ensure_equals("(7)", *value, "5");
}
TEST_METHOD(5) {
set_test_name("Large amounts of insertions");
table.insert("Host", "foo.com");
table.insert("Content-Length", "5");
table.insert("Accept", "text/html");
table.insert("Accept-Encoding", "gzip");
table.insert("Accept-Language", "nl");
table.insert("User-Agent", "Mozilla");
table.insert("Set-Cookie", "foo=bar");
table.insert("Connection", "keep-alive");
table.insert("Cache-Control", "no-cache");
table.insert("Pragma", "no-cache");
ensure(!table.lookup("MyHeader", &value));
ensure(table.lookup("Host", &value));
ensure_equals(*value, "foo.com");
ensure(table.lookup("Content-Length", &value));
ensure_equals(*value, "5");
ensure(table.lookup("Accept", &value));
ensure_equals(*value, "text/html");
ensure(table.lookup("Accept-Encoding", &value));
ensure_equals(*value, "gzip");
ensure(table.lookup("Accept-Language", &value));
ensure_equals(*value, "nl");
ensure(table.lookup("User-Agent", &value));
ensure_equals(*value, "Mozilla");
ensure(table.lookup("Set-Cookie", &value));
ensure_equals(*value, "foo=bar");
ensure(table.lookup("Connection", &value));
ensure_equals(*value, "keep-alive");
ensure(table.lookup("Cache-Control", &value));
ensure_equals(*value, "no-cache");
ensure(table.lookup("Pragma", &value));
ensure_equals(*value, "no-cache");
}
TEST_METHOD(6) {
set_test_name("Iterators work");
table.insert("Content-Length", "5");
table.insert("Host", "foo.com");
StringKeyTable<string>::Iterator it(table);
ensure(*it != NULL);
if (it.getKey() == "Content-Length") {
ensure_equals(it.getKey(), "Content-Length");
it.next();
ensure_equals(it.getKey(), "Host");
} else {
ensure_equals(it.getKey(), "Host");
it.next();
ensure_equals(it.getKey(), "Content-Length");
}
it.next();
ensure_equals<void *>(*it, NULL);
}
TEST_METHOD(7) {
set_test_name("Dynamically growing the bucket on insert");
table = StringKeyTable<string>(4);
ensure_equals(table.size(), 0u);
ensure_equals(table.arraySize(), 4u);
table.insert("Host", "foo.com");
table.insert("Content-Length", "5");
ensure_equals(table.size(), 2u);
ensure_equals(table.arraySize(), 4u);
table.insert("Accept", "text/html");
ensure_equals(table.size(), 3u);
ensure_equals(table.arraySize(), 8u);
ensure(!table.lookup("MyHeader", &value));
ensure_equals<void *>(value, NULL);
ensure(table.lookup("Host", &value));
ensure_equals(*value, "foo.com");
ensure(table.lookup("Content-Length", &value));
ensure_equals(*value, "5");
ensure(table.lookup("Accept", &value));
ensure_equals(*value, "text/html");
}
TEST_METHOD(8) {
set_test_name("Clearing");
table.insert("Host", "foo.com");
table.insert("Content-Length", "5");
table.insert("Accept", "text/html");
table.clear();
ensure_equals(table.size(), 0u);
ensure_equals(table.arraySize(), (unsigned int) StringKeyTable<string>::DEFAULT_SIZE);
ensure(!table.lookup("Host", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookup("Content-Length", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookup("Accept", &value));
ensure_equals<void *>(value, NULL);
}
TEST_METHOD(9) {
set_test_name("lookupRandom() works");
HashedStaticString key;
table.insert("a", "1");
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "a");
ensure_equals(*value, "1");
table.insert("b", "2");
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "b");
ensure_equals(*value, "2");
table.insert("c", "3");
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "c");
ensure_equals(*value, "3");
ensure(table.erase("b"));
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "c");
ensure_equals(*value, "3");
ensure(table.erase("c"));
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "a");
ensure_equals(*value, "1");
ensure(table.erase("a"));
ensure(!table.lookupRandom(&key, &value));
}
TEST_METHOD(10) {
set_test_name("Initial size 0");
StringKeyTable<string> t(0, 0);
ensure_equals(t.lookupCopy("a"), "");
t.insert("a", "b");
ensure_equals(t.lookupCopy("a"), "b");
}
TEST_METHOD(11) {
set_test_name("Move support");
class Foo {
private:
BOOST_MOVABLE_BUT_NOT_COPYABLE(Foo)
public:
int value;
Foo()
: value(0)
{ }
Foo(int v)
: value(v)
{ }
Foo(BOOST_RV_REF(Foo) other)
: value(other.value)
{
other.value = -1;
}
Foo &operator=(BOOST_RV_REF(Foo) other) {
value = other.value;
other.value = -1;
return *this;
}
};
StringKeyTable<Foo, SKT_EnableMoveSupport> t(1);
Foo *result;
ensure_equals("Initial table array size is 1", t.arraySize(), 1u);
t.insertByMoving("a", Foo(1));
ensure("1: a is in the table", t.lookup("a", &result));
ensure_equals("1: a's value is 1", result->value, 1);
Foo f(2);
t.insertByMoving("a", boost::move(f));
ensure("2: a is in the table", t.lookup("a", &result));
ensure_equals("2: a's value is 2", result->value, 2);
ensure_equals("2: original variable's value is -1", f.value, -1);
t.insertByMoving("b", Foo(3));
ensure_equals("3: New table array size is 2", t.arraySize(), 4u);
ensure("3: a is in the table", t.lookup("a", &result));
ensure_equals("3: a's value is 2", result->value, 2);
ensure("3: a is in the table", t.lookup("b", &result));
ensure_equals("3: b's value is 3", result->value, 3);
}
}
<commit_msg>Fix C++03 errors in StringKeyTableTest<commit_after>#include <TestSupport.h>
#include <string>
#include <DataStructures/StringKeyTable.h>
using namespace Passenger;
using namespace std;
namespace tut {
struct DataStructures_StringKeyTableTest {
StringKeyTable<string> table;
string *value;
DataStructures_StringKeyTableTest() {
value = NULL;
}
class Counter {
private:
BOOST_MOVABLE_BUT_NOT_COPYABLE(Counter)
public:
int value;
Counter()
: value(0)
{ }
Counter(int v)
: value(v)
{ }
Counter(BOOST_RV_REF(Counter) other)
: value(other.value)
{
other.value = -1;
}
Counter &operator=(BOOST_RV_REF(Counter) other) {
value = other.value;
other.value = -1;
return *this;
}
};
};
DEFINE_TEST_GROUP(DataStructures_StringKeyTableTest);
TEST_METHOD(1) {
set_test_name("Initial state");
ensure_equals(table.size(), 0u);
ensure_equals(table.arraySize(), (unsigned int) StringKeyTable<string>::DEFAULT_SIZE);
}
TEST_METHOD(2) {
set_test_name("On an empty StringKeyTable, iterators reach the end immediately");
StringKeyTable<string>::Iterator it(table);
ensure_equals<void *>(*it, NULL);
}
TEST_METHOD(3) {
set_test_name("On an empty StringKeyTable, lookups return NULL");
ensure(!table.lookup("hello", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookup("?", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookupRandom(NULL, &value));
ensure_equals<void *>(value, NULL);
}
TEST_METHOD(4) {
set_test_name("Insertions work");
table.insert("Content-Length", "5");
ensure_equals(table.size(), 1u);
ensure(!table.lookup("hello", &value));
ensure_equals<void *>("(1)", value, NULL);
ensure(!table.lookup("Host", &value));
ensure_equals<void *>("(2)", value, NULL);
ensure(table.lookup("Content-Length", &value));
ensure_equals("(3)", *value, "5");
table.insert("Host", "foo.com");
ensure_equals(table.size(), 2u);
ensure(!table.lookup("hello", &value));
ensure_equals<void *>("(5)", value, NULL);
ensure(table.lookup("Host", &value));
ensure_equals("(6)", *value, "foo.com");
ensure(table.lookup("Content-Length", &value));
ensure_equals("(7)", *value, "5");
}
TEST_METHOD(5) {
set_test_name("Large amounts of insertions");
table.insert("Host", "foo.com");
table.insert("Content-Length", "5");
table.insert("Accept", "text/html");
table.insert("Accept-Encoding", "gzip");
table.insert("Accept-Language", "nl");
table.insert("User-Agent", "Mozilla");
table.insert("Set-Cookie", "foo=bar");
table.insert("Connection", "keep-alive");
table.insert("Cache-Control", "no-cache");
table.insert("Pragma", "no-cache");
ensure(!table.lookup("MyHeader", &value));
ensure(table.lookup("Host", &value));
ensure_equals(*value, "foo.com");
ensure(table.lookup("Content-Length", &value));
ensure_equals(*value, "5");
ensure(table.lookup("Accept", &value));
ensure_equals(*value, "text/html");
ensure(table.lookup("Accept-Encoding", &value));
ensure_equals(*value, "gzip");
ensure(table.lookup("Accept-Language", &value));
ensure_equals(*value, "nl");
ensure(table.lookup("User-Agent", &value));
ensure_equals(*value, "Mozilla");
ensure(table.lookup("Set-Cookie", &value));
ensure_equals(*value, "foo=bar");
ensure(table.lookup("Connection", &value));
ensure_equals(*value, "keep-alive");
ensure(table.lookup("Cache-Control", &value));
ensure_equals(*value, "no-cache");
ensure(table.lookup("Pragma", &value));
ensure_equals(*value, "no-cache");
}
TEST_METHOD(6) {
set_test_name("Iterators work");
table.insert("Content-Length", "5");
table.insert("Host", "foo.com");
StringKeyTable<string>::Iterator it(table);
ensure(*it != NULL);
if (it.getKey() == "Content-Length") {
ensure_equals(it.getKey(), "Content-Length");
it.next();
ensure_equals(it.getKey(), "Host");
} else {
ensure_equals(it.getKey(), "Host");
it.next();
ensure_equals(it.getKey(), "Content-Length");
}
it.next();
ensure_equals<void *>(*it, NULL);
}
TEST_METHOD(7) {
set_test_name("Dynamically growing the bucket on insert");
table = StringKeyTable<string>(4);
ensure_equals(table.size(), 0u);
ensure_equals(table.arraySize(), 4u);
table.insert("Host", "foo.com");
table.insert("Content-Length", "5");
ensure_equals(table.size(), 2u);
ensure_equals(table.arraySize(), 4u);
table.insert("Accept", "text/html");
ensure_equals(table.size(), 3u);
ensure_equals(table.arraySize(), 8u);
ensure(!table.lookup("MyHeader", &value));
ensure_equals<void *>(value, NULL);
ensure(table.lookup("Host", &value));
ensure_equals(*value, "foo.com");
ensure(table.lookup("Content-Length", &value));
ensure_equals(*value, "5");
ensure(table.lookup("Accept", &value));
ensure_equals(*value, "text/html");
}
TEST_METHOD(8) {
set_test_name("Clearing");
table.insert("Host", "foo.com");
table.insert("Content-Length", "5");
table.insert("Accept", "text/html");
table.clear();
ensure_equals(table.size(), 0u);
ensure_equals(table.arraySize(), (unsigned int) StringKeyTable<string>::DEFAULT_SIZE);
ensure(!table.lookup("Host", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookup("Content-Length", &value));
ensure_equals<void *>(value, NULL);
ensure(!table.lookup("Accept", &value));
ensure_equals<void *>(value, NULL);
}
TEST_METHOD(9) {
set_test_name("lookupRandom() works");
HashedStaticString key;
table.insert("a", "1");
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "a");
ensure_equals(*value, "1");
table.insert("b", "2");
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "b");
ensure_equals(*value, "2");
table.insert("c", "3");
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "c");
ensure_equals(*value, "3");
ensure(table.erase("b"));
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "c");
ensure_equals(*value, "3");
ensure(table.erase("c"));
ensure(table.lookupRandom(&key, &value));
ensure_equals(key, "a");
ensure_equals(*value, "1");
ensure(table.erase("a"));
ensure(!table.lookupRandom(&key, &value));
}
TEST_METHOD(10) {
set_test_name("Initial size 0");
StringKeyTable<string> t(0, 0);
ensure_equals(t.lookupCopy("a"), "");
t.insert("a", "b");
ensure_equals(t.lookupCopy("a"), "b");
}
TEST_METHOD(11) {
set_test_name("Move support");
StringKeyTable<Counter, SKT_EnableMoveSupport> t(1);
Counter *result;
ensure_equals("Initial table array size is 1", t.arraySize(), 1u);
t.insertByMoving("a", Counter(1));
ensure("1: a is in the table", t.lookup("a", &result));
ensure_equals("1: a's value is 1", result->value, 1);
Counter f(2);
t.insertByMoving("a", boost::move(f));
ensure("2: a is in the table", t.lookup("a", &result));
ensure_equals("2: a's value is 2", result->value, 2);
ensure_equals("2: original variable's value is -1", f.value, -1);
t.insertByMoving("b", Counter(3));
ensure_equals("3: New table array size is 2", t.arraySize(), 4u);
ensure("3: a is in the table", t.lookup("a", &result));
ensure_equals("3: a's value is 2", result->value, 2);
ensure("3: a is in the table", t.lookup("b", &result));
ensure_equals("3: b's value is 3", result->value, 3);
}
}
<|endoftext|> |
<commit_before>/**
* The goal of these tests is to verify the behavior of all blob commands given
* the current state is notYetStarted. The initial state.
*/
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include <cstdint>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace ipmi_flash
{
namespace
{
using ::testing::Return;
using ::testing::UnorderedElementsAreArray;
class FirmwareHandlerNotYetStartedTest : public IpmiOnlyFirmwareStaticTest
{
protected:
std::uint16_t session = 1;
std::uint16_t flags =
blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;
};
/*
* There are the following calls (parameters may vary):
* Note: you cannot have a session yet, so only commands that don't take a
* session parameter are valid. Once you open() from this state, we will vary
* you transition out of this state (ensuring the above is true). Technically
* the firmware handler receives the session number with open(), but the blob
* manager is providing this normally.
*
* canHandleBlob
* getBlobIds
* deleteBlob
* stat
* open
*
* canHandleBlob is just a count check (or something similar) against what is
* returned by getBlobIds. It is tested in firmware_canhandle_unittest
*/
TEST_F(FirmwareHandlerNotYetStartedTest, GetBlobListValidateListContents)
{
/* TODO: Presently, /flash/verify is present from the beginning, however,
* this is going to change to simplify handling of open().
*/
std::vector<std::string> expectedBlobs = {staticLayoutBlobId, hashBlobId,
verifyBlobId};
EXPECT_THAT(handler->getBlobIds(),
UnorderedElementsAreArray(expectedBlobs));
}
/* TODO: Try deleting some blobs -- in this state it should just return failure,
* but it's not yet implemented
*/
/* stat(blob_id) */
TEST_F(FirmwareHandlerNotYetStartedTest, StatEachBlobIdVerifyResults)
{
/* In this original state, calling stat() on the blob ids will return the
* transported supported.
*/
blobs::BlobMeta expected;
expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
expected.size = 0;
/* TODO: note, once verifyblobid isn't present in this state we can use
* getblobids()'s output as input
*/
std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
for (const auto& blob : testBlobs)
{
blobs::BlobMeta meta = {};
EXPECT_TRUE(handler->stat(blob, &meta));
EXPECT_EQ(expected, meta);
}
}
/* open(each blob id) (verifyblobid will no longer be available at this state.
*/
TEST_F(FirmwareHandlerNotYetStartedTest, OpenStaticImageFileVerifyStateChange)
{
auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
EXPECT_CALL(imageMock, open(staticLayoutBlobId)).WillOnce(Return(true));
EXPECT_TRUE(handler->open(session, flags, staticLayoutBlobId));
EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,
realHandler->getCurrentState());
}
TEST_F(FirmwareHandlerNotYetStartedTest, OpenHashFileVerifyStateChange)
{
auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
EXPECT_CALL(imageMock, open(hashBlobId)).WillOnce(Return(true));
EXPECT_TRUE(handler->open(session, flags, hashBlobId));
EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,
realHandler->getCurrentState());
}
} // namespace
} // namespace ipmi_flash
<commit_msg>test: firmware notYetStarted: canHandleBlob<commit_after>/**
* The goal of these tests is to verify the behavior of all blob commands given
* the current state is notYetStarted. The initial state.
*/
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include <cstdint>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace ipmi_flash
{
namespace
{
using ::testing::Return;
using ::testing::UnorderedElementsAreArray;
class FirmwareHandlerNotYetStartedTest : public IpmiOnlyFirmwareStaticTest
{
protected:
std::uint16_t session = 1;
std::uint16_t flags =
blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;
};
/*
* There are the following calls (parameters may vary):
* Note: you cannot have a session yet, so only commands that don't take a
* session parameter are valid. Once you open() from this state, we will vary
* you transition out of this state (ensuring the above is true). Technically
* the firmware handler receives the session number with open(), but the blob
* manager is providing this normally.
*
* canHandleBlob
* getBlobIds
* deleteBlob
* stat
* open
*
* canHandleBlob is just a count check (or something similar) against what is
* returned by getBlobIds. It is tested in firmware_canhandle_unittest
*/
TEST_F(FirmwareHandlerNotYetStartedTest, GetBlobListValidateListContents)
{
/* TODO: Presently, /flash/verify is present from the beginning, however,
* this is going to change to simplify handling of open().
*/
std::vector<std::string> expectedBlobs = {staticLayoutBlobId, hashBlobId,
verifyBlobId};
EXPECT_THAT(handler->getBlobIds(),
UnorderedElementsAreArray(expectedBlobs));
for (const auto& blob : expectedBlobs)
{
EXPECT_TRUE(handler->canHandleBlob(blob));
}
}
/* TODO: Try deleting some blobs -- in this state it should just return failure,
* but it's not yet implemented
*/
/* stat(blob_id) */
TEST_F(FirmwareHandlerNotYetStartedTest, StatEachBlobIdVerifyResults)
{
/* In this original state, calling stat() on the blob ids will return the
* transported supported.
*/
blobs::BlobMeta expected;
expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
expected.size = 0;
/* TODO: note, once verifyblobid isn't present in this state we can use
* getblobids()'s output as input
*/
std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
for (const auto& blob : testBlobs)
{
blobs::BlobMeta meta = {};
EXPECT_TRUE(handler->stat(blob, &meta));
EXPECT_EQ(expected, meta);
}
}
/* open(each blob id) (verifyblobid will no longer be available at this state.
*/
TEST_F(FirmwareHandlerNotYetStartedTest, OpenStaticImageFileVerifyStateChange)
{
auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
EXPECT_CALL(imageMock, open(staticLayoutBlobId)).WillOnce(Return(true));
EXPECT_TRUE(handler->open(session, flags, staticLayoutBlobId));
EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,
realHandler->getCurrentState());
}
TEST_F(FirmwareHandlerNotYetStartedTest, OpenHashFileVerifyStateChange)
{
auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
EXPECT_CALL(imageMock, open(hashBlobId)).WillOnce(Return(true));
EXPECT_TRUE(handler->open(session, flags, hashBlobId));
EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,
realHandler->getCurrentState());
}
} // namespace
} // namespace ipmi_flash
<|endoftext|> |
<commit_before>/*
* SessionTexEngine.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionTexEngine.hpp"
#include <boost/foreach.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <r/RExec.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionModuleContext.hpp>
using namespace core;
namespace session {
namespace modules {
namespace tex {
namespace engine {
namespace {
FilePath texBinaryPath(const std::string& name)
{
std::string which;
Error error = r::exec::RFunction("Sys.which", name).call(&which);
if (error)
{
LOG_ERROR(error);
return FilePath();
}
else
{
return FilePath(which);
}
}
// this function attempts to emulate the behavior of tools::texi2dvi
// in appending extra paths to TEXINPUTS, BIBINPUTS, & BSTINPUTS
core::system::Option texEnvVar(const std::string& name,
const FilePath& extraPath,
bool ensureForwardSlashes)
{
std::string value = core::system::getenv(name);
if (value.empty())
value = ".";
if (ensureForwardSlashes)
boost::algorithm::replace_all(value, "\\", "/");
core::system::addToPath(&value, extraPath.absolutePath());
core::system::addToPath(&value, ""); // trailing : required by tex
return std::make_pair(name, value);
}
core::system::Option pdfLatexEnvVar()
{
std::string pdfLatexCmd =
string_utils::utf8ToSystem(texBinaryPath("pdflatex").absolutePath());
pdfLatexCmd += " --file-line-error --synctex=-1";
return std::make_pair("PDFLATEX", pdfLatexCmd);
}
core::system::Options texEnvironmentVars()
{
// custom environment for tex
core::system::Options envVars;
// TODO: R texi2dvi sets LC_COLLATE=C before calling texi2dvi, why?
envVars.push_back(std::make_pair("LC_COLLATE", "C"));
// first determine the R share directory
std::string rHomeShare;
r::exec::RFunction rHomeShareFunc("R.home", "share");
Error error = rHomeShareFunc.call(&rHomeShare);
if (error)
{
LOG_ERROR(error);
return core::system::Options();
}
FilePath rHomeSharePath(rHomeShare);
if (!rHomeSharePath.exists())
{
LOG_ERROR(core::pathNotFoundError(rHomeShare, ERROR_LOCATION));
return core::system::Options();
}
// R texmf path
FilePath rTexmfPath(rHomeSharePath.complete("texmf"));
// fixup tex related environment variables to point to the R
// tex, bib, and bst directories
envVars.push_back(texEnvVar("TEXINPUTS",
rTexmfPath.childPath("tex/latex"),
true));
envVars.push_back(texEnvVar("BIBINPUTS",
rTexmfPath.childPath("bibtex/bib"),
false));
envVars.push_back(texEnvVar("BSTINPUTS",
rTexmfPath.childPath("bibtex/bst"),
false));
// define a custom variation of PDFLATEX that includes the
// command line parameters we need
envVars.push_back(pdfLatexEnvVar());
return envVars;
}
shell_utils::ShellArgs texShellArgs()
{
shell_utils::ShellArgs args;
args << "--pdf";
args << "--quiet";
return args;
}
Error executeTexToPdf(const FilePath& texProgramPath,
const core::system::Options& envVars,
const shell_utils::ShellArgs& args,
const FilePath& texFilePath)
{
// copy extra environment variables
core::system::Options env;
core::system::environment(&env);
BOOST_FOREACH(const core::system::Option& var, envVars)
{
core::system::setenv(&env, var.first, var.second);
}
// setup args
shell_utils::ShellArgs procArgs;
procArgs << args;
procArgs << texFilePath.filename();
// set options
core::system::ProcessOptions procOptions;
procOptions.terminateChildren = true;
procOptions.environment = env;
procOptions.workingDir = texFilePath.parent();
// setup callbacks
core::system::ProcessCallbacks cb;
cb.onStdout = boost::bind(module_context::consoleWriteOutput, _2);
cb.onStderr = boost::bind(module_context::consoleWriteError, _2);
// run the program
using namespace core::shell_utils;
return module_context::processSupervisor().runProgram(
texProgramPath.absolutePath(),
procArgs,
procOptions,
cb);
}
SEXP rs_texToPdf(SEXP filePathSEXP)
{
FilePath texFilePath =
module_context::resolveAliasedPath(r::sexp::asString(filePathSEXP));
Error error = executeTexToPdf(texBinaryPath("texi2dvi"),
texEnvironmentVars(),
texShellArgs(),
texFilePath);
if (error)
module_context::consoleWriteError(error.summary() + "\n");
return R_NilValue;
}
} // anonymous namespace
Error initialize()
{
R_CallMethodDef runTexToPdfMethodDef;
runTexToPdfMethodDef.name = "rs_texToPdf" ;
runTexToPdfMethodDef.fun = (DL_FUNC) rs_texToPdf ;
runTexToPdfMethodDef.numArgs = 1;
r::routines::addCallMethod(runTexToPdfMethodDef);
return Success();
}
} // namespace engine
} // namespace tex
} // namespace modules
} // namesapce session
<commit_msg>add some tex todos<commit_after>/*
* SessionTexEngine.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionTexEngine.hpp"
#include <boost/foreach.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <r/RExec.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionModuleContext.hpp>
// TODO: why does R texi2dvi set LC_COLLATE=C?
// TODO: respect getOption("texi2dvi") and fallback appropriately
// TODO: investigate other texi2dvi and pdflatex options
// -- shell-escape
// -- clean
// -- alternative output file location
using namespace core;
namespace session {
namespace modules {
namespace tex {
namespace engine {
namespace {
FilePath texBinaryPath(const std::string& name)
{
std::string which;
Error error = r::exec::RFunction("Sys.which", name).call(&which);
if (error)
{
LOG_ERROR(error);
return FilePath();
}
else
{
return FilePath(which);
}
}
// this function attempts to emulate the behavior of tools::texi2dvi
// in appending extra paths to TEXINPUTS, BIBINPUTS, & BSTINPUTS
core::system::Option texEnvVar(const std::string& name,
const FilePath& extraPath,
bool ensureForwardSlashes)
{
std::string value = core::system::getenv(name);
if (value.empty())
value = ".";
if (ensureForwardSlashes)
boost::algorithm::replace_all(value, "\\", "/");
core::system::addToPath(&value, extraPath.absolutePath());
core::system::addToPath(&value, ""); // trailing : required by tex
return std::make_pair(name, value);
}
core::system::Option pdfLatexEnvVar()
{
std::string pdfLatexCmd =
string_utils::utf8ToSystem(texBinaryPath("pdflatex").absolutePath());
pdfLatexCmd += " --file-line-error --synctex=-1";
return std::make_pair("PDFLATEX", pdfLatexCmd);
}
core::system::Options texEnvironmentVars()
{
// custom environment for tex
core::system::Options envVars;
// TODO: R texi2dvi sets LC_COLLATE=C before calling texi2dvi, why?
envVars.push_back(std::make_pair("LC_COLLATE", "C"));
// first determine the R share directory
std::string rHomeShare;
r::exec::RFunction rHomeShareFunc("R.home", "share");
Error error = rHomeShareFunc.call(&rHomeShare);
if (error)
{
LOG_ERROR(error);
return core::system::Options();
}
FilePath rHomeSharePath(rHomeShare);
if (!rHomeSharePath.exists())
{
LOG_ERROR(core::pathNotFoundError(rHomeShare, ERROR_LOCATION));
return core::system::Options();
}
// R texmf path
FilePath rTexmfPath(rHomeSharePath.complete("texmf"));
// fixup tex related environment variables to point to the R
// tex, bib, and bst directories
envVars.push_back(texEnvVar("TEXINPUTS",
rTexmfPath.childPath("tex/latex"),
true));
envVars.push_back(texEnvVar("BIBINPUTS",
rTexmfPath.childPath("bibtex/bib"),
false));
envVars.push_back(texEnvVar("BSTINPUTS",
rTexmfPath.childPath("bibtex/bst"),
false));
// define a custom variation of PDFLATEX that includes the
// command line parameters we need
envVars.push_back(pdfLatexEnvVar());
return envVars;
}
shell_utils::ShellArgs texShellArgs()
{
shell_utils::ShellArgs args;
args << "--pdf";
args << "--quiet";
return args;
}
Error executeTexToPdf(const FilePath& texProgramPath,
const core::system::Options& envVars,
const shell_utils::ShellArgs& args,
const FilePath& texFilePath)
{
// copy extra environment variables
core::system::Options env;
core::system::environment(&env);
BOOST_FOREACH(const core::system::Option& var, envVars)
{
core::system::setenv(&env, var.first, var.second);
}
// setup args
shell_utils::ShellArgs procArgs;
procArgs << args;
procArgs << texFilePath.filename();
// set options
core::system::ProcessOptions procOptions;
procOptions.terminateChildren = true;
procOptions.environment = env;
procOptions.workingDir = texFilePath.parent();
// setup callbacks
core::system::ProcessCallbacks cb;
cb.onStdout = boost::bind(module_context::consoleWriteOutput, _2);
cb.onStderr = boost::bind(module_context::consoleWriteError, _2);
// run the program
using namespace core::shell_utils;
return module_context::processSupervisor().runProgram(
texProgramPath.absolutePath(),
procArgs,
procOptions,
cb);
}
SEXP rs_texToPdf(SEXP filePathSEXP)
{
FilePath texFilePath =
module_context::resolveAliasedPath(r::sexp::asString(filePathSEXP));
Error error = executeTexToPdf(texBinaryPath("texi2dvi"),
texEnvironmentVars(),
texShellArgs(),
texFilePath);
if (error)
module_context::consoleWriteError(error.summary() + "\n");
return R_NilValue;
}
} // anonymous namespace
Error initialize()
{
R_CallMethodDef runTexToPdfMethodDef;
runTexToPdfMethodDef.name = "rs_texToPdf" ;
runTexToPdfMethodDef.fun = (DL_FUNC) rs_texToPdf ;
runTexToPdfMethodDef.numArgs = 1;
r::routines::addCallMethod(runTexToPdfMethodDef);
return Success();
}
} // namespace engine
} // namespace tex
} // namespace modules
} // namesapce session
<|endoftext|> |
<commit_before>/*
* SessionData.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionData.hpp"
#include <core/Exec.hpp>
#include <r/RExec.hpp>
#include <r/RErrorCategory.hpp>
#include <r/RJson.hpp>
#include <r/RSourceManager.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncRProcess.hpp>
#include "DataViewer.hpp"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace data {
class AsyncDataPreviewRProcess : public async_r::AsyncRProcess
{
public:
static boost::shared_ptr<AsyncDataPreviewRProcess> create(
const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& continuation)
{
boost::shared_ptr<AsyncDataPreviewRProcess> pDataPreview(
new AsyncDataPreviewRProcess(request, continuation));
pDataPreview->start();
return pDataPreview;
}
private:
AsyncDataPreviewRProcess(
const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& continuation) :
continuation_(continuation),
request_(request)
{
}
FilePath pathFromModulesSource(std::string sourceFile)
{
FilePath modulesPath = session::options().modulesRSourcePath();
FilePath srcPath = modulesPath.completePath(sourceFile);
return srcPath;
}
FilePath pathFromSource(std::string sourceFile)
{
FilePath sourcesPath = session::options().coreRSourcePath();
FilePath srcPath = sourcesPath.completePath(sourceFile);
return srcPath;
}
Error saveRDS(const json::JsonRpcRequest& request)
{
r::sexp::Protect rProtect;
r::exec::RFunction rFunction("saveRDS");
rFunction.addParam(request.params);
rFunction.addParam("file", inputLocation_);
SEXP resultSEXP;
return rFunction.call(&resultSEXP, &rProtect);
}
void start()
{
inputLocation_ = module_context::tempFile("input", "rds").getAbsolutePath();
outputLocation_ = module_context::tempFile("output", "rds").getAbsolutePath();
Error err = saveRDS(request_);
if (err)
{
continuationWithError("Failed to prepare the operation.");
return;
}
std::string cmd = std::string(".rs.callWithRDS(") +
"\".rs.rpc.preview_data_import\", \"" +
inputLocation_ +
"\", \"" +
outputLocation_ +
"\")";
std::vector<core::FilePath> sources;
sources.push_back(pathFromSource("Tools.R"));
sources.push_back(pathFromModulesSource("ModuleTools.R"));
sources.push_back(pathFromModulesSource("SessionDataViewer.R"));
sources.push_back(pathFromModulesSource("SessionDataImportV2.R"));
async_r::AsyncRProcess::start(cmd.c_str(), FilePath(), async_r::R_PROCESS_VANILLA, sources);
}
Error readRDS(SEXP* pResult)
{
r::sexp::Protect rProtect;
r::exec::RFunction rFunction("readRDS");
rFunction.addParam(outputLocation_);
rFunction.call(pResult, &rProtect);
return Success();
}
void continuationWithError(const char* message)
{
json::Object jsonError;
jsonError["message"] = message;
if (errors_.size() > 0)
{
jsonError["message"] = json::toJsonArray(errors_);
}
json::Object jsonErrorResponse;
jsonErrorResponse["error"] = jsonError;
json::JsonRpcResponse response;
response.setResult(jsonErrorResponse);
continuation_(Success(), &response);
}
void onCompleted(int exitStatus)
{
if (terminationRequested())
{
json::JsonRpcResponse response;
continuation_(Success(), &response);
return;
}
if (exitStatus != EXIT_SUCCESS)
{
continuationWithError("Operation finished with error code.");
return;
}
SEXP resultSEXP;;
Error error = readRDS(&resultSEXP);
if (error)
{
continuationWithError("Failed to complete the operation.");
return;
}
else
{
core::json::Value resultValue;
error = r::json::jsonValueFromObject(resultSEXP, &resultValue);
if (error)
{
continuationWithError("Failed to parse result from the operation execution.");
return;
}
json::JsonRpcResponse response;
response.setResult(resultValue);
continuation_(Success(), &response);
}
}
void onStdout(const std::string& output)
{
output_ += output;
}
void onStderr(const std::string& output)
{
errors_.push_back(output);
}
const json::JsonRpcFunctionContinuation continuation_;
json::JsonRpcRequest request_;
std::vector<std::string> errors_;
std::string output_;
std::string inputLocation_;
std::string outputLocation_;
};
boost::shared_ptr<AsyncDataPreviewRProcess> s_pActiveDataPreview;
bool getPreviewDataImportAsync(
const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& continuation)
{
if (s_pActiveDataPreview &&
s_pActiveDataPreview->isRunning())
{
return true;
}
else
{
s_pActiveDataPreview = AsyncDataPreviewRProcess::create(request, continuation);
return false;
}
}
Error abortPreviewDataImportAsync(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
if (s_pActiveDataPreview &&
s_pActiveDataPreview->isRunning())
{
s_pActiveDataPreview->terminate();
}
return Success();
}
Error initialize()
{
using boost::bind;
using namespace session::module_context;
ExecBlock initBlock;
initBlock.addFunctions()
(data::viewer::initialize)
(bind(sourceModuleRFile, "SessionDataImport.R"))
(bind(sourceModuleRFile, "SessionDataImportV2.R"))
(bind(sourceModuleRFile, "SessionDataPreview.R"))
(bind(registerAsyncRpcMethod, "preview_data_import_async", getPreviewDataImportAsync))
(bind(registerRpcMethod, "preview_data_import_async_abort", abortPreviewDataImportAsync));
return initBlock.execute();
}
} // namespace data
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>import CodeTools.R for .rs.tryCatch (#7828)<commit_after>/*
* SessionData.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionData.hpp"
#include <core/Exec.hpp>
#include <r/RExec.hpp>
#include <r/RErrorCategory.hpp>
#include <r/RJson.hpp>
#include <r/RSourceManager.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncRProcess.hpp>
#include "DataViewer.hpp"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace data {
class AsyncDataPreviewRProcess : public async_r::AsyncRProcess
{
public:
static boost::shared_ptr<AsyncDataPreviewRProcess> create(
const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& continuation)
{
boost::shared_ptr<AsyncDataPreviewRProcess> pDataPreview(
new AsyncDataPreviewRProcess(request, continuation));
pDataPreview->start();
return pDataPreview;
}
private:
AsyncDataPreviewRProcess(
const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& continuation) :
continuation_(continuation),
request_(request)
{
}
FilePath pathFromModulesSource(std::string sourceFile)
{
FilePath modulesPath = session::options().modulesRSourcePath();
FilePath srcPath = modulesPath.completePath(sourceFile);
return srcPath;
}
FilePath pathFromSource(std::string sourceFile)
{
FilePath sourcesPath = session::options().coreRSourcePath();
FilePath srcPath = sourcesPath.completePath(sourceFile);
return srcPath;
}
Error saveRDS(const json::JsonRpcRequest& request)
{
r::sexp::Protect rProtect;
r::exec::RFunction rFunction("saveRDS");
rFunction.addParam(request.params);
rFunction.addParam("file", inputLocation_);
SEXP resultSEXP;
return rFunction.call(&resultSEXP, &rProtect);
}
void start()
{
inputLocation_ = module_context::tempFile("input", "rds").getAbsolutePath();
outputLocation_ = module_context::tempFile("output", "rds").getAbsolutePath();
Error err = saveRDS(request_);
if (err)
{
continuationWithError("Failed to prepare the operation.");
return;
}
std::string cmd = std::string(".rs.callWithRDS(") +
"\".rs.rpc.preview_data_import\", \"" +
inputLocation_ +
"\", \"" +
outputLocation_ +
"\")";
std::vector<core::FilePath> sources;
sources.push_back(pathFromSource("Tools.R"));
sources.push_back(pathFromModulesSource("ModuleTools.R"));
sources.push_back(pathFromModulesSource("SessionCodeTools.R"));
sources.push_back(pathFromModulesSource("SessionDataViewer.R"));
sources.push_back(pathFromModulesSource("SessionDataImportV2.R"));
async_r::AsyncRProcess::start(cmd.c_str(), FilePath(), async_r::R_PROCESS_VANILLA, sources);
}
Error readRDS(SEXP* pResult)
{
r::sexp::Protect rProtect;
r::exec::RFunction rFunction("readRDS");
rFunction.addParam(outputLocation_);
rFunction.call(pResult, &rProtect);
return Success();
}
void continuationWithError(const char* message)
{
json::Object jsonError;
jsonError["message"] = message;
if (errors_.size() > 0)
{
jsonError["message"] = json::toJsonArray(errors_);
}
json::Object jsonErrorResponse;
jsonErrorResponse["error"] = jsonError;
json::JsonRpcResponse response;
response.setResult(jsonErrorResponse);
continuation_(Success(), &response);
}
void onCompleted(int exitStatus)
{
if (terminationRequested())
{
json::JsonRpcResponse response;
continuation_(Success(), &response);
return;
}
if (exitStatus != EXIT_SUCCESS)
{
continuationWithError("Operation finished with error code.");
return;
}
SEXP resultSEXP;;
Error error = readRDS(&resultSEXP);
if (error)
{
continuationWithError("Failed to complete the operation.");
return;
}
else
{
core::json::Value resultValue;
error = r::json::jsonValueFromObject(resultSEXP, &resultValue);
if (error)
{
continuationWithError("Failed to parse result from the operation execution.");
return;
}
json::JsonRpcResponse response;
response.setResult(resultValue);
continuation_(Success(), &response);
}
}
void onStdout(const std::string& output)
{
output_ += output;
}
void onStderr(const std::string& output)
{
errors_.push_back(output);
}
const json::JsonRpcFunctionContinuation continuation_;
json::JsonRpcRequest request_;
std::vector<std::string> errors_;
std::string output_;
std::string inputLocation_;
std::string outputLocation_;
};
boost::shared_ptr<AsyncDataPreviewRProcess> s_pActiveDataPreview;
bool getPreviewDataImportAsync(
const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& continuation)
{
if (s_pActiveDataPreview &&
s_pActiveDataPreview->isRunning())
{
return true;
}
else
{
s_pActiveDataPreview = AsyncDataPreviewRProcess::create(request, continuation);
return false;
}
}
Error abortPreviewDataImportAsync(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
if (s_pActiveDataPreview &&
s_pActiveDataPreview->isRunning())
{
s_pActiveDataPreview->terminate();
}
return Success();
}
Error initialize()
{
using boost::bind;
using namespace session::module_context;
ExecBlock initBlock;
initBlock.addFunctions()
(data::viewer::initialize)
(bind(sourceModuleRFile, "SessionDataImport.R"))
(bind(sourceModuleRFile, "SessionDataImportV2.R"))
(bind(sourceModuleRFile, "SessionDataPreview.R"))
(bind(registerAsyncRpcMethod, "preview_data_import_async", getPreviewDataImportAsync))
(bind(registerRpcMethod, "preview_data_import_async_abort", abortPreviewDataImportAsync));
return initBlock.execute();
}
} // namespace data
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>/*
* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
* Numenta, Inc. a separate commercial license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#include <nta/types/BasicType.hpp>
#include <nta/engine/YAMLUtils.hpp>
#include <nta/ntypes/Value.hpp>
#include <nta/ntypes/Collection.hpp>
#include <nta/ntypes/MemStream.hpp>
#include <nta/engine/Spec.hpp>
#include <string.h> // strlen
#include <yaml-cpp/yaml.h>
#include <sstream>
namespace nta
{
namespace YAMLUtils
{
/*
* These functions are used internally by toValue and toValueMap
*/
static void toScalar(const YAML::Node& node, boost::shared_ptr<Scalar>& s);
static void toArray(const YAML::Node& node, boost::shared_ptr<Array>& a);
static Value toValue(const YAML::Node& node, NTA_BasicType dataType);
static void toScalar(const YAML::Node& node, boost::shared_ptr<Scalar>& s)
{
NTA_CHECK(node.Type() == YAML::NodeType::Scalar);
switch(s->getType())
{
case NTA_BasicType_Byte:
// We should have already detected this and gone down the string path
NTA_THROW << "Internal error: attempting to convert YAML string to scalar of type Byte";
break;
case NTA_BasicType_UInt16:
node >> s->value.uint16;
break;
case NTA_BasicType_Int16:
node >> s->value.int16;
break;
case NTA_BasicType_UInt32:
node >> s->value.uint32;
break;
case NTA_BasicType_Int32:
node >> s->value.int32;
break;
case NTA_BasicType_UInt64:
node >> s->value.uint64;
break;
case NTA_BasicType_Int64:
node >> s->value.int64;
break;
case NTA_BasicType_Real32:
node >> s->value.real32;
break;
case NTA_BasicType_Real64:
node >> s->value.real64;
break;
case NTA_BasicType_Handle:
NTA_THROW << "Attempt to specify a YAML value for a scalar of type Handle";
break;
default:
// should not happen
std::string val;
node >> val;
NTA_THROW << "Unknown data type " << s->getType() << " for yaml node '" << val << "'";
}
}
static void toArray(const YAML::Node& node, boost::shared_ptr<Array>& a)
{
NTA_CHECK(node.Type() == YAML::NodeType::Sequence);
a->allocateBuffer(node.size());
void* buffer = a->getBuffer();
for (size_t i = 0; i < node.size(); i++)
{
const YAML::Node& item = node[i];
NTA_CHECK(item.Type() == YAML::NodeType::Scalar);
switch(a->getType())
{
case NTA_BasicType_Byte:
// We should have already detected this and gone down the string path
NTA_THROW << "Internal error: attempting to convert YAML string to array of type Byte";
break;
case NTA_BasicType_UInt16:
item.to<UInt16>();
break;
case NTA_BasicType_Int16:
item.to<Int16>();
break;
case NTA_BasicType_UInt32:
item.to<UInt32>();
break;
case NTA_BasicType_Int32:
item.to<Int32>();
break;
case NTA_BasicType_UInt64:
item.to<UInt64>();
break;
case NTA_BasicType_Int64:
item.to<Int64>();
break;
case NTA_BasicType_Real32:
item.to<Real32>();
break;
case NTA_BasicType_Real64:
item.to<Real64>();
break;
default:
// should not happen
NTA_THROW << "Unknown data type " << a->getType();
}
}
}
static Value toValue(const YAML::Node& node, NTA_BasicType dataType)
{
if (node.Type() == YAML::NodeType::Map || node.Type() == YAML::NodeType::Null)
{
NTA_THROW << "YAML string does not not represent a value.";
}
if (node.Type() == YAML::NodeType::Scalar)
{
if (dataType == NTA_BasicType_Byte)
{
// node >> *str;
std::string val;
node.Read(val);
boost::shared_ptr<std::string> str(new std::string(val));
Value v(str);
return v;
} else {
boost::shared_ptr<Scalar> s(new Scalar(dataType));
toScalar(node, s);
Value v(s);
return v;
}
} else {
// array
boost::shared_ptr<Array> a(new Array(dataType));
toArray(node, a);
Value v(a);
return v;
}
}
/*
* For converting default values specified in nodespec
*/
Value toValue(const std::string& yamlstring, NTA_BasicType dataType)
{
// IMemStream s(yamlstring, ::strlen(yamlstring));
// yaml-cpp bug: append a space if it is only one character
// This is very inefficient, but should be ok since it is
// just used at construction time for short strings
std::string paddedstring(yamlstring);
if (paddedstring.size() < 2)
paddedstring = paddedstring + " ";
std::stringstream s(paddedstring);
// TODO -- return value? exceptions?
bool success = false;
YAML::Node doc;
try
{
YAML::Parser parser(s);
success = parser.GetNextDocument(doc);
// } catch(YAML::ParserException& e) {
} catch(...) {
success = false;
}
if (!success)
{
std::string ys(paddedstring);
if (ys.size() > 30)
{
ys = ys.substr(0, 30) + "...";
}
NTA_THROW << "Unable to parse YAML string '" << ys << "' for a scalar value";
}
Value v = toValue(doc, dataType);
return v;
}
/*
* For converting param specs for Regions and LinkPolicies
*/
ValueMap toValueMap(const char* yamlstring,
Collection<ParameterSpec>& parameters,
const std::string & nodeType,
const std::string & regionName)
{
ValueMap vm;
// yaml-cpp bug: append a space if it is only one character
// This is very inefficient, but should be ok since it is
// just used at construction time for short strings
std::string paddedstring(yamlstring);
// TODO: strip white space to determine if empty
bool empty = (paddedstring.size() == 0);
if (paddedstring.size() < 2)
paddedstring = paddedstring + " ";
std::stringstream s(paddedstring);
// IMemStream s(yamlstring, ::strlen(yamlstring));
// TODO: utf-8 compatible?
YAML::Node doc;
if (!empty)
{
YAML::Parser parser(s);
bool success = parser.GetNextDocument(doc);
if (!success)
NTA_THROW << "Unable to find document in YAML string";
// A ValueMap is specified as a dictionary
if (doc.Type() != YAML::NodeType::Map)
{
std::string ys(yamlstring);
if (ys.size() > 30)
{
ys = ys.substr(0, 30) + "...";
}
NTA_THROW << "YAML string '" << ys
<< "' does not not specify a dictionary of key-value pairs. "
<< "Region and Link parameters must be specified at a dictionary";
}
}
// Grab each value out of the YAML dictionary and put into the ValueMap
// if it is allowed by the nodespec.
YAML::Iterator i;
for (i = doc.begin(); i != doc.end(); i++)
{
const std::string key = i.first().to<std::string>();
if (!parameters.contains(key))
{
std::stringstream ss;
for (UInt j = 0; j < parameters.getCount(); j++)
{
ss << " " << parameters.getByIndex(j).first << "\n";
}
if (nodeType == std::string(""))
{
NTA_THROW << "Unknown parameter '" << key << "'\n"
<< "Valid parameters are:\n" << ss.str();
}
else
{
NTA_CHECK(regionName != std::string(""));
NTA_THROW << "Unknown parameter '" << key << "' for region '"
<< regionName << "' of type '" << nodeType << "'\n"
<< "Valid parameters are:\n" << ss.str();
}
}
if (vm.contains(key))
NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
ParameterSpec spec = parameters.getByName(key);
try
{
Value v = toValue(i.second(), spec.dataType);
if (v.isScalar() && spec.count != 1)
{
throw std::runtime_error("Expected array value but got scalar value");
}
if (!v.isScalar() && spec.count == 1)
{
throw std::runtime_error("Expected scalar value but got array value");
}
vm.add(key, v);
} catch (std::runtime_error& e) {
NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
}
}
// Populate ValueMap with default values if they were not specified in the YAML dictionary.
for (size_t i = 0; i < parameters.getCount(); i++)
{
std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
if (!vm.contains(item.first))
{
ParameterSpec & ps = item.second;
if (ps.defaultValue != "")
{
// TODO: This check should be uncommented after dropping NuPIC 1.x nodes (which don't comply)
// if (ps.accessMode != ParameterSpec::CreateAccess)
// {
// NTA_THROW << "Default value for non-create parameter: " << item.first;
// }
try {
#ifdef YAMLDEBUG
NTA_DEBUG << "Adding default value '" << ps.defaultValue
<< "' to parameter " << item.first
<< " of type " << BasicType::getName(ps.dataType)
<< " count " << ps.count;
#endif
Value v = toValue(ps.defaultValue, ps.dataType);
vm.add(item.first, v);
} catch (...) {
NTA_THROW << "Unable to set default value for item '"
<< item.first << "' of datatype "
<< BasicType::getName(ps.dataType)
<<" with value '" << ps.defaultValue << "'";
}
}
}
}
return vm;
}
} // end of YAMLUtils namespace
} // end of nta namespace
<commit_msg>name private functions _<commit_after>/*
* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
* Numenta, Inc. a separate commercial license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#include <nta/types/BasicType.hpp>
#include <nta/engine/YAMLUtils.hpp>
#include <nta/ntypes/Value.hpp>
#include <nta/ntypes/Collection.hpp>
#include <nta/ntypes/MemStream.hpp>
#include <nta/engine/Spec.hpp>
#include <string.h> // strlen
#include <yaml-cpp/yaml.h>
#include <sstream>
namespace nta
{
namespace YAMLUtils
{
/*
* These functions are used internally by toValue and toValueMap
*/
static void _toScalar(const YAML::Node& node, boost::shared_ptr<Scalar>& s);
static void _toArray(const YAML::Node& node, boost::shared_ptr<Array>& a);
static Value toValue(const YAML::Node& node, NTA_BasicType dataType);
static void _toScalar(const YAML::Node& node, boost::shared_ptr<Scalar>& s)
{
NTA_CHECK(node.Type() == YAML::NodeType::Scalar);
switch(s->getType())
{
case NTA_BasicType_Byte:
// We should have already detected this and gone down the string path
NTA_THROW << "Internal error: attempting to convert YAML string to scalar of type Byte";
break;
case NTA_BasicType_UInt16:
node >> s->value.uint16;
break;
case NTA_BasicType_Int16:
node >> s->value.int16;
break;
case NTA_BasicType_UInt32:
node >> s->value.uint32;
break;
case NTA_BasicType_Int32:
node >> s->value.int32;
break;
case NTA_BasicType_UInt64:
node >> s->value.uint64;
break;
case NTA_BasicType_Int64:
node >> s->value.int64;
break;
case NTA_BasicType_Real32:
node >> s->value.real32;
break;
case NTA_BasicType_Real64:
node >> s->value.real64;
break;
case NTA_BasicType_Handle:
NTA_THROW << "Attempt to specify a YAML value for a scalar of type Handle";
break;
default:
// should not happen
std::string val;
node >> val;
NTA_THROW << "Unknown data type " << s->getType() << " for yaml node '" << val << "'";
}
}
static void _toArray(const YAML::Node& node, boost::shared_ptr<Array>& a)
{
NTA_CHECK(node.Type() == YAML::NodeType::Sequence);
a->allocateBuffer(node.size());
void* buffer = a->getBuffer();
for (size_t i = 0; i < node.size(); i++)
{
const YAML::Node& item = node[i];
NTA_CHECK(item.Type() == YAML::NodeType::Scalar);
switch(a->getType())
{
case NTA_BasicType_Byte:
// We should have already detected this and gone down the string path
NTA_THROW << "Internal error: attempting to convert YAML string to array of type Byte";
break;
case NTA_BasicType_UInt16:
item.to<UInt16>();
break;
case NTA_BasicType_Int16:
item.to<Int16>();
break;
case NTA_BasicType_UInt32:
item.to<UInt32>();
break;
case NTA_BasicType_Int32:
item.to<Int32>();
break;
case NTA_BasicType_UInt64:
item.to<UInt64>();
break;
case NTA_BasicType_Int64:
item.to<Int64>();
break;
case NTA_BasicType_Real32:
item.to<Real32>();
break;
case NTA_BasicType_Real64:
item.to<Real64>();
break;
default:
// should not happen
NTA_THROW << "Unknown data type " << a->getType();
}
}
}
static Value toValue(const YAML::Node& node, NTA_BasicType dataType)
{
if (node.Type() == YAML::NodeType::Map || node.Type() == YAML::NodeType::Null)
{
NTA_THROW << "YAML string does not not represent a value.";
}
if (node.Type() == YAML::NodeType::Scalar)
{
if (dataType == NTA_BasicType_Byte)
{
// node >> *str;
std::string val;
node.Read(val);
boost::shared_ptr<std::string> str(new std::string(val));
Value v(str);
return v;
} else {
boost::shared_ptr<Scalar> s(new Scalar(dataType));
_toScalar(node, s);
Value v(s);
return v;
}
} else {
// array
boost::shared_ptr<Array> a(new Array(dataType));
_toArray(node, a);
Value v(a);
return v;
}
}
/*
* For converting default values specified in nodespec
*/
Value toValue(const std::string& yamlstring, NTA_BasicType dataType)
{
// IMemStream s(yamlstring, ::strlen(yamlstring));
// yaml-cpp bug: append a space if it is only one character
// This is very inefficient, but should be ok since it is
// just used at construction time for short strings
std::string paddedstring(yamlstring);
if (paddedstring.size() < 2)
paddedstring = paddedstring + " ";
std::stringstream s(paddedstring);
// TODO -- return value? exceptions?
bool success = false;
YAML::Node doc;
try
{
YAML::Parser parser(s);
success = parser.GetNextDocument(doc);
// } catch(YAML::ParserException& e) {
} catch(...) {
success = false;
}
if (!success)
{
std::string ys(paddedstring);
if (ys.size() > 30)
{
ys = ys.substr(0, 30) + "...";
}
NTA_THROW << "Unable to parse YAML string '" << ys << "' for a scalar value";
}
Value v = toValue(doc, dataType);
return v;
}
/*
* For converting param specs for Regions and LinkPolicies
*/
ValueMap toValueMap(const char* yamlstring,
Collection<ParameterSpec>& parameters,
const std::string & nodeType,
const std::string & regionName)
{
ValueMap vm;
// yaml-cpp bug: append a space if it is only one character
// This is very inefficient, but should be ok since it is
// just used at construction time for short strings
std::string paddedstring(yamlstring);
// TODO: strip white space to determine if empty
bool empty = (paddedstring.size() == 0);
if (paddedstring.size() < 2)
paddedstring = paddedstring + " ";
std::stringstream s(paddedstring);
// IMemStream s(yamlstring, ::strlen(yamlstring));
// TODO: utf-8 compatible?
YAML::Node doc;
if (!empty)
{
YAML::Parser parser(s);
bool success = parser.GetNextDocument(doc);
if (!success)
NTA_THROW << "Unable to find document in YAML string";
// A ValueMap is specified as a dictionary
if (doc.Type() != YAML::NodeType::Map)
{
std::string ys(yamlstring);
if (ys.size() > 30)
{
ys = ys.substr(0, 30) + "...";
}
NTA_THROW << "YAML string '" << ys
<< "' does not not specify a dictionary of key-value pairs. "
<< "Region and Link parameters must be specified at a dictionary";
}
}
// Grab each value out of the YAML dictionary and put into the ValueMap
// if it is allowed by the nodespec.
YAML::Iterator i;
for (i = doc.begin(); i != doc.end(); i++)
{
const std::string key = i.first().to<std::string>();
if (!parameters.contains(key))
{
std::stringstream ss;
for (UInt j = 0; j < parameters.getCount(); j++)
{
ss << " " << parameters.getByIndex(j).first << "\n";
}
if (nodeType == std::string(""))
{
NTA_THROW << "Unknown parameter '" << key << "'\n"
<< "Valid parameters are:\n" << ss.str();
}
else
{
NTA_CHECK(regionName != std::string(""));
NTA_THROW << "Unknown parameter '" << key << "' for region '"
<< regionName << "' of type '" << nodeType << "'\n"
<< "Valid parameters are:\n" << ss.str();
}
}
if (vm.contains(key))
NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
ParameterSpec spec = parameters.getByName(key);
try
{
Value v = toValue(i.second(), spec.dataType);
if (v.isScalar() && spec.count != 1)
{
throw std::runtime_error("Expected array value but got scalar value");
}
if (!v.isScalar() && spec.count == 1)
{
throw std::runtime_error("Expected scalar value but got array value");
}
vm.add(key, v);
} catch (std::runtime_error& e) {
NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
}
}
// Populate ValueMap with default values if they were not specified in the YAML dictionary.
for (size_t i = 0; i < parameters.getCount(); i++)
{
std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
if (!vm.contains(item.first))
{
ParameterSpec & ps = item.second;
if (ps.defaultValue != "")
{
// TODO: This check should be uncommented after dropping NuPIC 1.x nodes (which don't comply)
// if (ps.accessMode != ParameterSpec::CreateAccess)
// {
// NTA_THROW << "Default value for non-create parameter: " << item.first;
// }
try {
#ifdef YAMLDEBUG
NTA_DEBUG << "Adding default value '" << ps.defaultValue
<< "' to parameter " << item.first
<< " of type " << BasicType::getName(ps.dataType)
<< " count " << ps.count;
#endif
Value v = toValue(ps.defaultValue, ps.dataType);
vm.add(item.first, v);
} catch (...) {
NTA_THROW << "Unable to set default value for item '"
<< item.first << "' of datatype "
<< BasicType::getName(ps.dataType)
<<" with value '" << ps.defaultValue << "'";
}
}
}
}
return vm;
}
} // end of YAMLUtils namespace
} // end of nta namespace
<|endoftext|> |
<commit_before>#include "latex_display_driver.hpp"
#include "../document/bold_line_element.hpp"
#include "../document/italic_line_element.hpp"
#include "../document/code_line_element.hpp"
#include "../document/url_line_element.hpp"
#include <iostream>
using namespace std;
void LaTeXDisplayDriver::display(Document * doc) {
Paragraph *p = nullptr;
LineElement *l = nullptr;
BoldLineElement *bold_le(nullptr);
ItalicLineElement *italic_le(nullptr);
CodeLineElement *code_le(nullptr);
UrlLineElement *url_le(nullptr);
char delim('|');
bool is_verbatim(false),
is_quotation(false),
is_ulist(false);
cout << "\\documentclass{article}" << endl;
cout << "\\usepackage[english]{babel}" << endl;
cout << "\\usepackage[utf8]{inputenc}" << endl;
cout << "\\usepackage[T1]{fontenc}" << endl;
cout << "\\usepackage{hyperref}" << endl;
cout << "\\begin{document}" << endl;
for (size_t i(0); i < doc->size(); ++i) {
p = (*doc)[i];
if (is_verbatim
and p->level() != Paragraph::Level::Code) {
is_verbatim = false;
cout << "\\end{verbatim}" << endl;
}
if (is_quotation
and !is_ulist
and !is_verbatim
and p->level() != Paragraph::Level::Quote) {
is_quotation = false;
cout << "\\end{quotation}" << endl;
}
if (is_ulist
and !is_quotation
and !is_verbatim
and p->level() != Paragraph::Level::UList1) {
is_ulist = false;
cout << "\\end{itemize}" << endl;
}
switch (p->level()) {
case Paragraph::Level::Title1:
cout << "\\section{";
break;
case Paragraph::Level::Title2:
cout << "\\subsection{";
break;
case Paragraph::Level::Code:
if (!is_verbatim) {
cout << "\\begin{verbatim}" << endl;
is_verbatim = true;
}
break;
case Paragraph::Level::UList1:
if (!is_ulist) {
cout << "\\begin{itemize}" << endl;
is_ulist = true;
}
cout << "\\item ";
break;
case Paragraph::Level::Quote:
if (!is_quotation) {
cout << "\\begin{quotation}" << endl;
is_quotation = true;
}
break;
default:
break;
}
for (size_t j(0); j < p->size(); ++j) {
l = (*p)[j];
bold_le = dynamic_cast<BoldLineElement*>(l);
italic_le = dynamic_cast<ItalicLineElement*>(l);
code_le = dynamic_cast<CodeLineElement*>(l);
url_le = dynamic_cast<UrlLineElement*>(l);
if (italic_le) {
cout << "\\textit{";
} else if (bold_le) {
cout << "\\textbf{";
} else if (code_le and p->level() != Paragraph::Level::Code) {
cout << "\\verb" << delim;
} else if (url_le) {
cout << "\\href{" << url_le->url() << "}{";
}
cout << l->content();
if (italic_le or bold_le or url_le) {
cout << "}";
} else if (code_le and p->level() != Paragraph::Level::Code) {
cout << delim;
}
}
switch (p->level()) {
case Paragraph::Level::Code:
cout << endl;
break;
case Paragraph::Level::Title1:
case Paragraph::Level::Title2:
cout << "}";
default:
cout << endl << endl;
break;
}
}
cout << "\\end{document}" << endl;
}
/* vim: set ts=4 sw=4: */
<commit_msg>Have multiple choices a delimiters for \verb<commit_after>#include "latex_display_driver.hpp"
#include "../document/bold_line_element.hpp"
#include "../document/italic_line_element.hpp"
#include "../document/code_line_element.hpp"
#include "../document/url_line_element.hpp"
#include <iostream>
using namespace std;
void LaTeXDisplayDriver::display(Document * doc) {
Paragraph *p = nullptr;
LineElement *l = nullptr;
BoldLineElement *bold_le(nullptr);
ItalicLineElement *italic_le(nullptr);
CodeLineElement *code_le(nullptr);
UrlLineElement *url_le(nullptr);
string delim_list("|@,;:_");
char delim('|');
bool is_verbatim(false),
is_quotation(false),
is_ulist(false);
cout << "\\documentclass{article}" << endl;
cout << "\\usepackage[english]{babel}" << endl;
cout << "\\usepackage[utf8]{inputenc}" << endl;
cout << "\\usepackage[T1]{fontenc}" << endl;
cout << "\\usepackage{hyperref}" << endl;
cout << "\\begin{document}" << endl;
for (size_t i(0); i < doc->size(); ++i) {
p = (*doc)[i];
if (is_verbatim
and p->level() != Paragraph::Level::Code) {
is_verbatim = false;
cout << "\\end{verbatim}" << endl;
}
if (is_quotation
and !is_ulist
and !is_verbatim
and p->level() != Paragraph::Level::Quote) {
is_quotation = false;
cout << "\\end{quotation}" << endl;
}
if (is_ulist
and !is_quotation
and !is_verbatim
and p->level() != Paragraph::Level::UList1) {
is_ulist = false;
cout << "\\end{itemize}" << endl;
}
switch (p->level()) {
case Paragraph::Level::Title1:
cout << "\\section{";
break;
case Paragraph::Level::Title2:
cout << "\\subsection{";
break;
case Paragraph::Level::Code:
if (!is_verbatim) {
cout << "\\begin{verbatim}" << endl;
is_verbatim = true;
}
break;
case Paragraph::Level::UList1:
if (!is_ulist) {
cout << "\\begin{itemize}" << endl;
is_ulist = true;
}
cout << "\\item ";
break;
case Paragraph::Level::Quote:
if (!is_quotation) {
cout << "\\begin{quotation}" << endl;
is_quotation = true;
}
break;
default:
break;
}
for (size_t j(0); j < p->size(); ++j) {
l = (*p)[j];
bold_le = dynamic_cast<BoldLineElement*>(l);
italic_le = dynamic_cast<ItalicLineElement*>(l);
code_le = dynamic_cast<CodeLineElement*>(l);
url_le = dynamic_cast<UrlLineElement*>(l);
if (italic_le) {
cout << "\\textit{";
} else if (bold_le) {
cout << "\\textbf{";
} else if (code_le and p->level() != Paragraph::Level::Code) {
delim = delim_list.find_first_not_of(l->content());
cout << "\\verb" << delim;
} else if (url_le) {
cout << "\\href{" << url_le->url() << "}{";
}
cout << l->content();
if (italic_le or bold_le or url_le) {
cout << "}";
} else if (code_le and p->level() != Paragraph::Level::Code) {
cout << delim;
}
}
switch (p->level()) {
case Paragraph::Level::Code:
cout << endl;
break;
case Paragraph::Level::Title1:
case Paragraph::Level::Title2:
cout << "}";
default:
cout << endl << endl;
break;
}
}
cout << "\\end{document}" << endl;
}
/* vim: set ts=4 sw=4: */
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
// its affiliates and/or its licensors.
//
// 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 Image Engine Design 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.
//
//////////////////////////////////////////////////////////////////////////
// Houdini
#include <OP/OP_OperatorTable.h>
#include <OP/OP_Operator.h>
#include <UT/UT_Interrupt.h>
#include <CH/CH_LocalVariable.h>
// Cortex
#include <IECore/Object.h>
#include <IECore/Op.h>
#include <IECore/TypedParameter.h>
#include <IECore/Primitive.h>
// OpenEXR
#include <OpenEXR/ImathBox.h>
// C++
#include <sstream>
// IECoreHoudini
#include "CoreHoudini.h"
#include "SOP_OpHolder.h"
#include "SOP_ToHoudiniConverter.h"
#include "NodePassData.h"
#include "ToHoudiniGeometryConverter.h"
#include "ToHoudiniPointsConverter.h"
#include "ToHoudiniPolygonsConverter.h"
using namespace IECoreHoudini;
/// Add parameters to SOP
PRM_Template SOP_ToHoudiniConverter::myParameters[] = {
PRM_Template()
};
/// Don't worry about variables today
CH_LocalVariable SOP_ToHoudiniConverter::myVariables[] = {
{ 0, 0, 0 },
};
/// Houdini's static creator method
OP_Node *SOP_ToHoudiniConverter::myConstructor( OP_Network *net,
const char *name,
OP_Operator *op )
{
return new SOP_ToHoudiniConverter(net, name, op);
}
/// Ctor
SOP_ToHoudiniConverter::SOP_ToHoudiniConverter(OP_Network *net,
const char *name,
OP_Operator *op ) :
SOP_Node(net, name, op)
{
}
/// Dtor
SOP_ToHoudiniConverter::~SOP_ToHoudiniConverter()
{
}
/// Cook the SOP! This method does all the work
OP_ERROR SOP_ToHoudiniConverter::cookMySop(OP_Context &context)
{
if( lockInputs(context)>=UT_ERROR_ABORT )
return error();
// start our work
UT_Interrupt *boss = UTgetInterrupt();
boss->opStart("Building ToHoudiniConverter Geometry...");
gdp->clearAndDestroy();
GU_DetailHandle gdp_handle = inputGeoHandle(0);
const GU_Detail *input_gdp = gdp_handle.readLock();
const NodePassData *pass_data = 0;
if ( input_gdp->attribs().find("IECoreHoudini::NodePassData", GB_ATTRIB_MIXED) ) // looks like data passed from another OpHolder
{
GB_AttributeRef attrOffset = input_gdp->attribs().getOffset( "IECoreHoudini::NodePassData", GB_ATTRIB_MIXED );
pass_data = input_gdp->attribs().castAttribData<NodePassData>( attrOffset );
};
if ( !pass_data )
{
addError( SOP_MESSAGE, "Could not find Cortex Object on input geometry!" );
boss->opEnd();
return error();
}
if ( pass_data->type()==IECoreHoudini::NodePassData::CORTEX_OPHOLDER )
{
SOP_OpHolder *sop = dynamic_cast<SOP_OpHolder*>(const_cast<OP_Node*>(pass_data->nodePtr()));
IECore::OpPtr op = IECore::runTimeCast<IECore::Op>( sop->getParameterised() );
const IECore::Parameter *result_parameter = op->resultParameter();
const IECore::Object *result_ptr = result_parameter->getValue();
const IECore::Primitive *primitive = IECore::runTimeCast<const IECore::Primitive>( result_ptr );
if ( !primitive )
{
addError( SOP_MESSAGE, "Object was not a Cortex Primitive!" );
boss->opEnd();
return error();
}
ToHoudiniGeometryConverterPtr converter = ToHoudiniGeometryConverter::create( primitive );
if ( !converter->convert( myGdpHandle ) )
{
addError( SOP_MESSAGE, "Conversion Failed!" );
boss->opEnd();
return error();
}
}
gdp_handle.unlock( input_gdp );
// tidy up & go home!
boss->opEnd();
unlockInputs();
return error();
}
const char *SOP_ToHoudiniConverter::inputLabel( unsigned pos ) const
{
return "Cortex Primitive";
}
<commit_msg>fixing for Houdini 10 build<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
// its affiliates and/or its licensors.
//
// Copyright (c) 2010, 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 Image Engine Design 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.
//
//////////////////////////////////////////////////////////////////////////
// Houdini
#include "GB/GB_AttributeRef.h"
#include <OP/OP_OperatorTable.h>
#include <OP/OP_Operator.h>
#include <UT/UT_Interrupt.h>
#include <CH/CH_LocalVariable.h>
// Cortex
#include <IECore/Object.h>
#include <IECore/Op.h>
#include <IECore/TypedParameter.h>
#include <IECore/Primitive.h>
// OpenEXR
#include <OpenEXR/ImathBox.h>
// C++
#include <sstream>
// IECoreHoudini
#include "CoreHoudini.h"
#include "SOP_OpHolder.h"
#include "SOP_ToHoudiniConverter.h"
#include "NodePassData.h"
#include "ToHoudiniGeometryConverter.h"
#include "ToHoudiniPointsConverter.h"
#include "ToHoudiniPolygonsConverter.h"
using namespace IECoreHoudini;
/// Add parameters to SOP
PRM_Template SOP_ToHoudiniConverter::myParameters[] = {
PRM_Template()
};
/// Don't worry about variables today
CH_LocalVariable SOP_ToHoudiniConverter::myVariables[] = {
{ 0, 0, 0 },
};
/// Houdini's static creator method
OP_Node *SOP_ToHoudiniConverter::myConstructor( OP_Network *net,
const char *name,
OP_Operator *op )
{
return new SOP_ToHoudiniConverter(net, name, op);
}
/// Ctor
SOP_ToHoudiniConverter::SOP_ToHoudiniConverter(OP_Network *net,
const char *name,
OP_Operator *op ) :
SOP_Node(net, name, op)
{
}
/// Dtor
SOP_ToHoudiniConverter::~SOP_ToHoudiniConverter()
{
}
/// Cook the SOP! This method does all the work
OP_ERROR SOP_ToHoudiniConverter::cookMySop(OP_Context &context)
{
if( lockInputs(context)>=UT_ERROR_ABORT )
return error();
// start our work
UT_Interrupt *boss = UTgetInterrupt();
boss->opStart("Building ToHoudiniConverter Geometry...");
gdp->clearAndDestroy();
GU_DetailHandle gdp_handle = inputGeoHandle(0);
const GU_Detail *input_gdp = gdp_handle.readLock();
const NodePassData *pass_data = 0;
if ( input_gdp->attribs().find("IECoreHoudini::NodePassData", GB_ATTRIB_MIXED) ) // looks like data passed from another OpHolder
{
GB_AttributeRef attrOffset = input_gdp->attribs().getOffset( "IECoreHoudini::NodePassData", GB_ATTRIB_MIXED );
pass_data = input_gdp->attribs().castAttribData<NodePassData>( attrOffset );
};
if ( !pass_data )
{
addError( SOP_MESSAGE, "Could not find Cortex Object on input geometry!" );
boss->opEnd();
return error();
}
if ( pass_data->type()==IECoreHoudini::NodePassData::CORTEX_OPHOLDER )
{
SOP_OpHolder *sop = dynamic_cast<SOP_OpHolder*>(const_cast<OP_Node*>(pass_data->nodePtr()));
IECore::OpPtr op = IECore::runTimeCast<IECore::Op>( sop->getParameterised() );
const IECore::Parameter *result_parameter = op->resultParameter();
const IECore::Object *result_ptr = result_parameter->getValue();
const IECore::Primitive *primitive = IECore::runTimeCast<const IECore::Primitive>( result_ptr );
if ( !primitive )
{
addError( SOP_MESSAGE, "Object was not a Cortex Primitive!" );
boss->opEnd();
return error();
}
ToHoudiniGeometryConverterPtr converter = ToHoudiniGeometryConverter::create( primitive );
if ( !converter->convert( myGdpHandle ) )
{
addError( SOP_MESSAGE, "Conversion Failed!" );
boss->opEnd();
return error();
}
}
gdp_handle.unlock( input_gdp );
// tidy up & go home!
boss->opEnd();
unlockInputs();
return error();
}
const char *SOP_ToHoudiniConverter::inputLabel( unsigned pos ) const
{
return "Cortex Primitive";
}
<|endoftext|> |
<commit_before>// Copyright (c) 2022 PaddlePaddle 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 "paddle/phi/kernels/gaussian_random_kernel.h"
#include "paddle/phi/backends/onednn/onednn_reuse.h"
#include "paddle/phi/core/kernel_registry.h"
namespace phi {
template <typename T, typename Context>
void GaussianRandomKernel(const Context& ctx,
const IntArray& shape,
float mean,
float std,
int seed,
DataType dtype,
DenseTensor* out) {
std::normal_distribution<T> dist(mean, std);
auto engine = std::make_shared<std::mt19937_64>();
engine->seed(seed);
T* data = ctx.template Alloc<T>(out);
for (int64_t i = 0; i < out->numel(); ++i) {
data[i] = dist(*engine);
}
out->Resize(phi::make_ddim(shape.GetData()));
dnnl::memory::desc out_mem_desc(
vectorize(out->dims()),
funcs::ToOneDNNDataType(out->dtype()),
funcs::GetPlainOneDNNFormat(out->dims().size()));
out->set_mem_desc(out_mem_desc);
}
} // namespace phi
PD_REGISTER_KERNEL(
gaussian_random, OneDNN, ONEDNN, phi::GaussianRandomKernel, float) {}
<commit_msg>add seed check (#46747)<commit_after>// Copyright (c) 2022 PaddlePaddle 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 "paddle/phi/kernels/gaussian_random_kernel.h"
#include "paddle/phi/backends/onednn/onednn_reuse.h"
#include "paddle/phi/core/kernel_registry.h"
namespace phi {
template <typename T, typename Context>
void GaussianRandomKernel(const Context& ctx,
const IntArray& shape,
float mean,
float std,
int seed,
DataType dtype,
DenseTensor* out) {
std::normal_distribution<T> dist(mean, std);
std::shared_ptr<std::mt19937_64> engine;
if (seed) {
engine = std::make_shared<std::mt19937_64>();
engine->seed(seed);
} else {
engine = ctx.GetGenerator()->GetCPUEngine();
}
T* data = ctx.template Alloc<T>(out);
for (int64_t i = 0; i < out->numel(); ++i) {
data[i] = dist(*engine);
}
out->Resize(phi::make_ddim(shape.GetData()));
dnnl::memory::desc out_mem_desc(
vectorize(out->dims()),
funcs::ToOneDNNDataType(out->dtype()),
funcs::GetPlainOneDNNFormat(out->dims().size()));
out->set_mem_desc(out_mem_desc);
}
} // namespace phi
PD_REGISTER_KERNEL(
gaussian_random, OneDNN, ONEDNN, phi::GaussianRandomKernel, float) {}
<|endoftext|> |
<commit_before>#include "RocketControllerSystem.h"
#include "ShipManagerSystem.h"
#include "Transform.h"
#include "PhysicsBody.h"
#include "PhysicsSystem.h"
#include <PhysicsController.h>
#include "SpawnSoundEffectPacket.h"
#include "ShipModule.h"
#include "ParticleSystemCreationInfo.h"
#include "SpawnExplosionPacket.h"
#include "MeshOffsetTransform.h"
RocketControllerSystem::RocketControllerSystem(TcpServer* p_server)
: EntitySystem(SystemType::RocketControllerSystem, 3, ComponentType::StandardRocket,
ComponentType::Transform, ComponentType::PhysicsBody)
{
m_turnPower = 8.0f;
m_enginePower = 150.0f;
m_server = p_server;
}
RocketControllerSystem::~RocketControllerSystem()
{
}
void RocketControllerSystem::initialize()
{
}
void RocketControllerSystem::processEntities(const vector<Entity*>& p_entities)
{
float dt = m_world->getDelta();
float waitUntilActivation = 0.1f;
float rocketMaxAge = 15.0f;
for (unsigned int i = 0; i < p_entities.size(); i++)
{
StandardRocket* rocket = static_cast<StandardRocket*>(p_entities[i]->getComponent(ComponentType::StandardRocket));
if (rocket->m_age == 0)
{
//Align with movement direction
MeshOffsetTransform* meshOffset = static_cast<MeshOffsetTransform*>
( p_entities[i]->getComponent( ComponentType::MeshOffsetTransform) );
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
AglMatrix world = body->GetWorld();
world = meshOffset->offset.inverse()*world;
world = pb->getOffset()*world;
body->setTransform(world);
}
rocket->m_age += dt;
//Check collision
if (rocket->m_age > waitUntilActivation && rocket->m_age <= rocketMaxAge)
{
//Start targeting ships
ShipManagerSystem* shipManager = static_cast<ShipManagerSystem*>(m_world->getSystem(SystemType::ShipManagerSystem));
Entity* ship = m_world->getEntity(rocket->m_target);
Transform* from = static_cast<Transform*>(p_entities[i]->getComponent(ComponentType::Transform));
Transform* to = static_cast<Transform*>(ship->getComponent(ComponentType::Transform));
//START APPLY IMPULSE
MeshOffsetTransform* meshOffset = static_cast<MeshOffsetTransform*>
( p_entities[i]->getComponent( ComponentType::MeshOffsetTransform) );
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
AglVector3 imp = to->getTranslation() - from->getTranslation();
float distance = imp.length();
imp.normalize();
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
AglMatrix world = meshOffset->offset * pb->getOffset().inverse() * body->GetWorld();
AglVector3 rotAxis = AglVector3::crossProduct(imp, -world.GetForward());
rotAxis.normalize();
//Compute fraction of turn power that should be applied
AglVector3 angVel = body->GetAngularVelocity();
float angVelAxis = max(AglVector3::dotProduct(angVel, rotAxis), 0);
float amountToRotate = min(1.0f - AglVector3::dotProduct(imp, world.GetForward()), 1.0f); //0 -> 1
float frac = 1.0f;
if (amountToRotate / angVelAxis < 0.25f)
{
frac = (amountToRotate / angVelAxis) / 0.25f;
}
rotAxis *= m_turnPower * dt * frac;
if (true)//distance < 100)
{
frac = 1-frac;
if (distance < 100)
{
frac *= (0.5f + distance / 100.0f);
}
}
else
{
frac = 1.0f;
}
AglVector3 impulse = world.GetForward()*dt*m_enginePower*frac;
ps->getController()->ApplyExternalImpulse(pb->m_id, impulse, rotAxis);
//END APPLY IMPULSE
//Check collision
vector<unsigned int> cols = ps->getController()->CollidesWith(pb->m_id);
if (cols.size() > 0)
{
// Apply damage to first found collision
Entity* hitEntity = ps->getEntity(cols[0]);
if(hitEntity)
{
ShipModule* hitModule = static_cast<ShipModule*>(hitEntity->getComponent(
ComponentType::ShipModule));
StandardRocket* hitRocket = static_cast<StandardRocket*>(hitEntity->getComponent(
ComponentType::StandardRocket));
if(hitRocket==NULL)
{
if (hitModule)
{
hitModule->addDamageThisTick(101.0f,rocket->m_ownerId); // Above max hp.
}
explodeRocket(ps, pb, body, p_entities[i]);
}
}
}
}// if (rocket->m_age > waitUntilActivation && rocket->m_age <= rocketMaxAge)
else if(rocket->m_age > rocketMaxAge)
{
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
explodeRocket(ps, pb, body, p_entities[i]);
}
}
}
void RocketControllerSystem::explodeRocket(PhysicsSystem* p_physicsSystem,
PhysicsBody* p_physicsBody, RigidBody* p_rigidBody, Entity* p_entity)
{
// Remove the rocket...
p_physicsSystem->getController()->ApplyExternalImpulse(p_rigidBody->GetWorld().GetTranslation(), 20, 20);
p_physicsSystem->getController()->InactivateBody(p_physicsBody->m_id);
m_world->deleteEntity(p_entity);
// ...and play an explosion sound effect.
Transform* t = static_cast<Transform*>(p_entity->getComponent(ComponentType::Transform));
SpawnSoundEffectPacket soundEffectPacket;
soundEffectPacket.soundIdentifier = (int)SpawnSoundEffectPacket::Explosion;
soundEffectPacket.positional = true;
soundEffectPacket.position = t->getTranslation();
soundEffectPacket.attachedToNetsyncEntity = -1;
m_server->broadcastPacket(soundEffectPacket.pack());
SpawnExplosionPacket explosion;
explosion.position = t->getTranslation();
m_server->broadcastPacket(explosion.pack());
}
//Old funny fish
//Start targeting ships
/*ShipManagerSystem* shipManager = static_cast<ShipManagerSystem*>(m_world->getSystem(SystemType::ShipManagerSystem));
//TEMP: Target first ship in array
Entity* ship = shipManager->getShips()[0];
Transform* from = static_cast<Transform*>(p_entities[i]->getComponent(ComponentType::Transform));
Transform* to = static_cast<Transform*>(ship->getComponent(ComponentType::Transform));
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
AglVector3 imp = to->getTranslation() - from->getTranslation();
imp.normalize();
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
AglVector3 rotAxis = AglVector3::crossProduct(imp, body->GetWorld().GetForward());
rotAxis.normalize();
float rotFraction = (1.0f-max(AglVector3::dotProduct(imp, -body->GetWorld().GetForward()), 0.0f));
rotAxis *= 10.0f * rotFraction * dt;
AglVector3 impulse = -body->GetWorld().GetForward()*dt*50 * (1.0f - rotFraction);
ps->getController()->ApplyExternalImpulse(pb->m_id, impulse, rotAxis);*/<commit_msg>Better rocket logic<commit_after>#include "RocketControllerSystem.h"
#include "ShipManagerSystem.h"
#include "Transform.h"
#include "PhysicsBody.h"
#include "PhysicsSystem.h"
#include <PhysicsController.h>
#include "SpawnSoundEffectPacket.h"
#include "ShipModule.h"
#include "ParticleSystemCreationInfo.h"
#include "SpawnExplosionPacket.h"
#include "MeshOffsetTransform.h"
RocketControllerSystem::RocketControllerSystem(TcpServer* p_server)
: EntitySystem(SystemType::RocketControllerSystem, 3, ComponentType::StandardRocket,
ComponentType::Transform, ComponentType::PhysicsBody)
{
m_turnPower = 8.0f;
m_enginePower = 150.0f;
m_server = p_server;
}
RocketControllerSystem::~RocketControllerSystem()
{
}
void RocketControllerSystem::initialize()
{
}
void RocketControllerSystem::processEntities(const vector<Entity*>& p_entities)
{
float dt = m_world->getDelta();
float waitUntilActivation = 0.1f;
float rocketMaxAge = 15.0f;
for (unsigned int i = 0; i < p_entities.size(); i++)
{
StandardRocket* rocket = static_cast<StandardRocket*>(p_entities[i]->getComponent(ComponentType::StandardRocket));
if (rocket->m_age == 0)
{
//Align with movement direction
MeshOffsetTransform* meshOffset = static_cast<MeshOffsetTransform*>
( p_entities[i]->getComponent( ComponentType::MeshOffsetTransform) );
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
AglMatrix world = body->GetWorld();
world = meshOffset->offset.inverse()*world;
world = pb->getOffset()*world;
body->setTransform(world);
}
rocket->m_age += dt;
//Check collision
if (rocket->m_age > waitUntilActivation && rocket->m_age <= rocketMaxAge)
{
//Start targeting ships
ShipManagerSystem* shipManager = static_cast<ShipManagerSystem*>(m_world->getSystem(SystemType::ShipManagerSystem));
Entity* ship = m_world->getEntity(rocket->m_target);
Transform* from = static_cast<Transform*>(p_entities[i]->getComponent(ComponentType::Transform));
Transform* to = static_cast<Transform*>(ship->getComponent(ComponentType::Transform));
//START APPLY IMPULSE
MeshOffsetTransform* meshOffset = static_cast<MeshOffsetTransform*>
( p_entities[i]->getComponent( ComponentType::MeshOffsetTransform) );
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
AglVector3 imp = to->getTranslation() - from->getTranslation();
float distance = imp.length();
imp.normalize();
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
AglMatrix world = meshOffset->offset * pb->getOffset().inverse() * body->GetWorld();
AglVector3 rotAxis = AglVector3::crossProduct(imp, -world.GetForward());
rotAxis.normalize();
//Compute fraction of turn power that should be applied
AglVector3 angVel = body->GetAngularVelocity();
float angVelAxis = max(AglVector3::dotProduct(angVel, rotAxis), 0);
float amountToRotate = min(1.0f - AglVector3::dotProduct(imp, world.GetForward()), 1.0f); //0 -> 1
float frac = 1.0f;
if (amountToRotate / angVelAxis < 0.25f)
{
frac = (amountToRotate / angVelAxis) / 0.25f;
}
rotAxis *= m_turnPower * dt * frac;
if (true)//distance < 100)
{
frac = 1-frac;
/*if (distance < 100)
{
frac *= (0.5f + distance / 100.0f);
}*/
}
else
{
frac = 1.0f;
}
AglVector3 impulse = imp*0.25f + world.GetForward();
impulse.normalize();
impulse *= dt*m_enginePower*frac;
ps->getController()->ApplyExternalImpulse(pb->m_id, impulse, rotAxis);
//END APPLY IMPULSE
//Check collision
vector<unsigned int> cols = ps->getController()->CollidesWith(pb->m_id);
if (cols.size() > 0)
{
// Apply damage to first found collision
Entity* hitEntity = ps->getEntity(cols[0]);
if(hitEntity)
{
ShipModule* hitModule = static_cast<ShipModule*>(hitEntity->getComponent(
ComponentType::ShipModule));
StandardRocket* hitRocket = static_cast<StandardRocket*>(hitEntity->getComponent(
ComponentType::StandardRocket));
if(hitRocket==NULL)
{
if (hitModule)
{
hitModule->addDamageThisTick(101.0f,rocket->m_ownerId); // Above max hp.
}
explodeRocket(ps, pb, body, p_entities[i]);
}
}
}
}// if (rocket->m_age > waitUntilActivation && rocket->m_age <= rocketMaxAge)
else if(rocket->m_age > rocketMaxAge)
{
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
explodeRocket(ps, pb, body, p_entities[i]);
}
}
}
void RocketControllerSystem::explodeRocket(PhysicsSystem* p_physicsSystem,
PhysicsBody* p_physicsBody, RigidBody* p_rigidBody, Entity* p_entity)
{
// Remove the rocket...
p_physicsSystem->getController()->ApplyExternalImpulse(p_rigidBody->GetWorld().GetTranslation(), 20, 20);
p_physicsSystem->getController()->InactivateBody(p_physicsBody->m_id);
m_world->deleteEntity(p_entity);
// ...and play an explosion sound effect.
Transform* t = static_cast<Transform*>(p_entity->getComponent(ComponentType::Transform));
SpawnSoundEffectPacket soundEffectPacket;
soundEffectPacket.soundIdentifier = (int)SpawnSoundEffectPacket::Explosion;
soundEffectPacket.positional = true;
soundEffectPacket.position = t->getTranslation();
soundEffectPacket.attachedToNetsyncEntity = -1;
m_server->broadcastPacket(soundEffectPacket.pack());
SpawnExplosionPacket explosion;
explosion.position = t->getTranslation();
m_server->broadcastPacket(explosion.pack());
}
//Old funny fish
//Start targeting ships
/*ShipManagerSystem* shipManager = static_cast<ShipManagerSystem*>(m_world->getSystem(SystemType::ShipManagerSystem));
//TEMP: Target first ship in array
Entity* ship = shipManager->getShips()[0];
Transform* from = static_cast<Transform*>(p_entities[i]->getComponent(ComponentType::Transform));
Transform* to = static_cast<Transform*>(ship->getComponent(ComponentType::Transform));
PhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));
PhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));
AglVector3 imp = to->getTranslation() - from->getTranslation();
imp.normalize();
RigidBody* body = static_cast<RigidBody*>(ps->getController()->getBody(pb->m_id));
AglVector3 rotAxis = AglVector3::crossProduct(imp, body->GetWorld().GetForward());
rotAxis.normalize();
float rotFraction = (1.0f-max(AglVector3::dotProduct(imp, -body->GetWorld().GetForward()), 0.0f));
rotAxis *= 10.0f * rotFraction * dt;
AglVector3 impulse = -body->GetWorld().GetForward()*dt*50 * (1.0f - rotFraction);
ps->getController()->ApplyExternalImpulse(pb->m_id, impulse, rotAxis);*/<|endoftext|> |
<commit_before>#include "converter.hpp"
#include <iostream>
#include "../Server/DataStructures/InternalDataFacade.h"
#include "../../../../coding/matrix_traversal.hpp"
#include "../../../../coding/internal/file_data.hpp"
#include "../../../../base/bits.hpp"
#include "../../../../base/logging.hpp"
#include "../../../../routing/osrm_data_facade.hpp"
#include "../../../succinct/elias_fano.hpp"
#include "../../../succinct/elias_fano_compressed_list.hpp"
#include "../../../succinct/gamma_vector.hpp"
#include "../../../succinct/rs_bit_vector.hpp"
#include "../../../succinct/mapper.hpp"
namespace mapsme
{
void PrintStatus(bool b)
{
std::cout << (b ? "[Ok]" : "[Fail]") << std::endl;
}
string EdgeDataToString(QueryEdge::EdgeData const & d)
{
stringstream ss;
ss << "[" << d.distance << ", " << d.shortcut << ", " << d.forward << ", " << d.backward << ", " << d.id << "]";
return ss.str();
}
Converter::Converter()
{
}
void Converter::run(const std::string & name)
{
ServerPaths server_paths;
server_paths["hsgrdata"] = boost::filesystem::path(name + ".hsgr");
server_paths["ramindex"] = boost::filesystem::path(name + ".ramIndex");
server_paths["fileindex"] = boost::filesystem::path(name + ".fileIndex");
server_paths["geometries"] = boost::filesystem::path(name + ".geometry");
server_paths["nodesdata"] = boost::filesystem::path(name + ".nodes");
server_paths["edgesdata"] = boost::filesystem::path(name + ".edges");
server_paths["namesdata"] = boost::filesystem::path(name + ".names");
server_paths["timestamp"] = boost::filesystem::path(name + ".timestamp");
std::cout << "Create internal data facade for file: " << name << "...";
InternalDataFacade<QueryEdge::EdgeData> facade(server_paths);
PrintStatus(true);
uint64_t const nodeCount = facade.GetNumberOfNodes();
std::vector<uint64_t> edges;
std::vector<uint32_t> edgesData;
std::vector<bool> shortcuts;
std::vector<uint64_t> edgeId;
std::cout << "Repack graph...";
typedef pair<uint64_t, QueryEdge::EdgeData> EdgeInfoT;
typedef vector<EdgeInfoT> EdgeInfoVecT;
uint64_t copiedEdges = 0;
for (uint64_t node = 0; node < nodeCount; ++node)
{
EdgeInfoVecT edgesInfo;
for (auto edge : facade.GetAdjacentEdgeRange(node))
{
uint64_t target = facade.GetTarget(edge);
auto const & data = facade.GetEdgeData(edge);
edgesInfo.push_back(EdgeInfoT(target, data));
}
auto compareFn = [](EdgeInfoT const & a, EdgeInfoT const & b)
{
if (a.first != b.first)
return a.first < b.first;
if (a.second.forward != b.second.forward)
return a.second.forward > b.second.forward;
return false;
};
sort(edgesInfo.begin(), edgesInfo.end(), compareFn);
/*std::cout << "---" << std::endl;
for (auto e : edgesInfo)
std::cout << e.first << ", " << EdgeDataToString(e.second) << std::endl;*/
uint64_t lastTarget = 0;
for (auto edge : edgesInfo)
{
uint64_t target = edge.first;
auto const & data = edge.second;
if (target < lastTarget)
LOG(LCRITICAL, ("Invalid order of target nodes", target, lastTarget));
lastTarget = target;
assert(data.forward || data.backward);
auto addDataFn = [&](bool b)
{
uint64_t e = TraverseMatrixInRowOrder<uint64_t>(nodeCount, node, target, b);
if (!edges.empty() && (edges.back() >= e))
LOG(LCRITICAL, ("Invalid order of edges", e, edges.back(), nodeCount, node, target, b));
edges.push_back(e);
edgesData.push_back(data.distance);
shortcuts.push_back(data.shortcut);
int id1 = data.id;
int id2 = node;
if (data.shortcut)
edgeId.push_back(bits::ZigZagEncode(id2 - id1));
};
if (data.forward && data.backward)
{
addDataFn(false);
addDataFn(true);
copiedEdges++;
}
else
addDataFn(data.backward);
}
}
std::cout << "Edges count: " << edgeId.size() << std::endl;
PrintStatus(true);
std::cout << "Sort edges...";
std::sort(edges.begin(), edges.end());
PrintStatus(true);
std::cout << "Edges count: " << edges.size() << std::endl;
std::cout << "Nodes count: " << nodeCount << std::endl;
std::cout << "--- Save matrix" << std::endl;
succinct::elias_fano::elias_fano_builder builder(edges.back(), edges.size());
for (auto e : edges)
builder.push_back(e);
succinct::elias_fano matrix(&builder);
std::string fileName = name + "." + ROUTING_MATRIX_FILE_TAG;
succinct::mapper::freeze(matrix, fileName.c_str());
std::cout << "--- Save edge data" << std::endl;
succinct::elias_fano_compressed_list edgeVector(edgesData);
fileName = name + "." + ROUTING_EDGEDATA_FILE_TAG;
succinct::mapper::freeze(edgeVector, fileName.c_str());
succinct::elias_fano_compressed_list edgeIdVector(edgeId);
fileName = name + "." + ROUTING_EDGEID_FILE_TAG;
succinct::mapper::freeze(edgeIdVector, fileName.c_str());
std::cout << "--- Save edge shortcuts" << std::endl;
succinct::rs_bit_vector shortcutsVector(shortcuts);
fileName = name + "." + ROUTING_SHORTCUTS_FILE_TAG;
succinct::mapper::freeze(shortcutsVector, fileName.c_str());
if (edgeId.size() != shortcutsVector.num_ones())
LOG(LCRITICAL, ("Invalid data"));
/// @todo Restore this checking. Now data facade depends on mwm libraries.
std::cout << "--- Test packed data" << std::endl;
std::string fPath = name + ".mwm";
{
FilesContainerW routingCont(fPath);
auto appendFile = [&] (string const & tag)
{
string const fileName = name + "." + tag;
LOG(LINFO, ("Append file", fileName, "with tag", tag));
routingCont.Write(fileName, tag);
};
appendFile(ROUTING_SHORTCUTS_FILE_TAG);
appendFile(ROUTING_EDGEDATA_FILE_TAG);
appendFile(ROUTING_MATRIX_FILE_TAG);
appendFile(ROUTING_EDGEID_FILE_TAG);
routingCont.Finish();
}
FilesMappingContainer container;
container.Open(fPath);
typedef routing::OsrmDataFacade<QueryEdge::EdgeData> DataFacadeT;
DataFacadeT facadeNew;
facadeNew.Load(container);
uint64_t edgesCount = facadeNew.GetNumberOfEdges() - copiedEdges;
std::cout << "Check node count " << facade.GetNumberOfNodes() << " == " << facadeNew.GetNumberOfNodes() << "...";
PrintStatus(facade.GetNumberOfNodes() == facadeNew.GetNumberOfNodes());
std::cout << "Check edges count " << facade.GetNumberOfEdges() << " == " << edgesCount << "...";
PrintStatus(facade.GetNumberOfEdges() == edgesCount);
std::cout << "Check edges data ...";
bool error = false;
auto errorFn = [&](string const & s)
{
my::DeleteFileX(fPath);
LOG(LCRITICAL, (s));
};
typedef vector<QueryEdge::EdgeData> EdgeDataT;
assert(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges());
for (uint32_t i = 0; i < facade.GetNumberOfNodes(); ++i)
{
EdgeDataT v1, v2;
for (auto e : facade.GetAdjacentEdgeRange(i))
{
QueryEdge::EdgeData d = facade.GetEdgeData(e);
if (d.forward && d.backward)
{
d.backward = false;
v1.push_back(d);
d.forward = false;
d.backward = true;
}
v1.push_back(d);
}
for (auto e : facadeNew.GetAdjacentEdgeRange(i))
v2.push_back(facadeNew.GetEdgeData(e, i));
if (v1.size() != v2.size())
{
stringstream ss;
ss << "File name: " << name << std::endl;
ss << "Not equal edges count for node: " << i << std::endl;
ss << "v1: " << v1.size() << " v2: " << v2.size() << std::endl;
errorFn(ss.str());
}
sort(v1.begin(), v1.end(), EdgeLess());
sort(v2.begin(), v2.end(), EdgeLess());
// compare vectors
for (size_t k = 0; k < v1.size(); ++k)
{
QueryEdge::EdgeData const & d1 = v1[k];
QueryEdge::EdgeData const & d2 = v2[k];
if (d1.backward != d2.backward ||
d1.forward != d2.forward ||
d1.distance != d2.distance ||
(d1.id != d2.id && (d1.shortcut || d2.shortcut)) ||
d1.shortcut != d2.shortcut)
{
std::cout << "--- " << std::endl;
for (size_t j = 0; j < v1.size(); ++j)
std::cout << EdgeDataToString(v1[j]) << " - " << EdgeDataToString(v2[j]) << std::endl;
stringstream ss;
ss << "File name: " << name << std::endl;
ss << "Node: " << i << std::endl;
ss << EdgeDataToString(d1) << ", " << EdgeDataToString(d2) << std::endl;
errorFn(ss.str());
}
}
}
PrintStatus(!error);
my::DeleteFileX(fPath);
}
}
<commit_msg>[osrm] Fix error with duplicated shortcuts between nodes<commit_after>#include "converter.hpp"
#include <iostream>
#include "../Server/DataStructures/InternalDataFacade.h"
#include "../../../../coding/matrix_traversal.hpp"
#include "../../../../coding/internal/file_data.hpp"
#include "../../../../base/bits.hpp"
#include "../../../../base/logging.hpp"
#include "../../../../routing/osrm_data_facade.hpp"
#include "../../../succinct/elias_fano.hpp"
#include "../../../succinct/elias_fano_compressed_list.hpp"
#include "../../../succinct/gamma_vector.hpp"
#include "../../../succinct/rs_bit_vector.hpp"
#include "../../../succinct/mapper.hpp"
namespace mapsme
{
void PrintStatus(bool b)
{
std::cout << (b ? "[Ok]" : "[Fail]") << std::endl;
}
string EdgeDataToString(QueryEdge::EdgeData const & d)
{
stringstream ss;
ss << "[" << d.distance << ", " << d.shortcut << ", " << d.forward << ", " << d.backward << ", " << d.id << "]";
return ss.str();
}
Converter::Converter()
{
}
void Converter::run(const std::string & name)
{
ServerPaths server_paths;
server_paths["hsgrdata"] = boost::filesystem::path(name + ".hsgr");
server_paths["ramindex"] = boost::filesystem::path(name + ".ramIndex");
server_paths["fileindex"] = boost::filesystem::path(name + ".fileIndex");
server_paths["geometries"] = boost::filesystem::path(name + ".geometry");
server_paths["nodesdata"] = boost::filesystem::path(name + ".nodes");
server_paths["edgesdata"] = boost::filesystem::path(name + ".edges");
server_paths["namesdata"] = boost::filesystem::path(name + ".names");
server_paths["timestamp"] = boost::filesystem::path(name + ".timestamp");
std::cout << "Create internal data facade for file: " << name << "...";
InternalDataFacade<QueryEdge::EdgeData> facade(server_paths);
PrintStatus(true);
uint64_t const nodeCount = facade.GetNumberOfNodes();
std::vector<uint64_t> edges;
std::vector<uint32_t> edgesData;
std::vector<bool> shortcuts;
std::vector<uint64_t> edgeId;
std::cout << "Repack graph..." << std::endl;
typedef pair<uint64_t, QueryEdge::EdgeData> EdgeInfoT;
typedef vector<EdgeInfoT> EdgeInfoVecT;
uint64_t copiedEdges = 0, ignoredEdges = 0;
for (uint64_t node = 0; node < nodeCount; ++node)
{
EdgeInfoVecT edgesInfo;
for (auto edge : facade.GetAdjacentEdgeRange(node))
{
uint64_t target = facade.GetTarget(edge);
auto const & data = facade.GetEdgeData(edge);
edgesInfo.push_back(EdgeInfoT(target, data));
}
auto compareFn = [](EdgeInfoT const & a, EdgeInfoT const & b)
{
if (a.first != b.first)
return a.first < b.first;
if (a.second.forward != b.second.forward)
return a.second.forward > b.second.forward;
return a.second.id < b.second.id;
};
sort(edgesInfo.begin(), edgesInfo.end(), compareFn);
uint64_t lastTarget = 0;
for (auto edge : edgesInfo)
{
uint64_t target = edge.first;
auto const & data = edge.second;
if (target < lastTarget)
LOG(LCRITICAL, ("Invalid order of target nodes", target, lastTarget));
lastTarget = target;
assert(data.forward || data.backward);
auto addDataFn = [&](bool b)
{
uint64_t e = TraverseMatrixInRowOrder<uint64_t>(nodeCount, node, target, b);
auto compressId = [&](uint64_t id)
{
int id1 = id;
int id2 = node;
return bits::ZigZagEncode(id2 - id1);
};
if (!edges.empty())
CHECK_GREATER_OR_EQUAL(e, edges.back(), ());
if (!edges.empty() && (edges.back() == e))
{
LOG(LWARNING, ("Invalid order of edges", e, edges.back(), nodeCount, node, target, b));
CHECK(data.shortcut == shortcuts.back(), ());
auto last = edgesData.back();
if (data.distance <= last)
{
if (!edgeId.empty() && data.shortcut)
{
CHECK(shortcuts.back(), ());
auto oldId = node - bits::ZigZagDecode(edgeId.back());
if (data.distance == last)
edgeId.back() = compressId(min(oldId, (uint64_t)data.id));
else
edgeId.back() = compressId(data.id);
}
edgesData.back() = data.distance;
}
++ignoredEdges;
return;
}
edges.push_back(e);
edgesData.push_back(data.distance);
shortcuts.push_back(data.shortcut);
int id1 = data.id;
int id2 = node;
if (data.shortcut)
edgeId.push_back(bits::ZigZagEncode(id2 - id1));
};
if (data.forward && data.backward)
{
addDataFn(false);
addDataFn(true);
copiedEdges++;
}
else
addDataFn(data.backward);
}
}
std::cout << "Edges count: " << edgeId.size() << std::endl;
PrintStatus(true);
std::cout << "Sort edges...";
std::sort(edges.begin(), edges.end());
PrintStatus(true);
std::cout << "Edges count: " << edges.size() << std::endl;
std::cout << "Nodes count: " << nodeCount << std::endl;
std::cout << "--- Save matrix" << std::endl;
succinct::elias_fano::elias_fano_builder builder(edges.back(), edges.size());
for (auto e : edges)
builder.push_back(e);
succinct::elias_fano matrix(&builder);
std::string fileName = name + "." + ROUTING_MATRIX_FILE_TAG;
succinct::mapper::freeze(matrix, fileName.c_str());
std::cout << "--- Save edge data" << std::endl;
succinct::elias_fano_compressed_list edgeVector(edgesData);
fileName = name + "." + ROUTING_EDGEDATA_FILE_TAG;
succinct::mapper::freeze(edgeVector, fileName.c_str());
succinct::elias_fano_compressed_list edgeIdVector(edgeId);
fileName = name + "." + ROUTING_EDGEID_FILE_TAG;
succinct::mapper::freeze(edgeIdVector, fileName.c_str());
std::cout << "--- Save edge shortcuts" << std::endl;
succinct::rs_bit_vector shortcutsVector(shortcuts);
fileName = name + "." + ROUTING_SHORTCUTS_FILE_TAG;
succinct::mapper::freeze(shortcutsVector, fileName.c_str());
if (edgeId.size() != shortcutsVector.num_ones())
LOG(LCRITICAL, ("Invalid data"));
/// @todo Restore this checking. Now data facade depends on mwm libraries.
std::cout << "--- Test packed data" << std::endl;
std::string fPath = name + ".mwm";
{
FilesContainerW routingCont(fPath);
auto appendFile = [&] (string const & tag)
{
string const fileName = name + "." + tag;
LOG(LINFO, ("Append file", fileName, "with tag", tag));
routingCont.Write(fileName, tag);
};
appendFile(ROUTING_SHORTCUTS_FILE_TAG);
appendFile(ROUTING_EDGEDATA_FILE_TAG);
appendFile(ROUTING_MATRIX_FILE_TAG);
appendFile(ROUTING_EDGEID_FILE_TAG);
routingCont.Finish();
}
FilesMappingContainer container;
container.Open(fPath);
typedef routing::OsrmDataFacade<QueryEdge::EdgeData> DataFacadeT;
DataFacadeT facadeNew;
facadeNew.Load(container);
uint64_t edgesCount = facadeNew.GetNumberOfEdges() - copiedEdges + ignoredEdges;
std::cout << "Check node count " << facade.GetNumberOfNodes() << " == " << facadeNew.GetNumberOfNodes() << "...";
PrintStatus(facade.GetNumberOfNodes() == facadeNew.GetNumberOfNodes());
std::cout << "Check edges count " << facade.GetNumberOfEdges() << " == " << edgesCount << "...";
PrintStatus(facade.GetNumberOfEdges() == edgesCount);
std::cout << "Check edges data ...";
bool error = false;
auto errorFn = [&](string const & s)
{
my::DeleteFileX(fPath);
LOG(LCRITICAL, (s));
};
typedef vector<QueryEdge::EdgeData> EdgeDataT;
assert(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges());
for (uint32_t i = 0; i < facade.GetNumberOfNodes(); ++i)
{
EdgeDataT v1, v2;
// get all edges from osrm datafacade and store just minimal weights for duplicates
typedef pair<NodeID, QueryEdge::EdgeData> EdgeOsrmT;
vector<EdgeOsrmT> edgesOsrm;
for (auto e : facade.GetAdjacentEdgeRange(i))
edgesOsrm.push_back(EdgeOsrmT(facade.GetTarget(e), facade.GetEdgeData(e)));
auto edgeOsrmLess = [](EdgeOsrmT const & a, EdgeOsrmT const & b)
{
if (a.first != b.first)
return a.first < b.first;
if (a.second.forward != b.second.forward)
return a.second.forward < b.second.forward;
if (a.second.backward != b.second.backward)
return a.second.backward < b.second.backward;
if (a.second.distance != b.second.distance)
return a.second.distance < b.second.distance;
return a.second.id < b.second.id;
};
sort(edgesOsrm.begin(), edgesOsrm.end(), edgeOsrmLess);
for (size_t k = 1; k < edgesOsrm.size();)
{
auto const & e1 = edgesOsrm[k - 1];
auto const & e2 = edgesOsrm[k];
if (e1.first != e2.first ||
e1.second.forward != e2.second.forward ||
e1.second.backward != e2.second.backward)
{
++k;
continue;
}
if (e1.second.distance > e2.second.distance)
edgesOsrm.erase(edgesOsrm.begin() + k - 1);
else
edgesOsrm.erase(edgesOsrm.begin() + k);
}
for (auto e : edgesOsrm)
{
QueryEdge::EdgeData d = e.second;
if (d.forward && d.backward)
{
d.backward = false;
v1.push_back(d);
d.forward = false;
d.backward = true;
}
v1.push_back(d);
}
for (auto e : facadeNew.GetAdjacentEdgeRange(i))
v2.push_back(facadeNew.GetEdgeData(e, i));
if (v1.size() != v2.size())
{
auto printV = [](EdgeDataT const & v, stringstream & ss)
{
for (auto i : v)
ss << EdgeDataToString(i) << std::endl;
};
sort(v1.begin(), v1.end(), EdgeLess());
sort(v2.begin(), v2.end(), EdgeLess());
stringstream ss;
ss << "File name: " << name << std::endl;
ss << "Not equal edges count for node: " << i << std::endl;
ss << "v1: " << v1.size() << " v2: " << v2.size() << std::endl;
ss << "--- v1 ---" << std::endl;
printV(v1, ss);
ss << "--- v2 ---" << std::endl;
printV(v2, ss);
errorFn(ss.str());
}
sort(v1.begin(), v1.end(), EdgeLess());
sort(v2.begin(), v2.end(), EdgeLess());
// compare vectors
for (size_t k = 0; k < v1.size(); ++k)
{
QueryEdge::EdgeData const & d1 = v1[k];
QueryEdge::EdgeData const & d2 = v2[k];
if (d1.backward != d2.backward ||
d1.forward != d2.forward ||
d1.distance != d2.distance ||
(d1.id != d2.id && (d1.shortcut || d2.shortcut)) ||
d1.shortcut != d2.shortcut)
{
std::cout << "--- " << std::endl;
for (size_t j = 0; j < v1.size(); ++j)
std::cout << EdgeDataToString(v1[j]) << " - " << EdgeDataToString(v2[j]) << std::endl;
stringstream ss;
ss << "File name: " << name << std::endl;
ss << "Node: " << i << std::endl;
ss << EdgeDataToString(d1) << ", " << EdgeDataToString(d2) << std::endl;
errorFn(ss.str());
}
}
}
PrintStatus(!error);
my::DeleteFileX(fPath);
}
}
<|endoftext|> |
<commit_before>
//Implementations of the AST objects
//Much of the logic of creating these comes from bison grammar
#include "node.h"
//Symbol table
SymbolTable sym_table;
//Copy identifier
char* dup_char(char* name) {
size_t length = strlen(name)+1;
char* ident = (char*)GC_MALLOC_ATOMIC(length);
memcpy(ident,name,length);
return ident;
}
/*===================================Node===================================*/
void Node::describe() const {
printf("---Found generic node object with no fields.");
printf("---This SHOULD BE AN ERROR.");
}
llvm::Value* Node::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitNode(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*================================Expression================================*/
void Expression::describe() const {
printf("---Found generic Expression object with no fields\n");
}
llvm::Value* Expression::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitExpression(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*================================Statement=================================*/
void Statement::describe() const {
printf("---Found generic statement object with no fields\n");
}
llvm::Value* Statement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=================================Integer==================================*/
Integer::Integer(int64_t value) {
this->value = value;
}
void Integer::describe() const {
printf("---Found Literal Integer: %i\n", (int)value);
}
llvm::Value* Integer::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitInteger(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==================================Float===================================*/
Float::Float(double value) {
this->value = value;
}
void Float::describe() const {
printf("---Found Float: %f\n", value);
}
llvm::Value* Float::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitFloat(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*================================Identifier================================*/
Identifier::Identifier(char* name) {
this->name = dup_char(name);
}
void Identifier::describe() const {
printf("---Found Identifier: %s\n",name);
}
bool Identifier::assertDeclared() const {
if (!sym_table.check(name)) {
yyerror("Identifier does not exist in symbol table");
return true;
} else if (!sym_table.check(name,VARIABLE)) {
yyerror("Identifier was not a variable");
return true;
}
return false;
}
llvm::Value* Identifier::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitIdentifier(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=============================NullaryOperator==============================*/
NullaryOperator::NullaryOperator(char* op) {
printf("%s",op);
this->op = dup_char(op);
}
void NullaryOperator::describe() const {
printf("---Found Nullary Operator\n");
}
llvm::Value* NullaryOperator::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitNullaryOperator(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==============================UnaryOperator===============================*/
UnaryOperator::UnaryOperator(char* op, Expression* exp) {
this->op = dup_char(op);
this->exp = exp;
}
void UnaryOperator::describe() const {
printf("---Found Unary Operator\n");
}
llvm::Value* UnaryOperator::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitUnaryOperator(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==============================BinaryOperator==============================*/
BinaryOperator::BinaryOperator(Expression* left, char* op, Expression* right) {
this->op = dup_char(op);
this->left = left;
this->right = right;
}
void BinaryOperator::describe() const {
printf("---Found Binary Operator %s\n",this->op);
}
llvm::Value* BinaryOperator::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitBinaryOperator(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==================================Block===================================*/
Block::Block(std::vector<Statement*, gc_allocator<Statement*>>* statements) {
this->statements = statements;
}
void Block::describe() const {
printf("---Found Block\n");
}
Block::Block() {
this->statements = NULL;
}
llvm::Value* Block::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitBlock(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===============================FunctionCall===============================*/
FunctionCall::FunctionCall(Identifier* ident, std::vector<Expression*, gc_allocator<Expression*>>* args) {
this->ident = ident;
this->args = args;
if (!sym_table.check(ident->name)) {
yyerror("Called function does not exist in symbol table");
} else if (!sym_table.check(ident->name,FUNCTION)) {
yyerror("Identifier was not a function");
}
}
void FunctionCall::describe() const {
printf("---Found Function Call: %s\n",ident->name);
}
llvm::Value* FunctionCall::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitFunctionCall(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=================================Keyword==================================*/
Keyword::Keyword(char* name) {
this->name = dup_char(name);
}
void Keyword::describe() const {
printf("---Found Keyword: %s\n",name);
}
llvm::Value* Keyword::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitKeyword(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*============================VariableDefinition============================*/
VariableDefinition::VariableDefinition(Keyword* type, Identifier* ident, Expression* exp) {
this->type = type;
this->ident = ident;
this->exp = exp;
sym_table.insert(ident->name,VARIABLE);
}
void VariableDefinition::describe() const {
printf("---Found Variable Declaration: type='%s' identifier='%s'\n",
type->name,ident->name);
}
llvm::Value* VariableDefinition::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitVariableDefinition(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===========================StructureDefinition============================*/
StructureDefinition::StructureDefinition(Identifier* ident,Block* block) {
this->ident = ident;
this->block = block;
sym_table.insert(ident->name,STRUCTURE);
}
void StructureDefinition::describe() const {
printf("---Found Structure Definition: %s\n",ident->name);
}
llvm::Value* StructureDefinition::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitStructureDefinition(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*============================FunctionDefinition============================*/
FunctionDefinition::FunctionDefinition(Keyword* type, Identifier* ident,
std::vector<VariableDefinition*, gc_allocator<VariableDefinition*>>* args,
Block* block) {
this->type = type;
this->ident = ident;
this->args = args;
this->block = block;
sym_table.insert(ident->name,FUNCTION);
}
void FunctionDefinition::describe() const {
printf("---Found Function Definition: %s\n",ident->name);
}
llvm::Value* FunctionDefinition::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitFunctionDefinition(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==========================StructureDeclaration============================*/
StructureDeclaration::StructureDeclaration(Identifier* type,Identifier* ident) {
this->type = type;
this->ident = ident;
if (!sym_table.check(type->name)) {
yyerror("Structure definition does not exist in symbol table");
} else if (!sym_table.check(type->name,STRUCTURE)) {
yyerror("Type was not a declared structure type");
}
}
void StructureDeclaration::describe() const {
printf("---Found Structure Declaration: type='%s' identifier='%s'\n",
type->name,ident->name);
}
llvm::Value* StructureDeclaration::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitStructureDeclaration(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===========================ExpressionStatement============================*/
ExpressionStatement::ExpressionStatement(Expression* exp) {
this->exp = exp;
}
void ExpressionStatement::describe() const {
printf("---Expression(s) converted into statements\n");
}
llvm::Value* ExpressionStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitExpressionStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=============================ReturnStatement==============================*/
ReturnStatement::ReturnStatement(Expression* exp) {
this->exp = exp;
}
void ReturnStatement::describe() const {
if (exp) {
printf("---Found return statement with expression\n");
} else {
printf("---Found return statement, statement returns void\n");
}
}
llvm::Value* ReturnStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitReturnStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=============================AssignStatement==============================*/
AssignStatement::AssignStatement(Expression* target,Expression* valxp) {
this->target = target;
this->valxp = valxp;
}
void AssignStatement::describe() const {
printf("---Found Assignment Statement\n");
}
llvm::Value* AssignStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitAssignStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===============================IfStatement================================*/
IfStatement::IfStatement(Expression* exp,Block* block) {
this->exp = exp;
this->block = block;
}
void IfStatement::describe() const {
printf("---Found If Statement\n");
}
llvm::Value* IfStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitIfStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===============================SymbolTable================================*/
SymbolTable::SymbolTable() {
//Push global scope
this->push();
}
void SymbolTable::insert(char* ident,IdentType type) {
assert(frames.size());
std::map<std::string,IdentType>& lframe = frames.back();
if (this->check(ident))
yyerror("Identifier already exists");
lframe.insert(std::make_pair(std::string(ident),type));
}
bool SymbolTable::check(char* ident) {
assert(frames.size());
for (int i = 0; i<frames.size();i++) {
if (frames.at(i).count(std::string(ident))) {
printf("Found\n");
return true;
}
}
return false;
}
bool SymbolTable::check(char* ident,IdentType type) {
assert(frames.size());
for (int i = 0; i<frames.size();i++) {
if (frames.at(i).count(std::string(ident))) {
if (frames.at(i).at(std::string(ident))==type) {
return true;
}
}
}
return false;
}
void SymbolTable::push() {
//Push new scope
this->frames.push_back(std::map<std::string,IdentType>());
}
void SymbolTable::pop() {
//Pop current scope
assert(frames.size());
frames.pop_back();
}
<commit_msg>James allows parser to call Fork std functions<commit_after>
//Implementations of the AST objects
//Much of the logic of creating these comes from bison grammar
#include "node.h"
//Symbol table
SymbolTable sym_table;
//Copy identifier
char* dup_char(char* name) {
size_t length = strlen(name)+1;
char* ident = (char*)GC_MALLOC_ATOMIC(length);
memcpy(ident,name,length);
return ident;
}
/*===================================Node===================================*/
void Node::describe() const {
printf("---Found generic node object with no fields.");
printf("---This SHOULD BE AN ERROR.");
}
llvm::Value* Node::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitNode(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*================================Expression================================*/
void Expression::describe() const {
printf("---Found generic Expression object with no fields\n");
}
llvm::Value* Expression::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitExpression(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*================================Statement=================================*/
void Statement::describe() const {
printf("---Found generic statement object with no fields\n");
}
llvm::Value* Statement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=================================Integer==================================*/
Integer::Integer(int64_t value) {
this->value = value;
}
void Integer::describe() const {
printf("---Found Literal Integer: %i\n", (int)value);
}
llvm::Value* Integer::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitInteger(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==================================Float===================================*/
Float::Float(double value) {
this->value = value;
}
void Float::describe() const {
printf("---Found Float: %f\n", value);
}
llvm::Value* Float::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitFloat(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*================================Identifier================================*/
Identifier::Identifier(char* name) {
this->name = dup_char(name);
}
void Identifier::describe() const {
printf("---Found Identifier: %s\n",name);
}
bool Identifier::assertDeclared() const {
if (!sym_table.check(name)) {
yyerror("Identifier does not exist in symbol table");
return true;
} else if (!sym_table.check(name,VARIABLE)) {
yyerror("Identifier was not a variable");
return true;
}
return false;
}
llvm::Value* Identifier::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitIdentifier(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=============================NullaryOperator==============================*/
NullaryOperator::NullaryOperator(char* op) {
printf("%s",op);
this->op = dup_char(op);
}
void NullaryOperator::describe() const {
printf("---Found Nullary Operator\n");
}
llvm::Value* NullaryOperator::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitNullaryOperator(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==============================UnaryOperator===============================*/
UnaryOperator::UnaryOperator(char* op, Expression* exp) {
this->op = dup_char(op);
this->exp = exp;
}
void UnaryOperator::describe() const {
printf("---Found Unary Operator\n");
}
llvm::Value* UnaryOperator::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitUnaryOperator(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==============================BinaryOperator==============================*/
BinaryOperator::BinaryOperator(Expression* left, char* op, Expression* right) {
this->op = dup_char(op);
this->left = left;
this->right = right;
}
void BinaryOperator::describe() const {
printf("---Found Binary Operator %s\n",this->op);
}
llvm::Value* BinaryOperator::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitBinaryOperator(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==================================Block===================================*/
Block::Block(std::vector<Statement*, gc_allocator<Statement*>>* statements) {
this->statements = statements;
}
void Block::describe() const {
printf("---Found Block\n");
}
Block::Block() {
this->statements = NULL;
}
llvm::Value* Block::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitBlock(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===============================FunctionCall===============================*/
FunctionCall::FunctionCall(Identifier* ident, std::vector<Expression*, gc_allocator<Expression*>>* args) {
this->ident = ident;
this->args = args;
if (!sym_table.check(ident->name)) {
yyerror("Called function does not exist in symbol table");
} else if (!sym_table.check(ident->name,FUNCTION)) {
yyerror("Identifier was not a function");
}
}
void FunctionCall::describe() const {
printf("---Found Function Call: %s\n",ident->name);
}
llvm::Value* FunctionCall::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitFunctionCall(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=================================Keyword==================================*/
Keyword::Keyword(char* name) {
this->name = dup_char(name);
}
void Keyword::describe() const {
printf("---Found Keyword: %s\n",name);
}
llvm::Value* Keyword::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitKeyword(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*============================VariableDefinition============================*/
VariableDefinition::VariableDefinition(Keyword* type, Identifier* ident, Expression* exp) {
this->type = type;
this->ident = ident;
this->exp = exp;
sym_table.insert(ident->name,VARIABLE);
}
void VariableDefinition::describe() const {
printf("---Found Variable Declaration: type='%s' identifier='%s'\n",
type->name,ident->name);
}
llvm::Value* VariableDefinition::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitVariableDefinition(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===========================StructureDefinition============================*/
StructureDefinition::StructureDefinition(Identifier* ident,Block* block) {
this->ident = ident;
this->block = block;
sym_table.insert(ident->name,STRUCTURE);
}
void StructureDefinition::describe() const {
printf("---Found Structure Definition: %s\n",ident->name);
}
llvm::Value* StructureDefinition::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitStructureDefinition(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*============================FunctionDefinition============================*/
FunctionDefinition::FunctionDefinition(Keyword* type, Identifier* ident,
std::vector<VariableDefinition*, gc_allocator<VariableDefinition*>>* args,
Block* block) {
this->type = type;
this->ident = ident;
this->args = args;
this->block = block;
sym_table.insert(ident->name,FUNCTION);
}
void FunctionDefinition::describe() const {
printf("---Found Function Definition: %s\n",ident->name);
}
llvm::Value* FunctionDefinition::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitFunctionDefinition(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*==========================StructureDeclaration============================*/
StructureDeclaration::StructureDeclaration(Identifier* type,Identifier* ident) {
this->type = type;
this->ident = ident;
if (!sym_table.check(type->name)) {
yyerror("Structure definition does not exist in symbol table");
} else if (!sym_table.check(type->name,STRUCTURE)) {
yyerror("Type was not a declared structure type");
}
}
void StructureDeclaration::describe() const {
printf("---Found Structure Declaration: type='%s' identifier='%s'\n",
type->name,ident->name);
}
llvm::Value* StructureDeclaration::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitStructureDeclaration(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===========================ExpressionStatement============================*/
ExpressionStatement::ExpressionStatement(Expression* exp) {
this->exp = exp;
}
void ExpressionStatement::describe() const {
printf("---Expression(s) converted into statements\n");
}
llvm::Value* ExpressionStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitExpressionStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=============================ReturnStatement==============================*/
ReturnStatement::ReturnStatement(Expression* exp) {
this->exp = exp;
}
void ReturnStatement::describe() const {
if (exp) {
printf("---Found return statement with expression\n");
} else {
printf("---Found return statement, statement returns void\n");
}
}
llvm::Value* ReturnStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitReturnStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*=============================AssignStatement==============================*/
AssignStatement::AssignStatement(Expression* target,Expression* valxp) {
this->target = target;
this->valxp = valxp;
}
void AssignStatement::describe() const {
printf("---Found Assignment Statement\n");
}
llvm::Value* AssignStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitAssignStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===============================IfStatement================================*/
IfStatement::IfStatement(Expression* exp,Block* block) {
this->exp = exp;
this->block = block;
}
void IfStatement::describe() const {
printf("---Found If Statement\n");
}
llvm::Value* IfStatement::acceptVisitor(Visitor* v) {
llvm::Value* visitedVal = v->visitIfStatement(this);
if(visitedVal)
visitedVal->dump();
return visitedVal;
}
/*===============================SymbolTable================================*/
SymbolTable::SymbolTable() {
//Push global scope
char* print_int = "print_int";
char* print_float = "print_float";
this->push();
this->insert(print_int,FUNCTION);
this->insert(print_float,FUNCTION);
}
void SymbolTable::insert(char* ident,IdentType type) {
assert(frames.size());
std::map<std::string,IdentType>& lframe = frames.back();
if (this->check(ident))
yyerror("Identifier already exists");
lframe.insert(std::make_pair(std::string(ident),type));
}
bool SymbolTable::check(char* ident) {
assert(frames.size());
for (int i = 0; i<frames.size();i++) {
if (frames.at(i).count(std::string(ident))) {
printf("Found\n");
return true;
}
}
return false;
}
bool SymbolTable::check(char* ident,IdentType type) {
assert(frames.size());
for (int i = 0; i<frames.size();i++) {
if (frames.at(i).count(std::string(ident))) {
if (frames.at(i).at(std::string(ident))==type) {
return true;
}
}
}
return false;
}
void SymbolTable::push() {
//Push new scope
this->frames.push_back(std::map<std::string,IdentType>());
}
void SymbolTable::pop() {
//Pop current scope
assert(frames.size());
frames.pop_back();
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2PixelFormat.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
return GL_ALPHA;
case PF_L8:
case PF_L16:
case PF_FLOAT16_R:
case PF_FLOAT32_R:
return GL_LUMINANCE;
case PF_BYTE_LA:
case PF_SHORT_GR:
case PF_FLOAT16_GR:
case PF_FLOAT32_GR:
return GL_LUMINANCE_ALPHA;
// PVRTC compressed formats
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_R3G3B2:
case PF_R5G6B5:
case PF_FLOAT16_RGB:
case PF_FLOAT32_RGB:
case PF_SHORT_RGB:
return GL_RGB;
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
case PF_A2R10G10B10:
// This case in incorrect, swaps R & B channels
//#if GL_IMG_read_format || GL_IMG_texture_format_BGRA8888
// return GL_BGRA;
//#endif
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_R8G8B8A8:
case PF_A2B10G10R10:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
return GL_RGBA;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
// Formats are in native endian, so R8G8B8 on little endian is
// BGR, on big endian it is RGB.
case PF_R8G8B8:
return GL_RGB;
case PF_B8G8R8:
#if GL_EXT_bgra
return GL_BGR_EXT;
#else
return 0;
#endif
#else
case PF_R8G8B8:
#if GL_EXT_bgra
return GL_BGR_EXT;
#else
case PF_B8G8R8:
return GL_RGB;
#endif
#endif
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
#endif
case PF_B5G6R5:
#if GL_EXT_bgra
return GL_BGR_EXT;
#endif
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
case PF_L8:
case PF_R8G8B8:
case PF_B8G8R8:
case PF_BYTE_LA:
return GL_UNSIGNED_BYTE;
case PF_R5G6B5:
case PF_B5G6R5:
return GL_UNSIGNED_SHORT_5_6_5;
case PF_L16:
return GL_UNSIGNED_SHORT;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return 0;
case PF_B8G8R8A8:
return GL_UNSIGNED_BYTE;
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#else
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return GL_UNSIGNED_BYTE;
case PF_B8G8R8A8:
case PF_R8G8B8A8:
return 0;
#endif
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
return GL_FLOAT;
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
return GL_UNSIGNED_SHORT;
case PF_A2R10G10B10:
case PF_A2B10G10R10:
#if GL_EXT_texture_type_2_10_10_10_REV
return GL_UNSIGNED_INT_2_10_10_10_REV_EXT;
#endif
case PF_FLOAT16_R:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGB:
case PF_FLOAT16_RGBA:
#if GL_ARB_half_float_pixel
return GL_HALF_FLOAT_ARB;
#endif
case PF_R3G3B2:
case PF_A1R5G5B5:
#if GL_EXT_read_format_bgra
return GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT;
#endif
case PF_A4R4G4B4:
#if GL_EXT_read_format_bgra
return GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT;
#endif
// TODO not supported
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
{
switch (fmt)
{
case PF_L8:
return GL_LUMINANCE;
case PF_A8:
return GL_ALPHA;
case PF_BYTE_LA:
return GL_LUMINANCE_ALPHA;
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_R8G8B8:
case PF_B8G8R8:
case PF_X8B8G8R8:
case PF_X8R8G8B8:
if (!hwGamma)
{
return GL_RGBA;
}
case PF_A8R8G8B8:
case PF_B8G8R8A8:
if (!hwGamma)
{
return GL_RGBA;
}
case PF_A4L4:
case PF_L16:
case PF_A4R4G4B4:
case PF_R3G3B2:
case PF_A1R5G5B5:
case PF_R5G6B5:
case PF_B5G6R5:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_R:
case PF_FLOAT16_RGB:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
bool hwGamma)
{
GLenum format = getGLInternalFormat(mFormat, hwGamma);
if (format == GL_NONE)
{
if (hwGamma)
{
// TODO not supported
return 0;
}
else
{
return GL_RGBA;
}
}
else
{
return format;
}
}
//-----------------------------------------------------------------------------
PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum fmt)
{
switch (fmt)
{
#if GL_IMG_texture_compression_pvrtc
case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGB2;
case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGBA2;
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGB4;
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGBA4;
#endif
case GL_LUMINANCE:
return PF_L8;
case GL_ALPHA:
return PF_A8;
case GL_LUMINANCE_ALPHA:
return PF_BYTE_LA;
case GL_RGB:
return PF_X8R8G8B8;
case GL_RGBA:
#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) || (OGRE_PLATFORM == OGRE_PLATFORM_TEGRA2)
// seems that in windows we need this value to get the right color
return PF_X8B8G8R8;
#endif
return PF_A8R8G8B8;
#if GL_EXT_texture_compression_dxt1
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return PF_DXT1;
#endif
#if GL_EXT_texture_compression_s3tc
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
return PF_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return PF_DXT5;
#endif
default:
//TODO: not supported
return PF_A8R8G8B8;
};
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
PixelFormat format)
{
size_t count = 0;
do {
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
if (depth > 1)
{
depth = depth / 2;
}
/*
NOT needed, compressed formats will have mipmaps up to 1x1
if(PixelUtil::isValidExtent(width, height, depth, format))
count ++;
else
break;
*/
count++;
} while (!(width == 1 && height == 1 && depth == 1));
return count;
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::optionalPO2(size_t value)
{
const RenderSystemCapabilities *caps =
Root::getSingleton().getRenderSystem()->getCapabilities();
if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
return value;
}
else
{
return Bitwise::firstPO2From((uint32)value);
}
}
//-----------------------------------------------------------------------------
PixelBox* GLES2PixelUtil::convertToGLformat(const PixelBox &data,
GLenum *outputFormat)
{
GLenum glFormat = GLES2PixelUtil::getGLOriginFormat(data.format);
if (glFormat != 0)
{
// format already supported
return OGRE_NEW PixelBox(data);
}
PixelBox *converted = 0;
if (data.format == PF_R8G8B8)
{
// Convert BGR -> RGB
converted->format = PF_B8G8R8;
*outputFormat = GL_RGB;
converted = OGRE_NEW PixelBox(data);
uint32 *data = (uint32 *) converted->data;
for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++)
{
uint32 *color = data;
*color = (*color & 0x000000ff) << 16 |
(*color & 0x0000FF00) |
(*color & 0x00FF0000) >> 16;
data += 1;
}
}
return converted;
}
}
<commit_msg>GLES 2: Support for even more built in and extension supported pixel formats<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2PixelFormat.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
return GL_ALPHA;
case PF_L8:
case PF_L16:
case PF_FLOAT16_R:
case PF_FLOAT32_R:
return GL_LUMINANCE;
case PF_BYTE_LA:
case PF_SHORT_GR:
case PF_FLOAT16_GR:
case PF_FLOAT32_GR:
return GL_LUMINANCE_ALPHA;
// PVRTC compressed formats
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_R3G3B2:
case PF_R5G6B5:
case PF_FLOAT16_RGB:
case PF_FLOAT32_RGB:
case PF_SHORT_RGB:
return GL_RGB;
case PF_X8R8G8B8:
case PF_A8R8G8B8:
case PF_B8G8R8A8:
case PF_A1R5G5B5:
case PF_A4R4G4B4:
case PF_A2R10G10B10:
// This case in incorrect, swaps R & B channels
//#if GL_IMG_read_format || GL_IMG_texture_format_BGRA8888
// return GL_BGRA;
//#endif
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_R8G8B8A8:
case PF_A2B10G10R10:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
return GL_RGBA;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
// Formats are in native endian, so R8G8B8 on little endian is
// BGR, on big endian it is RGB.
case PF_R8G8B8:
return GL_RGB;
case PF_B8G8R8:
#if GL_EXT_bgra
return GL_BGR_EXT;
#else
return 0;
#endif
#else
case PF_R8G8B8:
#if GL_EXT_bgra
return GL_BGR_EXT;
#else
case PF_B8G8R8:
return GL_RGB;
#endif
#endif
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
#endif
case PF_B5G6R5:
#if GL_EXT_bgra
return GL_BGR_EXT;
#endif
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat mFormat)
{
switch (mFormat)
{
case PF_A8:
case PF_L8:
case PF_R8G8B8:
case PF_B8G8R8:
case PF_BYTE_LA:
return GL_UNSIGNED_BYTE;
case PF_R5G6B5:
case PF_B5G6R5:
return GL_UNSIGNED_SHORT_5_6_5;
case PF_L16:
return GL_UNSIGNED_SHORT;
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return 0;
case PF_B8G8R8A8:
return GL_UNSIGNED_BYTE;
case PF_R8G8B8A8:
return GL_UNSIGNED_BYTE;
#else
case PF_X8B8G8R8:
case PF_A8B8G8R8:
case PF_X8R8G8B8:
case PF_A8R8G8B8:
return GL_UNSIGNED_BYTE;
case PF_B8G8R8A8:
case PF_R8G8B8A8:
return 0;
#endif
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
return GL_FLOAT;
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
return GL_UNSIGNED_SHORT;
case PF_A2R10G10B10:
case PF_A2B10G10R10:
#if GL_EXT_texture_type_2_10_10_10_REV
return GL_UNSIGNED_INT_2_10_10_10_REV_EXT;
#endif
case PF_FLOAT16_R:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGB:
case PF_FLOAT16_RGBA:
#if GL_ARB_half_float_pixel
return GL_HALF_FLOAT_ARB;
#endif
case PF_R3G3B2:
case PF_A1R5G5B5:
#if GL_EXT_read_format_bgra
return GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT;
#endif
case PF_A4R4G4B4:
#if GL_EXT_read_format_bgra
return GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT;
#endif
// TODO not supported
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)
{
switch (fmt)
{
case PF_L8:
return GL_LUMINANCE;
case PF_A8:
return GL_ALPHA;
case PF_BYTE_LA:
return GL_LUMINANCE_ALPHA;
#if GL_IMG_texture_compression_pvrtc
case PF_PVRTC_RGB2:
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGB4:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case PF_PVRTC_RGBA2:
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case PF_PVRTC_RGBA4:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
#endif
case PF_R8G8B8:
case PF_B8G8R8:
case PF_X8B8G8R8:
case PF_X8R8G8B8:
if (!hwGamma)
{
return GL_RGBA;
}
case PF_A8R8G8B8:
case PF_B8G8R8A8:
if (!hwGamma)
{
return GL_RGBA;
}
case PF_A4R4G4B4:
return GL_RGBA4;
case PF_A1R5G5B5:
return GL_RGB5_A1;
case PF_A4L4:
case PF_L16:
case PF_R3G3B2:
case PF_R5G6B5:
case PF_B5G6R5:
case PF_A2R10G10B10:
case PF_A2B10G10R10:
case PF_FLOAT16_R:
case PF_FLOAT16_RGB:
case PF_FLOAT16_GR:
case PF_FLOAT16_RGBA:
case PF_FLOAT32_R:
case PF_FLOAT32_GR:
case PF_FLOAT32_RGB:
case PF_FLOAT32_RGBA:
case PF_SHORT_RGBA:
case PF_SHORT_RGB:
case PF_SHORT_GR:
case PF_DXT1:
#if GL_EXT_texture_compression_dxt1
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
#endif
case PF_DXT3:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
case PF_DXT5:
#if GL_EXT_texture_compression_s3tc
if (!hwGamma)
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
#endif
default:
return 0;
}
}
//-----------------------------------------------------------------------------
GLenum GLES2PixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,
bool hwGamma)
{
GLenum format = getGLInternalFormat(mFormat, hwGamma);
if (format == GL_NONE)
{
if (hwGamma)
{
// TODO not supported
return 0;
}
else
{
return GL_RGBA;
}
}
else
{
return format;
}
}
//-----------------------------------------------------------------------------
PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum fmt)
{
switch (fmt)
{
#if GL_IMG_texture_compression_pvrtc
case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGB2;
case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return PF_PVRTC_RGBA2;
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGB4;
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
return PF_PVRTC_RGBA4;
#endif
case GL_LUMINANCE:
return PF_L8;
case GL_ALPHA:
return PF_A8;
case GL_LUMINANCE_ALPHA:
return PF_BYTE_LA;
case GL_RGB5_A1:
return PF_A1R5G5B5;
case GL_RGBA4:
return PF_A4R4G4B4;
#if GL_OES_rgb8_rgba8
case GL_RGB8_OES:
return PF_X8R8G8B8;
case GL_RGBA8_OES:
return PF_A8R8G8B8;
#endif
case GL_RGB:
return PF_X8R8G8B8;
case GL_RGBA:
#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) || (OGRE_PLATFORM == OGRE_PLATFORM_TEGRA2)
// seems that in windows we need this value to get the right color
return PF_X8B8G8R8;
#endif
return PF_A8R8G8B8;
#if GL_EXT_texture_compression_dxt1
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return PF_DXT1;
#endif
#if GL_EXT_texture_compression_s3tc
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
return PF_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return PF_DXT5;
#endif
default:
//TODO: not supported
return PF_A8R8G8B8;
};
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,
PixelFormat format)
{
size_t count = 0;
do {
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
if (depth > 1)
{
depth = depth / 2;
}
/*
NOT needed, compressed formats will have mipmaps up to 1x1
if(PixelUtil::isValidExtent(width, height, depth, format))
count ++;
else
break;
*/
count++;
} while (!(width == 1 && height == 1 && depth == 1));
return count;
}
//-----------------------------------------------------------------------------
size_t GLES2PixelUtil::optionalPO2(size_t value)
{
const RenderSystemCapabilities *caps =
Root::getSingleton().getRenderSystem()->getCapabilities();
if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
return value;
}
else
{
return Bitwise::firstPO2From((uint32)value);
}
}
//-----------------------------------------------------------------------------
PixelBox* GLES2PixelUtil::convertToGLformat(const PixelBox &data,
GLenum *outputFormat)
{
GLenum glFormat = GLES2PixelUtil::getGLOriginFormat(data.format);
if (glFormat != 0)
{
// format already supported
return OGRE_NEW PixelBox(data);
}
PixelBox *converted = 0;
if (data.format == PF_R8G8B8)
{
// Convert BGR -> RGB
converted->format = PF_B8G8R8;
*outputFormat = GL_RGB;
converted = OGRE_NEW PixelBox(data);
uint32 *data = (uint32 *) converted->data;
for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++)
{
uint32 *color = data;
*color = (*color & 0x000000ff) << 16 |
(*color & 0x0000FF00) |
(*color & 0x00FF0000) >> 16;
data += 1;
}
}
return converted;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestCubeAxes3.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware SAS 2011
#include "vtkBYUReader.h"
#include "vtkCamera.h"
#include "vtkCubeAxesActor.h"
#include "vtkLight.h"
#include "vtkLODActor.h"
#include "vtkNew.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkTextProperty.h"
//----------------------------------------------------------------------------
int TestCubeAxesWithGridLines( int argc, char * argv [] )
{
vtkNew<vtkBYUReader> fohe;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g");
fohe->SetGeometryFileName(fname);
delete [] fname;
vtkNew<vtkPolyDataNormals> normals;
normals->SetInputConnection(fohe->GetOutputPort());
vtkNew<vtkPolyDataMapper> foheMapper;
foheMapper->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkLODActor> foheActor;
foheActor->SetMapper(foheMapper.GetPointer());
foheActor->GetProperty()->SetDiffuseColor(0.7, 0.3, 0.0);
vtkNew<vtkOutlineFilter> outline;
outline->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkPolyDataMapper> mapOutline;
mapOutline->SetInputConnection(outline->GetOutputPort());
vtkNew<vtkActor> outlineActor;
outlineActor->SetMapper(mapOutline.GetPointer());
outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);
vtkNew<vtkCamera> camera;
camera->SetClippingRange(1.0, 100.0);
camera->SetFocalPoint(0.9, 1.0, 0.0);
camera->SetPosition(11.63, 6.0, 10.77);
vtkNew<vtkLight> light;
light->SetFocalPoint(0.21406, 1.5, 0.0);
light->SetPosition(8.3761, 4.94858, 4.12505);
vtkNew<vtkRenderer> ren2;
ren2->SetActiveCamera(camera.GetPointer());
ren2->AddLight(light.GetPointer());
vtkNew<vtkRenderWindow> renWin;
renWin->SetMultiSamples(0);
renWin->AddRenderer(ren2.GetPointer());
renWin->SetWindowName("VTK - Cube Axes custom range");
renWin->SetSize(600, 600);
renWin->SetMultiSamples(0);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
ren2->AddViewProp(foheActor.GetPointer());
ren2->AddViewProp(outlineActor.GetPointer());
ren2->SetGradientBackground( true );
ren2->SetBackground(.1,.1,.1);
ren2->SetBackground2(.8,.8,.8);
normals->Update();
vtkNew<vtkCubeAxesActor> axes2;
axes2->SetBounds(normals->GetOutput()->GetBounds());
axes2->SetXAxisRange(20, 300);
axes2->SetYAxisRange(-0.01, 0.01);
axes2->SetCamera(ren2->GetActiveCamera());
axes2->SetXLabelFormat("%6.1f");
axes2->SetYLabelFormat("%6.1f");
axes2->SetZLabelFormat("%6.1f");
axes2->SetScreenSize(15.0);
axes2->SetFlyModeToClosestTriad();
axes2->SetCornerOffset(0.0);
// Draw all (outer) grid lines
axes2->SetDrawXGridlines(1);
axes2->SetDrawYGridlines(1);
axes2->SetDrawZGridlines(1);
// Use red color for X gridlines, title, and labels
axes2->GetXAxesGridlinesProperty()->SetColor(1., 0., 0.);
axes2->GetTitleTextProperty(0)->SetColor(1., 0., 0.);
axes2->GetLabelTextProperty(0)->SetColor(1., 0., 0.);
// Use green color for Y gridlines, title, and labels
axes2->GetYAxesGridlinesProperty()->SetColor(0., 1., 0.);
axes2->GetTitleTextProperty(1)->SetColor(0., 1., 0.);
axes2->GetLabelTextProperty(1)->SetColor(0., 1., 0.);
// Use blue color for Z gridlines, title, and labels
axes2->GetZAxesGridlinesProperty()->SetColor(0., 0., 1.);
axes2->GetTitleTextProperty(2)->SetColor(0., 0., 1.);
axes2->GetLabelTextProperty(2)->SetColor(0., 0., 1.);
ren2->AddViewProp(axes2.GetPointer());
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<commit_msg>Correct title<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestCubeAxes3.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware SAS 2011
#include "vtkBYUReader.h"
#include "vtkCamera.h"
#include "vtkCubeAxesActor.h"
#include "vtkLight.h"
#include "vtkLODActor.h"
#include "vtkNew.h"
#include "vtkOutlineFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkTextProperty.h"
//----------------------------------------------------------------------------
int TestCubeAxesWithGridLines( int argc, char * argv [] )
{
vtkNew<vtkBYUReader> fohe;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g");
fohe->SetGeometryFileName(fname);
delete [] fname;
vtkNew<vtkPolyDataNormals> normals;
normals->SetInputConnection(fohe->GetOutputPort());
vtkNew<vtkPolyDataMapper> foheMapper;
foheMapper->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkLODActor> foheActor;
foheActor->SetMapper(foheMapper.GetPointer());
foheActor->GetProperty()->SetDiffuseColor(0.7, 0.3, 0.0);
vtkNew<vtkOutlineFilter> outline;
outline->SetInputConnection(normals->GetOutputPort());
vtkNew<vtkPolyDataMapper> mapOutline;
mapOutline->SetInputConnection(outline->GetOutputPort());
vtkNew<vtkActor> outlineActor;
outlineActor->SetMapper(mapOutline.GetPointer());
outlineActor->GetProperty()->SetColor(0.0 ,0.0 ,0.0);
vtkNew<vtkCamera> camera;
camera->SetClippingRange(1.0, 100.0);
camera->SetFocalPoint(0.9, 1.0, 0.0);
camera->SetPosition(11.63, 6.0, 10.77);
vtkNew<vtkLight> light;
light->SetFocalPoint(0.21406, 1.5, 0.0);
light->SetPosition(8.3761, 4.94858, 4.12505);
vtkNew<vtkRenderer> ren2;
ren2->SetActiveCamera(camera.GetPointer());
ren2->AddLight(light.GetPointer());
vtkNew<vtkRenderWindow> renWin;
renWin->SetMultiSamples(0);
renWin->AddRenderer(ren2.GetPointer());
renWin->SetWindowName("Cube Axes with Outer Grid Lines");
renWin->SetSize(600, 600);
renWin->SetMultiSamples(0);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
ren2->AddViewProp(foheActor.GetPointer());
ren2->AddViewProp(outlineActor.GetPointer());
ren2->SetGradientBackground( true );
ren2->SetBackground(.1,.1,.1);
ren2->SetBackground2(.8,.8,.8);
normals->Update();
vtkNew<vtkCubeAxesActor> axes2;
axes2->SetBounds(normals->GetOutput()->GetBounds());
axes2->SetXAxisRange(20, 300);
axes2->SetYAxisRange(-0.01, 0.01);
axes2->SetCamera(ren2->GetActiveCamera());
axes2->SetXLabelFormat("%6.1f");
axes2->SetYLabelFormat("%6.1f");
axes2->SetZLabelFormat("%6.1f");
axes2->SetScreenSize(15.0);
axes2->SetFlyModeToClosestTriad();
axes2->SetCornerOffset(0.0);
// Draw all (outer) grid lines
axes2->SetDrawXGridlines(1);
axes2->SetDrawYGridlines(1);
axes2->SetDrawZGridlines(1);
// Use red color for X gridlines, title, and labels
axes2->GetXAxesGridlinesProperty()->SetColor(1., 0., 0.);
axes2->GetTitleTextProperty(0)->SetColor(1., 0., 0.);
axes2->GetLabelTextProperty(0)->SetColor(1., 0., 0.);
// Use green color for Y gridlines, title, and labels
axes2->GetYAxesGridlinesProperty()->SetColor(0., 1., 0.);
axes2->GetTitleTextProperty(1)->SetColor(0., 1., 0.);
axes2->GetLabelTextProperty(1)->SetColor(0., 1., 0.);
// Use blue color for Z gridlines, title, and labels
axes2->GetZAxesGridlinesProperty()->SetColor(0., 0., 1.);
axes2->GetTitleTextProperty(2)->SetColor(0., 0., 1.);
axes2->GetLabelTextProperty(2)->SetColor(0., 0., 1.);
ren2->AddViewProp(axes2.GetPointer());
renWin->Render();
int retVal = vtkRegressionTestImage( renWin.GetPointer() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: liImageRegistrationConsole.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <liImageRegistrationConsole.h>
#include <FL/fl_file_chooser.H>
/************************************
*
* Constructor
*
***********************************/
liImageRegistrationConsole
::liImageRegistrationConsole()
{
m_MovingImageViewer.SetLabel( "Moving Image" );
m_FixedImageViewer.SetLabel( "Fixed Image" );
m_InputMovingImageViewer.SetLabel( "Input Moving Image" );
m_MappedMovingImageViewer.SetLabel( "Mapped Moving Image" );
progressSlider->Observe( m_ResampleMovingImageFilter.GetPointer() );
fixedImageButton->Observe( m_FixedImageReader.GetPointer() );
loadFixedImageButton->Observe( m_FixedImageReader.GetPointer() );
inputMovingImageButton->Observe( m_MovingImageReader.GetPointer() );
loadMovingImageButton->Observe( m_MovingImageReader.GetPointer() );
this->ShowStatus("Let's start by loading an image...");
}
/************************************
*
* Destructor
*
***********************************/
liImageRegistrationConsole
::~liImageRegistrationConsole()
{
}
/************************************
*
* Load Moving Image
*
***********************************/
void
liImageRegistrationConsole
::LoadMovingImage( void )
{
const char * filename = fl_file_chooser("Moving Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadMovingImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Moving Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Load Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::LoadFixedImage( void )
{
const char * filename = fl_file_chooser("Fixed Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadFixedImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Fixed Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Show
*
***********************************/
void
liImageRegistrationConsole
::Show( void )
{
consoleWindow->show();
}
/************************************
*
* Hide
*
***********************************/
void
liImageRegistrationConsole
::Hide( void )
{
consoleWindow->hide();
m_FixedImageViewer.Hide();
m_MovingImageViewer.Hide();
m_InputMovingImageViewer.Hide();
m_MappedMovingImageViewer.Hide();
}
/************************************
*
* Quit
*
***********************************/
void
liImageRegistrationConsole
::Quit( void )
{
this->Hide();
}
/************************************
*
* Show Status
*
***********************************/
void
liImageRegistrationConsole
::ShowStatus( const char * message )
{
liImageRegistrationConsoleBase::ShowStatus( message );
statusTextOutput->value( message );
Fl::check();
}
/************************************
*
* Show Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::ShowFixedImage( void )
{
if( !m_FixedImageIsLoaded )
{
return;
}
m_FixedImageViewer.SetImage( m_FixedImageReader->GetOutput() );
m_FixedImageViewer.Show();
}
/************************************
*
* Show Input Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowInputMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_InputMovingImageViewer.SetImage( m_MovingImageReader->GetOutput() );
m_InputMovingImageViewer.Show();
}
/************************************
*
* Show Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
this->GenerateMovingImage();
m_MovingImageViewer.SetImage( m_ResampleInputMovingImageFilter->GetOutput() );
m_MovingImageViewer.Show();
}
/************************************
*
* Show Mapped Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_MappedMovingImageViewer.SetImage( m_ResampleMovingImageFilter->GetOutput() );
m_MappedMovingImageViewer.Show();
}
/************************************
*
* Execute
*
***********************************/
void
liImageRegistrationConsole
::Execute( void )
{
this->ShowStatus("Registering Moving Image against Fixed Image ...");
liImageRegistrationConsoleBase::Execute();
this->ShowStatus("Registration done ");
}
/************************************
*
* Update the parameters of the
* Transform
*
***********************************/
void
liImageRegistrationConsole
::UpdateTransformParameters( void )
{
typedef itk::AffineTransform<double,3> TransformType;
TransformType::Pointer affineTransform = TransformType::New();
TransformType::OffsetType offset;
TransformType::OutputVectorType axis;
const double angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
affineTransform->Rotate3D( axis, angle );
affineTransform->SetOffset( offset );
TransformType::MatrixType matrix;
matrix = affineTransform->GetMatrix();
offset = affineTransform->GetOffset();
std::cout << "Matrix = " << matrix << std::endl;
std::cout << "Offset = " << offset << std::endl;
const unsigned long numberOfParamenters =
affineTransform->GetNumberOfParameters();
TransformParametersType transformationParameters( numberOfParamenters );
unsigned int counter = 0;
for(unsigned int i=0; i<ImageDimension; i++)
{
for(unsigned int j=0; j<ImageDimension; j++)
{
transformationParameters[counter++] = matrix[i][j];
}
}
for(unsigned int k=0; k<ImageDimension; k++)
{
transformationParameters[counter++] = offset[k];
}
}
/************************************
*
* Generate Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
movingImageButton->selection_color( FL_RED );
movingImageButton->value( 1 );
movingImageButton->redraw();
AffineTransformType::OffsetType offset;
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
AffineTransformType::OutputVectorType axis;
AffineTransformType::ScalarType angle;
angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
m_InputTransform->SetIdentity();
m_InputTransform->SetOffset( offset );
m_InputTransform->Rotate3D( axis, angle );
liImageRegistrationConsoleBase::GenerateMovingImage();
movingImageButton->selection_color( FL_GREEN );
movingImageButton->value( 1 );
movingImageButton->redraw();
}
/************************************
*
* Generate Mapped Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
mappedMovingImageButton->selection_color( FL_RED );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
liImageRegistrationConsoleBase::GenerateMappedMovingImage();
mappedMovingImageButton->selection_color( FL_GREEN );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
}
<commit_msg>ENH: progress bar connected to the resampling filter.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: liImageRegistrationConsole.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <liImageRegistrationConsole.h>
#include <FL/fl_file_chooser.H>
/************************************
*
* Constructor
*
***********************************/
liImageRegistrationConsole
::liImageRegistrationConsole()
{
m_MovingImageViewer.SetLabel( "Moving Image" );
m_FixedImageViewer.SetLabel( "Fixed Image" );
m_InputMovingImageViewer.SetLabel( "Input Moving Image" );
m_MappedMovingImageViewer.SetLabel( "Mapped Moving Image" );
progressSlider->Observe( m_ResampleMovingImageFilter.GetPointer() );
progressSlider->Observe( m_ResampleInputMovingImageFilter.GetPointer() );
fixedImageButton->Observe( m_FixedImageReader.GetPointer() );
loadFixedImageButton->Observe( m_FixedImageReader.GetPointer() );
inputMovingImageButton->Observe( m_MovingImageReader.GetPointer() );
loadMovingImageButton->Observe( m_MovingImageReader.GetPointer() );
this->ShowStatus("Let's start by loading an image...");
}
/************************************
*
* Destructor
*
***********************************/
liImageRegistrationConsole
::~liImageRegistrationConsole()
{
}
/************************************
*
* Load Moving Image
*
***********************************/
void
liImageRegistrationConsole
::LoadMovingImage( void )
{
const char * filename = fl_file_chooser("Moving Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadMovingImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Moving Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Load Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::LoadFixedImage( void )
{
const char * filename = fl_file_chooser("Fixed Image filename","*.mh[da]","");
if( !filename )
{
return;
}
this->ShowStatus("Loading fixed image file...");
try
{
liImageRegistrationConsoleBase::LoadFixedImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
this->ShowStatus("Fixed Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Show
*
***********************************/
void
liImageRegistrationConsole
::Show( void )
{
consoleWindow->show();
}
/************************************
*
* Hide
*
***********************************/
void
liImageRegistrationConsole
::Hide( void )
{
consoleWindow->hide();
m_FixedImageViewer.Hide();
m_MovingImageViewer.Hide();
m_InputMovingImageViewer.Hide();
m_MappedMovingImageViewer.Hide();
}
/************************************
*
* Quit
*
***********************************/
void
liImageRegistrationConsole
::Quit( void )
{
this->Hide();
}
/************************************
*
* Show Status
*
***********************************/
void
liImageRegistrationConsole
::ShowStatus( const char * message )
{
liImageRegistrationConsoleBase::ShowStatus( message );
statusTextOutput->value( message );
Fl::check();
}
/************************************
*
* Show Fixed Image
*
***********************************/
void
liImageRegistrationConsole
::ShowFixedImage( void )
{
if( !m_FixedImageIsLoaded )
{
return;
}
m_FixedImageViewer.SetImage( m_FixedImageReader->GetOutput() );
m_FixedImageViewer.Show();
}
/************************************
*
* Show Input Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowInputMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_InputMovingImageViewer.SetImage( m_MovingImageReader->GetOutput() );
m_InputMovingImageViewer.Show();
}
/************************************
*
* Show Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
this->GenerateMovingImage();
m_MovingImageViewer.SetImage( m_ResampleInputMovingImageFilter->GetOutput() );
m_MovingImageViewer.Show();
}
/************************************
*
* Show Mapped Moving Image
*
***********************************/
void
liImageRegistrationConsole
::ShowMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
m_MappedMovingImageViewer.SetImage( m_ResampleMovingImageFilter->GetOutput() );
m_MappedMovingImageViewer.Show();
}
/************************************
*
* Execute
*
***********************************/
void
liImageRegistrationConsole
::Execute( void )
{
this->ShowStatus("Registering Moving Image against Fixed Image ...");
liImageRegistrationConsoleBase::Execute();
this->ShowStatus("Registration done ");
}
/************************************
*
* Update the parameters of the
* Transform
*
***********************************/
void
liImageRegistrationConsole
::UpdateTransformParameters( void )
{
typedef itk::AffineTransform<double,3> TransformType;
TransformType::Pointer affineTransform = TransformType::New();
TransformType::OffsetType offset;
TransformType::OutputVectorType axis;
const double angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
affineTransform->Rotate3D( axis, angle );
affineTransform->SetOffset( offset );
TransformType::MatrixType matrix;
matrix = affineTransform->GetMatrix();
offset = affineTransform->GetOffset();
std::cout << "Matrix = " << matrix << std::endl;
std::cout << "Offset = " << offset << std::endl;
const unsigned long numberOfParamenters =
affineTransform->GetNumberOfParameters();
TransformParametersType transformationParameters( numberOfParamenters );
unsigned int counter = 0;
for(unsigned int i=0; i<ImageDimension; i++)
{
for(unsigned int j=0; j<ImageDimension; j++)
{
transformationParameters[counter++] = matrix[i][j];
}
}
for(unsigned int k=0; k<ImageDimension; k++)
{
transformationParameters[counter++] = offset[k];
}
}
/************************************
*
* Generate Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
movingImageButton->selection_color( FL_RED );
movingImageButton->value( 1 );
movingImageButton->redraw();
AffineTransformType::OffsetType offset;
offset[0] = xTranslation->value();
offset[1] = yTranslation->value();
offset[2] = zTranslation->value();
AffineTransformType::OutputVectorType axis;
AffineTransformType::ScalarType angle;
angle = angleRotation->value() * atan( 1.0 ) / 45.0 ;
axis[0] = xRotation->value();
axis[1] = yRotation->value();
axis[2] = zRotation->value();
m_InputTransform->SetIdentity();
m_InputTransform->SetOffset( offset );
m_InputTransform->Rotate3D( axis, angle );
liImageRegistrationConsoleBase::GenerateMovingImage();
movingImageButton->selection_color( FL_GREEN );
movingImageButton->value( 1 );
movingImageButton->redraw();
}
/************************************
*
* Generate Mapped Moving Image
* Modify button colors and then
* delegate to base class
*
***********************************/
void
liImageRegistrationConsole
::GenerateMappedMovingImage( void )
{
if( !m_MovingImageIsLoaded )
{
return;
}
mappedMovingImageButton->selection_color( FL_RED );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
liImageRegistrationConsoleBase::GenerateMappedMovingImage();
mappedMovingImageButton->selection_color( FL_GREEN );
mappedMovingImageButton->value( 1 );
mappedMovingImageButton->redraw();
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFGameServerPlugin.cpp
// @Author : LvSheng.Huang
// @Date : 2012-07-14 08:51
// @Module : NFGameServerPlugin
//
// -------------------------------------------------------------------------
#include "NFGameLogicPlugin.h"
#include "NFCGameLogicModule.h"
#include "NFCBuffModule.h"
#include "NFCItemModule.h"
#include "NFCPackModule.h"
#include "NFCSkillModule.h"
#include "NFCBulletSkillConsumeProcessModule.h"
#include "NFCBriefSkillConsumeProcessModule.h"
#include "NFCSkillConsumeManagerModule.h"
#include "NFCPotionItemConsumeProcessModule.h"
#include "NFCCardItemConsumeProcessModule.h"
#include "NFCItemConsumeManagerModule.h"
#include "NFCNPCRefreshModule.h"
#include "NFCRebornItemConsumeProcessModule.h"
#include "NFCAwardPackModule.h"
#include "NFCEctypeModule.h"
#ifdef NF_DYNAMIC_PLUGIN
extern "C" __declspec( dllexport ) void DllStartPlugin( NFIPluginManager* pm )
{
CREATE_PLUGIN( pm, NFGameLogicPlugin )
};
extern "C" __declspec( dllexport ) void DllStopPlugin( NFIPluginManager* pm )
{
DESTROY_PLUGIN( pm, NFGameLogicPlugin )
};
#endif
//////////////////////////////////////////////////////////////////////////
const int NFGameLogicPlugin::GetPluginVersion()
{
return 0;
}
const std::string NFGameLogicPlugin::GetPluginName()
{
GET_PLUGIN_NAME( NFGameLogicPlugin )
}
void NFGameLogicPlugin::Install()
{
REGISTER_MODULE( pPluginManager, NFCGameLogicModule )
REGISTER_MODULE( pPluginManager, NFCBuffModule )
REGISTER_MODULE( pPluginManager, NFCItemModule )
REGISTER_MODULE( pPluginManager, NFCPackModule )
REGISTER_MODULE( pPluginManager, NFCSkillModule )
REGISTER_MODULE( pPluginManager, NFCRebornItemConsumeProcessModule )
REGISTER_MODULE( pPluginManager, NFCItemConsumeManagerModule )
REGISTER_MODULE( pPluginManager, NFCPotionItemConsumeProcessModule )
REGISTER_MODULE( pPluginManager, NFCCardItemConsumeProcessModule )
//Continue to add other item types of consumption
REGISTER_MODULE( pPluginManager, NFCSkillConsumeManagerModule )
REGISTER_MODULE( pPluginManager, NFCBriefSkillConsumeProcessModule )
REGISTER_MODULE( pPluginManager, NFCBulletSkillConsumeProcessModule )
//Continue to add other skill types of consumption
REGISTER_MODULE( pPluginManager, NFCNPCRefreshModule )
REGISTER_MODULE(pPluginManager, NFCAwardPackModule)
REGISTER_MODULE(pPluginManager, NFCEctypeModule)
}
void NFGameLogicPlugin::Uninstall()
{
UNREGISTER_MODULE(pPluginManager, NFCEctypeModule)
UNREGISTER_MODULE(pPluginManager, NFCAwardPackModule)
UNREGISTER_MODULE( pPluginManager, NFCNPCRefreshModule )
UNREGISTER_MODULE( pPluginManager, NFCBulletSkillConsumeProcessModule )
UNREGISTER_MODULE( pPluginManager, NFCBriefSkillConsumeProcessModule )
UNREGISTER_MODULE( pPluginManager, NFCSkillConsumeManagerModule )
UNREGISTER_MODULE( pPluginManager, NFCCardItemConsumeProcessModule )
UNREGISTER_MODULE( pPluginManager, NFCPotionItemConsumeProcessModule )
UNREGISTER_MODULE( pPluginManager, NFCItemConsumeManagerModule )
UNREGISTER_MODULE( pPluginManager, NFCRebornItemConsumeProcessModule )
UNREGISTER_MODULE( pPluginManager, NFCSkillModule )
UNREGISTER_MODULE( pPluginManager, NFCPackModule )
UNREGISTER_MODULE( pPluginManager, NFCItemModule )
UNREGISTER_MODULE( pPluginManager, NFCBuffModule )
UNREGISTER_MODULE( pPluginManager, NFCGameLogicModule )
}
<commit_msg>add NFCCostModule register<commit_after>// -------------------------------------------------------------------------
// @FileName : NFGameServerPlugin.cpp
// @Author : LvSheng.Huang
// @Date : 2012-07-14 08:51
// @Module : NFGameServerPlugin
//
// -------------------------------------------------------------------------
#include "NFGameLogicPlugin.h"
#include "NFCGameLogicModule.h"
#include "NFCBuffModule.h"
#include "NFCItemModule.h"
#include "NFCPackModule.h"
#include "NFCSkillModule.h"
#include "NFCBulletSkillConsumeProcessModule.h"
#include "NFCBriefSkillConsumeProcessModule.h"
#include "NFCSkillConsumeManagerModule.h"
#include "NFCPotionItemConsumeProcessModule.h"
#include "NFCCardItemConsumeProcessModule.h"
#include "NFCItemConsumeManagerModule.h"
#include "NFCNPCRefreshModule.h"
#include "NFCRebornItemConsumeProcessModule.h"
#include "NFCAwardPackModule.h"
#include "NFCEctypeModule.h"
#include "NFCCostModule.h"
#ifdef NF_DYNAMIC_PLUGIN
extern "C" __declspec( dllexport ) void DllStartPlugin( NFIPluginManager* pm )
{
CREATE_PLUGIN( pm, NFGameLogicPlugin )
};
extern "C" __declspec( dllexport ) void DllStopPlugin( NFIPluginManager* pm )
{
DESTROY_PLUGIN( pm, NFGameLogicPlugin )
};
#endif
//////////////////////////////////////////////////////////////////////////
const int NFGameLogicPlugin::GetPluginVersion()
{
return 0;
}
const std::string NFGameLogicPlugin::GetPluginName()
{
GET_PLUGIN_NAME( NFGameLogicPlugin )
}
void NFGameLogicPlugin::Install()
{
REGISTER_MODULE(pPluginManager, NFCGameLogicModule)
REGISTER_MODULE(pPluginManager, NFCBuffModule)
REGISTER_MODULE(pPluginManager, NFCItemModule)
REGISTER_MODULE(pPluginManager, NFCPackModule)
REGISTER_MODULE(pPluginManager, NFCSkillModule)
REGISTER_MODULE(pPluginManager, NFCRebornItemConsumeProcessModule)
REGISTER_MODULE(pPluginManager, NFCItemConsumeManagerModule)
REGISTER_MODULE(pPluginManager, NFCPotionItemConsumeProcessModule)
REGISTER_MODULE(pPluginManager, NFCCardItemConsumeProcessModule)
//Continue to ad other item types of consumption
REGISTER_MODULE(pPluginManager, NFCSkillConsumeManagerModule)
REGISTER_MODULE(pPluginManager, NFCBriefSkillConsumeProcessModule)
REGISTER_MODULE(pPluginManager, NFCBulletSkillConsumeProcessModule)
//Continue to add other skill types of consumption
REGISTER_MODULE(pPluginManager, NFCNPCRefreshModule)
REGISTER_MODULE(pPluginManager, NFCAwardPackModule)
REGISTER_MODULE(pPluginManager, NFCEctypeModule)
REGISTER_MODULE(pPluginManager, NFCCostModule)
}
void NFGameLogicPlugin::Uninstall()
{
UNREGISTER_MODULE(pPluginManager, NFCCostModule)
UNREGISTER_MODULE(pPluginManager, NFCEctypeModule)
UNREGISTER_MODULE(pPluginManager, NFCAwardPackModule)
UNREGISTER_MODULE(pPluginManager, NFCNPCRefreshModule)
UNREGISTER_MODULE(pPluginManager, NFCBulletSkillConsumeProcessModule)
UNREGISTER_MODULE(pPluginManager, NFCBriefSkillConsumeProcessModule)
UNREGISTER_MODULE(pPluginManager, NFCSkillConsumeManagerModule)
UNREGISTER_MODULE(pPluginManager, NFCCardItemConsumeProcessModule)
UNREGISTER_MODULE(pPluginManager, NFCPotionItemConsumeProcessModule)
UNREGISTER_MODULE(pPluginManager, NFCItemConsumeManagerModule)
UNREGISTER_MODULE(pPluginManager, NFCRebornItemConsumeProcessModule)
UNREGISTER_MODULE(pPluginManager, NFCSkillModule)
UNREGISTER_MODULE(pPluginManager, NFCPackModule)
UNREGISTER_MODULE(pPluginManager, NFCItemModule)
UNREGISTER_MODULE(pPluginManager, NFCBuffModule)
UNREGISTER_MODULE(pPluginManager, NFCGameLogicModule)
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: APNDataObject.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2003-10-06 14:39:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _APNDATAOBJECT_HXX_
#define _APNDATAOBJECT_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <comdef.h>
//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
/*
an APartment Neutral dataobject wrapper; this wrapper of a IDataObject
pointer can be used from any apartment without RPC_E_WRONG_THREAD
which normally occurs if an apartment tries to use an interface
pointer of another apartment; we use containment to hold the original
DataObject
*/
class CAPNDataObject : public IDataObject
{
public:
CAPNDataObject( IDataObjectPtr rIDataObject );
~CAPNDataObject( );
//-----------------------------------------------------------------
//IUnknown interface methods
//-----------------------------------------------------------------
STDMETHODIMP QueryInterface(REFIID iid, LPVOID* ppvObject);
STDMETHODIMP_( ULONG ) AddRef( );
STDMETHODIMP_( ULONG ) Release( );
//-----------------------------------------------------------------
// IDataObject interface methods
//-----------------------------------------------------------------
STDMETHODIMP GetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP GetDataHere( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP QueryGetData( LPFORMATETC pFormatetc );
STDMETHODIMP GetCanonicalFormatEtc( LPFORMATETC pFormatectIn, LPFORMATETC pFormatetcOut );
STDMETHODIMP SetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium, BOOL fRelease );
STDMETHODIMP EnumFormatEtc( DWORD dwDirection, IEnumFORMATETC** ppenumFormatetc );
STDMETHODIMP DAdvise( LPFORMATETC pFormatetc, DWORD advf, LPADVISESINK pAdvSink, DWORD* pdwConnection );
STDMETHODIMP DUnadvise( DWORD dwConnection );
STDMETHODIMP EnumDAdvise( LPENUMSTATDATA* ppenumAdvise );
operator IDataObject*( );
private:
HRESULT MarshalIDataObjectIntoCurrentApartment( IDataObject** ppIDataObj );
private:
IDataObjectPtr m_rIDataObjectOrg;
HGLOBAL m_hGlobal;
LONG m_nRefCnt;
// prevent copy and assignment
private:
CAPNDataObject( const CAPNDataObject& theOther );
CAPNDataObject& operator=( const CAPNDataObject& theOther );
};
#endif
<commit_msg>INTEGRATION: CWS dtransfix (1.2.32); FILE MERGED 2004/10/12 05:00:59 tra 1.2.32.1: #i32544#replaced MS COM auto pointer template with an own COM auto pointer template because MS COM auto pointers are not part of the .Net 2003 toolkit<commit_after>/*************************************************************************
*
* $RCSfile: APNDataObject.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-10-22 07:55:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _APNDATAOBJECT_HXX_
#define _APNDATAOBJECT_HXX_
#include <systools/win32/comtools.hxx>
//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
/*
an APartment Neutral dataobject wrapper; this wrapper of a IDataObject
pointer can be used from any apartment without RPC_E_WRONG_THREAD
which normally occurs if an apartment tries to use an interface
pointer of another apartment; we use containment to hold the original
DataObject
*/
class CAPNDataObject : public IDataObject
{
public:
CAPNDataObject( IDataObjectPtr rIDataObject );
~CAPNDataObject( );
//-----------------------------------------------------------------
//IUnknown interface methods
//-----------------------------------------------------------------
STDMETHODIMP QueryInterface(REFIID iid, LPVOID* ppvObject);
STDMETHODIMP_( ULONG ) AddRef( );
STDMETHODIMP_( ULONG ) Release( );
//-----------------------------------------------------------------
// IDataObject interface methods
//-----------------------------------------------------------------
STDMETHODIMP GetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP GetDataHere( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP QueryGetData( LPFORMATETC pFormatetc );
STDMETHODIMP GetCanonicalFormatEtc( LPFORMATETC pFormatectIn, LPFORMATETC pFormatetcOut );
STDMETHODIMP SetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium, BOOL fRelease );
STDMETHODIMP EnumFormatEtc( DWORD dwDirection, IEnumFORMATETC** ppenumFormatetc );
STDMETHODIMP DAdvise( LPFORMATETC pFormatetc, DWORD advf, LPADVISESINK pAdvSink, DWORD* pdwConnection );
STDMETHODIMP DUnadvise( DWORD dwConnection );
STDMETHODIMP EnumDAdvise( LPENUMSTATDATA* ppenumAdvise );
operator IDataObject*( );
private:
HRESULT MarshalIDataObjectIntoCurrentApartment( IDataObject** ppIDataObj );
private:
IDataObjectPtr m_rIDataObjectOrg;
HGLOBAL m_hGlobal;
LONG m_nRefCnt;
// prevent copy and assignment
private:
CAPNDataObject( const CAPNDataObject& theOther );
CAPNDataObject& operator=( const CAPNDataObject& theOther );
};
#endif
<|endoftext|> |
<commit_before>#include "render_utility.h"
#include "Snapshoot.h"
#include "BoundingBox.h"
#include "Image.h"
#include "ImageSprite.h"
#include <gl/glew.h>
namespace ee
{
Sprite* draw_all_to_one_spr(const std::vector<Sprite*>& sprites, Sprite* except)
{
std::vector<Sprite*> _sprites;
for (int i = 0, n = sprites.size(); i < n; ++i) {
if (sprites[i] != except) {
_sprites.push_back(sprites[i]);
}
}
return draw_all_to_one_spr(sprites);
}
Sprite* draw_all_to_one_spr(const std::vector<Sprite*>& sprites)
{
if (sprites.empty()) {
return NULL;
}
Rect r;
for (int i = 0, n = sprites.size(); i < n; ++i) {
std::vector<Vector> bound;
sprites[i]->GetBounding()->GetBoundPos(bound);
for (int j = 0, m = bound.size(); j < m; ++j) {
r.Combine(bound[j]);
}
}
int dx = static_cast<int>(r.CenterX()),
dy = static_cast<int>(r.CenterY());
Snapshoot ss(static_cast<int>(r.Width()), static_cast<int>(r.Height()));
for (int i = 0, n = sprites.size(); i < n; ++i) {
ss.DrawSprite(sprites[i], false, dx, dy);
}
Image* img = new Image(ss.GetFBO());
ImageSymbol* symbol = new ImageSymbol(img, "ss");
ImageSprite* spr = new ImageSprite(symbol);
spr->SetMirror(false, true);
spr->SetTransform(Vector(dx, dy), 0);
return spr;
}
void gl_debug()
{
GLenum err;
while ( ( err = glGetError() ) != GL_NO_ERROR) {
int zz = err;
std::cerr << err;
}
}
}<commit_msg>[FIXED] draw to target<commit_after>#include "render_utility.h"
#include "Snapshoot.h"
#include "BoundingBox.h"
#include "Image.h"
#include "ImageSprite.h"
#include <gl/glew.h>
namespace ee
{
Sprite* draw_all_to_one_spr(const std::vector<Sprite*>& sprites, Sprite* except)
{
std::vector<Sprite*> _sprites;
for (int i = 0, n = sprites.size(); i < n; ++i) {
if (sprites[i] != except) {
_sprites.push_back(sprites[i]);
}
}
return draw_all_to_one_spr(_sprites);
}
Sprite* draw_all_to_one_spr(const std::vector<Sprite*>& sprites)
{
if (sprites.empty()) {
return NULL;
}
Rect r;
for (int i = 0, n = sprites.size(); i < n; ++i) {
std::vector<Vector> bound;
sprites[i]->GetBounding()->GetBoundPos(bound);
for (int j = 0, m = bound.size(); j < m; ++j) {
r.Combine(bound[j]);
}
}
int dx = static_cast<int>(r.CenterX()),
dy = static_cast<int>(r.CenterY());
Snapshoot ss(static_cast<int>(r.Width()), static_cast<int>(r.Height()));
for (int i = 0, n = sprites.size(); i < n; ++i) {
ss.DrawSprite(sprites[i], false, r.Width(), r.Height(), dx, dy);
}
Image* img = new Image(ss.GetFBO());
ImageSymbol* symbol = new ImageSymbol(img, "ss");
ImageSprite* spr = new ImageSprite(symbol);
spr->SetMirror(false, true);
spr->SetTransform(Vector(dx, dy), 0);
return spr;
}
void gl_debug()
{
GLenum err;
while ( ( err = glGetError() ) != GL_NO_ERROR) {
int zz = err;
std::cerr << err;
}
}
}<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: GimbalJoint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Tim Dorn *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "GimbalJoint.h"
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/SimbodyEngine/Body.h>
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace SimTK;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Destructor.
*/
GimbalJoint::~GimbalJoint()
{
}
//_____________________________________________________________________________
/**
* Default constructor.
*/
GimbalJoint::GimbalJoint() : Joint()
{
setAuthors("Tim Dorn");
constructCoordinates();
}
//_____________________________________________________________________________
/**
* Convenience Constructor.
*/
GimbalJoint::GimbalJoint(const std::string &name, OpenSim::Body& parent,
Vec3 locationInParent, Vec3 orientationInParent,
OpenSim::Body& body, Vec3 locationInBody, Vec3 orientationInBody,
bool reverse) :
Joint(name, parent, locationInParent,orientationInParent,
body, locationInBody, orientationInBody, reverse)
{
setAuthors("Tim Dorn, Ajay Steh");
constructCoordinates();
}
//=============================================================================
// Simbody Model building.
//=============================================================================
//_____________________________________________________________________________
void GimbalJoint::addToSystem(SimTK::MultibodySystem& system) const
{
createMobilizedBody<MobilizedBody::Gimbal>(system);
// TODO: Joints require super class to be called last.
Super::addToSystem(system);
}
void GimbalJoint::initStateFromProperties(SimTK::State& s) const
{
Super::initStateFromProperties(s);
const MultibodySystem& system = _model->getMultibodySystem();
const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();
if (matter.getUseEulerAngles(s))
return;
const CoordinateSet& coordinateSet = get_CoordinateSet();
double xangle = coordinateSet[0].getDefaultValue();
double yangle = coordinateSet[1].getDefaultValue();
double zangle = coordinateSet[2].getDefaultValue();
Rotation r(BodyRotationSequence, xangle, XAxis, yangle, YAxis, zangle, ZAxis);
GimbalJoint* mutableThis = const_cast<GimbalJoint*>(this);
matter.getMobilizedBody(getChildBody().getIndex()).setQToFitRotation(s, r);
}
void GimbalJoint::setPropertiesFromState(const SimTK::State& state)
{
Super::setPropertiesFromState(state);
// Override default behavior in case of quaternions.
const MultibodySystem& system = _model->getMultibodySystem();
const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();
if (!matter.getUseEulerAngles(state)) {
Rotation r = matter.getMobilizedBody(getChildBody().getIndex()).getBodyRotation(state);
Vec3 angles = r.convertRotationToBodyFixedXYZ();
const CoordinateSet& coordinateSet = get_CoordinateSet();
coordinateSet[0].setDefaultValue(angles[0]);
coordinateSet[1].setDefaultValue(angles[1]);
coordinateSet[2].setDefaultValue(angles[2]);
}
}
<commit_msg>Update GimbalJoint.cpp<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: GimbalJoint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Tim Dorn *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "GimbalJoint.h"
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/SimbodyEngine/Body.h>
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace SimTK;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Destructor.
*/
GimbalJoint::~GimbalJoint()
{
}
//_____________________________________________________________________________
/**
* Default constructor.
*/
GimbalJoint::GimbalJoint() : Joint()
{
setAuthors("Tim Dorn, Ajay Seth");
constructCoordinates();
}
//_____________________________________________________________________________
/**
* Convenience Constructor.
*/
GimbalJoint::GimbalJoint(const std::string &name, OpenSim::Body& parent,
Vec3 locationInParent, Vec3 orientationInParent,
OpenSim::Body& body, Vec3 locationInBody, Vec3 orientationInBody,
bool reverse) :
Joint(name, parent, locationInParent,orientationInParent,
body, locationInBody, orientationInBody, reverse)
{
setAuthors("Tim Dorn, Ajay Seth");
constructCoordinates();
}
//=============================================================================
// Simbody Model building.
//=============================================================================
//_____________________________________________________________________________
void GimbalJoint::addToSystem(SimTK::MultibodySystem& system) const
{
createMobilizedBody<MobilizedBody::Gimbal>(system);
// TODO: Joints require super class to be called last.
Super::addToSystem(system);
}
void GimbalJoint::initStateFromProperties(SimTK::State& s) const
{
Super::initStateFromProperties(s);
const MultibodySystem& system = _model->getMultibodySystem();
const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();
if (matter.getUseEulerAngles(s))
return;
const CoordinateSet& coordinateSet = get_CoordinateSet();
double xangle = coordinateSet[0].getDefaultValue();
double yangle = coordinateSet[1].getDefaultValue();
double zangle = coordinateSet[2].getDefaultValue();
Rotation r(BodyRotationSequence, xangle, XAxis, yangle, YAxis, zangle, ZAxis);
GimbalJoint* mutableThis = const_cast<GimbalJoint*>(this);
matter.getMobilizedBody(getChildBody().getIndex()).setQToFitRotation(s, r);
}
void GimbalJoint::setPropertiesFromState(const SimTK::State& state)
{
Super::setPropertiesFromState(state);
// Override default behavior in case of quaternions.
const MultibodySystem& system = _model->getMultibodySystem();
const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();
if (!matter.getUseEulerAngles(state)) {
Rotation r = matter.getMobilizedBody(getChildBody().getIndex()).getBodyRotation(state);
Vec3 angles = r.convertRotationToBodyFixedXYZ();
const CoordinateSet& coordinateSet = get_CoordinateSet();
coordinateSet[0].setDefaultValue(angles[0]);
coordinateSet[1].setDefaultValue(angles[1]);
coordinateSet[2].setDefaultValue(angles[2]);
}
}
<|endoftext|> |
<commit_before>AliAnalysisTaskSECharmFraction* AddTaskSECharmFraction(TString fileout="d0D0.root",Int_t switchMC[5],Bool_t readmc=kFALSE,Bool_t usepid=kTRUE,Bool_t likesign=kFALSE,TString cutfile="D0toKpiCharmFractCuts.root",TString containerprefix="c",Int_t ppPbPb=0,Int_t analysLevel=2)
{
//
// Configuration macro for the task to analyze the fraction of prompt charm
// using the D0 impact parameter
// andrea.rossi@ts.infn.it
//
//==========================================================================
//######## !!! THE SWITCH FOR MC ANALYSIS IS NOT IMPLEMENTED YET!!! ##########à
switchMC[0]=1;
switchMC[1]=1;
switchMC[2]=1;
switchMC[3]=1;
switchMC[4]=1;
Int_t last=0;
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskCharmFraction", "No analysis manager to connect to.");
return NULL;
}
TString str,containername;
if(fileout=="standard"){
fileout=AliAnalysisManager::GetCommonFileName();
fileout+=":PWG3_D2H_";
fileout+="d0D0";
if(containerprefix!="c")fileout+=containerprefix;
str="d0D0";
}
else if(fileout=="standardUp"){
fileout=AliAnalysisManager::GetCommonFileName();
fileout+=":PWG3_D2H_Up_";
fileout+="d0D0";
if(containerprefix!="c")fileout+=containerprefix;
str="d0D0";
}
else {
str=fileout;
str.ReplaceAll(".root","");
}
str.Prepend("_");
AliAnalysisTaskSECharmFraction *hfTask;
if(!gSystem->AccessPathName(cutfile.Data(),kFileExists)){
TFile *f=TFile::Open(cutfile.Data());
AliRDHFCutsD0toKpi *cutTight= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsStandard");
cutTight->PrintAll();
AliRDHFCutsD0toKpi *cutLoose= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsLoose");
cutLoose->PrintAll();
hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose);
}
else {
//hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction");
AliRDHFCutsD0toKpi *cutTight=new AliRDHFCutsD0toKpi("D0toKpiCutsStandard");
AliRDHFCutsD0toKpi *cutLoose=new AliRDHFCutsD0toKpi("D0toKpiCutsLoose");
if(ppPbPb==1){
cutTight->SetStandardCutsPbPb2010();
cutTight->SetMinCentrality(0.);
cutTight->SetMaxCentrality(20.);
cutLoose->SetStandardCutsPbPb2010();
cutLoose->SetMinCentrality(40.);
cutLoose->SetMaxCentrality(80.);
}
else {
cutTight->SetStandardCutsPP2010();
cutLoose->SetStandardCutsPP2010();
}
hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose);
cutLoose->PrintAll();
}
if(ppPbPb==1){// Switch Off recalctulation of primary vertex w/o candidate's daughters
// a protection that must be kept here to be sure
//that this is done also if the cut objects are provided by outside
Printf("AddTaskSECharmFraction: Switch Off recalculation of primary vertex w/o candidate's daughters (PbPb analysis) \n");
AliRDHFCutsD0toKpi *cloose=hfTask->GetLooseCut();
AliRDHFCutsD0toKpi *ctight=hfTask->GetTightCut();
cloose->SetRemoveDaughtersFromPrim(kFALSE);
ctight->SetRemoveDaughtersFromPrim(kFALSE);
if(analysLevel<2){
printf("Cannot activate the filling of all the histograms for PbPb analysis \n changing analysis level to 2 \n");
analysLevel=2;
}
// Activate Default PID for proton rejection (TEMPORARY)
// cloose->SetUseDefaultPID(kTRUE);
// ctight->SetUseDefaultPID(kTRUE);
}
hfTask->SetReadMC(readmc);
hfTask->SetNMaxTrForVtx(2);
hfTask->SetAnalyzeLikeSign(likesign);
hfTask->SetUsePID(usepid);
hfTask->SetStandardMassSelection();
hfTask->SetAnalysisLevel(analysLevel);
// hfTask->SignalInvMassCut(0.27);
/* ############### HERE THE POSSIBILITY TO SWITCH ON/OFF THE TLISTS AND MC SELECTION WILL BE SET #########à
hfTask->SetUseCuts(setD0usecuts);
hfTask->SetCheckMC(setcheckMC);
hfTask->SetCheckMC_D0(setcheckMC_D0);
hfTask->SetCheckMC_2prongs(setcheckMC_2prongs);
hfTask->SetCheckMC_prompt(setcheckMC_prompt);
hfTask->SetCheckMC_fromB(setcheckMC_fromB);
hfTask->SetCheckMC_fromDstar(setSkipD0star);
hfTask->SetStudyPureBackground(setStudyPureBack);*/
// hfTask->SetSideBands(0);
// hfTask->SetDebugLevel(2);
mgr->AddTask(hfTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
//mgr->CreateContainer("cinput",TChain::Class(),AliAnalysisManager::kInputContainer);
mgr->ConnectInput(hfTask,0,cinput);
//Now container for general properties histograms
containername="outputNentries";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputNentries = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,1,coutputNentries);
containername="outputSignalType";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputSignalType = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,2,coutputSignalType);
containername="outputSignalType_LsCuts";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputSignalType_LsCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,3,coutputSignalType_LsCuts);
containername="outputSignalType_TghCuts";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputSignalType_TghCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,4,coutputSignalType_TghCuts);
containername="outputNormalizationCounter";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputNormCounter = mgr ->CreateContainer(containername.Data(), AliNormalizationCounter::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask, 5, coutputNormCounter);
//Now Container for MC TList
containername="listMCproperties";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistMCprop = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,6,clistMCprop);
// Now container for TLists
last=7;
//########## NO CUTS TLISTS CONTAINER ##############à
containername="listNCsign";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCsign = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCsign);
last++;
containername="listNCback";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCback = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCback);
last++;
containername="listNCfromB";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCfromB = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCfromB);
last++;
containername="listNCfromDstar";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCfromDstar);
last++;
containername="listNCother";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCother = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCother);
last++;
//######### LOOSE CUTS TLISTS CONTAINER #############
containername="listLSCsign";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCsign = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCsign);
last++;
containername="listLSCback";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCback = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCback);
last++;
containername="listLSCfromB";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCfromB = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCfromB);
last++;
containername="listLSCfromDstar";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCfromDstar);
last++;
containername="listLSCother";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCother = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCother);
last++;
//######### TIGHT CUTS TLISTS CONTAINER #############
containername="listTGHCsign";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCsign = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCsign);
last++;
containername="listTGHCback";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCback = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCback);
last++;
containername="listTGHCfromB";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCfromB = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCfromB);
last++;
containername="listTGHCfromDstar";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCfromDstar);
last++;
containername="listTGHCother";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCother = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCother);
last++;
// Container for Cuts Objects
containername="cutsObjectTight";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *cCutsObjectTight = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts
mgr->ConnectOutput(hfTask,last,cCutsObjectTight);
last++;
containername="cutsObjectLoose";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *cCutsObjectLoose = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts
mgr->ConnectOutput(hfTask,last,cCutsObjectLoose);
return hfTask;
}
<commit_msg>Centrality selection can be set from outside (Andrea<commit_after>AliAnalysisTaskSECharmFraction* AddTaskSECharmFraction(TString fileout="d0D0.root",Int_t switchMC[5],Bool_t readmc=kFALSE,Bool_t usepid=kTRUE,Bool_t likesign=kFALSE,TString cutfile="D0toKpiCharmFractCuts.root",TString containerprefix="c",Int_t ppPbPb=0,Int_t analysLevel=2, Float_t minC=0., Float_t maxC=20.,Float_t minCloose=40., Float_t maxCloose=80.)
{
//
// Configuration macro for the task to analyze the fraction of prompt charm
// using the D0 impact parameter
// andrea.rossi@ts.infn.it
//
//==========================================================================
//######## !!! THE SWITCH FOR MC ANALYSIS IS NOT IMPLEMENTED YET!!! ##########à
switchMC[0]=1;
switchMC[1]=1;
switchMC[2]=1;
switchMC[3]=1;
switchMC[4]=1;
Int_t last=0;
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskCharmFraction", "No analysis manager to connect to.");
return NULL;
}
TString str,containername;
if(fileout=="standard"){
fileout=AliAnalysisManager::GetCommonFileName();
fileout+=":PWG3_D2H_";
fileout+="d0D0";
if(containerprefix!="c")fileout+=containerprefix;
str="d0D0";
}
else if(fileout=="standardUp"){
fileout=AliAnalysisManager::GetCommonFileName();
fileout+=":PWG3_D2H_Up_";
fileout+="d0D0";
if(containerprefix!="c")fileout+=containerprefix;
str="d0D0";
}
else {
str=fileout;
str.ReplaceAll(".root","");
}
str.Prepend("_");
AliAnalysisTaskSECharmFraction *hfTask;
if(!gSystem->AccessPathName(cutfile.Data(),kFileExists)){
TFile *f=TFile::Open(cutfile.Data());
AliRDHFCutsD0toKpi *cutTight= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsStandard");
cutTight->PrintAll();
AliRDHFCutsD0toKpi *cutLoose= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsLoose");
cutLoose->PrintAll();
hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose);
}
else {
//hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction");
AliRDHFCutsD0toKpi *cutTight=new AliRDHFCutsD0toKpi("D0toKpiCutsStandard");
AliRDHFCutsD0toKpi *cutLoose=new AliRDHFCutsD0toKpi("D0toKpiCutsLoose");
if(ppPbPb==1){
cutTight->SetStandardCutsPbPb2010();
cutTight->SetMinCentrality(minC);
cutTight->SetMaxCentrality(maxC);
cutLoose->SetStandardCutsPbPb2010();
cutLoose->SetMinCentrality(minCloose);
cutLoose->SetMaxCentrality(maxCloose);
}
else {
cutTight->SetStandardCutsPP2010();
cutLoose->SetStandardCutsPP2010();
}
hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose);
cutLoose->PrintAll();
}
if(ppPbPb==1){// Switch Off recalctulation of primary vertex w/o candidate's daughters
// a protection that must be kept here to be sure
//that this is done also if the cut objects are provided by outside
Printf("AddTaskSECharmFraction: Switch Off recalculation of primary vertex w/o candidate's daughters (PbPb analysis) \n");
AliRDHFCutsD0toKpi *cloose=hfTask->GetLooseCut();
AliRDHFCutsD0toKpi *ctight=hfTask->GetTightCut();
cloose->SetRemoveDaughtersFromPrim(kFALSE);
ctight->SetRemoveDaughtersFromPrim(kFALSE);
if(analysLevel<2){
printf("Cannot activate the filling of all the histograms for PbPb analysis \n changing analysis level to 2 \n");
analysLevel=2;
}
// Activate Default PID for proton rejection (TEMPORARY)
// cloose->SetUseDefaultPID(kTRUE);
// ctight->SetUseDefaultPID(kTRUE);
}
hfTask->SetReadMC(readmc);
hfTask->SetNMaxTrForVtx(2);
hfTask->SetAnalyzeLikeSign(likesign);
hfTask->SetUsePID(usepid);
hfTask->SetStandardMassSelection();
hfTask->SetAnalysisLevel(analysLevel);
// hfTask->SignalInvMassCut(0.27);
/* ############### HERE THE POSSIBILITY TO SWITCH ON/OFF THE TLISTS AND MC SELECTION WILL BE SET #########à
hfTask->SetUseCuts(setD0usecuts);
hfTask->SetCheckMC(setcheckMC);
hfTask->SetCheckMC_D0(setcheckMC_D0);
hfTask->SetCheckMC_2prongs(setcheckMC_2prongs);
hfTask->SetCheckMC_prompt(setcheckMC_prompt);
hfTask->SetCheckMC_fromB(setcheckMC_fromB);
hfTask->SetCheckMC_fromDstar(setSkipD0star);
hfTask->SetStudyPureBackground(setStudyPureBack);*/
// hfTask->SetSideBands(0);
// hfTask->SetDebugLevel(2);
mgr->AddTask(hfTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
//mgr->CreateContainer("cinput",TChain::Class(),AliAnalysisManager::kInputContainer);
mgr->ConnectInput(hfTask,0,cinput);
//Now container for general properties histograms
containername="outputNentries";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputNentries = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,1,coutputNentries);
containername="outputSignalType";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputSignalType = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,2,coutputSignalType);
containername="outputSignalType_LsCuts";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputSignalType_LsCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,3,coutputSignalType_LsCuts);
containername="outputSignalType_TghCuts";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputSignalType_TghCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,4,coutputSignalType_TghCuts);
containername="outputNormalizationCounter";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *coutputNormCounter = mgr ->CreateContainer(containername.Data(), AliNormalizationCounter::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask, 5, coutputNormCounter);
//Now Container for MC TList
containername="listMCproperties";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistMCprop = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,6,clistMCprop);
// Now container for TLists
last=7;
//########## NO CUTS TLISTS CONTAINER ##############à
containername="listNCsign";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCsign = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCsign);
last++;
containername="listNCback";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCback = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCback);
last++;
containername="listNCfromB";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCfromB = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCfromB);
last++;
containername="listNCfromDstar";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCfromDstar);
last++;
containername="listNCother";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistNCother = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistNCother);
last++;
//######### LOOSE CUTS TLISTS CONTAINER #############
containername="listLSCsign";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCsign = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCsign);
last++;
containername="listLSCback";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCback = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCback);
last++;
containername="listLSCfromB";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCfromB = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCfromB);
last++;
containername="listLSCfromDstar";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCfromDstar);
last++;
containername="listLSCother";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistLSCother = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistLSCother);
last++;
//######### TIGHT CUTS TLISTS CONTAINER #############
containername="listTGHCsign";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCsign = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCsign);
last++;
containername="listTGHCback";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCback = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCback);
last++;
containername="listTGHCfromB";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCfromB = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCfromB);
last++;
containername="listTGHCfromDstar";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCfromDstar);
last++;
containername="listTGHCother";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *clistTGHCother = mgr->CreateContainer(containername.Data(),TList::Class(),
AliAnalysisManager::kOutputContainer,
fileout.Data());
mgr->ConnectOutput(hfTask,last,clistTGHCother);
last++;
// Container for Cuts Objects
containername="cutsObjectTight";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *cCutsObjectTight = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts
mgr->ConnectOutput(hfTask,last,cCutsObjectTight);
last++;
containername="cutsObjectLoose";
containername.Prepend(containerprefix.Data());
containername.Append(str.Data());
AliAnalysisDataContainer *cCutsObjectLoose = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts
mgr->ConnectOutput(hfTask,last,cCutsObjectLoose);
return hfTask;
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <Ancona/Framework/Audio/Jukebox.hpp>
#include <Ancona/Framework/Resource/ResourceLibrary.hpp>
#include <Ancona/Util/Assert.hpp>
#include <Ancona/System/Log.hpp>
using namespace ild;
std::unordered_map<std::string, std::unique_ptr<JukeboxSounds>> Jukebox::_jukeboxSounds = std::unordered_map<std::string, std::unique_ptr<JukeboxSounds>>();
std::string Jukebox::_musicKeyPlaying = "";
float Jukebox::_musicVolumePercent = 1.0f;
float Jukebox::_soundVolumePercent = 1.0f;
sf::Music * Jukebox::_music = nullptr;
unsigned long Jukebox::_nextSoundLifecycleJobID = 0;
void Jukebox::InitMusic(sf::Music * music) {
_music = music;
}
void Jukebox::RegisterSound(const std::string & soundKey) {
if (_jukeboxSounds.find(soundKey) == _jukeboxSounds.end()) {
_jukeboxSounds.emplace(soundKey, std::unique_ptr<JukeboxSounds>(new JukeboxSounds()));
}
_jukeboxSounds[soundKey]->Add(soundKey);
}
void Jukebox::ClearSounds() {
_jukeboxSounds.clear();
_nextSoundLifecycleJobID = 0;
}
unsigned long Jukebox::ReserveSoundLifecycleID(const std::string & soundKey) {
if (_jukeboxSounds.find(soundKey) == _jukeboxSounds.end()) {
ILD_Assert(true, "Sound key has not been registered in the Jukebox, please call Jukebox::RegisterSound before reserving a sound allocation.");
}
_nextSoundLifecycleJobID++;
_jukeboxSounds[soundKey]->CreateJob(_nextSoundLifecycleJobID);
return _nextSoundLifecycleJobID;
}
void Jukebox::PlaySound(const std::string & soundKey, const unsigned long & jobID, const float & volume) {
if (_jukeboxSounds.find(soundKey) == _jukeboxSounds.end()) {
ILD_Assert(true, "Sound key has not been registered in the Jukebox, please call Jukebox::RegisterSound before playing a sound");
}
_jukeboxSounds[soundKey]->Play(jobID, volume);
}
void Jukebox::PlayMusic(const std::string & musicKey) {
if (!_music) {
return;
}
if (musicKey == _musicKeyPlaying) {
return;
}
_musicKeyPlaying = musicKey;
auto resourceRoot = ResourceLibrary::ResourceRoot();
std::stringstream stream;
stream << resourceRoot << "/" << musicKey << ".ogg";
_music->openFromFile(stream.str());
_music->play();
}
void Jukebox::PlayMusic() {
if (!_music) {
return;
}
_music->setLoop(true);
_music->play();
}
void Jukebox::StopMusic() {
if (!_music) {
return;
}
_musicKeyPlaying = "";
_music->stop();
}
void Jukebox::PauseMusic() {
if (!_music) {
return;
}
_music->pause();
}
/* getters and setters */
void Jukebox::musicVolumePercent(float volume) {
if (!_music) {
return;
}
_musicVolumePercent = volume;
if (volume == 0.0f) {
_music->setVolume(0.0f);
} else {
auto realVolume = std::pow(100.0f, volume - 1);
_music->setVolume(realVolume * 100);
}
}
float Jukebox::musicVolumePercent() {
return _musicVolumePercent;
}
void Jukebox::soundVolumePercent(float volume) {
_soundVolumePercent = volume;
}
float Jukebox::soundVolumePercent() {
return _soundVolumePercent;
}
<commit_msg>set loop on music<commit_after>#include <sstream>
#include <Ancona/Framework/Audio/Jukebox.hpp>
#include <Ancona/Framework/Resource/ResourceLibrary.hpp>
#include <Ancona/Util/Assert.hpp>
#include <Ancona/System/Log.hpp>
using namespace ild;
std::unordered_map<std::string, std::unique_ptr<JukeboxSounds>> Jukebox::_jukeboxSounds = std::unordered_map<std::string, std::unique_ptr<JukeboxSounds>>();
std::string Jukebox::_musicKeyPlaying = "";
float Jukebox::_musicVolumePercent = 1.0f;
float Jukebox::_soundVolumePercent = 1.0f;
sf::Music * Jukebox::_music = nullptr;
unsigned long Jukebox::_nextSoundLifecycleJobID = 0;
void Jukebox::InitMusic(sf::Music * music) {
_music = music;
}
void Jukebox::RegisterSound(const std::string & soundKey) {
if (_jukeboxSounds.find(soundKey) == _jukeboxSounds.end()) {
_jukeboxSounds.emplace(soundKey, std::unique_ptr<JukeboxSounds>(new JukeboxSounds()));
}
_jukeboxSounds[soundKey]->Add(soundKey);
}
void Jukebox::ClearSounds() {
_jukeboxSounds.clear();
_nextSoundLifecycleJobID = 0;
}
unsigned long Jukebox::ReserveSoundLifecycleID(const std::string & soundKey) {
if (_jukeboxSounds.find(soundKey) == _jukeboxSounds.end()) {
ILD_Assert(true, "Sound key has not been registered in the Jukebox, please call Jukebox::RegisterSound before reserving a sound allocation.");
}
_nextSoundLifecycleJobID++;
_jukeboxSounds[soundKey]->CreateJob(_nextSoundLifecycleJobID);
return _nextSoundLifecycleJobID;
}
void Jukebox::PlaySound(const std::string & soundKey, const unsigned long & jobID, const float & volume) {
if (_jukeboxSounds.find(soundKey) == _jukeboxSounds.end()) {
ILD_Assert(true, "Sound key has not been registered in the Jukebox, please call Jukebox::RegisterSound before playing a sound");
}
_jukeboxSounds[soundKey]->Play(jobID, volume);
}
void Jukebox::PlayMusic(const std::string & musicKey) {
if (!_music) {
return;
}
if (musicKey == _musicKeyPlaying) {
return;
}
_musicKeyPlaying = musicKey;
auto resourceRoot = ResourceLibrary::ResourceRoot();
std::stringstream stream;
stream << resourceRoot << "/" << musicKey << ".ogg";
_music->openFromFile(stream.str());
_music->setLoop(true);
_music->play();
}
void Jukebox::PlayMusic() {
if (!_music) {
return;
}
_music->setLoop(true);
_music->play();
}
void Jukebox::StopMusic() {
if (!_music) {
return;
}
_musicKeyPlaying = "";
_music->stop();
}
void Jukebox::PauseMusic() {
if (!_music) {
return;
}
_music->pause();
}
/* getters and setters */
void Jukebox::musicVolumePercent(float volume) {
if (!_music) {
return;
}
_musicVolumePercent = volume;
if (volume == 0.0f) {
_music->setVolume(0.0f);
} else {
auto realVolume = std::pow(100.0f, volume - 1);
_music->setVolume(realVolume * 100);
}
}
float Jukebox::musicVolumePercent() {
return _musicVolumePercent;
}
void Jukebox::soundVolumePercent(float volume) {
_soundVolumePercent = volume;
}
float Jukebox::soundVolumePercent() {
return _soundVolumePercent;
}
<|endoftext|> |
<commit_before>#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QGridLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QListWidget>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QTabWidget>
#include <QtGui/QTableWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
#include "DebuggerWidget.h"
#include "GUIObjects/GUISystem.h"
#include "GUIPort.h"
#include "CoreAccess.h"
#include "MainWindow.h"
#include "DesktopHandler.h"
#include "Widgets/ProjectTabWidget.h"
#include "ComponentSystem.h"
DebuggerWidget::DebuggerWidget(SystemContainer *pSystem, QWidget *parent) :
QDialog(parent)
{
this->setWindowIcon(QIcon(QString(ICONPATH)+"Hopsan-Debug.png"));
mpSystem = pSystem;
this->resize(800, 600);
mpVerticalLayout = new QVBoxLayout(this);
//Trace tab
mpTraceTab = new QWidget();
mpTraceTabLayout = new QVBoxLayout(mpTraceTab);
mpTraceTable = new QTableWidget(0,0,mpTraceTab);
mpTraceTabLayout->addWidget(mpTraceTable);
//Variables tab
mpVariablesTab = new QWidget();
mpComponentsList = new QListWidget(mpVariablesTab);
mpPortsList = new QListWidget(mpVariablesTab);
mpVariablesList = new QListWidget(mpVariablesTab);
mpRemoveButton = new QPushButton(mpVariablesTab);
mpAddButton = new QPushButton(mpVariablesTab);
mpChoosenVariablesList = new QListWidget(mpVariablesTab);
mpVariablesTabLayout = new QGridLayout(mpVariablesTab);
mpVariablesTabLayout->addWidget(mpComponentsList, 1, 0, 1, 2);
mpVariablesTabLayout->addWidget(mpPortsList, 1, 2, 1, 2);
mpVariablesTabLayout->addWidget(mpVariablesList, 1, 4, 1, 2);
mpVariablesTabLayout->addWidget(mpAddButton, 3, 0, 1, 3);
mpVariablesTabLayout->addWidget(mpRemoveButton, 3, 3, 1, 3);
mpVariablesTabLayout->addWidget(mpChoosenVariablesList, 4, 0, 1, 6);
//Tab widget
mpTabWidget = new QTabWidget(this);
mpTabWidget->addTab(mpTraceTab, QString());
mpTabWidget->addTab(mpVariablesTab, QString());
mpTabWidget->setCurrentIndex(0);
mpVerticalLayout->addWidget(mpTabWidget);
//Buttons widget
mpButtonsWidget = new QWidget(this);
mpCurrentStepLabel = new QLabel(mpButtonsWidget);
mTimeIndicatorLabel = new QLabel(mpButtonsWidget);
QFont font;
font.setBold(true);
font.setWeight(75);
mTimeIndicatorLabel->setFont(font);
mpHorizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
mpAbortButton = new QPushButton(mpButtonsWidget);
mpInitializeButton = new QPushButton(mpButtonsWidget);
mpGotoButton = new QPushButton(mpButtonsWidget);
mpForwardButton = new QPushButton(mpButtonsWidget);
mpHorizontalLayout = new QHBoxLayout(mpButtonsWidget);
mpHorizontalLayout->addWidget(mpCurrentStepLabel);
mpHorizontalLayout->addWidget(mTimeIndicatorLabel);
mpHorizontalLayout->addItem(mpHorizontalSpacer);
mpHorizontalLayout->addWidget(mpAbortButton);
mpHorizontalLayout->addWidget(mpInitializeButton);
mpHorizontalLayout->addWidget(mpGotoButton);
mpHorizontalLayout->addWidget(mpForwardButton);
mpVerticalLayout->addWidget(mpButtonsWidget);
connect(mpAbortButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(mpComponentsList, SIGNAL(currentTextChanged(QString)), this, SLOT(updatePortsList(QString)));
connect(mpPortsList, SIGNAL(currentTextChanged(QString)), this, SLOT(updateVariablesList(QString)));
connect(mpAddButton, SIGNAL(clicked()), this, SLOT(addVariable()));
connect(mpRemoveButton, SIGNAL(clicked()), this, SLOT(removeVariable()));
connect(mpInitializeButton, SIGNAL(clicked()), this, SLOT(runInitialization()));
connect(mpForwardButton, SIGNAL(clicked()), this, SLOT(stepForward()));
connect(mpGotoButton, SIGNAL(clicked()), this, SLOT(simulateTo()));
retranslateUi();
setInitData();
}
void DebuggerWidget::retranslateUi()
{
setWindowTitle(tr("Hopsan Debugger"));
mpTabWidget->setTabText(mpTabWidget->indexOf(mpTraceTab), tr("Trace variables"));
mpRemoveButton->setText(tr("Remove"));
mpAddButton->setText(tr("Add"));
mpTabWidget->setTabText(mpTabWidget->indexOf(mpVariablesTab), tr("Select variables"));
mpCurrentStepLabel->setText(tr("Current time:"));
mTimeIndicatorLabel->setText(tr("0"));
mpAbortButton->setText(tr("Abort"));
mpGotoButton->setText(tr("Go to time"));
mpForwardButton->setText(tr("Step forward"));
mpInitializeButton->setText(tr("Initialize"));
}
void DebuggerWidget::setInitData()
{
mCurrentTime = gpMainWindow->getStartTimeFromToolBar();
mpComponentsList->addItems(mpSystem->getModelObjectNames());
mpGotoButton->setDisabled(true);
mpForwardButton->setDisabled(true);
QString dateString = QDateTime::currentDateTime().toString(Qt::DefaultLocaleShortDate);
qDebug() << "dateString = " << dateString.toUtf8();
dateString.replace(":", "_");
dateString.replace(".", "_");
dateString.replace(" ", "_");
dateString.replace("/", "_");
dateString.replace("\\", "_");
mOutputFile.setFileName(gDesktopHandler.getDocumentsPath()+"HopsanDebuggerOutput_"+dateString+".csv");
}
void DebuggerWidget::updatePortsList(QString component)
{
mpPortsList->clear();
mpVariablesList->clear();
QList<Port*> ports = mpSystem->getModelObject(component)->getPortListPtrs();
Q_FOREACH(const Port *port, ports)
{
mpPortsList->addItem(port->getName());
}
}
void DebuggerWidget::updateVariablesList(QString port)
{
if(port.isEmpty()) return;
mpVariablesList->clear();
QString component = mpComponentsList->currentItem()->text();
NodeInfo info(mpSystem->getModelObject(component)->getPort(port)->getNodeType());
QStringList variables = info.variableLabels;
mpVariablesList->addItems(variables);
}
void DebuggerWidget::addVariable()
{
if(mpPortsList->count() == 0 || mpVariablesList->count() == 0) return;
if(mpComponentsList->currentItem() == 0 || mpPortsList->currentItem() == 0 || mpVariablesList->currentItem() == 0) return;
QString component = mpComponentsList->currentItem()->text();
QString port = mpPortsList->currentItem()->text();
QString data = mpVariablesList->currentItem()->text();
if(component.isEmpty() || port.isEmpty() || data.isEmpty()) return;
QString fullName = component+"::"+port+"::"+data;
if(mVariables.contains(fullName)) return;
mVariables.append(fullName);
mpChoosenVariablesList->addItem(fullName);
mpTraceTable->insertColumn(0);
QTableWidgetItem *pItem = new QTableWidgetItem(fullName);
mpTraceTable->setHorizontalHeaderItem(0, pItem);
}
void DebuggerWidget::removeVariable()
{
if(mpChoosenVariablesList->currentItem() == 0) return;
mVariables.removeOne(mpChoosenVariablesList->currentItem()->text());
for(int c=0; c<mpTraceTable->columnCount(); ++c)
{
if(mpTraceTable->horizontalHeaderItem(c)->text() == mpChoosenVariablesList->currentItem()->text())
{
mpTraceTable->removeColumn(c);
break;
}
}
mpChoosenVariablesList->clear();
mpChoosenVariablesList->addItems(mVariables);
}
void DebuggerWidget::runInitialization()
{
double startT = getStartTime();
double stopT = getStopTime();
int nSteps = int((stopT-startT)/mpSystem->getTimeStep());
if(mpSystem->getCoreSystemAccessPtr()->initialize(startT,stopT, nSteps+1))
{
mpGotoButton->setEnabled(true);
mpForwardButton->setEnabled(true);
}
collectLastData(false);
updateTimeDisplay();
}
void DebuggerWidget::stepForward()
{
simulateTo(getCurrentTime()+getTimeStep());
}
void DebuggerWidget::simulateTo()
{
double targetTime = QInputDialog::getDouble(this, "Hopsan Debugger", "Choose target time", getCurrentTime()+getTimeStep(), getCurrentTime()+getTimeStep(), getStopTime());
simulateTo(targetTime);
}
void DebuggerWidget::simulateTo(double targetTime)
{
mpSystem->getCoreSystemAccessPtr()->simulate(getCurrentTime(), targetTime, -1, true);
collectLastData();
updateTimeDisplay();
}
void DebuggerWidget::collectLastData(bool overWriteGeneration)
{
mpSystem->collectPlotData(overWriteGeneration);
QString outputLine;
mpTraceTable->insertRow(mpTraceTable->rowCount());
QTableWidgetItem *pItem = new QTableWidgetItem(QString::number(getCurrentTime()));
mpTraceTable->setVerticalHeaderItem(mpTraceTable->rowCount()-1, pItem);
Q_FOREACH(const QString &var, mVariables)
{
QString component = var.split("::").at(0);
QString port = var.split("::").at(1);
QString data = var.split("::").at(2);
double value;
mpSystem->getCoreSystemAccessPtr()->getLastNodeData(component, port, data, value);
outputLine.append(QString::number(value)+",");
QTableWidgetItem *pDataItem = new QTableWidgetItem(QString::number(value));
for(int c=0; c<mpTraceTable->columnCount(); ++c)
{
if(mpTraceTable->horizontalHeaderItem(c)->text() == var)
{
mpTraceTable->setItem(mpTraceTable->rowCount()-1, c, pDataItem);
}
}
}
mpTraceTable->scrollToBottom();
//mpTraceTable->verticalScrollBar()->setSliderPosition (mpTraceTable->verticalScrollBar()->maximum());
outputLine.chop(1);
outputLine.append("\n");
mOutputFile.open(QFile::WriteOnly | QFile::Text | QFile::Append);
mOutputFile.write(outputLine .toUtf8());
mOutputFile.close();
}
void DebuggerWidget::updateTimeDisplay()
{
mTimeIndicatorLabel->setText(QString::number(getCurrentTime()));
}
double DebuggerWidget::getCurrentTime() const
{
return mpSystem->getCoreSystemAccessPtr()->getCurrentTime();
}
double DebuggerWidget::getTimeStep() const
{
return mpSystem->getTimeStep();
}
double DebuggerWidget::getStartTime() const
{
return gpMainWindow->getStartTimeFromToolBar();
}
double DebuggerWidget::getStopTime() const
{
return gpMainWindow->getFinishTimeFromToolBar();
}
<commit_msg>Made the debugger output csv file include the time vector.<commit_after>#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QGridLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QListWidget>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QTabWidget>
#include <QtGui/QTableWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
#include "DebuggerWidget.h"
#include "GUIObjects/GUISystem.h"
#include "GUIPort.h"
#include "CoreAccess.h"
#include "MainWindow.h"
#include "DesktopHandler.h"
#include "Widgets/ProjectTabWidget.h"
#include "ComponentSystem.h"
DebuggerWidget::DebuggerWidget(SystemContainer *pSystem, QWidget *parent) :
QDialog(parent)
{
this->setWindowIcon(QIcon(QString(ICONPATH)+"Hopsan-Debug.png"));
mpSystem = pSystem;
this->resize(800, 600);
mpVerticalLayout = new QVBoxLayout(this);
//Trace tab
mpTraceTab = new QWidget();
mpTraceTabLayout = new QVBoxLayout(mpTraceTab);
mpTraceTable = new QTableWidget(0,0,mpTraceTab);
mpTraceTabLayout->addWidget(mpTraceTable);
//Variables tab
mpVariablesTab = new QWidget();
mpComponentsList = new QListWidget(mpVariablesTab);
mpPortsList = new QListWidget(mpVariablesTab);
mpVariablesList = new QListWidget(mpVariablesTab);
mpRemoveButton = new QPushButton(mpVariablesTab);
mpAddButton = new QPushButton(mpVariablesTab);
mpChoosenVariablesList = new QListWidget(mpVariablesTab);
mpVariablesTabLayout = new QGridLayout(mpVariablesTab);
mpVariablesTabLayout->addWidget(mpComponentsList, 1, 0, 1, 2);
mpVariablesTabLayout->addWidget(mpPortsList, 1, 2, 1, 2);
mpVariablesTabLayout->addWidget(mpVariablesList, 1, 4, 1, 2);
mpVariablesTabLayout->addWidget(mpAddButton, 3, 0, 1, 3);
mpVariablesTabLayout->addWidget(mpRemoveButton, 3, 3, 1, 3);
mpVariablesTabLayout->addWidget(mpChoosenVariablesList, 4, 0, 1, 6);
//Tab widget
mpTabWidget = new QTabWidget(this);
mpTabWidget->addTab(mpTraceTab, QString());
mpTabWidget->addTab(mpVariablesTab, QString());
mpTabWidget->setCurrentIndex(0);
mpVerticalLayout->addWidget(mpTabWidget);
//Buttons widget
mpButtonsWidget = new QWidget(this);
mpCurrentStepLabel = new QLabel(mpButtonsWidget);
mTimeIndicatorLabel = new QLabel(mpButtonsWidget);
QFont font;
font.setBold(true);
font.setWeight(75);
mTimeIndicatorLabel->setFont(font);
mpHorizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
mpAbortButton = new QPushButton(mpButtonsWidget);
mpInitializeButton = new QPushButton(mpButtonsWidget);
mpGotoButton = new QPushButton(mpButtonsWidget);
mpForwardButton = new QPushButton(mpButtonsWidget);
mpHorizontalLayout = new QHBoxLayout(mpButtonsWidget);
mpHorizontalLayout->addWidget(mpCurrentStepLabel);
mpHorizontalLayout->addWidget(mTimeIndicatorLabel);
mpHorizontalLayout->addItem(mpHorizontalSpacer);
mpHorizontalLayout->addWidget(mpAbortButton);
mpHorizontalLayout->addWidget(mpInitializeButton);
mpHorizontalLayout->addWidget(mpGotoButton);
mpHorizontalLayout->addWidget(mpForwardButton);
mpVerticalLayout->addWidget(mpButtonsWidget);
connect(mpAbortButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(mpComponentsList, SIGNAL(currentTextChanged(QString)), this, SLOT(updatePortsList(QString)));
connect(mpPortsList, SIGNAL(currentTextChanged(QString)), this, SLOT(updateVariablesList(QString)));
connect(mpAddButton, SIGNAL(clicked()), this, SLOT(addVariable()));
connect(mpRemoveButton, SIGNAL(clicked()), this, SLOT(removeVariable()));
connect(mpInitializeButton, SIGNAL(clicked()), this, SLOT(runInitialization()));
connect(mpForwardButton, SIGNAL(clicked()), this, SLOT(stepForward()));
connect(mpGotoButton, SIGNAL(clicked()), this, SLOT(simulateTo()));
retranslateUi();
setInitData();
}
void DebuggerWidget::retranslateUi()
{
setWindowTitle(tr("Hopsan Debugger"));
mpTabWidget->setTabText(mpTabWidget->indexOf(mpTraceTab), tr("Trace variables"));
mpRemoveButton->setText(tr("Remove"));
mpAddButton->setText(tr("Add"));
mpTabWidget->setTabText(mpTabWidget->indexOf(mpVariablesTab), tr("Select variables"));
mpCurrentStepLabel->setText(tr("Current time:"));
mTimeIndicatorLabel->setText(tr("0"));
mpAbortButton->setText(tr("Abort"));
mpGotoButton->setText(tr("Go to time"));
mpForwardButton->setText(tr("Step forward"));
mpInitializeButton->setText(tr("Initialize"));
}
void DebuggerWidget::setInitData()
{
mCurrentTime = gpMainWindow->getStartTimeFromToolBar();
mpComponentsList->addItems(mpSystem->getModelObjectNames());
mpGotoButton->setDisabled(true);
mpForwardButton->setDisabled(true);
QString dateString = QDateTime::currentDateTime().toString(Qt::DefaultLocaleShortDate);
qDebug() << "dateString = " << dateString.toUtf8();
dateString.replace(":", "_");
dateString.replace(".", "_");
dateString.replace(" ", "_");
dateString.replace("/", "_");
dateString.replace("\\", "_");
mOutputFile.setFileName(gDesktopHandler.getDocumentsPath()+"HopsanDebuggerOutput_"+dateString+".csv");
}
void DebuggerWidget::updatePortsList(QString component)
{
mpPortsList->clear();
mpVariablesList->clear();
QList<Port*> ports = mpSystem->getModelObject(component)->getPortListPtrs();
Q_FOREACH(const Port *port, ports)
{
mpPortsList->addItem(port->getName());
}
}
void DebuggerWidget::updateVariablesList(QString port)
{
if(port.isEmpty()) return;
mpVariablesList->clear();
QString component = mpComponentsList->currentItem()->text();
NodeInfo info(mpSystem->getModelObject(component)->getPort(port)->getNodeType());
QStringList variables = info.variableLabels;
mpVariablesList->addItems(variables);
}
void DebuggerWidget::addVariable()
{
if(mpPortsList->count() == 0 || mpVariablesList->count() == 0) return;
if(mpComponentsList->currentItem() == 0 || mpPortsList->currentItem() == 0 || mpVariablesList->currentItem() == 0) return;
QString component = mpComponentsList->currentItem()->text();
QString port = mpPortsList->currentItem()->text();
QString data = mpVariablesList->currentItem()->text();
if(component.isEmpty() || port.isEmpty() || data.isEmpty()) return;
QString fullName = component+"::"+port+"::"+data;
if(mVariables.contains(fullName)) return;
mVariables.append(fullName);
mpChoosenVariablesList->addItem(fullName);
mpTraceTable->insertColumn(0);
QTableWidgetItem *pItem = new QTableWidgetItem(fullName);
mpTraceTable->setHorizontalHeaderItem(0, pItem);
}
void DebuggerWidget::removeVariable()
{
if(mpChoosenVariablesList->currentItem() == 0) return;
mVariables.removeOne(mpChoosenVariablesList->currentItem()->text());
for(int c=0; c<mpTraceTable->columnCount(); ++c)
{
if(mpTraceTable->horizontalHeaderItem(c)->text() == mpChoosenVariablesList->currentItem()->text())
{
mpTraceTable->removeColumn(c);
break;
}
}
mpChoosenVariablesList->clear();
mpChoosenVariablesList->addItems(mVariables);
}
void DebuggerWidget::runInitialization()
{
double startT = getStartTime();
double stopT = getStopTime();
int nSteps = int((stopT-startT)/mpSystem->getTimeStep());
if(mpSystem->getCoreSystemAccessPtr()->initialize(startT,stopT, nSteps+1))
{
mpGotoButton->setEnabled(true);
mpForwardButton->setEnabled(true);
}
collectLastData(false);
updateTimeDisplay();
}
void DebuggerWidget::stepForward()
{
simulateTo(getCurrentTime()+getTimeStep());
}
void DebuggerWidget::simulateTo()
{
double targetTime = QInputDialog::getDouble(this, "Hopsan Debugger", "Choose target time", getCurrentTime()+getTimeStep(), getCurrentTime()+getTimeStep(), getStopTime());
simulateTo(targetTime);
}
void DebuggerWidget::simulateTo(double targetTime)
{
mpSystem->getCoreSystemAccessPtr()->simulate(getCurrentTime(), targetTime, -1, true);
collectLastData();
updateTimeDisplay();
}
void DebuggerWidget::collectLastData(bool overWriteGeneration)
{
mpSystem->collectPlotData(overWriteGeneration);
QString outputLine;
outputLine.append(QString::number(getCurrentTime())+",");
mpTraceTable->insertRow(mpTraceTable->rowCount());
QTableWidgetItem *pItem = new QTableWidgetItem(QString::number(getCurrentTime()));
mpTraceTable->setVerticalHeaderItem(mpTraceTable->rowCount()-1, pItem);
Q_FOREACH(const QString &var, mVariables)
{
QString component = var.split("::").at(0);
QString port = var.split("::").at(1);
QString data = var.split("::").at(2);
double value;
mpSystem->getCoreSystemAccessPtr()->getLastNodeData(component, port, data, value);
outputLine.append(QString::number(value)+",");
QTableWidgetItem *pDataItem = new QTableWidgetItem(QString::number(value));
for(int c=0; c<mpTraceTable->columnCount(); ++c)
{
if(mpTraceTable->horizontalHeaderItem(c)->text() == var)
{
mpTraceTable->setItem(mpTraceTable->rowCount()-1, c, pDataItem);
}
}
}
mpTraceTable->scrollToBottom();
//mpTraceTable->verticalScrollBar()->setSliderPosition (mpTraceTable->verticalScrollBar()->maximum());
outputLine.chop(1);
outputLine.append("\n");
mOutputFile.open(QFile::WriteOnly | QFile::Text | QFile::Append);
mOutputFile.write(outputLine .toUtf8());
mOutputFile.close();
}
void DebuggerWidget::updateTimeDisplay()
{
mTimeIndicatorLabel->setText(QString::number(getCurrentTime()));
}
double DebuggerWidget::getCurrentTime() const
{
return mpSystem->getCoreSystemAccessPtr()->getCurrentTime();
}
double DebuggerWidget::getTimeStep() const
{
return mpSystem->getTimeStep();
}
double DebuggerWidget::getStartTime() const
{
return gpMainWindow->getStartTimeFromToolBar();
}
double DebuggerWidget::getStopTime() const
{
return gpMainWindow->getFinishTimeFromToolBar();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdresid.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2007-04-26 08:35:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_RESID_HXX
#define SD_RESID_HXX
#ifndef _RESID_HXX //autogen
#include <tools/resid.hxx>
#endif
#ifndef INCLUDED_SDDLLAPI_H
#include "sddllapi.h"
#endif
class SD_DLLPUBLIC SdResId : public ResId
{
public:
SdResId(USHORT nId);
};
#endif /* _SD_SDRESID_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.6.222); FILE MERGED 2008/04/01 12:38:23 thb 1.6.222.2: #i85898# Stripping all external header guards 2008/03/31 13:56:41 rt 1.6.222.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: sdresid.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_RESID_HXX
#define SD_RESID_HXX
#ifndef _RESID_HXX //autogen
#include <tools/resid.hxx>
#endif
#include "sddllapi.h"
class SD_DLLPUBLIC SdResId : public ResId
{
public:
SdResId(USHORT nId);
};
#endif /* _SD_SDRESID_HXX */
<|endoftext|> |
<commit_before>#include "TestScene.h"
#include <fstream>
#include "ShaderManager.h"
#include "Mesh.h"
#include "LightCulling.h"
#include "Director.h"
#include "ResourceManager.h"
using namespace Rendering;
using namespace Core;
using namespace Rendering::Camera;
using namespace Rendering::Light;
using namespace Resource;
using namespace Device;
using namespace Importer;
using namespace Math;
TestScene::TestScene(void)
{
}
TestScene::~TestScene(void)
{
}
void TestScene::OnInitialize()
{
MeshImporter importer;
importer.Initialize();
importer.Load("./Resources/Turrets Pack/turret_1.FBX");
// camera = new Object("Default");
// MainCamera* cam = camera->AddComponent<MainCamera>();
// //camera->GetTransform()->UpdateEulerAngles(Vector3(20, 340, 0));
// //camera->GetTransform()->UpdatePosition(Vector3(150, 200, 100));
//
// MeshImporter importer;
// importer.Initialize();
//
//// testObject = importer.Load("./Resources/Sponza/sponza.obj", "./Resources/Sponza/");
// //testObject = importer.Load("./Resources/Sphere/sphere.obj", "./Resources/Sphere/");
// testObject = importer.Load("./Resources/Capsule/capsule.obj");
//
// testObject->GetTransform()->UpdatePosition(Vector3(0, 0, 5));
//// testObject->GetTransform()->UpdateScale(Vector3(0.1f, 0.1f, 0.1f));
// testObject->GetTransform()->UpdateEulerAngles(Vector3(0, 90, 0));
// AddObject(testObject);
//
// light = new Object("Light");
// light->AddComponent<DirectionalLight>();
// light->GetTransform()->UpdateEulerAngles(Vector3(0, 0, 0));
//
// AddObject(light);
}
void TestScene::OnRenderPreview()
{
}
void TestScene::OnInput(const Device::Win32::Mouse& mouse, const Device::Win32::Keyboard& keyboard)
{
if(keyboard.states['W'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(0, 10, 0));
}
if(keyboard.states['A'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(-10, 0, 0));
}
if(keyboard.states['S'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(0, -10, 0));
}
if(keyboard.states['D'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(10, 0, 0));
}
if(keyboard.states['Y'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(10, 0, 0));
}
if(keyboard.states['G'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(0, -10, 0));
}
if(keyboard.states['H'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(-10, 0, 0));
}
if(keyboard.states['J'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(0, 10, 0));
}
}
void TestScene::OnUpdate(float dt)
{
//static float x = 0.0f;
//x += 0.01f;
//testObject->GetTransform()->UpdateEulerAngles(Math::Vector3(0, x, 0));
}
void TestScene::OnRenderPost()
{
}
void TestScene::OnDestroy()
{
}<commit_msg>테스트 경로 수정<commit_after>#include "TestScene.h"
#include <fstream>
#include "ShaderManager.h"
#include "Mesh.h"
#include "LightCulling.h"
#include "Director.h"
#include "ResourceManager.h"
using namespace Rendering;
using namespace Core;
using namespace Rendering::Camera;
using namespace Rendering::Light;
using namespace Resource;
using namespace Device;
using namespace Importer;
using namespace Math;
TestScene::TestScene(void)
{
}
TestScene::~TestScene(void)
{
}
void TestScene::OnInitialize()
{
MeshImporter importer;
importer.Initialize();
importer.Load("./Resources/Turrets Pack/turret_1.fbx");
// camera = new Object("Default");
// MainCamera* cam = camera->AddComponent<MainCamera>();
// //camera->GetTransform()->UpdateEulerAngles(Vector3(20, 340, 0));
// //camera->GetTransform()->UpdatePosition(Vector3(150, 200, 100));
//
// MeshImporter importer;
// importer.Initialize();
//
//// testObject = importer.Load("./Resources/Sponza/sponza.obj", "./Resources/Sponza/");
// //testObject = importer.Load("./Resources/Sphere/sphere.obj", "./Resources/Sphere/");
// testObject = importer.Load("./Resources/Capsule/capsule.obj");
//
// testObject->GetTransform()->UpdatePosition(Vector3(0, 0, 5));
//// testObject->GetTransform()->UpdateScale(Vector3(0.1f, 0.1f, 0.1f));
// testObject->GetTransform()->UpdateEulerAngles(Vector3(0, 90, 0));
// AddObject(testObject);
//
// light = new Object("Light");
// light->AddComponent<DirectionalLight>();
// light->GetTransform()->UpdateEulerAngles(Vector3(0, 0, 0));
//
// AddObject(light);
}
void TestScene::OnRenderPreview()
{
}
void TestScene::OnInput(const Device::Win32::Mouse& mouse, const Device::Win32::Keyboard& keyboard)
{
if(keyboard.states['W'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(0, 10, 0));
}
if(keyboard.states['A'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(-10, 0, 0));
}
if(keyboard.states['S'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(0, -10, 0));
}
if(keyboard.states['D'] == Win32::Keyboard::Type::Up)
{
Vector3 pos = testObject->GetTransform()->GetLocalPosition();
testObject->GetTransform()->UpdatePosition(pos + Vector3(10, 0, 0));
}
if(keyboard.states['Y'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(10, 0, 0));
}
if(keyboard.states['G'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(0, -10, 0));
}
if(keyboard.states['H'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(-10, 0, 0));
}
if(keyboard.states['J'] == Win32::Keyboard::Type::Up)
{
Vector3 e = testObject->GetTransform()->GetLocalEulerAngle();
testObject->GetTransform()->UpdateEulerAngles(e + Vector3(0, 10, 0));
}
}
void TestScene::OnUpdate(float dt)
{
//static float x = 0.0f;
//x += 0.01f;
//testObject->GetTransform()->UpdateEulerAngles(Math::Vector3(0, x, 0));
}
void TestScene::OnRenderPost()
{
}
void TestScene::OnDestroy()
{
}<|endoftext|> |
<commit_before>/*
@ Kingsley Chen
*/
#include "stdafx.h"
#include "gtest\gtest.h"
#include "kbase\strings\string_format.h"
#include <iostream>
#include <string>
namespace {
using namespace kbase;
using namespace kbase::internal;
template<typename CharT>
bool ComparePlaceholder(const Placeholder<CharT>& p, unsigned i, unsigned pos, const CharT* spec)
{
return p.index == i && p.pos == pos && p.format_specifier == spec;
}
}
TEST(StringFormatTest, AnalyzeFormatString)
{
PlaceholderList<char> placeholder_list;
std::string afmt;
auto analyzed_fmt = AnalyzeFormatString("blabla {0} {{}} {2} {1:04}", &placeholder_list);
afmt = "blabla @ {} @ @";
EXPECT_EQ(afmt, analyzed_fmt);
ASSERT_EQ(placeholder_list.size(), 3);
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[0], 0, 7, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[2], 2, 12, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[1], 1, 14, "04"));
analyzed_fmt = AnalyzeFormatString("test {0}{1:}{{}} {{{1:#4.3X}}}", &placeholder_list);
afmt = "test @@{} {@}";
EXPECT_EQ(afmt, analyzed_fmt);
ASSERT_EQ(placeholder_list.size(), 3);
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[0], 0, 5, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[1], 1, 6, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[2], 1, 11, "#4.3X"));
EXPECT_THROW(AnalyzeFormatString ("test { 0 }", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {}", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {{1}", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {1 }", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {1 {2}", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {1:", &placeholder_list), StringFormatSpecifierError);
}
TEST(StringFormatTest, tt)
{
auto str = kbase::StringFormat("hello {0:X} {1} Pi-day {2}", 255, "world", 3.14);
}<commit_msg>string_format: update unittest<commit_after>/*
@ Kingsley Chen
*/
#include "stdafx.h"
#include "gtest\gtest.h"
#define NDEBUG
#include "kbase\strings\string_format.h"
#undef NDEBUG
#include <iostream>
#include <string>
namespace {
using namespace kbase;
using namespace kbase::internal;
template<typename CharT>
bool ComparePlaceholder(const Placeholder<CharT>& p, unsigned i, unsigned pos, const CharT* spec)
{
return p.index == i && p.pos == pos && p.format_specifier == spec;
}
}
TEST(StringFormatTest, AnalyzeFormatString)
{
PlaceholderList<char> placeholder_list;
std::string afmt;
auto analyzed_fmt = AnalyzeFormatString("blabla {0} {{}} {2} {1:04}", &placeholder_list);
afmt = "blabla @ {} @ @";
EXPECT_EQ(afmt, analyzed_fmt);
ASSERT_EQ(placeholder_list.size(), 3);
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[0], 0, 7, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[2], 2, 12, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[1], 1, 14, "04"));
analyzed_fmt = AnalyzeFormatString("test {0}{1:}{{}} {{{1:#4.3X}}}", &placeholder_list);
afmt = "test @@{} {@}";
EXPECT_EQ(afmt, analyzed_fmt);
ASSERT_EQ(placeholder_list.size(), 3);
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[0], 0, 5, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[1], 1, 6, ""));
EXPECT_TRUE(ComparePlaceholder<char>(placeholder_list[2], 1, 11, "#4.3X"));
EXPECT_THROW(AnalyzeFormatString ("test { 0 }", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {}", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {{1}", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {1 }", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {1 {2}", &placeholder_list), StringFormatSpecifierError);
EXPECT_THROW(AnalyzeFormatString ("test {1:", &placeholder_list), StringFormatSpecifierError);
}
TEST(StringFormatTest, Format)
{
std::string str, exp_str;
str = StringFormat("abc {0:0>4X} {1} def {2:.4} {0:+}", 255, "test", 3.14, 123);
exp_str = "abc 00FF test def 3.1400 +255";
EXPECT_EQ(exp_str, str);
// --- a bunch of invalid cases ---.
EXPECT_ANY_THROW(StringFormat("{0} {1}", 123)); // redundant specifier
EXPECT_ANY_THROW(StringFormat("{0:>4}", 123)); // fill is missing
EXPECT_ANY_THROW(StringFormat("{0:.6+4}", 3.1464232)); // specifier order is wrong
EXPECT_ANY_THROW(StringFormat("{0: >bx}", 123)); // type-mark is more than once
EXPECT_ANY_THROW(StringFormat("{0: }", 123)); // empty specifier
}<|endoftext|> |
<commit_before>//Copyright 2016 Adam G. Smith
//
//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 "solaire/core/bin_utils.hpp"
namespace solaire {
static constexpr uint8_t POPCOUNT[16] = {
// 0000 0001 0010 0011 0100 0101 0110 0111
0, 1, 1, 2, 1, 2, 2, 3,
// 1000 1001 1010 1011 1100 1101 1110 1111
1, 2, 2, 3, 2, 3, 3, 4
};
static constexpr uint8_t REFLECT[16] = {
// 0000 0001 0010 0011 0100 0101 0110 0111
0, 8, 4, 12, 2, 10, 6, 14,
// 1000 1001 1010 1011 1100 1101 1110 1111
1, 9, 5, 13, 3, 11, 7, 15
};
void read_bits(void* const aOut, const uint32_t aOutOffset, const void* aIn, const uint32_t aInOffset, const uint32_t aBits) throw() {
const uint32_t outByte = aOutOffset / 8;
const uint32_t inByte = aOutOffset / 8;
uint8_t* outPtr = static_cast<uint8_t*>(aOut) + outByte;
const uint8_t* inPtr = static_cast<const uint8_t*>(aIn) + inByte;
const uint32_t outTrail = aOutOffset & 7;
const uint32_t inTrail = aOutOffset & 7;
uint8_t outBit = 1 << outTrail;
uint8_t inBit = 1 << inTrail;
uint8_t bit;
//! \todo Optimise
for(uint32_t i = 0; i < aBits; ++i) {
bit = *inPtr & inBit;
if(bit) {
*outPtr |= outBit;
}else {
*outPtr &= ~outBit;
}
if(outBit == 64) {
outBit = 1;
++outPtr;
}else {
outBit <<= 1;
}
if(inBit == 64) {
inBit = 1;
++inPtr;
}else{
inBit <<= 1;
}
}
}
constexpr uint32_t popcount(const uint8_t aValue) throw() {
return POPCOUNT[aValue & 15] + POPCOUNT[aValue >> 4];
}
constexpr uint32_t popcount(const uint16_t aValue) throw() {
return popcount(reinterpret_cast<const uint8_t*>(&aValue)[0]) + popcount(reinterpret_cast<const uint8_t*>(&aValue)[1]);
}
constexpr uint32_t popcount(const uint32_t aValue) throw() {
return popcount(reinterpret_cast<const uint16_t*>(&aValue)[0]) + popcount(reinterpret_cast<const uint16_t*>(&aValue)[1]);
}
constexpr uint32_t popcount(const uint64_t aValue) throw() {
return popcount(reinterpret_cast<const uint32_t*>(&aValue)[0]) + popcount(reinterpret_cast<const uint32_t*>(&aValue)[1]);
}
constexpr uint32_t popcount(const int8_t aValue) throw() {
return popcount(*reinterpret_cast<const uint8_t*>(&aValue));
}
constexpr uint32_t popcount(const int16_t aValue) throw() {
return popcount(*reinterpret_cast<const uint16_t*>(&aValue));
}
constexpr uint32_t popcount(const int32_t aValue) throw() {
return popcount(*reinterpret_cast<const uint32_t*>(&aValue));
}
constexpr uint32_t popcount(const int64_t aValue) throw() {
return popcount(*reinterpret_cast<const uint64_t*>(&aValue));
}
uint32_t popcount(const void* const aPtr, const uint32_t aBytes) throw() {
const uint8_t* i = static_cast<const uint8_t*>(aPtr);
uint32_t bytes = aBytes;
uint32_t ones = 0;
while(bytes >= 8) {
ones += popcount(*reinterpret_cast<const uint64_t*>(i));
i += 8;
bytes -= 8;
}
if(bytes >= 4) {
ones += popcount(*reinterpret_cast<const uint32_t*>(i));
i += 4;
bytes -= 4;
}
if(bytes >= 2) {
ones += popcount(*reinterpret_cast<const uint16_t*>(i));
i += 2;
bytes -= 2;
}
if(bytes >= 1) {
ones += popcount(*i);
}
return ones;
}
constexpr uint8_t reflect(const uint8_t aValue) throw() {
return (REFLECT[aValue & 15] << 4) | REFLECT[aValue >> 4];
}
constexpr uint16_t reflect(const uint16_t aValue) throw() {
return
(static_cast<uint16_t>(reflect(reinterpret_cast<const uint8_t*>(&aValue)[0])) << 8) |
reflect(reinterpret_cast<const uint8_t*>(&aValue)[1]);
}
constexpr uint32_t reflect(const uint32_t aValue) throw() {
return
(static_cast<uint32_t>(reflect(reinterpret_cast<const uint16_t*>(&aValue)[0])) << 16) |
reflect(reinterpret_cast<const uint16_t*>(&aValue)[1]);
}
constexpr uint64_t reflect(const uint64_t aValue) throw() {
return
(static_cast<uint64_t>(reflect(reinterpret_cast<const uint32_t*>(&aValue)[0])) << 32L) |
reflect(reinterpret_cast<const uint32_t*>(&aValue)[1]);
}
constexpr int8_t reflect(const int8_t aValue) throw() {
return reflect(*reinterpret_cast<const uint8_t*>(&aValue));
}
constexpr int16_t reflect(const int16_t aValue) throw() {
return reflect(*reinterpret_cast<const uint16_t*>(&aValue));
}
constexpr int32_t reflect(const int32_t aValue) throw() {
return reflect(*reinterpret_cast<const uint32_t*>(&aValue));
}
constexpr int64_t reflect(const int64_t aValue) throw() {
return reflect(*reinterpret_cast<const uint64_t*>(&aValue));
}
void reflect(void* const aOut, const void* const aIn, const uint32_t aBytes) throw() {
uint8_t* i = static_cast<uint8_t*>(aOut) + aBytes - 1;
const uint8_t* j = static_cast<const uint8_t*>(aIn);
const uint8_t* const end = j + aBytes;
while(j != end) {
*i = reflect(*j);
--i;
++j;
}
}
}<commit_msg>Added documentation for bin_utils<commit_after>//Copyright 2016 Adam G. Smith
//
//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 "solaire/core/bin_utils.hpp"
namespace solaire {
static constexpr uint8_t POPCOUNT[16] = {
// 0000 0001 0010 0011 0100 0101 0110 0111
0, 1, 1, 2, 1, 2, 2, 3,
// 1000 1001 1010 1011 1100 1101 1110 1111
1, 2, 2, 3, 2, 3, 3, 4
};
static constexpr uint8_t REFLECT[16] = {
// 0000 0001 0010 0011 0100 0101 0110 0111
0, 8, 4, 12, 2, 10, 6, 14,
// 1000 1001 1010 1011 1100 1101 1110 1111
1, 9, 5, 13, 3, 11, 7, 15
};
/*!
\brief Copy a number of bits from one location to another.
\param aOut The first byte to write into.
\param aOutOffset The offset into the first byte to write into.
\param aIn The first byte to read from.
\param aInOffset The offset into the first byte to read from.
\param aBits The number of bits to read.
*/
void read_bits(void* const aOut, const uint32_t aOutOffset, const void* aIn, const uint32_t aInOffset, const uint32_t aBits) throw() {
const uint32_t outByte = aOutOffset / 8;
const uint32_t inByte = aOutOffset / 8;
uint8_t* outPtr = static_cast<uint8_t*>(aOut) + outByte;
const uint8_t* inPtr = static_cast<const uint8_t*>(aIn) + inByte;
const uint32_t outTrail = aOutOffset & 7;
const uint32_t inTrail = aOutOffset & 7;
uint8_t outBit = 1 << outTrail;
uint8_t inBit = 1 << inTrail;
uint8_t bit;
//! \todo Optimise
for(uint32_t i = 0; i < aBits; ++i) {
bit = *inPtr & inBit;
if(bit) {
*outPtr |= outBit;
}else {
*outPtr &= ~outBit;
}
if(outBit == 64) {
outBit = 1;
++outPtr;
}else {
outBit <<= 1;
}
if(inBit == 64) {
inBit = 1;
++inPtr;
}else{
inBit <<= 1;
}
}
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const uint8_t aValue) throw() {
return POPCOUNT[aValue & 15] + POPCOUNT[aValue >> 4];
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const uint16_t aValue) throw() {
return popcount(reinterpret_cast<const uint8_t*>(&aValue)[0]) + popcount(reinterpret_cast<const uint8_t*>(&aValue)[1]);
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const uint32_t aValue) throw() {
return popcount(reinterpret_cast<const uint16_t*>(&aValue)[0]) + popcount(reinterpret_cast<const uint16_t*>(&aValue)[1]);
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const uint64_t aValue) throw() {
return popcount(reinterpret_cast<const uint32_t*>(&aValue)[0]) + popcount(reinterpret_cast<const uint32_t*>(&aValue)[1]);
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const int8_t aValue) throw() {
return popcount(*reinterpret_cast<const uint8_t*>(&aValue));
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const int16_t aValue) throw() {
return popcount(*reinterpret_cast<const uint16_t*>(&aValue));
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const int32_t aValue) throw() {
return popcount(*reinterpret_cast<const uint32_t*>(&aValue));
}
/*!
\brief Count the number of bits that are set.
\param aValue The value to count.
\return The number of set bits.
*/
constexpr uint32_t popcount(const int64_t aValue) throw() {
return popcount(*reinterpret_cast<const uint64_t*>(&aValue));
}
/*!
\brief Count the number of bits that are set.
\param aPtr The first byte to count.
\param aBytes The number of bytes in aPtr.
\return The number of set bits.
*/
uint32_t popcount(const void* const aPtr, const uint32_t aBytes) throw() {
const uint8_t* i = static_cast<const uint8_t*>(aPtr);
uint32_t bytes = aBytes;
uint32_t ones = 0;
while(bytes >= 8) {
ones += popcount(*reinterpret_cast<const uint64_t*>(i));
i += 8;
bytes -= 8;
}
if(bytes >= 4) {
ones += popcount(*reinterpret_cast<const uint32_t*>(i));
i += 4;
bytes -= 4;
}
if(bytes >= 2) {
ones += popcount(*reinterpret_cast<const uint16_t*>(i));
i += 2;
bytes -= 2;
}
if(bytes >= 1) {
ones += popcount(*i);
}
return ones;
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr uint8_t reflect(const uint8_t aValue) throw() {
return (REFLECT[aValue & 15] << 4) | REFLECT[aValue >> 4];
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr uint16_t reflect(const uint16_t aValue) throw() {
return
(static_cast<uint16_t>(reflect(reinterpret_cast<const uint8_t*>(&aValue)[0])) << 8) |
reflect(reinterpret_cast<const uint8_t*>(&aValue)[1]);
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr uint32_t reflect(const uint32_t aValue) throw() {
return
(static_cast<uint32_t>(reflect(reinterpret_cast<const uint16_t*>(&aValue)[0])) << 16) |
reflect(reinterpret_cast<const uint16_t*>(&aValue)[1]);
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr uint64_t reflect(const uint64_t aValue) throw() {
return
(static_cast<uint64_t>(reflect(reinterpret_cast<const uint32_t*>(&aValue)[0])) << 32L) |
reflect(reinterpret_cast<const uint32_t*>(&aValue)[1]);
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr int8_t reflect(const int8_t aValue) throw() {
return reflect(*reinterpret_cast<const uint8_t*>(&aValue));
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr int16_t reflect(const int16_t aValue) throw() {
return reflect(*reinterpret_cast<const uint16_t*>(&aValue));
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr int32_t reflect(const int32_t aValue) throw() {
return reflect(*reinterpret_cast<const uint32_t*>(&aValue));
}
/*!
\brief Reverse the order of bits.
\param aValue The value to reflect.
\return The reflected value.
*/
constexpr int64_t reflect(const int64_t aValue) throw() {
return reflect(*reinterpret_cast<const uint64_t*>(&aValue));
}
/*!
\brief Reverse the order of bits.
\param aOut The destination of the reversed data.
\param aIn The source of the data.
\param aBytes The number of bytes in aIn.
*/
void reflect(void* const aOut, const void* const aIn, const uint32_t aBytes) throw() {
uint8_t* i = static_cast<uint8_t*>(aOut) + aBytes - 1;
const uint8_t* j = static_cast<const uint8_t*>(aIn);
const uint8_t* const end = j + aBytes;
while(j != end) {
*i = reflect(*j);
--i;
++j;
}
}
}<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "rpminputstream.h"
#include "gzipinputstream.h"
#include "bz2inputstream.h"
#include "subinputstream.h"
#include "dostime.h"
#include <list>
using namespace jstreams;
using namespace std;
class RpmInputStream::RpmHeaderInfo {
};
/**
* RPM files as specified here:
* http://www.freestandards.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/swinstall.html
* and here:
* http://www.rpm.org/max-rpm-snapshot/s1-rpm-file-format-rpm-file-format.html
**/
bool
RpmInputStream::checkHeader(const char* data, int32_t datasize) {
static const char unsigned magic[] = {0xed,0xab,0xee,0xdb,0x03,0x00};
if (datasize < 6) return false;
// this check could be more strict
bool ok = memcmp(data, magic, 6) == 0;
return ok;
}
RpmInputStream::RpmInputStream(StreamBase<char>* input)
: SubStreamProvider(input), headerinfo(0) {
uncompressionStream = 0;
// skip the header
const char* b;
// lead:96 bytes
if (input->read(b, 96, 96) != 96) {
status = Error;
return;
}
// read signature
const unsigned char headmagic[] = {0x8e,0xad,0xe8,0x01};
if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
error = "error in signature\n";
status = Error;
return;
}
int32_t nindex = read4bytes((const unsigned char*)(b+8));
int32_t hsize = read4bytes((const unsigned char*)(b+12));
int32_t sz = nindex*16+hsize;
if (sz%8) {
sz+=8-sz%8;
}
input->read(b, sz, sz);
// read header
if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
error = "error in header\n";
status = Error;
return;
}
nindex = read4bytes((const unsigned char*)(b+8));
hsize = read4bytes((const unsigned char*)(b+12));
int32_t size = nindex*16+hsize;
if (input->read(b, size, size) != size) {
error = "could not read header\n";
status = Error;
return;
}
for (int32_t i=0; i<nindex; ++i) {
const unsigned char* e = (const unsigned char*)b+i*16;
int32_t tag = read4bytes(e);
int32_t type = read4bytes(e+4);
int32_t offset = read4bytes(e+8);
if (offset < 0 || offset >= hsize) {
// error: invalid offset
}
int32_t count = read4bytes(e+12);
int32_t end = hsize;
if (i < nindex-1) {
end = read4bytes(e+8+16);
}
if (end < offset) end = offset;
if (end > hsize) end = hsize;
// TODO actually put the data into the objects so the analyzers can use them
/* if (type == 6) {
string s(b+nindex*16+offset, end-offset);
printf("%s\n", s.c_str());
} else if (type == 8 || type == 9) {
list<string> v;
// TODO handle string arrays
}
printf("%i\t%i\t%i\t%i\n", tag, type, offset, count);*/
}
int64_t pos = input->getPosition();
if (input->read(b, 16, 16) != 16) {
error = "could not read payload\n";
status = Error;
return;
}
input->reset(pos);
if (BZ2InputStream::checkHeader(b, 16)) {
uncompressionStream = new BZ2InputStream(input);
} else {
uncompressionStream = new GZipInputStream(input);
}
if (uncompressionStream->getStatus() == Error) {
status = Error;
return;
}
}
RpmInputStream::~RpmInputStream() {
if (uncompressionStream) {
delete uncompressionStream;
}
if (headerinfo) {
delete headerinfo;
}
}
StreamBase<char>*
RpmInputStream::nextEntry() {
if (status) return 0;
if (entrystream) {
while (entrystream->getStatus() == Ok) {
entrystream->skip(entrystream->getSize());
}
delete entrystream;
entrystream = 0;
if (padding) {
uncompressionStream->skip(padding);
}
}
readHeader();
if (status) return 0;
entrystream = new SubInputStream(uncompressionStream, entryinfo.size);
return entrystream;
}
int32_t
RpmInputStream::read4bytes(const unsigned char *b) {
return (b[0]<<24) + (b[1]<<16) + (b[2]<<8) + b[3];
}
void
RpmInputStream::readHeader() {
//const unsigned char *hb;
const char *b;
int32_t toread;
int32_t nread;
// read the first 110 characters
toread = 110;
nread = uncompressionStream->read(b, toread, toread);
if (nread != toread) {
status = uncompressionStream->getStatus();
if (status == Eof) {
return;
}
error = "Error reading rpm entry: ";
if (nread == -1) {
error += uncompressionStream->getError();
} else {
error += " premature end of file.";
}
return;
}
// check header
if (memcmp(b, "070701", 6) != 0) {
status = Error;
error = "RPM Entry signature is unknown: ";
error.append(b, 6);
return;
}
entryinfo.size = readHexField(b+54);
entryinfo.mtime = readHexField(b+46);
int32_t filenamesize = readHexField(b+94);
if (status) {
error = "Error parsing entry field.";
return;
}
char namepadding = (filenamesize+2) % 4;
if (namepadding) namepadding = 4 - namepadding;
padding = entryinfo.size % 4;
if (padding) padding = 4-padding;
// read filename
toread = filenamesize+namepadding;
nread = uncompressionStream->read(b, toread, toread);
if (nread != toread) {
error = "Error reading rpm entry name.";
status = Error;
return;
}
int32_t len = filenamesize-1;
if (len > 2 && b[0] == '.' && b[1] == '/') {
b += 2;
}
entryinfo.filename = std::string((const char*)b, filenamesize-1);
}
int32_t
RpmInputStream::readHexField(const char *b) {
int32_t val = 0;
char c;
for (char i=0; i<8; ++i) {
val <<= 4;
c = b[i];
if (c > '9') {
val += 10+c-'a';
} else {
val += c-'0';
}
}
return val;
}
<commit_msg>Check for too short file names and omit the RPM trailer from the results.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "rpminputstream.h"
#include "gzipinputstream.h"
#include "bz2inputstream.h"
#include "subinputstream.h"
#include "dostime.h"
#include <list>
using namespace jstreams;
using namespace std;
class RpmInputStream::RpmHeaderInfo {
};
/**
* RPM files as specified here:
* http://www.freestandards.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/swinstall.html
* and here:
* http://www.rpm.org/max-rpm-snapshot/s1-rpm-file-format-rpm-file-format.html
**/
bool
RpmInputStream::checkHeader(const char* data, int32_t datasize) {
static const char unsigned magic[] = {0xed,0xab,0xee,0xdb,0x03,0x00};
if (datasize < 6) return false;
// this check could be more strict
bool ok = memcmp(data, magic, 6) == 0;
return ok;
}
RpmInputStream::RpmInputStream(StreamBase<char>* input)
: SubStreamProvider(input), headerinfo(0) {
uncompressionStream = 0;
// skip the header
const char* b;
// lead:96 bytes
if (input->read(b, 96, 96) != 96) {
status = Error;
return;
}
// read signature
const unsigned char headmagic[] = {0x8e,0xad,0xe8,0x01};
if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
error = "error in signature\n";
status = Error;
return;
}
int32_t nindex = read4bytes((const unsigned char*)(b+8));
int32_t hsize = read4bytes((const unsigned char*)(b+12));
int32_t sz = nindex*16+hsize;
if (sz%8) {
sz+=8-sz%8;
}
input->read(b, sz, sz);
// read header
if (input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
error = "error in header\n";
status = Error;
return;
}
nindex = read4bytes((const unsigned char*)(b+8));
hsize = read4bytes((const unsigned char*)(b+12));
int32_t size = nindex*16+hsize;
if (input->read(b, size, size) != size) {
error = "could not read header\n";
status = Error;
return;
}
for (int32_t i=0; i<nindex; ++i) {
const unsigned char* e = (const unsigned char*)b+i*16;
int32_t tag = read4bytes(e);
int32_t type = read4bytes(e+4);
int32_t offset = read4bytes(e+8);
if (offset < 0 || offset >= hsize) {
// error: invalid offset
}
int32_t count = read4bytes(e+12);
int32_t end = hsize;
if (i < nindex-1) {
end = read4bytes(e+8+16);
}
if (end < offset) end = offset;
if (end > hsize) end = hsize;
// TODO actually put the data into the objects so the analyzers can use them
/* if (type == 6) {
string s(b+nindex*16+offset, end-offset);
printf("%s\n", s.c_str());
} else if (type == 8 || type == 9) {
list<string> v;
// TODO handle string arrays
}
printf("%i\t%i\t%i\t%i\n", tag, type, offset, count);*/
}
int64_t pos = input->getPosition();
if (input->read(b, 16, 16) != 16) {
error = "could not read payload\n";
status = Error;
return;
}
input->reset(pos);
if (BZ2InputStream::checkHeader(b, 16)) {
uncompressionStream = new BZ2InputStream(input);
} else {
uncompressionStream = new GZipInputStream(input);
}
if (uncompressionStream->getStatus() == Error) {
status = Error;
return;
}
}
RpmInputStream::~RpmInputStream() {
if (uncompressionStream) {
delete uncompressionStream;
}
if (headerinfo) {
delete headerinfo;
}
}
StreamBase<char>*
RpmInputStream::nextEntry() {
if (status) return 0;
if (entrystream) {
while (entrystream->getStatus() == Ok) {
entrystream->skip(entrystream->getSize());
}
delete entrystream;
entrystream = 0;
if (padding) {
uncompressionStream->skip(padding);
}
}
readHeader();
if (status) return 0;
entrystream = new SubInputStream(uncompressionStream, entryinfo.size);
return entrystream;
}
int32_t
RpmInputStream::read4bytes(const unsigned char *b) {
return (b[0]<<24) + (b[1]<<16) + (b[2]<<8) + b[3];
}
void
RpmInputStream::readHeader() {
//const unsigned char *hb;
const char *b;
int32_t toread;
int32_t nread;
// read the first 110 characters
toread = 110;
nread = uncompressionStream->read(b, toread, toread);
if (nread != toread) {
status = uncompressionStream->getStatus();
if (status == Eof) {
return;
}
error = "Error reading rpm entry: ";
if (nread == -1) {
error += uncompressionStream->getError();
} else {
error += " premature end of file.";
}
return;
}
// check header
if (memcmp(b, "070701", 6) != 0) {
status = Error;
error = "RPM Entry signature is unknown: ";
error.append(b, 6);
return;
}
entryinfo.size = readHexField(b+54);
entryinfo.mtime = readHexField(b+46);
int32_t filenamesize = readHexField(b+94);
if (status) {
error = "Error parsing entry field.";
return;
}
char namepadding = (filenamesize+2) % 4;
if (namepadding) namepadding = 4 - namepadding;
padding = entryinfo.size % 4;
if (padding) padding = 4-padding;
// read filename
toread = filenamesize+namepadding;
nread = uncompressionStream->read(b, toread, toread);
if (nread != toread) {
error = "Error reading rpm entry name.";
status = Error;
return;
}
int32_t len = filenamesize-1;
if (len > 2 && b[0] == '.' && b[1] == '/') {
b += 2;
}
// check if the name is not shorter than specified
len = 0;
while (len < filenamesize && b[len] != '\0') len++;
entryinfo.filename = std::string((const char*)b, len);
// if an rpm has an entry 'TRAILER!!!' we are at the end
if ("TRAILER!!!" == entryinfo.filename) {
status = Eof;
}
}
int32_t
RpmInputStream::readHexField(const char *b) {
int32_t val = 0;
char c;
for (char i=0; i<8; ++i) {
val <<= 4;
c = b[i];
if (c > '9') {
val += 10+c-'a';
} else {
val += c-'0';
}
}
return val;
}
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "subinputstream.h"
#include <cassert>
using namespace jstreams;
SubInputStream::SubInputStream(StreamBase<char> *i, int64_t length)
: offset(i->getPosition()), input(i) {
assert(length >= -1);
// printf("substream offset: %lli\n", offset);
size = length;
}
int32_t
SubInputStream::read(const char*& start, int32_t min, int32_t max) {
if (size != -1) {
const int64_t left = size - position;
if (left == 0) {
return -1;
}
// restrict the amount of data that can be read
if (max <= 0 || max > left) {
max = (int32_t)left;
}
if (min > max) min = max;
if (left < min) min = (int32_t)left;
}
int32_t nread = input->read(start, min, max);
if (nread < -1) {
fprintf(stderr, "substream too short.\n");
status = Error;
error = input->getError();
} else if (nread < min) {
if (size == -1) {
status = Eof;
if (nread > 0) {
position += nread;
size = position;
}
} else {
// fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! nread %i min %i max %i size %lli\n", nread, min, max, size);
// fprintf(stderr, "pos %lli parentpos %lli\n", position, input->getPosition());
// fprintf(stderr, "status: %i error: %s\n", input->getStatus(), input->getError());
// we expected data but didn't get enough so that's an error
status = Error;
error = "Premature end of stream\n";
nread = -2;
}
} else {
position += nread;
if (position == size) {
status = Eof;
}
}
return nread;
}
int64_t
SubInputStream::reset(int64_t newpos) {
assert(newpos >= 0);
// fprintf(stderr, "subreset pos: %lli newpos: %lli offset: %lli\n", position,
// newpos, offset);
position = input->reset(newpos + offset);
if (position < offset) {
fprintf(stderr, "########### position %lli newpos %lli\n", position, newpos);
status = Error;
error = input->getError();
} else {
position -= offset;
status = input->getStatus();
}
return position;
}
int64_t
SubInputStream::skip(int64_t ntoskip) {
// printf("subskip pos: %lli ntoskip: %lli offset: %lli\n", position, ntoskip, offset);
if (size == position) {
status = Eof;
return -1;
}
if (size != -1) {
const int64_t left = size - position;
// restrict the amount of data that can be skipped
if (ntoskip > left) {
ntoskip = left;
}
}
int64_t skipped = input->skip(ntoskip);
if (input->getStatus() == Error) {
status = Error;
error = input->getError();
} else {
position += skipped;
if (position == size) {
status = Eof;
}
}
return skipped;
}
<commit_msg>Fix substream error when the encapsulated stream does not return and characters when skipping.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "subinputstream.h"
#include <cassert>
using namespace jstreams;
SubInputStream::SubInputStream(StreamBase<char> *i, int64_t length)
: offset(i->getPosition()), input(i) {
assert(length >= -1);
// printf("substream offset: %lli\n", offset);
size = length;
}
int32_t
SubInputStream::read(const char*& start, int32_t min, int32_t max) {
if (size != -1) {
const int64_t left = size - position;
if (left == 0) {
return -1;
}
// restrict the amount of data that can be read
if (max <= 0 || max > left) {
max = (int32_t)left;
}
if (min > max) min = max;
if (left < min) min = (int32_t)left;
}
int32_t nread = input->read(start, min, max);
if (nread < -1) {
fprintf(stderr, "substream too short.\n");
status = Error;
error = input->getError();
} else if (nread < min) {
if (size == -1) {
status = Eof;
if (nread > 0) {
position += nread;
size = position;
}
} else {
// fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! nread %i min %i max %i size %lli\n", nread, min, max, size);
// fprintf(stderr, "pos %lli parentpos %lli\n", position, input->getPosition());
// fprintf(stderr, "status: %i error: %s\n", input->getStatus(), input->getError());
// we expected data but didn't get enough so that's an error
status = Error;
error = "Premature end of stream\n";
nread = -2;
}
} else {
position += nread;
if (position == size) {
status = Eof;
}
}
return nread;
}
int64_t
SubInputStream::reset(int64_t newpos) {
assert(newpos >= 0);
// fprintf(stderr, "subreset pos: %lli newpos: %lli offset: %lli\n", position,
// newpos, offset);
position = input->reset(newpos + offset);
if (position < offset) {
fprintf(stderr, "########### position %lli newpos %lli\n", position, newpos);
status = Error;
error = input->getError();
} else {
position -= offset;
status = input->getStatus();
}
return position;
}
int64_t
SubInputStream::skip(int64_t ntoskip) {
// printf("subskip pos: %lli ntoskip: %lli offset: %lli\n", position, ntoskip, offset);
if (size == position) {
status = Eof;
return -1;
}
if (size != -1) {
const int64_t left = size - position;
// restrict the amount of data that can be skipped
if (ntoskip > left) {
ntoskip = left;
}
}
int64_t skipped = input->skip(ntoskip);
if (input->getStatus() == Error) {
status = Error;
error = input->getError();
} else {
position += skipped;
if (position == size) {
status = Eof;
} else if (skipped <= 0) {
status = Error;
error = "Could not read until the end of the stream.";
}
}
return skipped;
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <lac/full_matrix.templates.h>
#include <lac/lapack_templates.h>
#include <base/logstream.h>
DEAL_II_NAMESPACE_OPEN
// Need to explicitly state the Lapack
// inversion since it only works with
// floats and doubles in case LAPACK was
// detected by configure.
#ifdef HAVE_LIBLAPACK
template <>
void
FullMatrix<float>::gauss_jordan ()
{
Assert (!this->empty(), ExcEmptyMatrix());
Assert (this->n_cols() == this->n_rows(), ExcNotQuadratic());
// In case we have the LAPACK functions
// getrf and getri detected at configure,
// we use these algorithms for inversion
// since they provide better performance
// than the deal.II native functions.
//
// Note that BLAS/LAPACK stores matrix
// elements column-wise (i.e., all values in
// one column, then all in the next, etc.),
// whereas the FullMatrix stores them
// row-wise.
// We ignore that difference, and give our
// row-wise data to LAPACK,
// let LAPACK build the inverse of the
// transpose matrix, and read the result as
// if it were row-wise again. In other words,
// we just got ((A^T)^{-1})^T, which is
// A^{-1}.
const int nn = this->n();
float* values = const_cast<float*> (this->data());
ipiv.resize(nn);
int info;
// Use the LAPACK function getrf for
// calculating the LU factorization.
getrf(&nn, &nn, values, &nn, &ipiv[0], &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
inv_work.resize (nn);
// Use the LAPACK function getri for
// calculating the actual inverse using
// the LU factorization.
getri(&nn, values, &nn, &ipiv[0], &inv_work[0], &nn, &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
}
template <>
void
FullMatrix<double>::gauss_jordan ()
{
Assert (!this->empty(), ExcEmptyMatrix());
Assert (this->n_cols() == this->n_rows(), ExcNotQuadratic());
// In case we have the LAPACK functions
// getrf and getri detected at configure,
// we use these algorithms for inversion
// since they provide better performance
// than the deal.II native functions.
//
// Note that BLAS/LAPACK stores matrix
// elements column-wise (i.e., all values in
// one column, then all in the next, etc.),
// whereas the FullMatrix stores them
// row-wise.
// We ignore that difference, and give our
// row-wise data to LAPACK,
// let LAPACK build the inverse of the
// transpose matrix, and read the result as
// if it were row-wise again. In other words,
// we just got ((A^T)^{-1})^T, which is
// A^{-1}.
const int nn = this->n();
double* values = const_cast<double*> (this->data());
ipiv.resize(nn);
int info;
// Use the LAPACK function getrf for
// calculating the LU factorization.
getrf(&nn, &nn, values, &nn, &ipiv[0], &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
inv_work.resize (nn);
// Use the LAPACK function getri for
// calculating the actual inverse using
// the LU factorization.
std::cout << " blas";
getri(&nn, values, &nn, &ipiv[0], &inv_work[0], &nn, &info);
std::cout << " 2 mal" << std::endl;
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
}
// ... and now the usual instantiations
// of gauss_jordan() and all the rest.
template void FullMatrix<long double>::gauss_jordan ();
template void FullMatrix<std::complex<float> >::gauss_jordan ();
template void FullMatrix<std::complex<double> >::gauss_jordan ();
template void FullMatrix<std::complex<long double> >::gauss_jordan ();
#else
template void FullMatrix<float>::gauss_jordan ();
template void FullMatrix<double>::gauss_jordan ();
template void FullMatrix<long double>::gauss_jordan ();
template void FullMatrix<std::complex<float> >::gauss_jordan ();
template void FullMatrix<std::complex<double> >::gauss_jordan ();
template void FullMatrix<std::complex<long double> >::gauss_jordan ();
#endif
#include "full_matrix.inst"
// do a few functions that currently don't fit the scheme because they have
// two template arguments that need to be different (the case of same
// arguments is covered by the default copy constructor and copy operator that
// is declared separately)
#define TEMPL_OP_EQ(S1,S2) \
template FullMatrix<S1>& FullMatrix<S1>::operator = \
(const FullMatrix<S2>&)
TEMPL_OP_EQ(double,float);
TEMPL_OP_EQ(float,double);
TEMPL_OP_EQ(long double,double);
TEMPL_OP_EQ(double,long double);
TEMPL_OP_EQ(long double,float);
TEMPL_OP_EQ(float,long double);
TEMPL_OP_EQ(std::complex<double>,std::complex<float>);
TEMPL_OP_EQ(std::complex<float>,std::complex<double>);
TEMPL_OP_EQ(std::complex<long double>,std::complex<double>);
TEMPL_OP_EQ(std::complex<double>,std::complex<long double>);
TEMPL_OP_EQ(std::complex<long double>,std::complex<float>);
TEMPL_OP_EQ(std::complex<float>,std::complex<long double>);
#undef TEMPL_OP_EQ
DEAL_II_NAMESPACE_CLOSE
<commit_msg>Can do a bit better by checking for DGETRF_ instead of LIBLACK only.<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <lac/full_matrix.templates.h>
#include <lac/lapack_templates.h>
#include <base/logstream.h>
DEAL_II_NAMESPACE_OPEN
// Need to explicitly state the Lapack
// inversion since it only works with
// floats and doubles in case LAPACK was
// detected by configure.
#if defined(HAVE_DGETRF_) && defined (HAVE_SGETRF_)
template <>
void
FullMatrix<float>::gauss_jordan ()
{
Assert (!this->empty(), ExcEmptyMatrix());
Assert (this->n_cols() == this->n_rows(), ExcNotQuadratic());
// In case we have the LAPACK functions
// getrf and getri detected at configure,
// we use these algorithms for inversion
// since they provide better performance
// than the deal.II native functions.
//
// Note that BLAS/LAPACK stores matrix
// elements column-wise (i.e., all values in
// one column, then all in the next, etc.),
// whereas the FullMatrix stores them
// row-wise.
// We ignore that difference, and give our
// row-wise data to LAPACK,
// let LAPACK build the inverse of the
// transpose matrix, and read the result as
// if it were row-wise again. In other words,
// we just got ((A^T)^{-1})^T, which is
// A^{-1}.
const int nn = this->n();
float* values = const_cast<float*> (this->data());
ipiv.resize(nn);
int info;
// Use the LAPACK function getrf for
// calculating the LU factorization.
getrf(&nn, &nn, values, &nn, &ipiv[0], &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
inv_work.resize (nn);
// Use the LAPACK function getri for
// calculating the actual inverse using
// the LU factorization.
getri(&nn, values, &nn, &ipiv[0], &inv_work[0], &nn, &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
}
template <>
void
FullMatrix<double>::gauss_jordan ()
{
Assert (!this->empty(), ExcEmptyMatrix());
Assert (this->n_cols() == this->n_rows(), ExcNotQuadratic());
// In case we have the LAPACK functions
// getrf and getri detected at configure,
// we use these algorithms for inversion
// since they provide better performance
// than the deal.II native functions.
//
// Note that BLAS/LAPACK stores matrix
// elements column-wise (i.e., all values in
// one column, then all in the next, etc.),
// whereas the FullMatrix stores them
// row-wise.
// We ignore that difference, and give our
// row-wise data to LAPACK,
// let LAPACK build the inverse of the
// transpose matrix, and read the result as
// if it were row-wise again. In other words,
// we just got ((A^T)^{-1})^T, which is
// A^{-1}.
const int nn = this->n();
double* values = const_cast<double*> (this->data());
ipiv.resize(nn);
int info;
// Use the LAPACK function getrf for
// calculating the LU factorization.
getrf(&nn, &nn, values, &nn, &ipiv[0], &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
inv_work.resize (nn);
// Use the LAPACK function getri for
// calculating the actual inverse using
// the LU factorization.
getri(&nn, values, &nn, &ipiv[0], &inv_work[0], &nn, &info);
Assert(info >= 0, ExcInternalError());
Assert(info == 0, LACExceptions::ExcSingular());
}
// ... and now the usual instantiations
// of gauss_jordan() and all the rest.
template void FullMatrix<long double>::gauss_jordan ();
template void FullMatrix<std::complex<float> >::gauss_jordan ();
template void FullMatrix<std::complex<double> >::gauss_jordan ();
template void FullMatrix<std::complex<long double> >::gauss_jordan ();
#else
template void FullMatrix<float>::gauss_jordan ();
template void FullMatrix<double>::gauss_jordan ();
template void FullMatrix<long double>::gauss_jordan ();
template void FullMatrix<std::complex<float> >::gauss_jordan ();
template void FullMatrix<std::complex<double> >::gauss_jordan ();
template void FullMatrix<std::complex<long double> >::gauss_jordan ();
#endif
#include "full_matrix.inst"
// do a few functions that currently don't fit the scheme because they have
// two template arguments that need to be different (the case of same
// arguments is covered by the default copy constructor and copy operator that
// is declared separately)
#define TEMPL_OP_EQ(S1,S2) \
template FullMatrix<S1>& FullMatrix<S1>::operator = \
(const FullMatrix<S2>&)
TEMPL_OP_EQ(double,float);
TEMPL_OP_EQ(float,double);
TEMPL_OP_EQ(long double,double);
TEMPL_OP_EQ(double,long double);
TEMPL_OP_EQ(long double,float);
TEMPL_OP_EQ(float,long double);
TEMPL_OP_EQ(std::complex<double>,std::complex<float>);
TEMPL_OP_EQ(std::complex<float>,std::complex<double>);
TEMPL_OP_EQ(std::complex<long double>,std::complex<double>);
TEMPL_OP_EQ(std::complex<double>,std::complex<long double>);
TEMPL_OP_EQ(std::complex<long double>,std::complex<float>);
TEMPL_OP_EQ(std::complex<float>,std::complex<long double>);
#undef TEMPL_OP_EQ
DEAL_II_NAMESPACE_CLOSE
<|endoftext|> |
<commit_before>/*
Persons Model
Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "personsmodeltest.h"
#include <personsmodel.h>
#include <personitem.h>
#include <contactitem.h>
#include <personactionsmodel.h>
#include <qtest_kde.h>
#include <Nepomuk2/Vocabulary/NCO>
#include <QStandardItemModel>
QTEST_KDEMAIN_CORE( PersonsModelTest )
PersonsModelTest::PersonsModelTest(QObject* parent): QObject(parent)
{}
void PersonsModelTest::testInit()
{
QBENCHMARK {
PersonsModel m(0, PersonsModel::FeatureIM);
QTest::kWaitForSignal(&m, SIGNAL(modelInitialized()));
}
}
void PersonsModelTest::testPhotos()
{
PersonsModel m(PersonsModel::FeatureAvatars, 0);
QTest::kWaitForSignal(&m, SIGNAL(modelInitialized()));
int count = 0;
QBENCHMARK {
for(int i=0; i<m.rowCount(); ++i) {
QModelIndex idx = m.index(i, 0);
QVariant ret = idx.data(PersonsModel::PhotoRole);
count += ret.toList().size();
}
}
QVERIFY(count>0); //there should be someone with photos...
}
void PersonsModelTest::testActions()
{
PersonsModel m(PersonsModel::FeatureEmails, 0);
QTest::kWaitForSignal(&m, SIGNAL(modelInitialized()));
for(int i=0; i<m.rowCount(); ++i) {
PersonActionsModel a;
a.setPerson(&m, i);
if (a.rowCount(QModelIndex()) == 0) {
qDebug() << "error: " << i << m.index(i, 0).data();
}
QVERIFY(a.rowCount(QModelIndex())>0);
}
}
<commit_msg>Fix role used in PersonsModelTest<commit_after>/*
Persons Model
Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "personsmodeltest.h"
#include <personsmodel.h>
#include <personitem.h>
#include <contactitem.h>
#include <personactionsmodel.h>
#include <qtest_kde.h>
#include <Nepomuk2/Vocabulary/NCO>
#include <QStandardItemModel>
QTEST_KDEMAIN_CORE( PersonsModelTest )
PersonsModelTest::PersonsModelTest(QObject* parent): QObject(parent)
{}
void PersonsModelTest::testInit()
{
QBENCHMARK {
PersonsModel m(0, PersonsModel::FeatureIM);
QTest::kWaitForSignal(&m, SIGNAL(modelInitialized()));
}
}
void PersonsModelTest::testPhotos()
{
PersonsModel m(PersonsModel::FeatureAvatars, 0);
QTest::kWaitForSignal(&m, SIGNAL(modelInitialized()));
int count = 0;
QBENCHMARK {
for(int i=0; i<m.rowCount(); ++i) {
QModelIndex idx = m.index(i, 0);
QVariant ret = idx.data(PersonsModel::PhotosRole);
count += ret.toList().size();
}
}
QVERIFY(count>0); //there should be someone with photos...
}
void PersonsModelTest::testActions()
{
PersonsModel m(PersonsModel::FeatureEmails, 0);
QTest::kWaitForSignal(&m, SIGNAL(modelInitialized()));
for(int i=0; i<m.rowCount(); ++i) {
PersonActionsModel a;
a.setPerson(&m, i);
if (a.rowCount(QModelIndex()) == 0) {
qDebug() << "error: " << i << m.index(i, 0).data();
}
QVERIFY(a.rowCount(QModelIndex())>0);
}
}
<|endoftext|> |
<commit_before>/*
* SessionDependencies.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionDependencies.hpp"
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/join.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/system/Environment.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/RExec.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionConsoleProcess.hpp>
#include <session/projects/SessionProjects.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace {
struct EmbeddedPackage
{
bool empty() const { return archivePath.empty(); }
std::string name;
std::string version;
std::string sha1;
std::string archivePath;
};
EmbeddedPackage embeddedPackageInfo(const std::string& name)
{
// determine location of archives
FilePath archivesDir = session::options().sessionPackageArchivesPath();
std::vector<FilePath> children;
Error error = archivesDir.children(&children);
if (error)
{
LOG_ERROR(error);
return EmbeddedPackage();
}
// we saw the regex with explicit character class ranges fail to match
// on a windows 8.1 system so we are falling back to a simpler regex
//
// (note see below for another approach involving setting the locale
// of the regex directly -- this assumes that the matching issue is
// somehow related to locales)
boost::regex re(name + "_([^_]+)_([^\\.]+)\\.tar\\.gz");
/* another approach (which we didn't try) based on setting the regex locale
boost::regex re;
re.imbue(std::locale("en_US.UTF-8"));
re.assign(name + "_([0-9]+\\.[0-9]+\\.[0-9]+)_([\\d\\w]+)\\.tar\\.gz");
*/
BOOST_FOREACH(const FilePath& child, children)
{
boost::smatch match;
std::string name = child.filename();
if (boost::regex_match(name, match, re))
{
EmbeddedPackage pkg;
pkg.name = name;
pkg.version = match[1];
pkg.sha1 = match[2];
pkg.archivePath = string_utils::utf8ToSystem(child.absolutePath());
return pkg;
}
}
// none found
return EmbeddedPackage();
}
} // anonymous namespace
namespace modules {
namespace dependencies {
namespace {
const int kCRANPackageDependency = 0;
const int kEmbeddedPackageDependency = 1;
struct Dependency
{
Dependency() : type(0), source(false), versionSatisfied(true) {}
bool empty() const { return name.empty(); }
int type;
std::string name;
std::string version;
bool source;
std::string availableVersion;
bool versionSatisfied;
};
std::string nameFromDep(const Dependency& dep)
{
return dep.name;
}
std::vector<std::string> packageNames(const std::vector<Dependency> deps)
{
std::vector<std::string> names;
std::transform(deps.begin(),
deps.end(),
std::back_inserter(names),
nameFromDep);
return names;
}
std::vector<Dependency> dependenciesFromJson(const json::Array& depsJson)
{
std::vector<Dependency> deps;
BOOST_FOREACH(const json::Value& depJsonValue, depsJson)
{
if (json::isType<json::Object>(depJsonValue))
{
Dependency dep;
json::Object depJson = depJsonValue.get_obj();
Error error = json::readObject(depJson,
"type", &(dep.type),
"name", &(dep.name),
"version", &(dep.version),
"source", &(dep.source));
if (!error)
{
deps.push_back(dep);
}
else
{
LOG_ERROR(error);
}
}
}
return deps;
}
json::Array dependenciesToJson(const std::vector<Dependency>& deps)
{
json::Array depsJson;
BOOST_FOREACH(const Dependency& dep, deps)
{
json::Object depJson;
depJson["type"] = dep.type;
depJson["name"] = dep.name;
depJson["version"] = dep.version;
depJson["source"] = dep.source;
depJson["available_version"] = dep.availableVersion;
depJson["version_satisfied"] = dep.versionSatisfied;
depsJson.push_back(depJson);
}
return depsJson;
}
bool embeddedPackageRequiresUpdate(const EmbeddedPackage& pkg)
{
// if this package came from the rstudio ide then check if it needs
// an update (i.e. has a different SHA1)
r::exec::RFunction func(".rs.rstudioIDEPackageRequiresUpdate",
pkg.name, pkg.sha1);
bool requiresUpdate = false;
Error error = func.call(&requiresUpdate);
if (error)
LOG_ERROR(error);
return requiresUpdate;
}
void silentUpdateEmbeddedPackage(const EmbeddedPackage& pkg)
{
// suppress output which occurs during silent update
r::session::utils::SuppressOutputInScope suppressOutput;
Error error = r::exec::RFunction(".rs.updateRStudioIDEPackage",
pkg.name, pkg.archivePath).call();
if (error)
LOG_ERROR(error);
}
Error unsatisfiedDependencies(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get list of dependencies and silentUpdate flag
json::Array depsJson;
bool silentUpdate;
Error error = json::readParams(request.params, &depsJson, &silentUpdate);
if (error)
return error;
std::vector<Dependency> deps = dependenciesFromJson(depsJson);
// build the list of unsatisifed dependencies
using namespace module_context;
std::vector<Dependency> unsatisfiedDeps;
BOOST_FOREACH(Dependency& dep, deps)
{
switch(dep.type)
{
case kCRANPackageDependency:
if (!isPackageVersionInstalled(dep.name, dep.version))
{
// presume package is available unless we can demonstrate otherwise
// (we don't want to block installation attempt unless we're
// reasonably confident it will not result in a viable version)
r::sexp::Protect protect;
SEXP versionInfo = R_NilValue;
// find the version that will be installed from CRAN
error = r::exec::RFunction(".rs.packageCRANVersionAvailable",
dep.name, dep.version, dep.source).call(&versionInfo, &protect);
if (error) {
LOG_ERROR(error);
} else {
// if these fail, we'll fall back on defaults set above
r::sexp::getNamedListElement(versionInfo, "version",
&dep.availableVersion);
r::sexp::getNamedListElement(versionInfo, "satisfied",
&dep.versionSatisfied);
}
unsatisfiedDeps.push_back(dep);
}
break;
case kEmbeddedPackageDependency:
EmbeddedPackage pkg = embeddedPackageInfo(dep.name);
// package isn't installed so report that it reqires installation
if (!isPackageInstalled(dep.name))
{
unsatisfiedDeps.push_back(dep);
}
// silent update if necessary (as long as we aren't packified)
else if (silentUpdate && !packratContext().packified)
{
// package installed was from IDE but is out of date
if (embeddedPackageRequiresUpdate(pkg))
{
silentUpdateEmbeddedPackage(pkg);
}
// package installed wasn't from the IDE but is older than
// the version we currently have embedded
else if (!isPackageVersionInstalled(pkg.name, pkg.version))
{
silentUpdateEmbeddedPackage(pkg);
}
else
{
// the only remaining case is a newer version of the package is
// already installed (e.g. directly from github). in this case
// we do nothing
}
}
break;
}
}
// return unsatisfied dependencies
pResponse->setResult(dependenciesToJson(unsatisfiedDeps));
return Success();
}
Error installDependencies(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get list of dependencies
json::Array depsJson;
Error error = json::readParams(request.params, &depsJson);
if (error)
return error;
std::vector<Dependency> deps = dependenciesFromJson(depsJson);
// Ensure we have a writeable user library
error = r::exec::RFunction(".rs.ensureWriteableUserLibrary").call();
if (error)
return error;
// force unload as necessary
std::vector<std::string> names = packageNames(deps);
error = r::exec::RFunction(".rs.forceUnloadForPackageInstall", names).call();
if (error)
LOG_ERROR(error);
// R binary
FilePath rProgramPath;
error = module_context::rScriptPath(&rProgramPath);
if (error)
return error;
// options
core::system::ProcessOptions options;
options.terminateChildren = true;
options.redirectStdErrToStdOut = true;
// build lists of cran packages and archives
std::vector<std::string> cranPackages;
std::vector<std::string> cranSourcePackages;
std::vector<std::string> embeddedPackages;
BOOST_FOREACH(const Dependency& dep, deps)
{
switch(dep.type)
{
case kCRANPackageDependency:
if (dep.source)
cranSourcePackages.push_back("'" + dep.name + "'");
else
cranPackages.push_back("'" + dep.name + "'");
break;
case kEmbeddedPackageDependency:
EmbeddedPackage pkg = embeddedPackageInfo(dep.name);
if (!pkg.empty())
embeddedPackages.push_back(pkg.archivePath);
break;
}
}
// build install command
std::string cmd("{ " + module_context::CRANDownloadOptions() + "; ");
if (!cranPackages.empty())
{
std::string pkgList = boost::algorithm::join(cranPackages, ",");
cmd += "utils::install.packages(c(" + pkgList + "), " +
"repos = '"+ module_context::CRANReposURL() + "'";
cmd += ");";
}
if (!cranSourcePackages.empty())
{
std::string pkgList = boost::algorithm::join(cranSourcePackages, ",");
cmd += "utils::install.packages(c(" + pkgList + "), " +
"repos = '"+ module_context::CRANReposURL() + "', ";
cmd += "type = 'source');";
}
BOOST_FOREACH(const std::string& pkg, embeddedPackages)
{
cmd += "utils::install.packages('" + pkg + "', "
"repos = NULL, type = 'source');";
}
cmd += "}";
// build args
std::vector<std::string> args;
args.push_back("--slave");
// for packrat projects we execute the profile and set the working
// directory to the project directory; for other contexts we just
// propagate the R_LIBS
if (module_context::packratContext().modeOn)
{
options.workingDir = projects::projectContext().directory();
}
else
{
args.push_back("--vanilla");
core::system::Options childEnv;
core::system::environment(&childEnv);
std::string libPaths = module_context::libPathsString();
if (!libPaths.empty())
core::system::setenv(&childEnv, "R_LIBS", libPaths);
options.environment = childEnv;
}
// for windows we need to forward setInternet2
#ifdef _WIN32
if (!r::session::utils::isR3_3() && userSettings().useInternet2())
args.push_back("--internet2");
#endif
args.push_back("-e");
args.push_back(cmd);
// create and execute console process
boost::shared_ptr<console_process::ConsoleProcess> pCP;
pCP = console_process::ConsoleProcess::create(
string_utils::utf8ToSystem(rProgramPath.absolutePath()),
args,
options,
"Installing Packages",
true,
console_process::InteractionNever);
// return console process
pResponse->setResult(pCP->toJson());
return Success();
}
} // anonymous namespace
Error initialize()
{
// install handlers
using boost::bind;
using namespace session::module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "unsatisfied_dependencies", unsatisfiedDependencies))
(bind(registerRpcMethod, "install_dependencies", installDependencies));
return initBlock.execute();
}
} // namepsace dependencies
} // namespace modules
namespace module_context {
Error installEmbeddedPackage(const std::string& name)
{
EmbeddedPackage pkg = embeddedPackageInfo(name);
return module_context::installPackage(pkg.archivePath);
}
} // anonymous namespace
} // namesapce session
} // namespace rstudio
<commit_msg>avoid shadowing 'name' variable<commit_after>/*
* SessionDependencies.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionDependencies.hpp"
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/join.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/system/Environment.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/RExec.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionConsoleProcess.hpp>
#include <session/projects/SessionProjects.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace {
struct EmbeddedPackage
{
bool empty() const { return archivePath.empty(); }
std::string name;
std::string version;
std::string sha1;
std::string archivePath;
};
EmbeddedPackage embeddedPackageInfo(const std::string& name)
{
// determine location of archives
FilePath archivesDir = session::options().sessionPackageArchivesPath();
std::vector<FilePath> children;
Error error = archivesDir.children(&children);
if (error)
{
LOG_ERROR(error);
return EmbeddedPackage();
}
// we saw the regex with explicit character class ranges fail to match
// on a windows 8.1 system so we are falling back to a simpler regex
//
// (note see below for another approach involving setting the locale
// of the regex directly -- this assumes that the matching issue is
// somehow related to locales)
boost::regex re(name + "_([^_]+)_([^\\.]+)\\.tar\\.gz");
/* another approach (which we didn't try) based on setting the regex locale
boost::regex re;
re.imbue(std::locale("en_US.UTF-8"));
re.assign(name + "_([0-9]+\\.[0-9]+\\.[0-9]+)_([\\d\\w]+)\\.tar\\.gz");
*/
BOOST_FOREACH(const FilePath& child, children)
{
boost::smatch match;
std::string filename = child.filename();
if (boost::regex_match(filename, match, re))
{
EmbeddedPackage pkg;
pkg.name = name;
pkg.version = match[1];
pkg.sha1 = match[2];
pkg.archivePath = string_utils::utf8ToSystem(child.absolutePath());
return pkg;
}
}
// none found
return EmbeddedPackage();
}
} // anonymous namespace
namespace modules {
namespace dependencies {
namespace {
const int kCRANPackageDependency = 0;
const int kEmbeddedPackageDependency = 1;
struct Dependency
{
Dependency() : type(0), source(false), versionSatisfied(true) {}
bool empty() const { return name.empty(); }
int type;
std::string name;
std::string version;
bool source;
std::string availableVersion;
bool versionSatisfied;
};
std::string nameFromDep(const Dependency& dep)
{
return dep.name;
}
std::vector<std::string> packageNames(const std::vector<Dependency> deps)
{
std::vector<std::string> names;
std::transform(deps.begin(),
deps.end(),
std::back_inserter(names),
nameFromDep);
return names;
}
std::vector<Dependency> dependenciesFromJson(const json::Array& depsJson)
{
std::vector<Dependency> deps;
BOOST_FOREACH(const json::Value& depJsonValue, depsJson)
{
if (json::isType<json::Object>(depJsonValue))
{
Dependency dep;
json::Object depJson = depJsonValue.get_obj();
Error error = json::readObject(depJson,
"type", &(dep.type),
"name", &(dep.name),
"version", &(dep.version),
"source", &(dep.source));
if (!error)
{
deps.push_back(dep);
}
else
{
LOG_ERROR(error);
}
}
}
return deps;
}
json::Array dependenciesToJson(const std::vector<Dependency>& deps)
{
json::Array depsJson;
BOOST_FOREACH(const Dependency& dep, deps)
{
json::Object depJson;
depJson["type"] = dep.type;
depJson["name"] = dep.name;
depJson["version"] = dep.version;
depJson["source"] = dep.source;
depJson["available_version"] = dep.availableVersion;
depJson["version_satisfied"] = dep.versionSatisfied;
depsJson.push_back(depJson);
}
return depsJson;
}
bool embeddedPackageRequiresUpdate(const EmbeddedPackage& pkg)
{
// if this package came from the rstudio ide then check if it needs
// an update (i.e. has a different SHA1)
r::exec::RFunction func(".rs.rstudioIDEPackageRequiresUpdate",
pkg.name, pkg.sha1);
bool requiresUpdate = false;
Error error = func.call(&requiresUpdate);
if (error)
LOG_ERROR(error);
return requiresUpdate;
}
void silentUpdateEmbeddedPackage(const EmbeddedPackage& pkg)
{
// suppress output which occurs during silent update
r::session::utils::SuppressOutputInScope suppressOutput;
Error error = r::exec::RFunction(".rs.updateRStudioIDEPackage",
pkg.name, pkg.archivePath).call();
if (error)
LOG_ERROR(error);
}
Error unsatisfiedDependencies(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get list of dependencies and silentUpdate flag
json::Array depsJson;
bool silentUpdate;
Error error = json::readParams(request.params, &depsJson, &silentUpdate);
if (error)
return error;
std::vector<Dependency> deps = dependenciesFromJson(depsJson);
// build the list of unsatisifed dependencies
using namespace module_context;
std::vector<Dependency> unsatisfiedDeps;
BOOST_FOREACH(Dependency& dep, deps)
{
switch(dep.type)
{
case kCRANPackageDependency:
if (!isPackageVersionInstalled(dep.name, dep.version))
{
// presume package is available unless we can demonstrate otherwise
// (we don't want to block installation attempt unless we're
// reasonably confident it will not result in a viable version)
r::sexp::Protect protect;
SEXP versionInfo = R_NilValue;
// find the version that will be installed from CRAN
error = r::exec::RFunction(".rs.packageCRANVersionAvailable",
dep.name, dep.version, dep.source).call(&versionInfo, &protect);
if (error) {
LOG_ERROR(error);
} else {
// if these fail, we'll fall back on defaults set above
r::sexp::getNamedListElement(versionInfo, "version",
&dep.availableVersion);
r::sexp::getNamedListElement(versionInfo, "satisfied",
&dep.versionSatisfied);
}
unsatisfiedDeps.push_back(dep);
}
break;
case kEmbeddedPackageDependency:
EmbeddedPackage pkg = embeddedPackageInfo(dep.name);
// package isn't installed so report that it reqires installation
if (!isPackageInstalled(dep.name))
{
unsatisfiedDeps.push_back(dep);
}
// silent update if necessary (as long as we aren't packified)
else if (silentUpdate && !packratContext().packified)
{
// package installed was from IDE but is out of date
if (embeddedPackageRequiresUpdate(pkg))
{
silentUpdateEmbeddedPackage(pkg);
}
// package installed wasn't from the IDE but is older than
// the version we currently have embedded
else if (!isPackageVersionInstalled(pkg.name, pkg.version))
{
silentUpdateEmbeddedPackage(pkg);
}
else
{
// the only remaining case is a newer version of the package is
// already installed (e.g. directly from github). in this case
// we do nothing
}
}
break;
}
}
// return unsatisfied dependencies
pResponse->setResult(dependenciesToJson(unsatisfiedDeps));
return Success();
}
Error installDependencies(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// get list of dependencies
json::Array depsJson;
Error error = json::readParams(request.params, &depsJson);
if (error)
return error;
std::vector<Dependency> deps = dependenciesFromJson(depsJson);
// Ensure we have a writeable user library
error = r::exec::RFunction(".rs.ensureWriteableUserLibrary").call();
if (error)
return error;
// force unload as necessary
std::vector<std::string> names = packageNames(deps);
error = r::exec::RFunction(".rs.forceUnloadForPackageInstall", names).call();
if (error)
LOG_ERROR(error);
// R binary
FilePath rProgramPath;
error = module_context::rScriptPath(&rProgramPath);
if (error)
return error;
// options
core::system::ProcessOptions options;
options.terminateChildren = true;
options.redirectStdErrToStdOut = true;
// build lists of cran packages and archives
std::vector<std::string> cranPackages;
std::vector<std::string> cranSourcePackages;
std::vector<std::string> embeddedPackages;
BOOST_FOREACH(const Dependency& dep, deps)
{
switch(dep.type)
{
case kCRANPackageDependency:
if (dep.source)
cranSourcePackages.push_back("'" + dep.name + "'");
else
cranPackages.push_back("'" + dep.name + "'");
break;
case kEmbeddedPackageDependency:
EmbeddedPackage pkg = embeddedPackageInfo(dep.name);
if (!pkg.empty())
embeddedPackages.push_back(pkg.archivePath);
break;
}
}
// build install command
std::string cmd("{ " + module_context::CRANDownloadOptions() + "; ");
if (!cranPackages.empty())
{
std::string pkgList = boost::algorithm::join(cranPackages, ",");
cmd += "utils::install.packages(c(" + pkgList + "), " +
"repos = '"+ module_context::CRANReposURL() + "'";
cmd += ");";
}
if (!cranSourcePackages.empty())
{
std::string pkgList = boost::algorithm::join(cranSourcePackages, ",");
cmd += "utils::install.packages(c(" + pkgList + "), " +
"repos = '"+ module_context::CRANReposURL() + "', ";
cmd += "type = 'source');";
}
BOOST_FOREACH(const std::string& pkg, embeddedPackages)
{
cmd += "utils::install.packages('" + pkg + "', "
"repos = NULL, type = 'source');";
}
cmd += "}";
// build args
std::vector<std::string> args;
args.push_back("--slave");
// for packrat projects we execute the profile and set the working
// directory to the project directory; for other contexts we just
// propagate the R_LIBS
if (module_context::packratContext().modeOn)
{
options.workingDir = projects::projectContext().directory();
}
else
{
args.push_back("--vanilla");
core::system::Options childEnv;
core::system::environment(&childEnv);
std::string libPaths = module_context::libPathsString();
if (!libPaths.empty())
core::system::setenv(&childEnv, "R_LIBS", libPaths);
options.environment = childEnv;
}
// for windows we need to forward setInternet2
#ifdef _WIN32
if (!r::session::utils::isR3_3() && userSettings().useInternet2())
args.push_back("--internet2");
#endif
args.push_back("-e");
args.push_back(cmd);
// create and execute console process
boost::shared_ptr<console_process::ConsoleProcess> pCP;
pCP = console_process::ConsoleProcess::create(
string_utils::utf8ToSystem(rProgramPath.absolutePath()),
args,
options,
"Installing Packages",
true,
console_process::InteractionNever);
// return console process
pResponse->setResult(pCP->toJson());
return Success();
}
} // anonymous namespace
Error initialize()
{
// install handlers
using boost::bind;
using namespace session::module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "unsatisfied_dependencies", unsatisfiedDependencies))
(bind(registerRpcMethod, "install_dependencies", installDependencies));
return initBlock.execute();
}
} // namepsace dependencies
} // namespace modules
namespace module_context {
Error installEmbeddedPackage(const std::string& name)
{
EmbeddedPackage pkg = embeddedPackageInfo(name);
return module_context::installPackage(pkg.archivePath);
}
} // anonymous namespace
} // namesapce session
} // namespace rstudio
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2017 Roman Lebedev
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.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "RawSpeed-API.h" // for RawDecoder, Buffer, FileReader
#include <benchmark/benchmark.h> // for State, Benchmark, DoNotOptimize
#include <chrono> // for duration, high_resolution_clock
#include <ctime> // for clock, clock_t
#include <map> // for map<>::mapped_type
#include <memory> // for unique_ptr
#include <ratio> // for milli, ratio
#include <string> // for string, to_string
// IWYU pragma: no_include <sys/time.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define HAVE_STEADY_CLOCK
using rawspeed::CameraMetaData;
using rawspeed::FileReader;
using rawspeed::RawImage;
using rawspeed::RawParser;
namespace {
struct CPUClock {
using rep = std::clock_t;
using period = std::ratio<1, CLOCKS_PER_SEC>;
using duration = std::chrono::duration<rep, period>;
using time_point = std::chrono::time_point<CPUClock, duration>;
// static constexpr bool is_steady = false;
static time_point now() noexcept {
return time_point{duration{std::clock()}};
}
};
#if defined(HAVE_STEADY_CLOCK)
template <bool HighResIsSteady = std::chrono::high_resolution_clock::is_steady>
struct ChooseSteadyClock {
using type = std::chrono::high_resolution_clock;
};
template <> struct ChooseSteadyClock<false> {
using type = std::chrono::steady_clock;
};
#endif
struct ChooseClockType {
#if defined(HAVE_STEADY_CLOCK)
using type = ChooseSteadyClock<>::type;
#else
using type = std::chrono::high_resolution_clock;
#endif
};
template <typename Clock, typename period = std::ratio<1, 1>> struct Timer {
using rep = double;
using duration = std::chrono::duration<rep, period>;
mutable typename Clock::time_point start = Clock::now();
duration operator()() const {
duration elapsed = Clock::now() - start;
start = Clock::now();
return elapsed;
}
};
} // namespace
static int currThreadCount;
extern "C" int __attribute__((pure)) rawspeed_get_number_of_processor_cores() {
return currThreadCount;
}
static inline void BM_RawSpeed(benchmark::State& state, const char* fileName,
int threads) {
currThreadCount = threads;
#ifdef HAVE_PUGIXML
static const CameraMetaData metadata(CMAKE_SOURCE_DIR "/data/cameras.xml");
#else
static const CameraMetaData metadata{};
#endif
FileReader reader(fileName);
const auto map(reader.readFile());
Timer<ChooseClockType::type> WT;
Timer<CPUClock> TT;
for (auto _ : state) {
RawParser parser(map.get());
auto decoder(parser.getDecoder(&metadata));
decoder->failOnUnknown = false;
decoder->checkSupport(&metadata);
decoder->decodeRaw();
decoder->decodeMetaData(&metadata);
RawImage raw = decoder->mRaw;
benchmark::DoNotOptimize(raw);
}
std::string label("FileSize,KB=");
label += std::to_string(map->getSize() / (1UL << 10UL));
state.SetLabel(label.c_str());
const auto WallTime = WT();
const auto TotalTime = TT();
const auto ThreadingFactor = TotalTime.count() / WallTime.count();
state.counters["CPUTime,s"] = TotalTime.count();
state.counters["ThreadingFactor"] = ThreadingFactor;
state.SetItemsProcessed(state.iterations());
state.SetBytesProcessed(state.iterations() * map->getSize());
}
static void addBench(const char* fName, std::string tName, int threads) {
tName += std::to_string(threads);
auto* b =
benchmark::RegisterBenchmark(tName.c_str(), &BM_RawSpeed, fName, threads);
b->Unit(benchmark::kMillisecond);
b->UseRealTime();
}
int main(int argc, char** argv) {
benchmark::Initialize(&argc, argv);
auto hasFlag = [argc, argv](std::string flag) {
bool found = false;
for (int i = 1; i < argc; ++i) {
if (!argv[i] || argv[i] != flag)
continue;
found = true;
argv[i] = nullptr;
}
return found;
};
bool threading = hasFlag("-t");
#ifdef _OPENMP
const auto threadsMax = omp_get_num_procs();
#else
const auto threadsMax = 1;
#endif
const auto threadsMin = threading ? 1 : threadsMax;
for (int i = 1; i < argc; i++) {
if (!argv[i])
continue;
const char* fName = argv[i];
std::string tName(fName);
tName += "/threads:";
for (auto threads = threadsMin; threads <= threadsMax; threads++)
addBench(fName, tName, threads);
}
benchmark::RunSpecifiedBenchmarks();
}
<commit_msg>rsbench: show image's pixel count<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2017 Roman Lebedev
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.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "RawSpeed-API.h" // for RawDecoder, Buffer, FileReader
#include <benchmark/benchmark.h> // for State, Benchmark, DoNotOptimize
#include <chrono> // for duration, high_resolution_clock
#include <ctime> // for clock, clock_t
#include <map> // for map<>::mapped_type
#include <memory> // for unique_ptr
#include <ratio> // for milli, ratio
#include <string> // for string, to_string
// IWYU pragma: no_include <sys/time.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define HAVE_STEADY_CLOCK
using rawspeed::CameraMetaData;
using rawspeed::FileReader;
using rawspeed::RawImage;
using rawspeed::RawParser;
namespace {
struct CPUClock {
using rep = std::clock_t;
using period = std::ratio<1, CLOCKS_PER_SEC>;
using duration = std::chrono::duration<rep, period>;
using time_point = std::chrono::time_point<CPUClock, duration>;
// static constexpr bool is_steady = false;
static time_point now() noexcept {
return time_point{duration{std::clock()}};
}
};
#if defined(HAVE_STEADY_CLOCK)
template <bool HighResIsSteady = std::chrono::high_resolution_clock::is_steady>
struct ChooseSteadyClock {
using type = std::chrono::high_resolution_clock;
};
template <> struct ChooseSteadyClock<false> {
using type = std::chrono::steady_clock;
};
#endif
struct ChooseClockType {
#if defined(HAVE_STEADY_CLOCK)
using type = ChooseSteadyClock<>::type;
#else
using type = std::chrono::high_resolution_clock;
#endif
};
template <typename Clock, typename period = std::ratio<1, 1>> struct Timer {
using rep = double;
using duration = std::chrono::duration<rep, period>;
mutable typename Clock::time_point start = Clock::now();
duration operator()() const {
duration elapsed = Clock::now() - start;
start = Clock::now();
return elapsed;
}
};
} // namespace
static int currThreadCount;
extern "C" int __attribute__((pure)) rawspeed_get_number_of_processor_cores() {
return currThreadCount;
}
static inline void BM_RawSpeed(benchmark::State& state, const char* fileName,
int threads) {
currThreadCount = threads;
#ifdef HAVE_PUGIXML
static const CameraMetaData metadata(CMAKE_SOURCE_DIR "/data/cameras.xml");
#else
static const CameraMetaData metadata{};
#endif
FileReader reader(fileName);
const auto map(reader.readFile());
Timer<ChooseClockType::type> WT;
Timer<CPUClock> TT;
unsigned pixels = 0;
for (auto _ : state) {
RawParser parser(map.get());
auto decoder(parser.getDecoder(&metadata));
decoder->failOnUnknown = false;
decoder->checkSupport(&metadata);
decoder->decodeRaw();
decoder->decodeMetaData(&metadata);
RawImage raw = decoder->mRaw;
benchmark::DoNotOptimize(raw);
pixels = raw->getUncroppedDim().area();
}
std::string label("FileSize,MB=");
label += std::to_string(double(map->getSize()) / double(1UL << 20UL));
label += "; MPix=";
label += std::to_string(double(pixels) / 1e+06);
state.SetLabel(label.c_str());
const auto WallTime = WT();
const auto TotalTime = TT();
const auto ThreadingFactor = TotalTime.count() / WallTime.count();
state.counters.insert({
{"Pixels/s", benchmark::Counter(pixels, benchmark::Counter::kIsRate)},
{"CPUTime,s", TotalTime.count()},
{"ThreadingFactor", ThreadingFactor},
});
state.SetItemsProcessed(state.iterations());
state.SetBytesProcessed(state.iterations() * map->getSize());
}
static void addBench(const char* fName, std::string tName, int threads) {
tName += std::to_string(threads);
auto* b =
benchmark::RegisterBenchmark(tName.c_str(), &BM_RawSpeed, fName, threads);
b->Unit(benchmark::kMillisecond);
b->UseRealTime();
}
int main(int argc, char** argv) {
benchmark::Initialize(&argc, argv);
auto hasFlag = [argc, argv](std::string flag) {
bool found = false;
for (int i = 1; i < argc; ++i) {
if (!argv[i] || argv[i] != flag)
continue;
found = true;
argv[i] = nullptr;
}
return found;
};
bool threading = hasFlag("-t");
#ifdef _OPENMP
const auto threadsMax = omp_get_num_procs();
#else
const auto threadsMax = 1;
#endif
const auto threadsMin = threading ? 1 : threadsMax;
for (int i = 1; i < argc; i++) {
if (!argv[i])
continue;
const char* fName = argv[i];
std::string tName(fName);
tName += "/threads:";
for (auto threads = threadsMin; threads <= threadsMax; threads++)
addBench(fName, tName, threads);
}
benchmark::RunSpecifiedBenchmarks();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
// todo r2m adaptation : remove this
//#include "t_hash.h"
#include "ssdb_impl.h"
#include "codec/encode.h"
#include "codec/decode.h"
static int hset_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, const Bytes &val, char log_type);
static int hdel_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, char log_type);
static int incr_hsize(SSDBImpl *ssdb, const Bytes &name, int64_t incr);
/**
* @return -1: error, 0: item updated, 1: new item inserted
*/
int SSDBImpl::hset(const Bytes &name, const Bytes &key, const Bytes &val, char log_type){
Transaction trans(binlogs);
int ret = hset_one(this, name, key, val, log_type);
if(ret >= 0){
if(ret > 0){
if(incr_hsize(this, name, ret) == -1){
return -1;
}
}
leveldb::Status s = binlogs->commit();
if(!s.ok()){
return -1;
}
}
return ret;
}
int SSDBImpl::hdel(const Bytes &name, const Bytes &key, char log_type){
Transaction trans(binlogs);
int ret = hdel_one(this, name, key, log_type);
if(ret >= 0){
if(ret > 0){
if(incr_hsize(this, name, -ret) == -1){
return -1;
}
}
leveldb::Status s = binlogs->commit();
if(!s.ok()){
return -1;
}
}
return ret;
}
int SSDBImpl::hincr(const Bytes &name, const Bytes &key, int64_t by, int64_t *new_val, char log_type){
Transaction trans(binlogs);
std::string old;
int ret = this->hget(name, key, &old);
if(ret == -1){
return -1;
}else if(ret == 0){
*new_val = by;
}else{
*new_val = str_to_int64(old) + by;
if(errno != 0){
return 0;
}
}
ret = hset_one(this, name, key, str(*new_val), log_type);
if(ret == -1){
return -1;
}
if(ret >= 0){
if(ret > 0){
if(incr_hsize(this, name, ret) == -1){
return -1;
}
}
leveldb::Status s = binlogs->commit();
if(!s.ok()){
return -1;
}
}
return 1;
}
int64_t SSDBImpl::hsize(const Bytes &name){
HashMetaVal hv;
std::string size_key = encode_meta_key(name);
int ret = GetHashMetaVal(size_key, hv);
if (ret != 1){
return ret;
} else{
return (int64_t)hv.length;
}
}
int SSDBImpl::HDelKeyNoLock(const Bytes &name, char log_type){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (ret != 1){
return ret;
}
HIterator *it = this->hscan_internal(name, "", "", hv.version, -1);
int num = 0;
while(it->next()){
ret = hdel_one(this, name, it->key, log_type);
if (-1 == ret){
return -1;
} else if (ret > 0){
num++;
}
}
if (num > 0){
if(incr_hsize(this, name, -num) == -1){
return -1;
}
}
return num;
}
int64_t SSDBImpl::hclear(const Bytes &name){
Transaction trans(binlogs);
int num = HDelKeyNoLock(name);
if (num > 0){
leveldb::Status s = binlogs->commit();
if (!s.ok()){
return -1;
}
}
return num;
}
int SSDBImpl::hget(const Bytes &name, const Bytes &key, std::string *val){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (ret != 1){
return ret;
}
std::string dbkey = encode_hash_key(name, key, hv.version);
leveldb::Status s = ldb->Get(leveldb::ReadOptions(), dbkey, val);
if(s.IsNotFound()){
return 0;
}
if(!s.ok()){
log_error("%s", s.ToString().c_str());
return -1;
}
return 1;
}
HIterator* SSDBImpl::hscan(const Bytes &name, const Bytes &start, const Bytes &end, uint64_t limit){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (0 == ret && hv.del == KEY_DELETE_MASK){
return hscan_internal(name, start, end, hv.version+1, limit);
} else if (ret > 0){
return hscan_internal(name, start, end, hv.version, limit);
} else{
return hscan_internal(name, start, end, 0, limit);
}
}
HIterator* SSDBImpl::hscan_internal(const Bytes &name, const Bytes &start, const Bytes &end, uint16_t version, uint64_t limit){
std::string key_start, key_end;
key_start = encode_hash_key(name, start, version);
if(!end.empty()){
key_end = encode_hash_key(name, end, version);
}
return new HIterator(this->iterator(key_start, key_end, limit), name, version);
}
HIterator* SSDBImpl::hrscan_internal(const Bytes &name, const Bytes &start, const Bytes &end, uint16_t version, uint64_t limit){
std::string key_start, key_end;
key_start = encode_hash_key(name, start, version);
if(start.empty()){
key_start.append(1, 255);
}
if(!end.empty()){
key_end = encode_hash_key(name, end, version);
}
return new HIterator(this->rev_iterator(key_start, key_end, limit), name, version);
}
HIterator* SSDBImpl::hrscan(const Bytes &name, const Bytes &start, const Bytes &end, uint64_t limit){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (0 == ret && hv.del == KEY_DELETE_MASK){
return hrscan_internal(name, start, end, hv.version+1, limit);
} else if (ret > 0){
return hrscan_internal(name, start, end, hv.version, limit);
} else{
return hrscan_internal(name, start, end, 0, limit);
}
}
/*// todo r2m adaptation //编码规则决定无法支持该操作,redis也不支持该操作
static void get_hnames(Iterator *it, std::vector<std::string> *list){
while(it->next()){
Bytes ks = it->key();
if(ks.data()[0] != DataType::HSIZE){
break;
}
std::string n;
if(decode_hsize_key(ks, &n) == -1){
continue;
}
list->push_back(n);
}
}*/
// todo r2m adaptation
int SSDBImpl::hlist(const Bytes &name_s, const Bytes &name_e, uint64_t limit,
std::vector<std::string> *list){
/* std::string start;
std::string end;
start = encode_hsize_key(name_s);
if(!name_e.empty()){
end = encode_hsize_key(name_e);
}
Iterator *it = this->iterator(start, end, limit);
get_hnames(it, list);
delete it;*/
return 0;
}
// todo r2m adaptation
int SSDBImpl::hrlist(const Bytes &name_s, const Bytes &name_e, uint64_t limit,
std::vector<std::string> *list){
/* std::string start;
std::string end;
start = encode_hsize_key(name_s);
if(name_s.empty()){
start.append(1, 255);
}
if(!name_e.empty()){
end = encode_hsize_key(name_e);
}
Iterator *it = this->rev_iterator(start, end, limit);
get_hnames(it, list);
delete it;*/
return 0;
}
int SSDBImpl::GetHashMetaVal(const std::string &meta_key, HashMetaVal &hv){
std::string meta_val;
leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &meta_val);
if (s.IsNotFound()){
return 0;
} else if (!s.ok() && !s.IsNotFound()){
return -1;
} else{
int ret = hv.DecodeMetaVal(meta_val);
if (ret == -1 || hv.type != DataType::HSIZE){
return -1;
} else if (hv.del == KEY_DELETE_MASK){
return 0;
}
}
return 1;
}
int SSDBImpl::GetHashItemValInternal(const std::string &item_key, std::string *val){
leveldb::Status s = ldb->Get(leveldb::ReadOptions(), item_key, val);
if (s.IsNotFound()){
return 0;
} else if (!s.ok() && !s.IsNotFound()){
return -1;
}
return 1;
}
// returns the number of newly added items
static int hset_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, const Bytes &val, char log_type){
int ret = 0;
std::string dbval;
HashMetaVal hv;
std::string meta_key = encode_meta_key(name.String());
ret = ssdb->GetHashMetaVal(meta_key, hv);
if (ret == -1){
return -1;
} else if (ret == 0 && hv.del == KEY_DELETE_MASK){
std::string hkey = encode_hash_key(name, key, (uint16_t)(hv.version+1));
ssdb->binlogs->Put(hkey, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, hkey);
ret = 1;
} else if (ret == 0){
std::string hkey = encode_hash_key(name, key);
ssdb->binlogs->Put(hkey, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, hkey);
ret = 1;
} else{
std::string item_key = encode_hash_key(name, key, hv.version);
ret = ssdb->GetHashItemValInternal(item_key, &dbval);
if (ret == -1){
return -1;
} else if (ret == 0){
ssdb->binlogs->Put(item_key, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, item_key);
ret = 1;
} else{
if(dbval != val){
ssdb->binlogs->Put(item_key, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, item_key);
}
ret = 0;
}
}
return ret;
}
static int hdel_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, char log_type){
int ret = 0;
std::string dbval;
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
ret = ssdb->GetHashMetaVal(meta_key, hv);
if (ret != 1){
return ret;
}
std::string hkey = encode_hash_key(name, key, hv.version);
ret = ssdb->GetHashItemValInternal(hkey, &dbval);
if (ret != 1){
return ret;
}
ssdb->binlogs->Delete(hkey);
ssdb->binlogs->add_log(log_type, BinlogCommand::HDEL, hkey);
return 1;
}
static int incr_hsize(SSDBImpl *ssdb, const Bytes &name, int64_t incr){
HashMetaVal hv;
std::string size_key = encode_meta_key(name);
int ret = ssdb->GetHashMetaVal(size_key, hv);
if (ret == -1){
return ret;
} else if (ret == 0 && hv.del == KEY_DELETE_MASK){
if (incr > 0){
std::string size_val = encode_hash_meta_val((uint64_t)incr, (uint16_t)(hv.version+1));
ssdb->binlogs->Put(size_key, size_val);
} else{
return -1;
}
} else if (ret == 0){
if (incr > 0){
std::string size_val = encode_hash_meta_val((uint64_t)incr);
ssdb->binlogs->Put(size_key, size_val);
} else{
return -1;
}
} else{
uint64_t len = hv.length;
if (incr > 0) {
len += incr;
} else if (incr < 0) {
uint64_t u64 = static_cast<uint64_t>(-incr);
if (len < u64) {
return -1;
}
len = len - u64;
}
if (len == 0){
ssdb->binlogs->Delete(size_key);
} else{
std::string size_val = encode_hash_meta_val(len, hv.version);
ssdb->binlogs->Put(size_key, size_val);
}
}
return 0;
}
<commit_msg>modify hincr<commit_after>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
// todo r2m adaptation : remove this
//#include "t_hash.h"
#include "ssdb_impl.h"
#include "codec/encode.h"
#include "codec/decode.h"
static int hset_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, const Bytes &val, char log_type);
static int hdel_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, char log_type);
static int incr_hsize(SSDBImpl *ssdb, const Bytes &name, int64_t incr);
/**
* @return -1: error, 0: item updated, 1: new item inserted
*/
int SSDBImpl::hset(const Bytes &name, const Bytes &key, const Bytes &val, char log_type){
Transaction trans(binlogs);
int ret = hset_one(this, name, key, val, log_type);
if(ret >= 0){
if(ret > 0){
if(incr_hsize(this, name, ret) == -1){
return -1;
}
}
leveldb::Status s = binlogs->commit();
if(!s.ok()){
return -1;
}
}
return ret;
}
int SSDBImpl::hdel(const Bytes &name, const Bytes &key, char log_type){
Transaction trans(binlogs);
int ret = hdel_one(this, name, key, log_type);
if(ret >= 0){
if(ret > 0){
if(incr_hsize(this, name, -ret) == -1){
return -1;
}
}
leveldb::Status s = binlogs->commit();
if(!s.ok()){
return -1;
}
}
return ret;
}
int SSDBImpl::hincr(const Bytes &name, const Bytes &key, int64_t by, int64_t *new_val, char log_type){
Transaction trans(binlogs);
std::string old;
int ret = this->hget(name, key, &old);
if(ret == -1){
return -1;
}else if(ret == 0){
*new_val = by;
}else{
int64_t oldvalue = str_to_int64(old);
if(errno != 0){
return 0;
}
if ((by < 0 && oldvalue < 0 && by < (LLONG_MIN-oldvalue)) ||
(by > 0 && oldvalue > 0 && by > (LLONG_MAX-oldvalue))) {
return 0;
}
*new_val = oldvalue + by;
}
ret = hset_one(this, name, key, str(*new_val), log_type);
if(ret == -1){
return -1;
}
if(ret >= 0){
if(ret > 0){
if(incr_hsize(this, name, ret) == -1){
return -1;
}
}
leveldb::Status s = binlogs->commit();
if(!s.ok()){
return -1;
}
}
return 1;
}
int64_t SSDBImpl::hsize(const Bytes &name){
HashMetaVal hv;
std::string size_key = encode_meta_key(name);
int ret = GetHashMetaVal(size_key, hv);
if (ret != 1){
return ret;
} else{
return (int64_t)hv.length;
}
}
int SSDBImpl::HDelKeyNoLock(const Bytes &name, char log_type){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (ret != 1){
return ret;
}
HIterator *it = this->hscan_internal(name, "", "", hv.version, -1);
int num = 0;
while(it->next()){
ret = hdel_one(this, name, it->key, log_type);
if (-1 == ret){
return -1;
} else if (ret > 0){
num++;
}
}
if (num > 0){
if(incr_hsize(this, name, -num) == -1){
return -1;
}
}
return num;
}
int64_t SSDBImpl::hclear(const Bytes &name){
Transaction trans(binlogs);
int num = HDelKeyNoLock(name);
if (num > 0){
leveldb::Status s = binlogs->commit();
if (!s.ok()){
return -1;
}
}
return num;
}
int SSDBImpl::hget(const Bytes &name, const Bytes &key, std::string *val){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (ret != 1){
return ret;
}
std::string dbkey = encode_hash_key(name, key, hv.version);
leveldb::Status s = ldb->Get(leveldb::ReadOptions(), dbkey, val);
if(s.IsNotFound()){
return 0;
}
if(!s.ok()){
log_error("%s", s.ToString().c_str());
return -1;
}
return 1;
}
HIterator* SSDBImpl::hscan(const Bytes &name, const Bytes &start, const Bytes &end, uint64_t limit){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (0 == ret && hv.del == KEY_DELETE_MASK){
return hscan_internal(name, start, end, hv.version+1, limit);
} else if (ret > 0){
return hscan_internal(name, start, end, hv.version, limit);
} else{
return hscan_internal(name, start, end, 0, limit);
}
}
HIterator* SSDBImpl::hscan_internal(const Bytes &name, const Bytes &start, const Bytes &end, uint16_t version, uint64_t limit){
std::string key_start, key_end;
key_start = encode_hash_key(name, start, version);
if(!end.empty()){
key_end = encode_hash_key(name, end, version);
}
return new HIterator(this->iterator(key_start, key_end, limit), name, version);
}
HIterator* SSDBImpl::hrscan_internal(const Bytes &name, const Bytes &start, const Bytes &end, uint16_t version, uint64_t limit){
std::string key_start, key_end;
key_start = encode_hash_key(name, start, version);
if(start.empty()){
key_start.append(1, 255);
}
if(!end.empty()){
key_end = encode_hash_key(name, end, version);
}
return new HIterator(this->rev_iterator(key_start, key_end, limit), name, version);
}
HIterator* SSDBImpl::hrscan(const Bytes &name, const Bytes &start, const Bytes &end, uint64_t limit){
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
int ret = GetHashMetaVal(meta_key, hv);
if (0 == ret && hv.del == KEY_DELETE_MASK){
return hrscan_internal(name, start, end, hv.version+1, limit);
} else if (ret > 0){
return hrscan_internal(name, start, end, hv.version, limit);
} else{
return hrscan_internal(name, start, end, 0, limit);
}
}
/*// todo r2m adaptation //编码规则决定无法支持该操作,redis也不支持该操作
static void get_hnames(Iterator *it, std::vector<std::string> *list){
while(it->next()){
Bytes ks = it->key();
if(ks.data()[0] != DataType::HSIZE){
break;
}
std::string n;
if(decode_hsize_key(ks, &n) == -1){
continue;
}
list->push_back(n);
}
}*/
// todo r2m adaptation
int SSDBImpl::hlist(const Bytes &name_s, const Bytes &name_e, uint64_t limit,
std::vector<std::string> *list){
/* std::string start;
std::string end;
start = encode_hsize_key(name_s);
if(!name_e.empty()){
end = encode_hsize_key(name_e);
}
Iterator *it = this->iterator(start, end, limit);
get_hnames(it, list);
delete it;*/
return 0;
}
// todo r2m adaptation
int SSDBImpl::hrlist(const Bytes &name_s, const Bytes &name_e, uint64_t limit,
std::vector<std::string> *list){
/* std::string start;
std::string end;
start = encode_hsize_key(name_s);
if(name_s.empty()){
start.append(1, 255);
}
if(!name_e.empty()){
end = encode_hsize_key(name_e);
}
Iterator *it = this->rev_iterator(start, end, limit);
get_hnames(it, list);
delete it;*/
return 0;
}
int SSDBImpl::GetHashMetaVal(const std::string &meta_key, HashMetaVal &hv){
std::string meta_val;
leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &meta_val);
if (s.IsNotFound()){
return 0;
} else if (!s.ok() && !s.IsNotFound()){
return -1;
} else{
int ret = hv.DecodeMetaVal(meta_val);
if (ret == -1 || hv.type != DataType::HSIZE){
return -1;
} else if (hv.del == KEY_DELETE_MASK){
return 0;
}
}
return 1;
}
int SSDBImpl::GetHashItemValInternal(const std::string &item_key, std::string *val){
leveldb::Status s = ldb->Get(leveldb::ReadOptions(), item_key, val);
if (s.IsNotFound()){
return 0;
} else if (!s.ok() && !s.IsNotFound()){
return -1;
}
return 1;
}
// returns the number of newly added items
static int hset_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, const Bytes &val, char log_type){
int ret = 0;
std::string dbval;
HashMetaVal hv;
std::string meta_key = encode_meta_key(name.String());
ret = ssdb->GetHashMetaVal(meta_key, hv);
if (ret == -1){
return -1;
} else if (ret == 0 && hv.del == KEY_DELETE_MASK){
std::string hkey = encode_hash_key(name, key, (uint16_t)(hv.version+1));
ssdb->binlogs->Put(hkey, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, hkey);
ret = 1;
} else if (ret == 0){
std::string hkey = encode_hash_key(name, key);
ssdb->binlogs->Put(hkey, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, hkey);
ret = 1;
} else{
std::string item_key = encode_hash_key(name, key, hv.version);
ret = ssdb->GetHashItemValInternal(item_key, &dbval);
if (ret == -1){
return -1;
} else if (ret == 0){
ssdb->binlogs->Put(item_key, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, item_key);
ret = 1;
} else{
if(dbval != val){
ssdb->binlogs->Put(item_key, slice(val));
ssdb->binlogs->add_log(log_type, BinlogCommand::HSET, item_key);
}
ret = 0;
}
}
return ret;
}
static int hdel_one(SSDBImpl *ssdb, const Bytes &name, const Bytes &key, char log_type){
int ret = 0;
std::string dbval;
HashMetaVal hv;
std::string meta_key = encode_meta_key(name);
ret = ssdb->GetHashMetaVal(meta_key, hv);
if (ret != 1){
return ret;
}
std::string hkey = encode_hash_key(name, key, hv.version);
ret = ssdb->GetHashItemValInternal(hkey, &dbval);
if (ret != 1){
return ret;
}
ssdb->binlogs->Delete(hkey);
ssdb->binlogs->add_log(log_type, BinlogCommand::HDEL, hkey);
return 1;
}
static int incr_hsize(SSDBImpl *ssdb, const Bytes &name, int64_t incr){
HashMetaVal hv;
std::string size_key = encode_meta_key(name);
int ret = ssdb->GetHashMetaVal(size_key, hv);
if (ret == -1){
return ret;
} else if (ret == 0 && hv.del == KEY_DELETE_MASK){
if (incr > 0){
std::string size_val = encode_hash_meta_val((uint64_t)incr, (uint16_t)(hv.version+1));
ssdb->binlogs->Put(size_key, size_val);
} else{
return -1;
}
} else if (ret == 0){
if (incr > 0){
std::string size_val = encode_hash_meta_val((uint64_t)incr);
ssdb->binlogs->Put(size_key, size_val);
} else{
return -1;
}
} else{
uint64_t len = hv.length;
if (incr > 0) {
len += incr;
} else if (incr < 0) {
uint64_t u64 = static_cast<uint64_t>(-incr);
if (len < u64) {
return -1;
}
len = len - u64;
}
if (len == 0){
ssdb->binlogs->Delete(size_key);
} else{
std::string size_val = encode_hash_meta_val(len, hv.version);
ssdb->binlogs->Put(size_key, size_val);
}
}
return 0;
}
<|endoftext|> |
<commit_before>/* Please refer to license.txt */
#include "interface.hpp"
#include <iostream>
#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"
#include "../file/file.hpp"
namespace GEngine
{
namespace mui
{
Interface::Interface()
{
//d2d = nullptr;
cegui_system = nullptr;
cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
cegui_logfile_path = CEGUI_LOGFILE_PATH;
cegui_schemes_path = CEGUI_SCHEMES_PATH;
cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
cegui_fonts_path = CEGUI_FONTS_PATH;
cegui_layouts_path = CEGUI_LAYOUTS_PATH;
cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;
cegui_resourceprovider = nullptr;
//cegui_root_window = nullptr;
//cegui_windowmanager = nullptr;
}
Interface::~Interface()
{
/*if (d2d)
{
d2d = nullptr;
}
if (cegui_root_window)
{
delete cegui_root_window;
}*/
cegui_system = nullptr;
cegui_resourceprovider = nullptr;
}
bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
//d2d = &_d2d;
//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.
try
{
CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();
std::string log_directory("");
mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
if (!mfile::FileManager::directoryExists(log_directory))
{
mfile::FileManager::mkDir(log_directory);
}
CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);
//Initialise the required dirs for the CEGUI DefaultResourceProvider.
cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
//Set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
//This is only needed if the resourceprovider's schemas is set.
//Setup default group for validation schemas.
//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
//{
// parser->setProperty("SchemaDefaultResourceGroup", "schemas");
//}
//Load the schemes specified in cegui_schemes.
for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
{
CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
}
//TODO: Handle the mouse.
/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/
//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.
sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);
//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
mapSFMLKeysToCEGUI();
mapSFMLMouseToCEGUI();
d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
d2d.cegui_renderer = &myRenderer;
d2d.default_d2d = true;
}
catch(CEGUI::Exception& e)
{
std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
return false;
}
addD2D(d2d); //Add the D2D to the list of D2Ds.
return true; //Success.
}
bool Interface::loadFont(std::string filepath)
{
font.loadFromFile(filepath);
return true;
}
void Interface::update()
{
std::vector<mgfx::d2d::D2D* >::iterator iter;
for (iter = windows.begin(); iter != windows.end(); ++iter)
//for (int i = 0; i < windows.size(); ++i)
{
if (windows.size() > 1)
{
std::cout << "More than one.\n";
}
mgfx::d2d::D2D *d2d = *iter; //First point to this so I don't have to type crazy things every time.
//mgfx::d2d::D2D *d2d = windows[i]; //First point to this so I don't have to type crazy things every time.
CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.
context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.
//Now, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
}
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.
/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
//First, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
//onMouseButtonUp //Use this to check if the frame window's button was pressed.
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}
CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
//return cegui_root_window;
return d2d.getRootWindow();
}
void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
/*cegui_root_window = window;
CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
d2d.cegui_root_window = window;
d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}
CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
/*if (root) //If it's supposed to be the root window...
{
setRootWindow(window); //Set it.
}*/
return window;
}
void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
if (!d2d.cegui_renderer)
{
d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
}
if (!d2d.cegui_gui_context)
{
d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
}
windows.push_back(&d2d);
}
} //namespace mui
} //namespace GEngine
<commit_msg>Trying out another fix.<commit_after>/* Please refer to license.txt */
#include "interface.hpp"
#include <iostream>
#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"
#include "../file/file.hpp"
namespace GEngine
{
namespace mui
{
Interface::Interface()
{
//d2d = nullptr;
cegui_system = nullptr;
cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
cegui_logfile_path = CEGUI_LOGFILE_PATH;
cegui_schemes_path = CEGUI_SCHEMES_PATH;
cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
cegui_fonts_path = CEGUI_FONTS_PATH;
cegui_layouts_path = CEGUI_LAYOUTS_PATH;
cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;
cegui_resourceprovider = nullptr;
//cegui_root_window = nullptr;
//cegui_windowmanager = nullptr;
}
Interface::~Interface()
{
/*if (d2d)
{
d2d = nullptr;
}
if (cegui_root_window)
{
delete cegui_root_window;
}*/
cegui_system = nullptr;
cegui_resourceprovider = nullptr;
}
bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
//d2d = &_d2d;
//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.
try
{
CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();
std::string log_directory("");
mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
if (!mfile::FileManager::directoryExists(log_directory))
{
mfile::FileManager::mkDir(log_directory);
}
CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);
//Initialise the required dirs for the CEGUI DefaultResourceProvider.
cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
//Set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
//This is only needed if the resourceprovider's schemas is set.
//Setup default group for validation schemas.
//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
//{
// parser->setProperty("SchemaDefaultResourceGroup", "schemas");
//}
//Load the schemes specified in cegui_schemes.
for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
{
CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
}
//TODO: Handle the mouse.
/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/
//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.
sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);
//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
mapSFMLKeysToCEGUI();
mapSFMLMouseToCEGUI();
d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
d2d.cegui_renderer = &myRenderer;
d2d.default_d2d = true;
}
catch(CEGUI::Exception& e)
{
std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
return false;
}
addD2D(d2d); //Add the D2D to the list of D2Ds.
return true; //Success.
}
bool Interface::loadFont(std::string filepath)
{
font.loadFromFile(filepath);
return true;
}
void Interface::update()
{
for (std::vector<mgfx::d2d::D2D* >::iterator iter = windows.begin(); iter != windows.end(); ++iter)
//for (int i = 0; i < windows.size(); ++i)
{
if (windows.size() > 1)
{
//std::cout << "More than one & i = " << i << "\n";
}
mgfx::d2d::D2D *d2d = *iter; //First point to this so I don't have to type crazy things every time.
//mgfx::d2d::D2D *d2d = windows[i]; //First point to this so I don't have to type crazy things every time.
CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.
context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.
//Now, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
}
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.
/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
//First, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
//onMouseButtonUp //Use this to check if the frame window's button was pressed.
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}
CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
//return cegui_root_window;
return d2d.getRootWindow();
}
void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
/*cegui_root_window = window;
CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
d2d.cegui_root_window = window;
d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}
CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
/*if (root) //If it's supposed to be the root window...
{
setRootWindow(window); //Set it.
}*/
return window;
}
void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
if (!d2d.cegui_renderer)
{
d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
}
if (!d2d.cegui_gui_context)
{
d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
}
windows.push_back(&d2d);
}
} //namespace mui
} //namespace GEngine
<|endoftext|> |
<commit_before>/* Please refer to license.txt */
#include "interface.hpp"
#include <iostream>
#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"
#include "../file/file.hpp"
namespace GEngine
{
namespace mui
{
Interface::Interface()
{
//d2d = nullptr;
cegui_system = nullptr;
cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
cegui_logfile_path = CEGUI_LOGFILE_PATH;
cegui_schemes_path = CEGUI_SCHEMES_PATH;
cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
cegui_fonts_path = CEGUI_FONTS_PATH;
cegui_layouts_path = CEGUI_LAYOUTS_PATH;
cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;
cegui_resourceprovider = nullptr;
//cegui_root_window = nullptr;
//cegui_windowmanager = nullptr;
}
Interface::~Interface()
{
/*if (d2d)
{
d2d = nullptr;
}
if (cegui_root_window)
{
delete cegui_root_window;
}*/
cegui_system = nullptr;
cegui_resourceprovider = nullptr;
}
bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
//d2d = &_d2d;
//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.
try
{
CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();
std::string log_directory("");
mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
if (!mfile::FileManager::directoryExists(log_directory))
{
mfile::FileManager::mkDir(log_directory);
}
CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);
//Initialise the required dirs for the CEGUI DefaultResourceProvider.
cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
//Set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
//This is only needed if the resourceprovider's schemas is set.
//Setup default group for validation schemas.
//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
//{
// parser->setProperty("SchemaDefaultResourceGroup", "schemas");
//}
//Load the schemes specified in cegui_schemes.
for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
{
CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
}
//TODO: Handle the mouse.
/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/
//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.
sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);
//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
mapSFMLKeysToCEGUI();
mapSFMLMouseToCEGUI();
d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
d2d.cegui_renderer = &myRenderer;
d2d.default_d2d = true;
}
catch(CEGUI::Exception& e)
{
std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
return false;
}
addD2D(d2d); //Add the D2D to the list of D2Ds.
return true; //Success.
}
bool Interface::loadFont(std::string filepath)
{
font.loadFromFile(filepath);
return true;
}
void Interface::update()
{
for (std::vector<mgfx::d2d::D2D* >::iterator iterator = windows.begin(); iterator != windows.end(); ++iterator)
//for (int i = 0; i < windows.size(); ++i)
{
if (windows.size() > 1)
{
//std::cout << "More than one & i = " << i << "\n";
}
mgfx::d2d::D2D *d2d = *iterator; //First point to this so I don't have to type crazy things every time.
//mgfx::d2d::D2D *d2d = windows[i]; //First point to this so I don't have to type crazy things every time.
CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.
context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.
//Now, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
}
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.
/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
//First, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
//onMouseButtonUp //Use this to check if the frame window's button was pressed.
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}
CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
//return cegui_root_window;
return d2d.getRootWindow();
}
void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
/*cegui_root_window = window;
CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
d2d.cegui_root_window = window;
d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}
CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
/*if (root) //If it's supposed to be the root window...
{
setRootWindow(window); //Set it.
}*/
return window;
}
void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
if (!d2d.cegui_renderer)
{
d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
}
if (!d2d.cegui_gui_context)
{
d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
}
windows.push_back(&d2d);
}
} //namespace mui
} //namespace GEngine
<commit_msg>Bah, I'll just go with the weird fix.<commit_after>/* Please refer to license.txt */
#include "interface.hpp"
#include <iostream>
#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"
#include "../file/file.hpp"
namespace GEngine
{
namespace mui
{
Interface::Interface()
{
//d2d = nullptr;
cegui_system = nullptr;
cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
cegui_logfile_path = CEGUI_LOGFILE_PATH;
cegui_schemes_path = CEGUI_SCHEMES_PATH;
cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
cegui_fonts_path = CEGUI_FONTS_PATH;
cegui_layouts_path = CEGUI_LAYOUTS_PATH;
cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;
cegui_resourceprovider = nullptr;
//cegui_root_window = nullptr;
//cegui_windowmanager = nullptr;
}
Interface::~Interface()
{
/*if (d2d)
{
d2d = nullptr;
}
if (cegui_root_window)
{
delete cegui_root_window;
}*/
cegui_system = nullptr;
cegui_resourceprovider = nullptr;
}
bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
//d2d = &_d2d;
//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.
try
{
CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();
std::string log_directory("");
mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
if (!mfile::FileManager::directoryExists(log_directory))
{
mfile::FileManager::mkDir(log_directory);
}
CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);
//Initialise the required dirs for the CEGUI DefaultResourceProvider.
cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");
//Set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
//This is only needed if the resourceprovider's schemas is set.
//Setup default group for validation schemas.
//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
//{
// parser->setProperty("SchemaDefaultResourceGroup", "schemas");
//}
//Load the schemes specified in cegui_schemes.
for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
{
CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
}
//TODO: Handle the mouse.
/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/
//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.
sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);
//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
mapSFMLKeysToCEGUI();
mapSFMLMouseToCEGUI();
d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
d2d.cegui_renderer = &myRenderer;
d2d.default_d2d = true;
}
catch(CEGUI::Exception& e)
{
std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
return false;
}
addD2D(d2d); //Add the D2D to the list of D2Ds.
return true; //Success.
}
bool Interface::loadFont(std::string filepath)
{
font.loadFromFile(filepath);
return true;
}
void Interface::update()
{
//for (std::vector<mgfx::d2d::D2D* >::iterator iter = windows.begin(); iter != windows.end(); ++iter)
for (int i = 0; i < windows.size(); ++i)
{
if (windows.size() > 1)
{
//std::cout << "More than one & i = " << i << "\n";
}
//mgfx::d2d::D2D *d2d = *iter; //First point to this so I don't have to type crazy things every time.
mgfx::d2d::D2D *d2d = windows[i]; //First point to this so I don't have to type crazy things every time.
CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.
context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.
//Now, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
}
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.
/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
//First, handle injecting events into CEGUI.
for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
{
switch (d2d->window->events[i].type)
{
case sf::Event::KeyPressed:
context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::KeyReleased:
context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
break;
case sf::Event::TextEntered:
context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
break;
case sf::Event::MouseMoved:
{
sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
context.injectMousePosition(coords.x, coords.y);
}
break;
case sf::Event::MouseButtonPressed:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
context.injectMouseButtonDown(CEGUI::LeftButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
{
context.injectMouseButtonDown(CEGUI::MiddleButton);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
{
context.injectMouseButtonDown(CEGUI::RightButton);
}
break;
case sf::Event::MouseButtonReleased:
switch (d2d->window->events[i].mouseButton.button)
{
case sf::Mouse::Left:
context.injectMouseButtonUp(CEGUI::LeftButton);
break;
case sf::Mouse::Middle:
context.injectMouseButtonUp(CEGUI::MiddleButton);
break;
case sf::Mouse::Right:
context.injectMouseButtonUp(CEGUI::RightButton);
break;
}
break;
case sf::Event::MouseWheelMoved:
context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
break;
default:
break;
}
}
//onMouseButtonUp //Use this to check if the frame window's button was pressed.
CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}
CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
//return cegui_root_window;
return d2d.getRootWindow();
}
void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
/*cegui_root_window = window;
CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
d2d.cegui_root_window = window;
d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}
CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
/*if (root) //If it's supposed to be the root window...
{
setRootWindow(window); //Set it.
}*/
return window;
}
void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
if (!d2d.cegui_renderer)
{
d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
}
if (!d2d.cegui_gui_context)
{
d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
}
windows.push_back(&d2d);
}
} //namespace mui
} //namespace GEngine
<|endoftext|> |
<commit_before>#ifndef XGBOOST_IO_PAGE_ROW_ITER_INL_HPP_
#define XGBOOST_IO_PAGE_ROW_ITER_INL_HPP_
/*!
* \file page_row_iter-inl.hpp
* row iterator based on sparse page
* \author Tianqi Chen
*/
#include "../data.h"
#include "../utils/iterator.h"
#include "../utils/thread_buffer.h"
#include "./simple_fmatrix-inl.hpp"
#include "./page_fmatrix-inl.hpp"
namespace xgboost {
namespace io {
/*! \brief page structure that can be used to store a rowbatch */
struct RowBatchPage {
public:
RowBatchPage(void) {
data_ = new int[kPageSize];
utils::Assert(data_ != NULL, "fail to allocate row batch page");
this->Clear();
}
~RowBatchPage(void) {
if (data_ != NULL) delete [] data_;
}
/*!
* \brief Push one row into page
* \param row an instance row
* \return false or true to push into
*/
inline bool PushRow(const RowBatch::Inst &row) {
const size_t dsize = row.length * sizeof(RowBatch::Entry);
if (FreeBytes() < dsize+ sizeof(int)) return false;
row_ptr(Size() + 1) = row_ptr(Size()) + row.length;
memcpy(data_ptr(row_ptr(Size())) , row.data, dsize);
++ data_[0];
return true;
}
/*!
* \brief get a row batch representation from the page
* \param p_rptr a temporal space that can be used to provide
* ind_ptr storage for RowBatch
* \return a new RowBatch object
*/
inline RowBatch GetRowBatch(std::vector<size_t> *p_rptr, size_t base_rowid) {
RowBatch batch;
batch.base_rowid = base_rowid;
batch.data_ptr = this->data_ptr(0);
batch.size = static_cast<size_t>(this->Size());
std::vector<size_t> &rptr = *p_rptr;
rptr.resize(this->Size() + 1);
for (size_t i = 0; i < rptr.size(); ++i) {
rptr[i] = static_cast<size_t>(this->row_ptr(static_cast<int>(i)));
}
batch.ind_ptr = &rptr[0];
return batch;
}
/*! \brief get i-th row from the batch */
inline RowBatch::Inst operator[](int i) {
return RowBatch::Inst(data_ptr(0) + row_ptr(i),
static_cast<bst_uint>(row_ptr(i+1) - row_ptr(i)));
}
/*!
* \brief clear the page, cleanup the content
*/
inline void Clear(void) {
memset(&data_[0], 0, sizeof(int) * kPageSize);
}
/*!
* \brief load one page form instream
* \return true if loading is successful
*/
inline bool Load(utils::IStream &fi) {
return fi.Read(&data_[0], sizeof(int) * kPageSize) != 0;
}
/*! \brief save one page into outstream */
inline void Save(utils::IStream &fo) {
fo.Write(&data_[0], sizeof(int) * kPageSize);
}
/*! \return number of elements */
inline int Size(void) const {
return data_[0];
}
/*! \brief page size 64 MB */
static const size_t kPageSize = 64 << 18;
private:
/*! \return number of elements */
inline size_t FreeBytes(void) {
return (kPageSize - (Size() + 2)) * sizeof(int)
- row_ptr(Size()) * sizeof(RowBatch::Entry) ;
}
/*! \brief equivalent row pointer at i */
inline int& row_ptr(int i) {
return data_[kPageSize - i - 1];
}
inline RowBatch::Entry* data_ptr(int i) {
return (RowBatch::Entry*)(&data_[1]) + i;
}
// content of data
int *data_;
};
/*! \brief thread buffer iterator */
class ThreadRowPageIterator: public utils::IIterator<RowBatch> {
public:
ThreadRowPageIterator(void) {
itr.SetParam("buffer_size", "2");
page_ = NULL;
base_rowid_ = 0;
}
virtual ~ThreadRowPageIterator(void) {
}
virtual void Init(void) {
}
virtual void BeforeFirst(void) {
itr.BeforeFirst();
base_rowid_ = 0;
}
virtual bool Next(void) {
if(!itr.Next(page_)) return false;
out_ = page_->GetRowBatch(&tmp_ptr_, base_rowid_);
base_rowid_ += out_.size;
return true;
}
virtual const RowBatch &Value(void) const{
return out_;
}
/*! \brief load and initialize the iterator with fi */
inline void Load(const utils::FileStream &fi) {
itr.get_factory().SetFile(fi);
itr.Init();
this->BeforeFirst();
}
/*!
* \brief save a row iterator to output stream, in row iterator format
*/
inline static void Save(utils::IIterator<RowBatch> *iter,
utils::IStream &fo) {
RowBatchPage page;
iter->BeforeFirst();
while (iter->Next()) {
const RowBatch &batch = iter->Value();
for (size_t i = 0; i < batch.size; ++i) {
if (!page.PushRow(batch[i])) {
page.Save(fo);
page.Clear();
utils::Check(page.PushRow(batch[i]), "row is too big");
}
}
}
if (page.Size() != 0) page.Save(fo);
}
private:
// base row id
size_t base_rowid_;
// temporal ptr
std::vector<size_t> tmp_ptr_;
// output data
RowBatch out_;
// page pointer type
typedef RowBatchPage* PagePtr;
// loader factory for page
struct Factory {
public:
long file_begin_;
utils::FileStream fi;
Factory(void) {}
inline void SetFile(const utils::FileStream &fi) {
this->fi = fi;
file_begin_ = this->fi.Tell();
}
inline bool Init(void) {
return true;
}
inline void SetParam(const char *name, const char *val) {}
inline bool LoadNext(PagePtr &val) {
return val->Load(fi);
}
inline PagePtr Create(void) {
PagePtr a = new RowBatchPage();
return a;
}
inline void FreeSpace(PagePtr &a) {
delete a;
}
inline void Destroy(void) {
fi.Close();
}
inline void BeforeFirst(void) {
fi.Seek(file_begin_);
}
};
protected:
PagePtr page_;
utils::ThreadBuffer<PagePtr,Factory> itr;
};
/*! \brief data matrix using page */
class DMatrixPage : public DataMatrix {
public:
DMatrixPage(void) : DataMatrix(kMagic) {
iter_ = new ThreadRowPageIterator();
fmat_ = new FMatrixS(iter_);
}
// virtual destructor
virtual ~DMatrixPage(void) {
delete fmat_;
}
virtual IFMatrix *fmat(void) const {
return fmat_;
}
/*! \brief load and initialize the iterator with fi */
inline void Load(utils::FileStream &fi,
bool silent = false,
const char *fname = NULL){
int magic;
utils::Check(fi.Read(&magic, sizeof(magic)) != 0, "invalid input file format");
utils::Check(magic == kMagic, "invalid format,magic number mismatch");
this->info.LoadBinary(fi);
iter_->Load(fi);
if (!silent) {
printf("DMatrixPage: %lux%lu matrix is loaded",
static_cast<unsigned long>(info.num_row()),
static_cast<unsigned long>(info.num_col()));
if (fname != NULL) {
printf(" from %s\n", fname);
} else {
printf("\n");
}
if (info.group_ptr.size() != 0) {
printf("data contains %u groups\n", (unsigned)info.group_ptr.size()-1);
}
}
}
/*! \brief save a DataMatrix as DMatrixPage*/
inline static void Save(const char* fname, const DataMatrix &mat, bool silent) {
utils::FileStream fs(utils::FopenCheck(fname, "wb"));
int magic = kMagic;
fs.Write(&magic, sizeof(magic));
mat.info.SaveBinary(fs);
ThreadRowPageIterator::Save(mat.fmat()->RowIterator(), fs);
fs.Close();
if (!silent) {
printf("DMatrixPage: %lux%lu is saved to %s\n",
static_cast<unsigned long>(mat.info.num_row()),
static_cast<unsigned long>(mat.info.num_col()), fname);
}
}
/*! \brief the real fmatrix */
FMatrixS *fmat_;
/*! \brief row iterator */
ThreadRowPageIterator *iter_;
/*! \brief magic number used to identify DMatrix */
static const int kMagic = 0xffffab02;
};
} // namespace io
} // namespace xgboost
#endif // XGBOOST_IO_PAGE_ROW_ITER_INL_HPP_
<commit_msg>make rowbatch page flexible<commit_after>#ifndef XGBOOST_IO_PAGE_ROW_ITER_INL_HPP_
#define XGBOOST_IO_PAGE_ROW_ITER_INL_HPP_
/*!
* \file page_row_iter-inl.hpp
* row iterator based on sparse page
* \author Tianqi Chen
*/
#include "../data.h"
#include "../utils/iterator.h"
#include "../utils/thread_buffer.h"
#include "./simple_fmatrix-inl.hpp"
#include "./page_fmatrix-inl.hpp"
namespace xgboost {
namespace io {
/*! \brief page structure that can be used to store a rowbatch */
struct RowBatchPage {
public:
RowBatchPage(size_t page_size) : kPageSize(page_size) {
data_ = new int[kPageSize];
utils::Assert(data_ != NULL, "fail to allocate row batch page");
this->Clear();
}
~RowBatchPage(void) {
if (data_ != NULL) delete [] data_;
}
/*!
* \brief Push one row into page
* \param row an instance row
* \return false or true to push into
*/
inline bool PushRow(const RowBatch::Inst &row) {
const size_t dsize = row.length * sizeof(RowBatch::Entry);
if (FreeBytes() < dsize+ sizeof(int)) return false;
row_ptr(Size() + 1) = row_ptr(Size()) + row.length;
memcpy(data_ptr(row_ptr(Size())) , row.data, dsize);
++ data_[0];
return true;
}
/*!
* \brief get a row batch representation from the page
* \param p_rptr a temporal space that can be used to provide
* ind_ptr storage for RowBatch
* \return a new RowBatch object
*/
inline RowBatch GetRowBatch(std::vector<size_t> *p_rptr, size_t base_rowid) {
RowBatch batch;
batch.base_rowid = base_rowid;
batch.data_ptr = this->data_ptr(0);
batch.size = static_cast<size_t>(this->Size());
std::vector<size_t> &rptr = *p_rptr;
rptr.resize(this->Size() + 1);
for (size_t i = 0; i < rptr.size(); ++i) {
rptr[i] = static_cast<size_t>(this->row_ptr(static_cast<int>(i)));
}
batch.ind_ptr = &rptr[0];
return batch;
}
/*! \brief get i-th row from the batch */
inline RowBatch::Inst operator[](int i) {
return RowBatch::Inst(data_ptr(0) + row_ptr(i),
static_cast<bst_uint>(row_ptr(i+1) - row_ptr(i)));
}
/*!
* \brief clear the page, cleanup the content
*/
inline void Clear(void) {
memset(&data_[0], 0, sizeof(int) * kPageSize);
}
/*!
* \brief load one page form instream
* \return true if loading is successful
*/
inline bool Load(utils::IStream &fi) {
return fi.Read(&data_[0], sizeof(int) * kPageSize) != 0;
}
/*! \brief save one page into outstream */
inline void Save(utils::IStream &fo) {
fo.Write(&data_[0], sizeof(int) * kPageSize);
}
/*! \return number of elements */
inline int Size(void) const {
return data_[0];
}
private:
/*! \return number of elements */
inline size_t FreeBytes(void) {
return (kPageSize - (Size() + 2)) * sizeof(int)
- row_ptr(Size()) * sizeof(RowBatch::Entry) ;
}
/*! \brief equivalent row pointer at i */
inline int& row_ptr(int i) {
return data_[kPageSize - i - 1];
}
inline RowBatch::Entry* data_ptr(int i) {
return (RowBatch::Entry*)(&data_[1]) + i;
}
// page size
const size_t kPageSize;
// content of data
int *data_;
};
/*! \brief thread buffer iterator */
class ThreadRowPageIterator: public utils::IIterator<RowBatch> {
public:
ThreadRowPageIterator(void) {
itr.SetParam("buffer_size", "2");
page_ = NULL;
base_rowid_ = 0;
}
virtual ~ThreadRowPageIterator(void) {
}
virtual void Init(void) {
}
virtual void BeforeFirst(void) {
itr.BeforeFirst();
base_rowid_ = 0;
}
virtual bool Next(void) {
if(!itr.Next(page_)) return false;
out_ = page_->GetRowBatch(&tmp_ptr_, base_rowid_);
base_rowid_ += out_.size;
return true;
}
virtual const RowBatch &Value(void) const{
return out_;
}
/*! \brief load and initialize the iterator with fi */
inline void Load(const utils::FileStream &fi) {
itr.get_factory().SetFile(fi);
itr.Init();
this->BeforeFirst();
}
/*!
* \brief save a row iterator to output stream, in row iterator format
*/
inline static void Save(utils::IIterator<RowBatch> *iter,
utils::IStream &fo) {
RowBatchPage page(kPageSize);
iter->BeforeFirst();
while (iter->Next()) {
const RowBatch &batch = iter->Value();
for (size_t i = 0; i < batch.size; ++i) {
if (!page.PushRow(batch[i])) {
page.Save(fo);
page.Clear();
utils::Check(page.PushRow(batch[i]), "row is too big");
}
}
}
if (page.Size() != 0) page.Save(fo);
}
/*! \brief page size 64 MB */
static const size_t kPageSize = 64 << 18;
private:
// base row id
size_t base_rowid_;
// temporal ptr
std::vector<size_t> tmp_ptr_;
// output data
RowBatch out_;
// page pointer type
typedef RowBatchPage* PagePtr;
// loader factory for page
struct Factory {
public:
long file_begin_;
utils::FileStream fi;
Factory(void) {}
inline void SetFile(const utils::FileStream &fi) {
this->fi = fi;
file_begin_ = this->fi.Tell();
}
inline bool Init(void) {
return true;
}
inline void SetParam(const char *name, const char *val) {}
inline bool LoadNext(PagePtr &val) {
return val->Load(fi);
}
inline PagePtr Create(void) {
PagePtr a = new RowBatchPage(kPageSize);
return a;
}
inline void FreeSpace(PagePtr &a) {
delete a;
}
inline void Destroy(void) {
fi.Close();
}
inline void BeforeFirst(void) {
fi.Seek(file_begin_);
}
};
protected:
PagePtr page_;
utils::ThreadBuffer<PagePtr,Factory> itr;
};
/*! \brief data matrix using page */
class DMatrixPage : public DataMatrix {
public:
DMatrixPage(void) : DataMatrix(kMagic) {
iter_ = new ThreadRowPageIterator();
fmat_ = new FMatrixS(iter_);
}
// virtual destructor
virtual ~DMatrixPage(void) {
delete fmat_;
}
virtual IFMatrix *fmat(void) const {
return fmat_;
}
/*! \brief load and initialize the iterator with fi */
inline void Load(utils::FileStream &fi,
bool silent = false,
const char *fname = NULL){
int magic;
utils::Check(fi.Read(&magic, sizeof(magic)) != 0, "invalid input file format");
utils::Check(magic == kMagic, "invalid format,magic number mismatch");
this->info.LoadBinary(fi);
iter_->Load(fi);
if (!silent) {
printf("DMatrixPage: %lux%lu matrix is loaded",
static_cast<unsigned long>(info.num_row()),
static_cast<unsigned long>(info.num_col()));
if (fname != NULL) {
printf(" from %s\n", fname);
} else {
printf("\n");
}
if (info.group_ptr.size() != 0) {
printf("data contains %u groups\n", (unsigned)info.group_ptr.size()-1);
}
}
}
/*! \brief save a DataMatrix as DMatrixPage*/
inline static void Save(const char* fname, const DataMatrix &mat, bool silent) {
utils::FileStream fs(utils::FopenCheck(fname, "wb"));
int magic = kMagic;
fs.Write(&magic, sizeof(magic));
mat.info.SaveBinary(fs);
ThreadRowPageIterator::Save(mat.fmat()->RowIterator(), fs);
fs.Close();
if (!silent) {
printf("DMatrixPage: %lux%lu is saved to %s\n",
static_cast<unsigned long>(mat.info.num_row()),
static_cast<unsigned long>(mat.info.num_col()), fname);
}
}
/*! \brief the real fmatrix */
FMatrixS *fmat_;
/*! \brief row iterator */
ThreadRowPageIterator *iter_;
/*! \brief magic number used to identify DMatrix */
static const int kMagic = 0xffffab02;
};
} // namespace io
} // namespace xgboost
#endif // XGBOOST_IO_PAGE_ROW_ITER_INL_HPP_
<|endoftext|> |
<commit_before>/*
* Concatenate several istreams.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_cat.hxx"
#include "istream_oo.hxx"
#include "Pointer.hxx"
#include "Bucket.hxx"
#include "util/ConstBuffer.hxx"
#include <boost/intrusive/slist.hpp>
#include <iterator>
#include <assert.h>
#include <stdarg.h>
struct CatIstream final : public Istream {
struct Input final
: IstreamHandler,
boost::intrusive::slist_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
CatIstream &cat;
IstreamPointer istream;
Input(CatIstream &_cat, Istream &_istream)
:cat(_cat), istream(_istream, *this) {}
void Read(FdTypeMask direct) {
istream.SetDirect(direct);
istream.Read();
}
bool FillBucketList(IstreamBucketList &list, GError **error_r) {
return istream.FillBucketList(list, error_r);
}
size_t ConsumeBucketList(size_t nbytes) {
return istream.ConsumeBucketList(nbytes);
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
return cat.OnInputData(*this, data, length);
}
ssize_t OnDirect(FdType type, int fd, size_t max_length) override {
return cat.OnInputDirect(*this, type, fd, max_length);
}
void OnEof() override {
assert(istream.IsDefined());
istream.Clear();
cat.OnInputEof(*this);
}
void OnError(GError *error) override {
assert(istream.IsDefined());
istream.Clear();
cat.OnInputError(*this, error);
}
struct Disposer {
void operator()(Input *input) {
input->istream.Close();
}
};
};
bool reading = false;
typedef boost::intrusive::slist<Input,
boost::intrusive::constant_time_size<false>> InputList;
InputList inputs;
CatIstream(struct pool &p, ConstBuffer<Istream *> _inputs);
Input &GetCurrent() {
return inputs.front();
}
const Input &GetCurrent() const {
return inputs.front();
}
bool IsCurrent(const Input &input) const {
return &GetCurrent() == &input;
}
bool IsEOF() const {
return inputs.empty();
}
void CloseAllInputs() {
inputs.clear_and_dispose(Input::Disposer());
}
size_t OnInputData(Input &i, const void *data, size_t length) {
return IsCurrent(i)
? InvokeData(data, length)
: 0;
}
ssize_t OnInputDirect(gcc_unused Input &i, FdType type, int fd,
size_t max_length) {
assert(IsCurrent(i));
return InvokeDirect(type, fd, max_length);
}
void OnInputEof(Input &i) {
const bool current = IsCurrent(i);
inputs.erase(inputs.iterator_to(i));
if (IsEOF()) {
assert(current);
DestroyEof();
} else if (current && !reading) {
/* only call Input::_Read() if this function was not called
from CatIstream:Read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
GetCurrent().Read(GetHandlerDirect());
}
}
void OnInputError(gcc_unused Input &i, GError *error) {
inputs.erase(inputs.iterator_to(i));
CloseAllInputs();
DestroyError(error);
}
/* virtual methods from class Istream */
off_t _GetAvailable(bool partial) override;
off_t _Skip(gcc_unused off_t length) override;
void _Read() override;
bool _FillBucketList(IstreamBucketList &list, GError **error_r) override;
size_t _ConsumeBucketList(size_t nbytes) override;
int _AsFd() override;
void _Close() override;
};
/*
* istream implementation
*
*/
off_t
CatIstream::_GetAvailable(bool partial)
{
off_t available = 0;
for (const auto &input : inputs) {
const off_t a = input.istream.GetAvailable(partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
off_t
CatIstream::_Skip(off_t length)
{
return inputs.empty()
? 0
: inputs.front().istream.Skip(length);
}
void
CatIstream::_Read()
{
if (IsEOF()) {
DestroyEof();
return;
}
const ScopePoolRef ref(GetPool() TRACE_ARGS);
reading = true;
CatIstream::InputList::const_iterator prev;
do {
prev = inputs.begin();
GetCurrent().Read(GetHandlerDirect());
} while (!IsEOF() && inputs.begin() != prev);
reading = false;
}
bool
CatIstream::_FillBucketList(IstreamBucketList &list, GError **error_r)
{
assert(!list.HasMore());
for (auto &input : inputs) {
if (!input.FillBucketList(list, error_r)) {
inputs.erase(inputs.iterator_to(input));
CloseAllInputs();
Destroy();
return false;
}
if (list.HasMore())
break;
}
return true;
}
size_t
CatIstream::_ConsumeBucketList(size_t nbytes)
{
size_t total = 0;
for (auto &input : inputs) {
size_t consumed = input.ConsumeBucketList(nbytes);
Consumed(consumed);
total += consumed;
nbytes -= consumed;
if (nbytes == 0)
break;
}
return total;
}
int
CatIstream::_AsFd()
{
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (std::next(inputs.begin()) != inputs.end())
/* not on last input */
return -1;
auto &i = GetCurrent();
int fd = i.istream.AsFd();
if (fd >= 0)
Destroy();
return fd;
}
void
CatIstream::_Close()
{
CloseAllInputs();
Destroy();
}
/*
* constructor
*
*/
inline CatIstream::CatIstream(struct pool &p, ConstBuffer<Istream *> _inputs)
:Istream(p)
{
auto i = inputs.before_begin();
for (Istream *_input : _inputs) {
if (_input == nullptr)
continue;
auto *input = NewFromPool<Input>(p, *this, *_input);
i = inputs.insert_after(i, *input);
}
}
Istream *
_istream_cat_new(struct pool &pool, Istream *const* inputs, unsigned n_inputs)
{
return NewFromPool<CatIstream>(pool, pool,
ConstBuffer<Istream *>(inputs, n_inputs));
}
<commit_msg>istream/cat: use class IstreamSink<commit_after>/*
* Concatenate several istreams.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_cat.hxx"
#include "istream_oo.hxx"
#include "Sink.hxx"
#include "Bucket.hxx"
#include "util/ConstBuffer.hxx"
#include <boost/intrusive/slist.hpp>
#include <iterator>
#include <assert.h>
#include <stdarg.h>
struct CatIstream final : public Istream {
struct Input final
: IstreamSink,
boost::intrusive::slist_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
CatIstream &cat;
Input(CatIstream &_cat, Istream &_istream)
:IstreamSink(_istream), cat(_cat) {}
off_t GetAvailable(bool partial) const {
return input.GetAvailable(partial);
}
off_t Skip(off_t length) {
return input.Skip(length);
}
void Read(FdTypeMask direct) {
input.SetDirect(direct);
input.Read();
}
bool FillBucketList(IstreamBucketList &list, GError **error_r) {
return input.FillBucketList(list, error_r);
}
size_t ConsumeBucketList(size_t nbytes) {
return input.ConsumeBucketList(nbytes);
}
int AsFd() {
return input.AsFd();
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
return cat.OnInputData(*this, data, length);
}
ssize_t OnDirect(FdType type, int fd, size_t max_length) override {
return cat.OnInputDirect(*this, type, fd, max_length);
}
void OnEof() override {
assert(input.IsDefined());
ClearInput();
cat.OnInputEof(*this);
}
void OnError(GError *error) override {
assert(input.IsDefined());
ClearInput();
cat.OnInputError(*this, error);
}
struct Disposer {
void operator()(Input *input) {
input->input.Close();
}
};
};
bool reading = false;
typedef boost::intrusive::slist<Input,
boost::intrusive::constant_time_size<false>> InputList;
InputList inputs;
CatIstream(struct pool &p, ConstBuffer<Istream *> _inputs);
Input &GetCurrent() {
return inputs.front();
}
const Input &GetCurrent() const {
return inputs.front();
}
bool IsCurrent(const Input &input) const {
return &GetCurrent() == &input;
}
bool IsEOF() const {
return inputs.empty();
}
void CloseAllInputs() {
inputs.clear_and_dispose(Input::Disposer());
}
size_t OnInputData(Input &i, const void *data, size_t length) {
return IsCurrent(i)
? InvokeData(data, length)
: 0;
}
ssize_t OnInputDirect(gcc_unused Input &i, FdType type, int fd,
size_t max_length) {
assert(IsCurrent(i));
return InvokeDirect(type, fd, max_length);
}
void OnInputEof(Input &i) {
const bool current = IsCurrent(i);
inputs.erase(inputs.iterator_to(i));
if (IsEOF()) {
assert(current);
DestroyEof();
} else if (current && !reading) {
/* only call Input::_Read() if this function was not called
from CatIstream:Read() - in this case,
istream_cat_read() would provide the loop. This is
advantageous because we avoid unnecessary recursing. */
GetCurrent().Read(GetHandlerDirect());
}
}
void OnInputError(gcc_unused Input &i, GError *error) {
inputs.erase(inputs.iterator_to(i));
CloseAllInputs();
DestroyError(error);
}
/* virtual methods from class Istream */
off_t _GetAvailable(bool partial) override;
off_t _Skip(gcc_unused off_t length) override;
void _Read() override;
bool _FillBucketList(IstreamBucketList &list, GError **error_r) override;
size_t _ConsumeBucketList(size_t nbytes) override;
int _AsFd() override;
void _Close() override;
};
/*
* istream implementation
*
*/
off_t
CatIstream::_GetAvailable(bool partial)
{
off_t available = 0;
for (const auto &input : inputs) {
const off_t a = input.GetAvailable(partial);
if (a != (off_t)-1)
available += a;
else if (!partial)
/* if the caller wants the exact number of bytes, and
one input cannot provide it, we cannot provide it
either */
return (off_t)-1;
}
return available;
}
off_t
CatIstream::_Skip(off_t length)
{
return inputs.empty()
? 0
: inputs.front().Skip(length);
}
void
CatIstream::_Read()
{
if (IsEOF()) {
DestroyEof();
return;
}
const ScopePoolRef ref(GetPool() TRACE_ARGS);
reading = true;
CatIstream::InputList::const_iterator prev;
do {
prev = inputs.begin();
GetCurrent().Read(GetHandlerDirect());
} while (!IsEOF() && inputs.begin() != prev);
reading = false;
}
bool
CatIstream::_FillBucketList(IstreamBucketList &list, GError **error_r)
{
assert(!list.HasMore());
for (auto &input : inputs) {
if (!input.FillBucketList(list, error_r)) {
inputs.erase(inputs.iterator_to(input));
CloseAllInputs();
Destroy();
return false;
}
if (list.HasMore())
break;
}
return true;
}
size_t
CatIstream::_ConsumeBucketList(size_t nbytes)
{
size_t total = 0;
for (auto &input : inputs) {
size_t consumed = input.ConsumeBucketList(nbytes);
Consumed(consumed);
total += consumed;
nbytes -= consumed;
if (nbytes == 0)
break;
}
return total;
}
int
CatIstream::_AsFd()
{
/* we can safely forward the as_fd() call to our input if it's the
last one */
if (std::next(inputs.begin()) != inputs.end())
/* not on last input */
return -1;
auto &i = GetCurrent();
int fd = i.AsFd();
if (fd >= 0)
Destroy();
return fd;
}
void
CatIstream::_Close()
{
CloseAllInputs();
Destroy();
}
/*
* constructor
*
*/
inline CatIstream::CatIstream(struct pool &p, ConstBuffer<Istream *> _inputs)
:Istream(p)
{
auto i = inputs.before_begin();
for (Istream *_input : _inputs) {
if (_input == nullptr)
continue;
auto *input = NewFromPool<Input>(p, *this, *_input);
i = inputs.insert_after(i, *input);
}
}
Istream *
_istream_cat_new(struct pool &pool, Istream *const* inputs, unsigned n_inputs)
{
return NewFromPool<CatIstream>(pool, pool,
ConstBuffer<Istream *>(inputs, n_inputs));
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <stddef.h>
#include <stddef.h>
#include <cassert>
#include <type_traits>
#ifndef NULL
#error NULL not defined
#endif
#ifndef offsetof
#error offsetof not defined
#endif
int main()
{
void *p = NULL;
assert(!p);
static_assert(sizeof(size_t) == sizeof(void*),
"sizeof(size_t) == sizeof(void*)");
static_assert(std::is_unsigned<size_t>::value,
"std::is_unsigned<size_t>::value");
static_assert(std::is_integral<size_t>::value,
"std::is_integral<size_t>::value");
static_assert(sizeof(ptrdiff_t) == sizeof(void*),
"sizeof(ptrdiff_t) == sizeof(void*)");
static_assert(std::is_signed<ptrdiff_t>::value,
"std::is_signed<ptrdiff_t>::value");
static_assert(std::is_integral<ptrdiff_t>::value,
"std::is_integral<ptrdiff_t>::value");
static_assert(std::is_same<decltype(nullptr), nullptr_t>::value,
"decltype(nullptr) == nullptr_t");
static_assert(sizeof(nullptr_t) == sizeof(void*),
"sizeof(nullptr_t) == sizeof(void*)");
static_assert(std::is_pod<max_align_t>::value,
"std::is_pod<max_align_t>::value");
static_assert((std::alignment_of<max_align_t>::value >=
std::alignment_of<long long>::value),
"std::alignment_of<max_align_t>::value >= "
"std::alignment_of<long long>::value");
static_assert(std::alignment_of<max_align_t>::value >=
std::alignment_of<long double>::value,
"std::alignment_of<max_align_t>::value >= "
"std::alignment_of<long double>::value");
static_assert(std::alignment_of<max_align_t>::value >=
std::alignment_of<void*>::value,
"std::alignment_of<max_align_t>::value >= "
"std::alignment_of<void*>::value");
}
<commit_msg>Fix test failure in C++98 mode due to imperfect static_assert emulation.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <stddef.h>
#include <stddef.h>
#include <cassert>
#include <type_traits>
#ifndef NULL
#error NULL not defined
#endif
#ifndef offsetof
#error offsetof not defined
#endif
int main()
{
void *p = NULL;
assert(!p);
static_assert(sizeof(size_t) == sizeof(void*),
"sizeof(size_t) == sizeof(void*)");
static_assert(std::is_unsigned<size_t>::value,
"std::is_unsigned<size_t>::value");
static_assert(std::is_integral<size_t>::value,
"std::is_integral<size_t>::value");
static_assert(sizeof(ptrdiff_t) == sizeof(void*),
"sizeof(ptrdiff_t) == sizeof(void*)");
static_assert(std::is_signed<ptrdiff_t>::value,
"std::is_signed<ptrdiff_t>::value");
static_assert(std::is_integral<ptrdiff_t>::value,
"std::is_integral<ptrdiff_t>::value");
static_assert((std::is_same<decltype(nullptr), nullptr_t>::value),
"decltype(nullptr) == nullptr_t");
static_assert(sizeof(nullptr_t) == sizeof(void*),
"sizeof(nullptr_t) == sizeof(void*)");
static_assert(std::is_pod<max_align_t>::value,
"std::is_pod<max_align_t>::value");
static_assert((std::alignment_of<max_align_t>::value >=
std::alignment_of<long long>::value),
"std::alignment_of<max_align_t>::value >= "
"std::alignment_of<long long>::value");
static_assert(std::alignment_of<max_align_t>::value >=
std::alignment_of<long double>::value,
"std::alignment_of<max_align_t>::value >= "
"std::alignment_of<long double>::value");
static_assert(std::alignment_of<max_align_t>::value >=
std::alignment_of<void*>::value,
"std::alignment_of<max_align_t>::value >= "
"std::alignment_of<void*>::value");
}
<|endoftext|> |
<commit_before>#include "AssemblyRegister.h"
#include "core/log.h"
#include "ProDBGAPI.h"
#include <stdlib.h>
#include <string.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace prodbg
{
enum
{
MaxRegisterCount = 256,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AssemblyRegister* AssemblyRegister_buildFromReader(PDReader* reader, AssemblyRegister* registers, int* countIn)
{
PDReaderIterator it;
int count = *countIn;
PDRead_findArray(reader, &it, "registers", 0);
if (!it)
{
log_info("Unable to find any registers array\n");
*countIn = 0;
return 0;
}
if (!registers)
{
registers = (AssemblyRegister*)malloc(sizeof(AssemblyRegister) * MaxRegisterCount);
memset(registers, 0, sizeof(AssemblyRegister) * MaxRegisterCount);
}
while (PDRead_getNextEntry(reader, &it))
{
AssemblyRegister* reg = 0;
uint64_t regValue;
const char* name = "";
PDRead_findString(reader, &name, "name", it);
uint32_t type = PDRead_findU64(reader, ®Value, "register", it);
// find entry or insert
for (int i = 0; i < count; ++i)
{
if (!strcmp(name, registers[i].name))
{
reg = ®isters[i];
break;
}
}
// insert the reg if we couldn't find it
if (!reg)
{
if (count >= MaxRegisterCount)
{
log_error("More than %d registers! Unable to handle this without bumping the limit\n", count);
*countIn = count;
return registers;
}
reg = ®isters[count++];
strcpy(reg->name, name);
reg->nameLength = (int)strlen(name);
switch (type & PDReadStatus_typeMask)
{
case PDReadType_u8 : reg->type = AssemblyRegisterType_u8; break;
case PDReadType_u16 : reg->type = AssemblyRegisterType_u16; break;
case PDReadType_u32 : reg->type = AssemblyRegisterType_u32; break;
case PDReadType_u64 : reg->type = AssemblyRegisterType_u64; break;
case PDReadType_float : reg->type = AssemblyRegisterType_float; break;
case PDReadType_double : reg->type = AssemblyRegisterType_double; break;
}
PDRead_findU16(reader, ®->readOnly, "read_only", it);
PDRead_findU16(reader, ®->statusFlags, "flags", it);
}
// TODO: Handle if we have registers that are wider than 64-bit
reg->value.u64 = regValue;
}
*countIn = count;
return registers;
}
}
<commit_msg>Fixed so float/dobules works correctly<commit_after>#include "AssemblyRegister.h"
#include "core/log.h"
#include "ProDBGAPI.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace prodbg
{
enum
{
MaxRegisterCount = 256,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AssemblyRegister* AssemblyRegister_buildFromReader(PDReader* reader, AssemblyRegister* registers, int* countIn)
{
PDReaderIterator it;
int count = *countIn;
PDRead_findArray(reader, &it, "registers", 0);
if (!it)
{
log_info("Unable to find any registers array\n");
*countIn = 0;
return 0;
}
if (!registers)
{
registers = (AssemblyRegister*)malloc(sizeof(AssemblyRegister) * MaxRegisterCount);
memset(registers, 0, sizeof(AssemblyRegister) * MaxRegisterCount);
}
while (PDRead_getNextEntry(reader, &it))
{
AssemblyRegister* reg = 0;
uint64_t regValue;
const char* name = "";
PDRead_findString(reader, &name, "name", it);
uint32_t type = PDRead_findU64(reader, ®Value, "register", it);
// find entry or insert
for (int i = 0; i < count; ++i)
{
if (!strcmp(name, registers[i].name))
{
reg = ®isters[i];
break;
}
}
// insert the reg if we couldn't find it
if (!reg)
{
if (count >= MaxRegisterCount)
{
log_error("More than %d registers! Unable to handle this without bumping the limit\n", count);
*countIn = count;
return registers;
}
reg = ®isters[count++];
strcpy(reg->name, name);
reg->nameLength = (int)strlen(name);
switch (type & PDReadStatus_typeMask)
{
case PDReadType_u8 : reg->type = AssemblyRegisterType_u8; break;
case PDReadType_u16 : reg->type = AssemblyRegisterType_u16; break;
case PDReadType_u32 : reg->type = AssemblyRegisterType_u32; break;
case PDReadType_u64 : reg->type = AssemblyRegisterType_u64; break;
case PDReadType_float :
{
PDRead_findFloat(reader, ®->value.f, "register", it);
reg->type = AssemblyRegisterType_float;
break;
}
case PDReadType_double :
{
PDRead_findDouble(reader, ®->value.d, "register", it);
reg->type = AssemblyRegisterType_double;
break;
}
}
}
reg->value.u64 = regValue;
switch (type & PDReadStatus_typeMask)
{
case PDReadType_float :
{
PDRead_findFloat(reader, ®->value.f, "register", it);
break;
}
case PDReadType_double :
{
PDRead_findDouble(reader, ®->value.d, "register", it);
break;
}
}
PDRead_findU16(reader, ®->readOnly, "read_only", it);
PDRead_findU16(reader, ®->statusFlags, "flags", it);
}
*countIn = count;
return registers;
}
}
<|endoftext|> |
<commit_before>// Sietronics Sieray CPI format
// Licence: Lesser GNU Public License 2.1 (LGPL)
#define BUILDING_XYLIB
#include "cpi.h"
#include "util.h"
using namespace std;
using namespace xylib::util;
namespace xylib {
const FormatInfo CpiDataSet::fmt_info(
"cpi",
"Sietronics Sieray CPI",
"cpi",
false, // whether binary
false, // whether has multi-blocks
&CpiDataSet::ctor,
&CpiDataSet::check
);
bool CpiDataSet::check(istream &f, string*)
{
string line;
getline(f, line);
return str_startwith(line, "SIETRONICS XRD SCAN");
}
void CpiDataSet::load_data(std::istream &f)
{
/* format example:
SIETRONICS XRD SCAN
10.00
155.00
0.010
Cu
1.54056
1-1-1900
0.600
HH117 CaO:Nb2O5 neutron batch .0
SCANDATA
8992
9077
9017
9018
9129
9057
...
*/
Block* blk = new Block;
string s;
getline (f, s); // first line
getline (f, s);//xmin
double xmin = my_strtod(s);
getline (f, s); //xmax
getline (f, s); //xstep
double xstep = my_strtod(s);
StepColumn *xcol = new StepColumn(xmin, xstep);
blk->add_column(xcol);
// ignore the rest of the header
while (!str_startwith(s, "SCANDATA"))
getline (f, s);
// data
VecColumn *ycol = new VecColumn();
while (getline(f, s))
ycol->add_val(my_strtod(s));
blk->add_column(ycol);
add_block(blk);
}
} // namespace xylib
<commit_msg>cpi.cpp: avoid infinite loop<commit_after>// Sietronics Sieray CPI format
// Licence: Lesser GNU Public License 2.1 (LGPL)
#define BUILDING_XYLIB
#include "cpi.h"
#include "util.h"
using namespace std;
using namespace xylib::util;
namespace xylib {
const FormatInfo CpiDataSet::fmt_info(
"cpi",
"Sietronics Sieray CPI",
"cpi",
false, // whether binary
false, // whether has multi-blocks
&CpiDataSet::ctor,
&CpiDataSet::check
);
bool CpiDataSet::check(istream &f, string*)
{
string line;
getline(f, line);
return str_startwith(line, "SIETRONICS XRD SCAN");
}
void CpiDataSet::load_data(std::istream &f)
{
/* format example:
SIETRONICS XRD SCAN
10.00
155.00
0.010
Cu
1.54056
1-1-1900
0.600
HH117 CaO:Nb2O5 neutron batch .0
SCANDATA
8992
9077
9017
9018
9129
9057
...
*/
Block* blk = new Block;
string s;
getline (f, s); // first line
getline (f, s);//xmin
double xmin = my_strtod(s);
getline (f, s); //xmax
getline (f, s); //xstep
double xstep = my_strtod(s);
StepColumn *xcol = new StepColumn(xmin, xstep);
blk->add_column(xcol);
// ignore the rest of the header
while (getline(f, s))
if (str_startwith(s, "SCANDATA"))
break;
format_assert(this, f, "missing SCANDATA");
// data
VecColumn *ycol = new VecColumn();
while (getline(f, s))
ycol->add_val(my_strtod(s));
blk->add_column(ycol);
add_block(blk);
}
} // namespace xylib
<|endoftext|> |
<commit_before>#include <QtCore/QFile>
#include <QtTest/QtTest>
#include <QMimeDatabase>
class tst_QMimeType : public QObject
{
Q_OBJECT
public:
tst_QMimeType();
~tst_QMimeType();
private Q_SLOTS:
void initTestCase();
void findByName_data();
void findByName();
void findByData_data();
void findByData();
void findByFile_data();
void findByFile();
private:
QMimeDatabase database;
};
tst_QMimeType::tst_QMimeType() :
database()
{
}
tst_QMimeType::~tst_QMimeType()
{
}
void tst_QMimeType::initTestCase()
{
}
void tst_QMimeType::findByName_data()
{
QTest::addColumn<QString>("filePath");
QTest::addColumn<QString>("mimeType");
QTest::addColumn<QString>("xFail");
QString prefix = QLatin1String(SRCDIR "testfiles/");
QFile f(prefix + QLatin1String("list"));
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray line(1024, Qt::Uninitialized);
while (!f.atEnd()) {
int len = f.readLine(line.data(), 1023);
if (len <= 2 || line.at(0) == '#')
continue;
QString string = QString::fromLatin1(line.constData(), len - 1).trimmed();
QStringList list = string.split(QLatin1Char(' '), QString::SkipEmptyParts);
QVERIFY(list.size() >= 2);
QString filePath = list.at(0);
QString mimeType = list.at(1);
QString xFail;
if (list.size() == 3)
xFail = list.at(2);
QTest::newRow(filePath.toLatin1().constData()) << prefix + filePath << mimeType << xFail;
}
}
void tst_QMimeType::findByName()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
//qDebug() << Q_FUNC_INFO << filePath;
const QString resultMimeTypeName = database.findByName(filePath).name();
//qDebug() << Q_FUNC_INFO << "findByName() returned" << resultMimeTypeName;
// Results are ambiguous when multiple MIME types have the same glob
// -> accept the current result if the found MIME type actually
// matches the file's extension.
const QMimeType foundMimeType = database.mimeTypeForName(resultMimeTypeName);
const QString extension = QFileInfo(filePath).suffix();
//qDebug() << Q_FUNC_INFO << "globPatterns:" << foundMimeType.globPatterns() << "- extension:" << QString() + "*." + extension;
if (foundMimeType.globPatterns().contains("*." + extension))
return;
const bool shouldFail = (xFail.length() >= 1 && xFail.at(0) == QLatin1Char('x'));
if (shouldFail) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
} else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_QMimeType::findByData_data()
{
findByName_data();
}
void tst_QMimeType::findByData()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
QFile f(filePath);
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray data = f.readAll();
const QString resultMimeTypeName = database.findByData(data).name();
if (xFail.length() >= 2 && xFail.at(1) == QLatin1Char('x')) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
}
else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_QMimeType::findByFile_data()
{
findByName_data();
}
void tst_QMimeType::findByFile()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
const QString resultMimeTypeName = database.findByFile(QFileInfo(filePath)).name();
//qDebug() << Q_FUNC_INFO << filePath << "->" << resultMimeTypeName;
if (xFail.length() >= 3 && xFail.at(2) == QLatin1Char('x')) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
}
else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
QTEST_APPLESS_MAIN(tst_QMimeType)
#include "tst_qmimedatabase.moc"
<commit_msg>corrected class name.<commit_after>#include <QtCore/QFile>
#include <QtTest/QtTest>
#include <QMimeDatabase>
class tst_qmimedatabase : public QObject
{
Q_OBJECT
public:
tst_qmimedatabase();
~tst_qmimedatabase();
private Q_SLOTS:
void initTestCase();
void findByName_data();
void findByName();
void findByData_data();
void findByData();
void findByFile_data();
void findByFile();
private:
QMimeDatabase database;
};
tst_qmimedatabase::tst_qmimedatabase() :
database()
{
}
tst_qmimedatabase::~tst_qmimedatabase()
{
}
void tst_qmimedatabase::initTestCase()
{
}
void tst_qmimedatabase::findByName_data()
{
QTest::addColumn<QString>("filePath");
QTest::addColumn<QString>("mimeType");
QTest::addColumn<QString>("xFail");
QString prefix = QLatin1String(SRCDIR "testfiles/");
QFile f(prefix + QLatin1String("list"));
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray line(1024, Qt::Uninitialized);
while (!f.atEnd()) {
int len = f.readLine(line.data(), 1023);
if (len <= 2 || line.at(0) == '#')
continue;
QString string = QString::fromLatin1(line.constData(), len - 1).trimmed();
QStringList list = string.split(QLatin1Char(' '), QString::SkipEmptyParts);
QVERIFY(list.size() >= 2);
QString filePath = list.at(0);
QString mimeType = list.at(1);
QString xFail;
if (list.size() == 3)
xFail = list.at(2);
QTest::newRow(filePath.toLatin1().constData()) << prefix + filePath << mimeType << xFail;
}
}
void tst_qmimedatabase::findByName()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
//qDebug() << Q_FUNC_INFO << filePath;
const QString resultMimeTypeName = database.findByName(filePath).name();
//qDebug() << Q_FUNC_INFO << "findByName() returned" << resultMimeTypeName;
// Results are ambiguous when multiple MIME types have the same glob
// -> accept the current result if the found MIME type actually
// matches the file's extension.
const QMimeType foundMimeType = database.mimeTypeForName(resultMimeTypeName);
const QString extension = QFileInfo(filePath).suffix();
//qDebug() << Q_FUNC_INFO << "globPatterns:" << foundMimeType.globPatterns() << "- extension:" << QString() + "*." + extension;
if (foundMimeType.globPatterns().contains("*." + extension))
return;
const bool shouldFail = (xFail.length() >= 1 && xFail.at(0) == QLatin1Char('x'));
if (shouldFail) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
} else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_qmimedatabase::findByData_data()
{
findByName_data();
}
void tst_qmimedatabase::findByData()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
QFile f(filePath);
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray data = f.readAll();
const QString resultMimeTypeName = database.findByData(data).name();
if (xFail.length() >= 2 && xFail.at(1) == QLatin1Char('x')) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
}
else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_qmimedatabase::findByFile_data()
{
findByName_data();
}
void tst_qmimedatabase::findByFile()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
const QString resultMimeTypeName = database.findByFile(QFileInfo(filePath)).name();
//qDebug() << Q_FUNC_INFO << filePath << "->" << resultMimeTypeName;
if (xFail.length() >= 3 && xFail.at(2) == QLatin1Char('x')) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
}
else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
QTEST_APPLESS_MAIN(tst_qmimedatabase)
#include "tst_qmimedatabase.moc"
<|endoftext|> |
<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "RndBoundingBoxIC.h"
#include "MooseRandom.h"
template<>
InputParameters validParams<RndBoundingBoxIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addClassDescription("Random noise with different min/max inside/outside of a bounding box");
params.addRequiredParam<Real>("x1", "The x coordinate of the lower left-hand corner of the box");
params.addRequiredParam<Real>("y1", "The y coordinate of the lower left-hand corner of the box");
params.addParam<Real>("z1", 0.0, "The z coordinate of the lower left-hand corner of the box");
params.addRequiredParam<Real>("x2", "The x coordinate of the upper right-hand corner of the box");
params.addRequiredParam<Real>("y2", "The y coordinate of the upper right-hand corner of the box");
params.addParam<Real>("z2", 0.0, "The z coordinate of the upper right-hand corner of the box");
params.addRequiredParam<Real>("mx_invalue", "The max value of the variable invalue the box");
params.addRequiredParam<Real>("mx_outvalue", "The max value of the variable outvalue the box");
params.addParam<Real>("mn_invalue", 0.0, "The min value of the variable invalue the box");
params.addParam<Real>("mn_outvalue", 0.0, "The min value of the variable outvalue the box");
return params;
}
RndBoundingBoxIC::RndBoundingBoxIC(const std::string & name,
InputParameters parameters) :
InitialCondition(name, parameters),
_x1(parameters.get<Real>("x1")),
_y1(parameters.get<Real>("y1")),
_z1(parameters.get<Real>("z1")),
_x2(parameters.get<Real>("x2")),
_y2(parameters.get<Real>("y2")),
_z2(parameters.get<Real>("z2")),
_mx_invalue(parameters.get<Real>("mx_invalue")),
_mx_outvalue(parameters.get<Real>("mx_outvalue")),
_mn_invalue(parameters.get<Real>("mn_invalue")),
_mn_outvalue(parameters.get<Real>("mn_outvalue")),
_range_invalue(_mx_invalue - _mn_invalue),
_range_outvalue(_mx_outvalue - _mn_outvalue),
_bottom_left(_x1, _y1, _z1),
_top_right(_x2, _y2, _z2)
{
mooseAssert(_range_invalue >= 0.0, "Inside Min > Inside Max for RandomIC!");
mooseAssert(_range_outvalue >= 0.0, "Outside Min > Outside Max for RandomIC!");
}
Real
RndBoundingBoxIC::value(const Point & p)
{
//Random number between 0 and 1
Real rand_num = MooseRandom::rand();
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
if (p(i) < _bottom_left(i) || p(i) > _top_right(i))
return rand_num * _range_outvalue + _mn_outvalue;
return rand_num * _range_invalue + _mn_invalue;
}
<commit_msg>Update MultiRectangleBoxIC.C<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "MultiRectangleBoxIC.h"
#include "MooseRandom.h"
template<>
InputParameters validParams<RndBoundingBoxIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addClassDescription("Random noise with different min/max inside/outside of a bounding box");
params.addRequiredParam<Real>("x1", "The x coordinate of the lower left-hand corner of the box");
params.addRequiredParam<Real>("y1", "The y coordinate of the lower left-hand corner of the box");
params.addParam<Real>("z1", 0.0, "The z coordinate of the lower left-hand corner of the box");
params.addRequiredParam<Real>("x2", "The x coordinate of the upper right-hand corner of the box");
params.addRequiredParam<Real>("y2", "The y coordinate of the upper right-hand corner of the box");
params.addParam<Real>("z2", 0.0, "The z coordinate of the upper right-hand corner of the box");
params.addRequiredParam<Real>("mx_invalue", "The max value of the variable invalue the box");
params.addRequiredParam<Real>("mx_outvalue", "The max value of the variable outvalue the box");
params.addParam<Real>("mn_invalue", 0.0, "The min value of the variable invalue the box");
params.addParam<Real>("mn_outvalue", 0.0, "The min value of the variable outvalue the box");
return params;
}
RndBoundingBoxIC::RndBoundingBoxIC(const std::string & name,
InputParameters parameters) :
InitialCondition(name, parameters),
_x1(parameters.get<Real>("x1")),
_y1(parameters.get<Real>("y1")),
_z1(parameters.get<Real>("z1")),
_x2(parameters.get<Real>("x2")),
_y2(parameters.get<Real>("y2")),
_z2(parameters.get<Real>("z2")),
_mx_invalue(parameters.get<Real>("mx_invalue")),
_mx_outvalue(parameters.get<Real>("mx_outvalue")),
_mn_invalue(parameters.get<Real>("mn_invalue")),
_mn_outvalue(parameters.get<Real>("mn_outvalue")),
_range_invalue(_mx_invalue - _mn_invalue),
_range_outvalue(_mx_outvalue - _mn_outvalue),
_bottom_left(_x1, _y1, _z1),
_top_right(_x2, _y2, _z2)
{
mooseAssert(_range_invalue >= 0.0, "Inside Min > Inside Max for RandomIC!");
mooseAssert(_range_outvalue >= 0.0, "Outside Min > Outside Max for RandomIC!");
}
Real
RndBoundingBoxIC::value(const Point & p)
{
//Random number between 0 and 1
Real rand_num = MooseRandom::rand();
for (unsigned int i = 0; i < LIBMESH_DIM; ++i)
if (p(i) < _bottom_left(i) || p(i) > _top_right(i))
return rand_num * _range_outvalue + _mn_outvalue;
return rand_num * _range_invalue + _mn_invalue;
}
<|endoftext|> |
<commit_before>#include "InternetButton/InternetButton.h"
InternetButton b = InternetButton();
int ohpm(String command);
int j=0;
int i=0;
int sirenPin = 0;
int sirenCounter = 0;
int disconnectTimer = 0;
boolean alarm = false;
boolean light = false;
boolean trouble = false;
boolean disconnected = false;
void setup()
{
Particle.function("ohpm", ohpm);
pinMode(sirenPin, OUTPUT);
delay(10);
RGB.control(true);
RGB.color(0, 0, 0);
b.begin();
greenWave();
beep1();
}
void loop() {
if (alarm == true) {
tone(sirenPin, 4000);
for (int x=0; x<5; x++) {
b.allLedsOn(255,0,0);
delay(50);
b.allLedsOff();
delay(50);
}
tone(sirenPin, 5000);
for (int y=0; y<5; y++) {
b.allLedsOn(0,0,255);
delay(50);
b.allLedsOff();
delay(50);
}
}
if (trouble == true) {
orangeWave(1);
sirenCounter = sirenCounter + 1;
if (sirenCounter == 20) {
tone(sirenPin, 4000);
}
if (sirenCounter > 20) {
noTone(sirenPin);
sirenCounter = 0;
}
}
if (disconnected == true) {
yellowWave(1);
blueWave(1);
sirenCounter = sirenCounter + 1;
if (sirenCounter == 20) {
tone(sirenPin, 4000);
}
if (sirenCounter > 20) {
noTone(sirenPin);
sirenCounter = 0;
}
}
disconnectTimer = disconnectTimer + 1;
if (disconnectTimer >= 60000) {
disconnected = true;
}
delay(10);
}
int ohpm(String command)
{
if (command == "1") {
alarm = true;
}
if (command == "2") {
alarm = false;
b.allLedsOff();
noTone(sirenPin);
greenWave();
}
if (command == "3") {
light = true;
b.allLedsOn(100, 100, 100);
}
if (command == "4") {
light = false;
b.allLedsOn(0, 0, 0);
}
if (command == "5") {
trouble = true;
}
if (command == "6") {
trouble = false;
blueWave(2);
}
if (command == "7") {
yellowWave(2);
}
if (command == "10") {
disconnectTimer = 0;
//beep1();
b.smoothLedOn(6, 0, 5, 0);
delay(50);
b.smoothLedOn(6, 0, 0, 0);
}
}
void blueWave(int n) {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 0, 0, 255);
delay(50);
b.smoothLedOn(q, 0, 0, 0);
}
}
void yellowWave(int n) {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 255, 255, 0);
delay(50);
b.smoothLedOn(q, 0, 0, 0);
}
}
void orangeWave(int n) {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 255, 153, 0);
delay(20);
b.smoothLedOn(q, 0, 0, 0);
}
}
void greenWave() {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 0, 50, 0);
delay(50);
}
//delay(10);
for (int w=0; w<12; w++) {
b.ledOff(w);
delay(50);
}
}
void beep1()
{
beep(4000, 50, 50);
beep(4000, 50, 0);
}
void beep2()
{
beep(4000, 50, 50);
beep(4000, 1000, 0);
}
void beep3()
{
beep(4000, 200, 50);
beep(4650, 500, 0);
}
void beep4()
{
beep(4125, 100, 50);
beep(4000, 500, 0);
}
void beep(int freq, int duration, int wait)
{
tone(sirenPin, freq);
delay(duration);
noTone(sirenPin);
delay(wait);
}
<commit_msg>Pressing down on Internet Button now mutes audio and video feedback. Changes are not registered in openHAB.<commit_after>#include "InternetButton/InternetButton.h"
InternetButton b = InternetButton();
int ohpm(String command);
int j=0;
int i=0;
int sirenPin = 0;
int sirenCounter = 0;
int disconnectTimer = 0;
boolean alarm = false;
boolean light = false;
boolean trouble = false;
boolean disconnected = false;
void setup()
{
Particle.function("ohpm", ohpm);
pinMode(sirenPin, OUTPUT);
delay(10);
RGB.control(true);
RGB.color(0, 0, 0);
b.begin();
greenWave();
beep1();
}
void loop() {
if(b.allButtonsOn()) {
alarm = false;
trouble = false;
light = false;
noTone(0);
b.allLedsOff();
}
if (alarm == true) {
tone(sirenPin, 4000);
for (int x=0; x<5; x++) {
b.allLedsOn(255,0,0);
delay(50);
b.allLedsOff();
delay(50);
}
tone(sirenPin, 5000);
for (int y=0; y<5; y++) {
b.allLedsOn(0,0,255);
delay(50);
b.allLedsOff();
delay(50);
}
}
if (trouble == true) {
orangeWave(1);
sirenCounter = sirenCounter + 1;
if (sirenCounter == 20) {
tone(sirenPin, 4000);
}
if (sirenCounter > 20) {
noTone(sirenPin);
sirenCounter = 0;
}
}
if (disconnected == true) {
yellowWave(1);
blueWave(1);
sirenCounter = sirenCounter + 1;
if (sirenCounter == 20) {
tone(sirenPin, 4000);
}
if (sirenCounter > 20) {
noTone(sirenPin);
sirenCounter = 0;
}
}
disconnectTimer = disconnectTimer + 1;
if (disconnectTimer >= 60000) {
disconnected = true;
}
delay(10);
}
int ohpm(String command)
{
if (command == "1") {
alarm = true;
}
if (command == "2") {
alarm = false;
b.allLedsOff();
noTone(sirenPin);
greenWave();
}
if (command == "3") {
light = true;
b.allLedsOn(100, 100, 100);
}
if (command == "4") {
light = false;
b.allLedsOn(0, 0, 0);
}
if (command == "5") {
trouble = true;
}
if (command == "6") {
trouble = false;
blueWave(2);
}
if (command == "7") {
yellowWave(2);
}
if (command == "10") {
disconnectTimer = 0;
//beep1();
b.smoothLedOn(6, 0, 5, 0);
delay(50);
b.smoothLedOn(6, 0, 0, 0);
}
}
void blueWave(int n) {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 0, 0, 255);
delay(50);
b.smoothLedOn(q, 0, 0, 0);
}
}
void yellowWave(int n) {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 255, 255, 0);
delay(50);
b.smoothLedOn(q, 0, 0, 0);
}
}
void orangeWave(int n) {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 255, 153, 0);
delay(20);
b.smoothLedOn(q, 0, 0, 0);
}
}
void greenWave() {
for (int q=0; q<12; q++) {
b.smoothLedOn(q, 0, 50, 0);
delay(50);
}
//delay(10);
for (int w=0; w<12; w++) {
b.ledOff(w);
delay(50);
}
}
void beep1()
{
beep(4000, 50, 50);
beep(4000, 50, 0);
}
void beep2()
{
beep(4000, 50, 50);
beep(4000, 1000, 0);
}
void beep3()
{
beep(4000, 200, 50);
beep(4650, 500, 0);
}
void beep4()
{
beep(4125, 100, 50);
beep(4000, 500, 0);
}
void beep(int freq, int duration, int wait)
{
tone(sirenPin, freq);
delay(duration);
noTone(sirenPin);
delay(wait);
}<|endoftext|> |
<commit_before>/**
* @file trace.H
*
* Internal trace definitions and functions. External users should
* not directly include or use this file. trace/interface.H is the external
* file.
*/
#ifndef __TRACE_TRACE_H
#define __TRACE_TRACE_H
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <util/singleton.H>
#include <sys/mutex.h>
/******************************************************************************/
// Globals/Constants
/******************************************************************************/
const uint32_t TRACE_BUF_VERSION = 0x01; // Trace buffer version
const uint32_t TRACE_FIELDTRACE = 0x4654; // Field Trace - "FT"
const uint32_t TRACE_FIELDBIN = 0x4644; // Binary Field Trace - "FD"
const uint32_t TRACE_DEBUG_ON = 1; //Set to this when debug trace on
const uint32_t TRACE_DEBUG_OFF = 0; //Set to this when debug trace off
const uint32_t TRAC_COMP_SIZE = 16; // Max component name size
const uint32_t TRAC_MAX_ARGS = 9; // Max number of arguments in trace
/******************************************************************************/
// Typedef/Enumerations
/******************************************************************************/
typedef uint32_t trace_hash_val; // Hash values are 32 bytes
/*
* @brief Structure is put at beginning of all trace buffers
*/
typedef struct trace_buf_head {
unsigned char ver; /*!< version of this struct (1) */
unsigned char hdr_len; /*!< size of this struct in bytes */
unsigned char time_flg; /*!< meaning of timestamp entry field */
unsigned char endian_flg; /*!< flag for big ('B') or little ('L') endian*/
char comp[TRAC_COMP_SIZE]; /*!< the buffer name as specified in init call*/
uint32_t size; /*!< size of buffer, including this struct */
uint32_t times_wrap; /*!< how often the buffer wrapped */
uint32_t next_free; /*!< offset of the byte behind the latest entry*/
uint32_t te_count; /*!< Updated each time a trace is done */
uint32_t extracted; /*!< Not currently used */
}trace_buf_head_t;
/*!
* @brief Timestamp and thread id for each trace entry.
*/
typedef struct trace_entry_stamp {
uint32_t tbh; /*!< timestamp upper part */
uint32_t tbl; /*!< timestamp lower part */
uint32_t tid; /*!< process/thread id */
}trace_entry_stamp_t;
/*
* @brief Structure is used by adal app. layer to fill in trace info.
*/
typedef struct trace_entry_head {
uint16_t length; /*!< size of trace entry */
uint16_t tag; /*!< type of entry: xTRACE xDUMP, (un)packed */
uint32_t hash; /*!< a value for the (format) string */
uint32_t line; /*!< source file line number of trace call */
}trace_entry_head_t;
/*
* @brief Parameter traces can be all contained in one write.
*/
typedef struct trace_entire_entry {
trace_entry_stamp_t stamp;
trace_entry_head_t head;
uint64_t args[TRAC_MAX_ARGS + 1]; /*!< Add 1 for the required buffer size */
} trace_entire_entry_t;
/*
* @brief Binary first writes header and time stamp.
*/
typedef struct trace_bin_entry {
trace_entry_stamp_t stamp;
trace_entry_head_t head;
} trace_bin_entry_t;
/**
* @brief New version name of this typedef
*/
typedef trace_buf_head_t trace_desc_t;
/******************************************************************************/
// Trace Class
/******************************************************************************/
namespace TRACE
{
// Singleton definition
class Trace;
typedef Singleton<Trace> theTrace;
/**
* @brief Trace Singleton Class
*
* This class managers the internals of the host boot trace implementation.
*/
class Trace
{
public:
/**
* @brief Initialize a trace buffer
*
* @param o_td[out] Trace descriptor to initialize
* @param i_comp[in] Component name for trace buffer
* @param i_size[in] Size to allocate for trace buffer
*
* @return void
*/
void initBuffer(trace_desc_t **o_td,
const char* i_comp,
const size_t i_size );
/**
* @brief Write component trace out to input buffer
*
* Note that to continue to support tracepp, we must keep the
* name of this function as is.
*
* @param io_td[inout] Trace descriptor of buffer to write to.
* @param i_hash[in] Descriptive string hash value
* @param i_fmt [in] Formatting string
* @param i_line[in] Line number trace was done at
* @param i_type[in] Type of trace (TRACE_DEBUG, TRACE_FIELD)
*
* @return void
*/
void trace_adal_write_all(trace_desc_t *io_td,
const trace_hash_val i_hash,
const char * i_fmt,
const uint32_t i_line,
const int32_t i_type, ...);
/**
* @brief Write binary data out to trace buffer
*
* Note that to continue to support tracepp, we must keep the
* name of this function as is.
*
* @param io_td[inout] Trace descriptor of buffer to write to.
* @param i_hash[in] Descriptive string hash value
* @param i_line[in] Line number trace was done at
* @param i_ptr[in] Pointer to binary data
* @param i_size[in] Size of binary data
* @param i_type[in] Type of trace (TRACE_DEBUG, TRACE_FIELD)
*
* @return void
*/
void trace_adal_write_bin(trace_desc_t * io_td,
const trace_hash_val i_hash,
const uint32_t i_line,
const void *i_ptr,
const uint32_t i_size,
const int32_t type);
protected:
/**
* @brief Constructor for the trace object.
*/
Trace();
/**
* @brief Destructor for the trace object.
*/
~Trace();
private:
/**
* @brief Initialize a new trace buffer
*
* Internal function responsible setting up the defaults in a newly created
* trace buffer.
*
* @param[out] o_buf Trace descriptor of component buffer to initialize.
* @param[in] i_comp Component name
*
* @return void
*
*/
void initValuesBuffer(trace_desc_t *o_buf,
const char *i_comp);
/**
* @brief Write the trace data into the buffer
*
* Internal function responsible for copying the trace data into the appropriate
* buffer.
*
* @param[inout] io_td Trace descriptor of component buffer to write to.
* @param[in] i_ptr Pointer to data to copy into the trace buffer.
* @param[in] i_size Size of the i_ptr data to copy into the buffer.
*
* @return void
*
*/
void writeData(trace_desc_t * io_td,
const void *i_ptr,
const uint32_t i_size);
/**
* @brief Retrieve full trace buffer for component i_comp
*
* This function assumes memory has already been allocated for
* the full trace buffer in o_data.
*
* @param i_td_ptr Trace descriptor of buffer to retrieve.
* @param o_data Pre-allocated pointer to where data will be stored.
*
* TODO - Not Supported Yet
*
* @return Non-zero return code on error
*/
int32_t getBuffer(const trace_desc_t * i_td_ptr,
void *o_data);
/**
* @brief Retrieve partial trace buffer for component i_comp
*
* This function assumes memory has already been allocated for
* the trace buffer (size io_size). This function will copy
* in up to io_size in bytes to the buffer and set io_size
* to the exact size that is copied in.
*
* TODO - Not Supported Yet
*
* @param i_td_ptr Trace descriptor of buffer to retrieve.
* @param o_data Pre-allocated pointer to where data will be stored.
* @param io_size Size of trace data to retrieve (input)
* Actual size of trace data stored (output)
*
* @return Non-zero return code on error
*/
int32_t getBufferPartial(const trace_desc_t * i_td_ptr,
void *o_data,
uint32_t *io_size);
/**
* @brief Retrieve trace descriptor for input component name
*
* @param i_comp Component name to retrieve trace descriptor for.
*
* TODO - Not Supported Yet
*
* @return Valid trace descriptor on success, NULL on failure.
*/
trace_desc_t * getTd(const char *i_comp);
/**
* @brief Reset all trace buffers
*
* TODO - Not Supported Yet
*
* @return Non-zero return code on error
*/
int32_t resetBuf(void);
/**
* @brief Convert timestamp
*
* @param [out] o_entry Trace entry stamp to fill in the time info for.
*
* @return Void
*/
void convertTime(trace_entry_stamp_t *o_entry);
// Disabled copy constructor and assignment operator
Trace(const Trace & right);
Trace & operator=(const Trace & right);
// Global Mutex
mutex_t iv_trac_mutex;
};
} // namespace TRACE
#endif
<commit_msg>Fixed doxygen tags within trace header file.<commit_after>/**
* @file trace.H
*
* Internal trace definitions and functions. External users should
* not directly include or use this file. trace/interface.H is the external
* file.
*/
#ifndef __TRACE_TRACE_H
#define __TRACE_TRACE_H
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <util/singleton.H>
#include <sys/mutex.h>
/******************************************************************************/
// Globals/Constants
/******************************************************************************/
const uint32_t TRACE_BUF_VERSION = 0x01; // Trace buffer version
const uint32_t TRACE_FIELDTRACE = 0x4654; // Field Trace - "FT"
const uint32_t TRACE_FIELDBIN = 0x4644; // Binary Field Trace - "FD"
const uint32_t TRACE_DEBUG_ON = 1; //Set to this when debug trace on
const uint32_t TRACE_DEBUG_OFF = 0; //Set to this when debug trace off
const uint32_t TRAC_COMP_SIZE = 16; // Max component name size
const uint32_t TRAC_MAX_ARGS = 9; // Max number of arguments in trace
/******************************************************************************/
// Typedef/Enumerations
/******************************************************************************/
typedef uint32_t trace_hash_val; // Hash values are 32 bytes
/*
* @brief Structure is put at beginning of all trace buffers
*/
typedef struct trace_buf_head {
unsigned char ver; /*!< version of this struct (1) */
unsigned char hdr_len; /*!< size of this struct in bytes */
unsigned char time_flg; /*!< meaning of timestamp entry field */
unsigned char endian_flg; /*!< flag for big ('B') or little ('L') endian*/
char comp[TRAC_COMP_SIZE]; /*!< the buffer name as specified in init call*/
uint32_t size; /*!< size of buffer, including this struct */
uint32_t times_wrap; /*!< how often the buffer wrapped */
uint32_t next_free; /*!< offset of the byte behind the latest entry*/
uint32_t te_count; /*!< Updated each time a trace is done */
uint32_t extracted; /*!< Not currently used */
}trace_buf_head_t;
/*!
* @brief Timestamp and thread id for each trace entry.
*/
typedef struct trace_entry_stamp {
uint32_t tbh; /*!< timestamp upper part */
uint32_t tbl; /*!< timestamp lower part */
uint32_t tid; /*!< process/thread id */
}trace_entry_stamp_t;
/*
* @brief Structure is used by adal app. layer to fill in trace info.
*/
typedef struct trace_entry_head {
uint16_t length; /*!< size of trace entry */
uint16_t tag; /*!< type of entry: xTRACE xDUMP, (un)packed */
uint32_t hash; /*!< a value for the (format) string */
uint32_t line; /*!< source file line number of trace call */
}trace_entry_head_t;
/*
* @brief Parameter traces can be all contained in one write.
*/
typedef struct trace_entire_entry {
trace_entry_stamp_t stamp;
trace_entry_head_t head;
uint64_t args[TRAC_MAX_ARGS + 1]; /*!< Add 1 for the required buffer size */
} trace_entire_entry_t;
/*
* @brief Binary first writes header and time stamp.
*/
typedef struct trace_bin_entry {
trace_entry_stamp_t stamp;
trace_entry_head_t head;
} trace_bin_entry_t;
/**
* @brief New version name of this typedef
*/
typedef trace_buf_head_t trace_desc_t;
/******************************************************************************/
// Trace Class
/******************************************************************************/
namespace TRACE
{
// Singleton definition
class Trace;
typedef Singleton<Trace> theTrace;
/**
* @brief Trace Singleton Class
*
* This class managers the internals of the host boot trace implementation.
*/
class Trace
{
public:
/**
* @brief Initialize a trace buffer
*
* @param [out] o_td Trace descriptor to initialize
* @param [in] i_comp Component name for trace buffer
* @param [in] i_size Size to allocate for trace buffer
*
* @return void
*/
void initBuffer(trace_desc_t **o_td,
const char* i_comp,
const size_t i_size );
/**
* @brief Write component trace out to input buffer
*
* Note that to continue to support tracepp, we must keep the
* name of this function as is.
*
* @param [in,out] io_td Trace descriptor of buffer to write to.
* @param [in] i_hash Descriptive string hash value
* @param [in] i_fmt Formatting string
* @param [in] i_line Line number trace was done at
* @param [in] i_type Type of trace (TRACE_DEBUG, TRACE_FIELD)
*
* @return void
*/
void trace_adal_write_all(trace_desc_t *io_td,
const trace_hash_val i_hash,
const char * i_fmt,
const uint32_t i_line,
const int32_t i_type, ...);
/**
* @brief Write binary data out to trace buffer
*
* Note that to continue to support tracepp, we must keep the
* name of this function as is.
*
* @param [in,out] io_td Trace descriptor of buffer to write to.
* @param [in] i_hash Descriptive string hash value
* @param [in] i_line Line number trace was done at
* @param [in] i_ptr Pointer to binary data
* @param [in] i_size Size of binary data
* @param [in] i_type Type of trace (TRACE_DEBUG, TRACE_FIELD)
*
* @return void
*/
void trace_adal_write_bin(trace_desc_t * io_td,
const trace_hash_val i_hash,
const uint32_t i_line,
const void *i_ptr,
const uint32_t i_size,
const int32_t i_type);
protected:
/**
* @brief Constructor for the trace object.
*/
Trace();
/**
* @brief Destructor for the trace object.
*/
~Trace();
private:
/**
* @brief Initialize a new trace buffer
*
* Internal function responsible setting up the defaults in a newly created
* trace buffer.
*
* @param [out] o_buf Trace descriptor of component buffer to initialize.
* @param [in] i_comp Component name
*
* @return void
*
*/
void initValuesBuffer(trace_desc_t *o_buf,
const char *i_comp);
/**
* @brief Write the trace data into the buffer
*
* Internal function responsible for copying the trace data into the appropriate
* buffer.
*
* @param [in,out] io_td Trace descriptor of component buffer to write to.
* @param [in] i_ptr Pointer to data to copy into the trace buffer.
* @param [in] i_size Size of the i_ptr data to copy into the buffer.
*
* @return void
*
*/
void writeData(trace_desc_t * io_td,
const void *i_ptr,
const uint32_t i_size);
/**
* @brief Retrieve full trace buffer for component i_comp
*
* This function assumes memory has already been allocated for
* the full trace buffer in o_data.
*
* @param [in] i_td_ptr Trace descriptor of buffer to retrieve.
* @param [out] o_data Pre-allocated pointer to where data will be stored.
*
* TODO - Not Supported Yet
*
* @return Non-zero return code on error
*/
int32_t getBuffer(const trace_desc_t * i_td_ptr,
void *o_data);
/**
* @brief Retrieve partial trace buffer for component i_comp
*
* This function assumes memory has already been allocated for
* the trace buffer (size io_size). This function will copy
* in up to io_size in bytes to the buffer and set io_size
* to the exact size that is copied in.
*
* TODO - Not Supported Yet
*
* @param [in] i_td_ptr Trace descriptor of buffer to retrieve.
* @param [out] o_data Pre-allocated pointer to where data will be stored.
* @param [in,out] io_size Size of trace data to retrieve (input)
* Actual size of trace data stored (output)
*
* @return Non-zero return code on error
*/
int32_t getBufferPartial(const trace_desc_t * i_td_ptr,
void *o_data,
uint32_t *io_size);
/**
* @brief Retrieve trace descriptor for input component name
*
* @param [in] i_comp Component name to retrieve trace descriptor for.
*
* TODO - Not Supported Yet
*
* @return Valid trace descriptor on success, NULL on failure.
*/
trace_desc_t * getTd(const char *i_comp);
/**
* @brief Reset all trace buffers
*
* TODO - Not Supported Yet
*
* @return Non-zero return code on error
*/
int32_t resetBuf(void);
/**
* @brief Convert timestamp
*
* @param [out] o_entry Trace entry stamp to fill in the time info for.
*
* @return Void
*/
void convertTime(trace_entry_stamp_t *o_entry);
// Disabled copy constructor and assignment operator
Trace(const Trace & right);
Trace & operator=(const Trace & right);
// Global Mutex
mutex_t iv_trac_mutex;
};
} // namespace TRACE
#endif
<|endoftext|> |
<commit_before>/* individual.hpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Header file for interface of an individual representing a
* gentically generated solution function
*/
#ifndef _INDIVIDUAL_H_
#define _INDIVIDUAL_H_
#include <vector>
#include <memory>
#include "../problem/problem.hpp"
namespace individual {
using problem::Problem;
using std::string;
enum Function {
null,
constant, input,
sqrt, sin, log, exp,
add, subtract, divide, multiply, pow,
lesser, greater };
struct Size {
int internals = 0;
int leafs = 0;
};
class Node {
private:
Function function = null;
int arity = 0; // space for time trade-off
double k = 0; // excess for internal nodes
std::vector<Node> children;
void set_constant(const double &, const double &);
void mutate_self(const double &, const double &);
public:
Node() {};
Node(const Problem &, const int & depth = 0);
string print() const;
string represent() const;
double evaluate(const double &) const;
const Size size() const;
Node & visit(const Size &, Size &);
void mutate_tree(const double &, const double &, const double &);
};
class Individual {
private:
Size size;
double fitness;
Node root;
void update_size();
public:
Individual() {}
Individual(const Problem &);
string print_formula() const;
string print_calculation(const problem::pairs &) const;
int get_internals() const {return size.internals;}
int get_leafs() const {return size.leafs;}
int get_total() const {return size.internals + size.leafs;}
double get_fitness() const {return fitness;}
void evaluate(const problem::pairs &);
void mutate(const double &, const double &, const double &);
friend void crossover(Individual &, Individual &);
Node & operator[](const Size &);
};
}
#endif /* _INDIVIDUAL_H_ */
<commit_msg>Add default constructor to Size struct<commit_after>/* individual.hpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Header file for interface of an individual representing a
* gentically generated solution function
*/
#ifndef _INDIVIDUAL_H_
#define _INDIVIDUAL_H_
#include <vector>
#include <memory>
#include "../problem/problem.hpp"
namespace individual {
using problem::Problem;
using std::string;
enum Function {
null,
constant, input,
sqrt, sin, log, exp,
add, subtract, divide, multiply, pow,
lesser, greater };
struct Size {
int internals;
int leafs;
Size(const int & i = 0, const int & l = 0): internals(i), leafs(l) {}
};
class Node {
private:
Function function = null;
int arity = 0; // space for time trade-off
double k = 0; // excess for internal nodes
std::vector<Node> children;
void set_constant(const double &, const double &);
void mutate_self(const double &, const double &);
public:
Node() {};
Node(const Problem &, const int & depth = 0);
string print() const;
string represent() const;
double evaluate(const double &) const;
const Size size() const;
Node & visit(const Size &, Size &);
void mutate_tree(const double &, const double &, const double &);
};
class Individual {
private:
Size size;
double fitness;
Node root;
void update_size();
public:
Individual() {}
Individual(const Problem &);
string print_formula() const;
string print_calculation(const problem::pairs &) const;
int get_internals() const {return size.internals;}
int get_leafs() const {return size.leafs;}
int get_total() const {return size.internals + size.leafs;}
double get_fitness() const {return fitness;}
void evaluate(const problem::pairs &);
void mutate(const double &, const double &, const double &);
friend void crossover(Individual &, Individual &);
Node & operator[](const Size &);
};
}
#endif /* _INDIVIDUAL_H_ */
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file 11cxx_async_can.cxx
* This file implements an asynchronous CAN driver for the LPC11Cxx
* microcontrollers, using the builtin ROM drivers.
*
* @author Balazs Racz
* @date 14 Dec 2013
*/
#ifdef TARGET_LPC11Cxx
#include "11CXX_rom_driver_CAN.h"
#include "can.h"
#include "nmranet_config.h"
#include "executor/StateFlow.hxx"
#include "utils/Hub.hxx"
typedef struct _ROM
{
const unsigned p_usbd;
const unsigned p_clib;
const CAND *pCAND;
} ROM;
/** Pointer to the ROM call structures. */
const ROM *const *const rom = (ROM **)0x1fff1ff8;
namespace lpc11cxx
{
#define FIRST_TX_OBJ 1
#define FIRST_RX_OBJ 16
class CanPipeMember;
class CanRxFlow;
/* Static instances of the CAN drivers */
CanPipeMember *g_tx_instance = nullptr;
CanRxFlow *g_rx_instance = nullptr;
CanHubFlow *g_pipe = nullptr;
class CanPipeMember : public CanHubPort
{
public:
CanPipeMember(Service *s)
: CanHubPort(s)
, freeTxBuffers_(0xFFFFFFFF)
, frameToWrite_(nullptr)
, bufferFull_(0)
{
}
Action entry() OVERRIDE
{
AtomicHolder h(this);
HASSERT(!frameToWrite_);
frameToWrite_ = message()->data()->mutable_frame();
return call_immediately(STATE(try_send));
}
Action try_send()
{
HASSERT(frameToWrite_);
const struct can_frame *frame = nullptr;
uint8_t buf_num = FIRST_TX_OBJ;
{
AtomicHolder h(this);
// Looks for a free tx buffer.
while (buf_num < FIRST_RX_OBJ &&
(!(freeTxBuffers_ & (1 << buf_num))))
{
buf_num++;
}
if (buf_num >= FIRST_RX_OBJ)
{
// Wait for ISR to wake us up.
bufferFull_ = 1;
return wait();
}
freeTxBuffers_ &= ~(1 << buf_num);
// We decided to send the frame.
frame = frameToWrite_;
frameToWrite_ = nullptr; // no callbacks from ISR.
}
CAN_MSG_OBJ msg_obj;
msg_obj.msgobj = buf_num;
msg_obj.mode_id = frame->can_id |
(frame->can_rtr ? CAN_MSGOBJ_RTR : 0) |
(frame->can_eff ? CAN_MSGOBJ_EXT : 0);
msg_obj.mask = 0x0;
msg_obj.dlc = frame->can_dlc;
memcpy(msg_obj.data, frame->data, frame->can_dlc);
(*rom)->pCAND->can_transmit(&msg_obj);
// The incoming frame is no longer needed.
return release_and_exit();
}
void TxFinishedFromIsr(uint8_t buf_num)
{
HASSERT(!(freeTxBuffers_ & (1 << buf_num)));
freeTxBuffers_ |= (1 << buf_num);
if (frameToWrite_ && bufferFull_)
{
bufferFull_ = 0;
service()->executor()->add_from_isr(this, priority());
}
}
private:
uint32_t freeTxBuffers_;
const struct can_frame *frameToWrite_;
// 1 if we are waiting for a free tx buffer.
unsigned bufferFull_ : 1;
};
class CanRxFlow : public StateFlowBase, private Atomic
{
public:
CanRxFlow(Service *s)
: StateFlowBase(s)
, bufFull_(0)
, rxPending_(1)
, frameLost_(0)
{
/* Configures msgobj NN to receive all extended frames. */
CAN_MSG_OBJ msg_obj;
msg_obj.msgobj = FIRST_RX_OBJ;
msg_obj.mode_id = 0x000 | CAN_MSGOBJ_EXT;
msg_obj.mask = 0x000;
msg_obj.dlc = 0x000;
(*rom)->pCAND->config_rxmsgobj(&msg_obj);
start_flow(STATE(wait_or_copy));
}
// Callback inside the ISR context. @param buf_num is the number of the
// message object in the hardware.
void isr(uint8_t buf_num)
{
if (bufFull_)
{
// Another interrupt came in before we have cleared the buffer.
frameLost_ = 1;
return;
}
else
{
bufFull_ = 1;
}
if (!rxPending_)
{
service()->executor()->add_from_isr(this);
}
}
Action wait_or_copy()
{
{
AtomicHolder h(this);
if (!bufFull_)
{
rxPending_ = 0;
return wait();
}
}
return allocate_and_call(g_pipe, STATE(allocation_complete));
}
// Scheduled by the ISR when the frame has arrived.
Action allocation_complete()
{
HASSERT(bufFull_);
auto *b = get_allocation_result(g_pipe);
{
AtomicHolder h(this);
copy_hardware_frame(FIRST_RX_OBJ, b->data()->mutable_frame());
}
b->data()->skipMember_ = g_tx_instance;
g_pipe->send(b);
return call_immediately(STATE(wait_or_copy));
}
private:
// Has to run either in ISR or in a critical section. Retrieves a hardware
// buffer and copies it to the class-local can_frame.
void copy_hardware_frame(uint8_t buf_num, struct can_frame* frame)
{
HASSERT(bufFull_);
CAN_MSG_OBJ msg_obj;
/* Determine which CAN message has been received */
msg_obj.msgobj = buf_num;
/* Now load up the msg_obj structure with the CAN message */
(*rom)->pCAND->can_receive(&msg_obj);
// Here we need to be in a critical section; otherwise another CAN
// interrupt might come in between these two calls.
bufFull_ = 0;
rxPending_ = 0;
frame->can_id = msg_obj.mode_id & ((1 << 29) - 1);
// JMRI crashes the node here.
// HASSERT(frame->can_id & 0xfff);
frame->can_rtr = (msg_obj.mode_id & CAN_MSGOBJ_RTR) ? 1 : 0;
frame->can_eff = (msg_obj.mode_id & CAN_MSGOBJ_EXT) ? 1 : 0;
frame->can_err = 0;
frame->can_dlc = msg_obj.dlc;
memcpy(frame->data, msg_obj.data, msg_obj.dlc);
}
// 1 if the hardware object for RX has a frame.
unsigned bufFull_ : 1;
// 1 if the state flow is in operation, 0 if the state flow can be
// scheduled.
unsigned rxPending_ : 1;
// 1 if we have lost a frame.
unsigned frameLost_ : 1;
};
/** CAN receive callback. Called by the ROM can driver in an ISR context.
@param msg_obj_num the number of CAN buffer that has the new frame.
*/
void CAN_rx(uint8_t msg_obj_num)
{
HASSERT(g_rx_instance);
g_rx_instance->isr(msg_obj_num);
// We always assume there is someone woken up. This is not nice.
portYIELD();
}
/** CAN transmit callback. Called by the ROM can driver in an ISR context.
@param msg_obj_num the number of CAN buffer that finished transmission.
*/
void CAN_tx(uint8_t msg_obj_num)
{
HASSERT(g_tx_instance);
g_tx_instance->TxFinishedFromIsr(msg_obj_num);
// We always assume there is someone woken up. This is not nice.
portYIELD();
}
/** CAN error callback. Called by the ROM can driver in an ISR context.
@param error_info defines what kind of error occured on the bus.
*/
void CAN_error(uint32_t error_info)
{
return;
}
/** Function pointer table to pass to the ROM drivers with callbacks. */
static const CAN_CALLBACKS callbacks = {CAN_rx, CAN_tx, CAN_error, NULL,
NULL, NULL, NULL, NULL, };
/** Clock initialization constants for 125 kbaud */
const uint32_t ClkInitTable125[2] = {0x00000000UL, // CANCLKDIV
0x00001C57UL // CAN_BTR
};
/** Clock initialization constants for 250 kbaud */
static const uint32_t ClkInitTable250[2] = {0x00000000UL, // CANCLKDIV
0x00001C4BUL // CAN_BTR
};
void CreateCanDriver(CanHubFlow *parent)
{
if (config_nmranet_can_bitrate() == 250000) {
/* Initialize the CAN controller */
(*rom)->pCAND->init_can((uint32_t *)&ClkInitTable250[0], 1);
} else if ((config_nmranet_can_bitrate() == 125000)) {
/* Initialize the CAN controller */
(*rom)->pCAND->init_can((uint32_t *)&ClkInitTable125[0], 1);
} else {
DIE("Unknown can bitrate.");
}
/* Configure the CAN callback functions */
(*rom)->pCAND->config_calb((CAN_CALLBACKS *)&callbacks);
g_pipe = parent;
g_rx_instance = new CanRxFlow(parent->service());
g_tx_instance = new CanPipeMember(parent->service());
parent->register_port(g_tx_instance);
/* Enable the CAN Interrupt */
NVIC_SetPriority(CAN_IRQn, 1);
NVIC_EnableIRQ(CAN_IRQn);
}
} // namespace lpc11cxx
extern "C" {
/** Overrides the system's weak interrupt handler and calls the builtin ROM
* interrupt handler. */
void CAN_IRQHandler(void)
{
(*rom)->pCAND->isr();
}
}
#else
#error You need to define TARGET_LPC11Cxx if you want to compiple its rom driver.
#endif
<commit_msg>reformat 11cxx async can<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file 11cxx_async_can.cxx
* This file implements an asynchronous CAN driver for the LPC11Cxx
* microcontrollers, using the builtin ROM drivers.
*
* @author Balazs Racz
* @date 14 Dec 2013
*/
#ifdef TARGET_LPC11Cxx
#include "11CXX_rom_driver_CAN.h"
#include "can.h"
#include "nmranet_config.h"
#include "executor/StateFlow.hxx"
#include "utils/Hub.hxx"
typedef struct _ROM
{
const unsigned p_usbd;
const unsigned p_clib;
const CAND *pCAND;
} ROM;
/** Pointer to the ROM call structures. */
const ROM *const *const rom = (ROM **)0x1fff1ff8;
namespace lpc11cxx
{
#define FIRST_TX_OBJ 1
#define FIRST_RX_OBJ 16
class CanPipeMember;
class CanRxFlow;
/* Static instances of the CAN drivers */
CanPipeMember *g_tx_instance = nullptr;
CanRxFlow *g_rx_instance = nullptr;
CanHubFlow *g_pipe = nullptr;
class CanPipeMember : public CanHubPort
{
public:
CanPipeMember(Service *s)
: CanHubPort(s)
, freeTxBuffers_(0xFFFFFFFF)
, frameToWrite_(nullptr)
, bufferFull_(0)
{
}
Action entry() OVERRIDE
{
AtomicHolder h(this);
HASSERT(!frameToWrite_);
frameToWrite_ = message()->data()->mutable_frame();
return call_immediately(STATE(try_send));
}
Action try_send()
{
HASSERT(frameToWrite_);
const struct can_frame *frame = nullptr;
uint8_t buf_num = FIRST_TX_OBJ;
{
AtomicHolder h(this);
// Looks for a free tx buffer.
while (buf_num < FIRST_RX_OBJ &&
(!(freeTxBuffers_ & (1 << buf_num))))
{
buf_num++;
}
if (buf_num >= FIRST_RX_OBJ)
{
// Wait for ISR to wake us up.
bufferFull_ = 1;
return wait();
}
freeTxBuffers_ &= ~(1 << buf_num);
// We decided to send the frame.
frame = frameToWrite_;
frameToWrite_ = nullptr; // no callbacks from ISR.
}
CAN_MSG_OBJ msg_obj;
msg_obj.msgobj = buf_num;
msg_obj.mode_id = frame->can_id |
(frame->can_rtr ? CAN_MSGOBJ_RTR : 0) |
(frame->can_eff ? CAN_MSGOBJ_EXT : 0);
msg_obj.mask = 0x0;
msg_obj.dlc = frame->can_dlc;
memcpy(msg_obj.data, frame->data, frame->can_dlc);
(*rom)->pCAND->can_transmit(&msg_obj);
// The incoming frame is no longer needed.
return release_and_exit();
}
void TxFinishedFromIsr(uint8_t buf_num)
{
HASSERT(!(freeTxBuffers_ & (1 << buf_num)));
freeTxBuffers_ |= (1 << buf_num);
if (frameToWrite_ && bufferFull_)
{
bufferFull_ = 0;
service()->executor()->add_from_isr(this, priority());
}
}
private:
uint32_t freeTxBuffers_;
const struct can_frame *frameToWrite_;
// 1 if we are waiting for a free tx buffer.
unsigned bufferFull_ : 1;
};
class CanRxFlow : public StateFlowBase, private Atomic
{
public:
CanRxFlow(Service *s)
: StateFlowBase(s)
, bufFull_(0)
, rxPending_(1)
, frameLost_(0)
{
/* Configures msgobj NN to receive all extended frames. */
CAN_MSG_OBJ msg_obj;
msg_obj.msgobj = FIRST_RX_OBJ;
msg_obj.mode_id = 0x000 | CAN_MSGOBJ_EXT;
msg_obj.mask = 0x000;
msg_obj.dlc = 0x000;
(*rom)->pCAND->config_rxmsgobj(&msg_obj);
start_flow(STATE(wait_or_copy));
}
// Callback inside the ISR context. @param buf_num is the number of the
// message object in the hardware.
void isr(uint8_t buf_num)
{
if (bufFull_)
{
// Another interrupt came in before we have cleared the buffer.
frameLost_ = 1;
return;
}
else
{
bufFull_ = 1;
}
if (!rxPending_)
{
rxPending_ = 1;
// highest priority
service()->executor()->add_from_isr(this, 0);
}
}
Action wait_or_copy()
{
{
AtomicHolder h(this);
if (!bufFull_)
{
rxPending_ = 0;
return wait();
}
}
return allocate_and_call(g_pipe, STATE(allocation_complete));
}
// Scheduled by the ISR when the frame has arrived.
Action allocation_complete()
{
HASSERT(bufFull_);
auto *b = get_allocation_result(g_pipe);
{
AtomicHolder h(this);
copy_hardware_frame(FIRST_RX_OBJ, b->data()->mutable_frame());
}
b->data()->skipMember_ = g_tx_instance;
g_pipe->send(b);
return call_immediately(STATE(wait_or_copy));
}
private:
// Has to run either in ISR or in a critical section. Retrieves a hardware
// buffer and copies it to the class-local can_frame.
void copy_hardware_frame(uint8_t buf_num, struct can_frame* frame)
{
HASSERT(bufFull_);
CAN_MSG_OBJ msg_obj;
/* Determine which CAN message has been received */
msg_obj.msgobj = buf_num;
/* Now load up the msg_obj structure with the CAN message */
(*rom)->pCAND->can_receive(&msg_obj);
// Here we need to be in a critical section; otherwise another CAN
// interrupt might come in between these two calls.
bufFull_ = 0;
rxPending_ = 0;
frame->can_id = msg_obj.mode_id & ((1 << 29) - 1);
// JMRI crashes the node here.
// HASSERT(frame->can_id & 0xfff);
frame->can_rtr = (msg_obj.mode_id & CAN_MSGOBJ_RTR) ? 1 : 0;
frame->can_eff = (msg_obj.mode_id & CAN_MSGOBJ_EXT) ? 1 : 0;
frame->can_err = 0;
frame->can_dlc = msg_obj.dlc;
memcpy(frame->data, msg_obj.data, msg_obj.dlc);
}
// 1 if the hardware object for RX has a frame.
unsigned bufFull_ : 1;
// 1 if the state flow is in operation, 0 if the state flow can be
// scheduled.
unsigned rxPending_ : 1;
// 1 if we have lost a frame.
unsigned frameLost_ : 1;
};
/** CAN receive callback. Called by the ROM can driver in an ISR context.
@param msg_obj_num the number of CAN buffer that has the new frame.
*/
void CAN_rx(uint8_t msg_obj_num)
{
HASSERT(g_rx_instance);
g_rx_instance->isr(msg_obj_num);
// We always assume there is someone woken up. This is not nice.
portYIELD();
}
/** CAN transmit callback. Called by the ROM can driver in an ISR context.
@param msg_obj_num the number of CAN buffer that finished transmission.
*/
void CAN_tx(uint8_t msg_obj_num)
{
HASSERT(g_tx_instance);
g_tx_instance->TxFinishedFromIsr(msg_obj_num);
// We always assume there is someone woken up. This is not nice.
portYIELD();
}
/** CAN error callback. Called by the ROM can driver in an ISR context.
@param error_info defines what kind of error occured on the bus.
*/
void CAN_error(uint32_t error_info)
{
return;
}
/** Function pointer table to pass to the ROM drivers with callbacks. */
static const CAN_CALLBACKS callbacks = {CAN_rx, CAN_tx, CAN_error, NULL,
NULL, NULL, NULL, NULL, };
/** Clock initialization constants for 125 kbaud */
static const uint32_t ClkInitTable125[2] = {0x00000000UL, // CANCLKDIV
0x00001C57UL // CAN_BTR
};
/** Clock initialization constants for 250 kbaud */
static const uint32_t ClkInitTable250[2] = {0x00000000UL, // CANCLKDIV
0x00001C4BUL // CAN_BTR
};
void CreateCanDriver(CanHubFlow *parent)
{
if (config_nmranet_can_bitrate() == 250000) {
/* Initialize the CAN controller */
(*rom)->pCAND->init_can((uint32_t *)&ClkInitTable250[0], 1);
} else if ((config_nmranet_can_bitrate() == 125000)) {
/* Initialize the CAN controller */
(*rom)->pCAND->init_can((uint32_t *)&ClkInitTable125[0], 1);
} else {
DIE("Unknown can bitrate.");
}
/* Configure the CAN callback functions */
(*rom)->pCAND->config_calb((CAN_CALLBACKS *)&callbacks);
g_pipe = parent;
g_rx_instance = new CanRxFlow(parent->service());
g_tx_instance = new CanPipeMember(parent->service());
parent->register_port(g_tx_instance);
/* Enable the CAN Interrupt */
NVIC_SetPriority(CAN_IRQn, 1);
NVIC_EnableIRQ(CAN_IRQn);
}
} // namespace lpc11cxx
extern "C" {
/** Overrides the system's weak interrupt handler and calls the builtin ROM
* interrupt handler. */
void CAN_IRQHandler(void)
{
(*rom)->pCAND->isr();
}
}
#else
#error You need to define TARGET_LPC11Cxx if you want to compiple its rom driver.
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConfigConversionEffect.h"
#include "GrContext.h"
#include "GrTBackendEffectFactory.h"
#include "GrSimpleTextureEffect.h"
#include "gl/GrGLEffect.h"
#include "gl/GrGLShaderBuilder.h"
#include "SkMatrix.h"
class GrGLConfigConversionEffect : public GrGLEffect {
public:
GrGLConfigConversionEffect(const GrBackendEffectFactory& factory,
const GrDrawEffect& drawEffect)
: INHERITED (factory) {
const GrConfigConversionEffect& effect = drawEffect.castEffect<GrConfigConversionEffect>();
fSwapRedAndBlue = effect.swapsRedAndBlue();
fPMConversion = effect.pmConversion();
}
virtual void emitCode(GrGLShaderBuilder* builder,
const GrDrawEffect&,
const GrEffectKey& key,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) SK_OVERRIDE {
builder->fsCodeAppendf("\t\t%s = ", outputColor);
builder->fsAppendTextureLookup(samplers[0], coords[0].c_str(), coords[0].type());
builder->fsCodeAppend(";\n");
if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
SkASSERT(fSwapRedAndBlue);
builder->fsCodeAppendf("\t%s = %s.bgra;\n", outputColor, outputColor);
} else {
const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
switch (fPMConversion) {
case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
builder->fsCodeAppendf(
"\t\t%s = vec4(ceil(%s.%s * %s.a * 255.0) / 255.0, %s.a);\n",
outputColor, outputColor, swiz, outputColor, outputColor);
break;
case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
// Add a compensation(0.001) here to avoid the side effect of the floor operation.
// In Intel GPUs, the integer value converted from floor(%s.r * 255.0) / 255.0
// is less than the integer value converted from %s.r by 1 when the %s.r is
// converted from the integer value 2^n, such as 1, 2, 4, 8, etc.
builder->fsCodeAppendf(
"\t\t%s = vec4(floor(%s.%s * %s.a * 255.0 + 0.001) / 255.0, %s.a);\n",
outputColor, outputColor, swiz, outputColor, outputColor);
break;
case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
builder->fsCodeAppendf("\t\t%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.%s / %s.a * 255.0) / 255.0, %s.a);\n",
outputColor, outputColor, outputColor, swiz, outputColor, outputColor);
break;
case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
builder->fsCodeAppendf("\t\t%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.%s / %s.a * 255.0) / 255.0, %s.a);\n",
outputColor, outputColor, outputColor, swiz, outputColor, outputColor);
break;
default:
SkFAIL("Unknown conversion op.");
break;
}
}
SkString modulate;
GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
builder->fsCodeAppend(modulate.c_str());
}
static inline void GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&,
GrEffectKeyBuilder* b) {
const GrConfigConversionEffect& conv = drawEffect.castEffect<GrConfigConversionEffect>();
uint32_t key = (conv.swapsRedAndBlue() ? 0 : 1) | (conv.pmConversion() << 1);
b->add32(key);
}
private:
bool fSwapRedAndBlue;
GrConfigConversionEffect::PMConversion fPMConversion;
typedef GrGLEffect INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion,
const SkMatrix& matrix)
: GrSingleTextureEffect(texture, matrix)
, fSwapRedAndBlue(swapRedAndBlue)
, fPMConversion(pmConversion) {
SkASSERT(kRGBA_8888_GrPixelConfig == texture->config() ||
kBGRA_8888_GrPixelConfig == texture->config());
// Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
SkASSERT(swapRedAndBlue || kNone_PMConversion != pmConversion);
}
const GrBackendEffectFactory& GrConfigConversionEffect::getFactory() const {
return GrTBackendEffectFactory<GrConfigConversionEffect>::getInstance();
}
bool GrConfigConversionEffect::onIsEqual(const GrEffect& s) const {
const GrConfigConversionEffect& other = CastEffect<GrConfigConversionEffect>(s);
return this->texture(0) == s.texture(0) &&
other.fSwapRedAndBlue == fSwapRedAndBlue &&
other.fPMConversion == fPMConversion;
}
void GrConfigConversionEffect::getConstantColorComponents(GrColor* color,
uint32_t* validFlags) const {
this->updateConstantColorComponentsForModulation(color, validFlags);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_EFFECT_TEST(GrConfigConversionEffect);
GrEffect* GrConfigConversionEffect::TestCreate(SkRandom* random,
GrContext*,
const GrDrawTargetCaps&,
GrTexture* textures[]) {
PMConversion pmConv = static_cast<PMConversion>(random->nextULessThan(kPMConversionCnt));
bool swapRB;
if (kNone_PMConversion == pmConv) {
swapRB = true;
} else {
swapRB = random->nextBool();
}
return SkNEW_ARGS(GrConfigConversionEffect,
(textures[GrEffectUnitTest::kSkiaPMTextureIdx],
swapRB,
pmConv,
GrEffectUnitTest::TestMatrix(random)));
}
///////////////////////////////////////////////////////////////////////////////
void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
PMConversion* pmToUPMRule,
PMConversion* upmToPMRule) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
uint32_t* srcData = data.get();
uint32_t* firstRead = data.get() + 256 * 256;
uint32_t* secondRead = data.get() + 2 * 256 * 256;
// Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
// values in row y. We set r,g, and b to the same value since they are handled identically.
for (int y = 0; y < 256; ++y) {
for (int x = 0; x < 256; ++x) {
uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
color[3] = y;
color[2] = SkTMin(x, y);
color[1] = SkTMin(x, y);
color[0] = SkTMin(x, y);
}
}
GrTextureDesc desc;
desc.fFlags = kRenderTarget_GrTextureFlagBit |
kNoStencil_GrTextureFlagBit;
desc.fWidth = 256;
desc.fHeight = 256;
desc.fConfig = kRGBA_8888_GrPixelConfig;
SkAutoTUnref<GrTexture> readTex(context->createUncachedTexture(desc, NULL, 0));
if (!readTex.get()) {
return;
}
SkAutoTUnref<GrTexture> tempTex(context->createUncachedTexture(desc, NULL, 0));
if (!tempTex.get()) {
return;
}
desc.fFlags = kNone_GrTextureFlags;
SkAutoTUnref<GrTexture> dataTex(context->createUncachedTexture(desc, data, 0));
if (!dataTex.get()) {
return;
}
static const PMConversion kConversionRules[][2] = {
{kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
{kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
};
GrContext::AutoWideOpenIdentityDraw awoid(context, NULL);
bool failed = true;
for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
*pmToUPMRule = kConversionRules[i][0];
*upmToPMRule = kConversionRules[i][1];
static const SkRect kDstRect = SkRect::MakeWH(SkIntToScalar(256), SkIntToScalar(256));
static const SkRect kSrcRect = SkRect::MakeWH(SK_Scalar1, SK_Scalar1);
// We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
// from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
// We then verify that two reads produced the same values.
SkAutoTUnref<GrEffect> pmToUPM1(SkNEW_ARGS(GrConfigConversionEffect, (dataTex,
false,
*pmToUPMRule,
SkMatrix::I())));
SkAutoTUnref<GrEffect> upmToPM(SkNEW_ARGS(GrConfigConversionEffect, (readTex,
false,
*upmToPMRule,
SkMatrix::I())));
SkAutoTUnref<GrEffect> pmToUPM2(SkNEW_ARGS(GrConfigConversionEffect, (tempTex,
false,
*pmToUPMRule,
SkMatrix::I())));
context->setRenderTarget(readTex->asRenderTarget());
GrPaint paint1;
paint1.addColorEffect(pmToUPM1);
context->drawRectToRect(paint1, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
context->setRenderTarget(tempTex->asRenderTarget());
GrPaint paint2;
paint2.addColorEffect(upmToPM);
context->drawRectToRect(paint2, kDstRect, kSrcRect);
context->setRenderTarget(readTex->asRenderTarget());
GrPaint paint3;
paint3.addColorEffect(pmToUPM2);
context->drawRectToRect(paint3, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
failed = false;
for (int y = 0; y < 256 && !failed; ++y) {
for (int x = 0; x <= y; ++x) {
if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
failed = true;
break;
}
}
}
}
if (failed) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
}
}
const GrEffect* GrConfigConversionEffect::Create(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion,
const SkMatrix& matrix) {
if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
// If we returned a GrConfigConversionEffect that was equivalent to a GrSimpleTextureEffect
// then we may pollute our texture cache with redundant shaders. So in the case that no
// conversions were requested we instead return a GrSimpleTextureEffect.
return GrSimpleTextureEffect::Create(texture, matrix);
} else {
if (kRGBA_8888_GrPixelConfig != texture->config() &&
kBGRA_8888_GrPixelConfig != texture->config() &&
kNone_PMConversion != pmConversion) {
// The PM conversions assume colors are 0..255
return NULL;
}
return SkNEW_ARGS(GrConfigConversionEffect, (texture,
swapRedAndBlue,
pmConversion,
matrix));
}
}
<commit_msg>Make GrGLConfigConversionEffect work for Imagination and some other GPUs.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConfigConversionEffect.h"
#include "GrContext.h"
#include "GrTBackendEffectFactory.h"
#include "GrSimpleTextureEffect.h"
#include "gl/GrGLEffect.h"
#include "gl/GrGLShaderBuilder.h"
#include "SkMatrix.h"
class GrGLConfigConversionEffect : public GrGLEffect {
public:
GrGLConfigConversionEffect(const GrBackendEffectFactory& factory,
const GrDrawEffect& drawEffect)
: INHERITED (factory) {
const GrConfigConversionEffect& effect = drawEffect.castEffect<GrConfigConversionEffect>();
fSwapRedAndBlue = effect.swapsRedAndBlue();
fPMConversion = effect.pmConversion();
}
virtual void emitCode(GrGLShaderBuilder* builder,
const GrDrawEffect&,
const GrEffectKey& key,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) SK_OVERRIDE {
// Using highp for GLES here in order to avoid some precision issues on specific GPUs.
GrGLShaderVar tmpVar("tmpColor", kVec4f_GrSLType, 0, GrGLShaderVar::kHigh_Precision);
SkString tmpDecl;
tmpVar.appendDecl(builder->ctxInfo(), &tmpDecl);
builder->fsCodeAppendf("%s;", tmpDecl.c_str());
builder->fsCodeAppendf("%s = ", tmpVar.c_str());
builder->fsAppendTextureLookup(samplers[0], coords[0].c_str(), coords[0].type());
builder->fsCodeAppend(";");
if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
SkASSERT(fSwapRedAndBlue);
builder->fsCodeAppendf("%s = %s.bgra;", outputColor, tmpVar.c_str());
} else {
const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
switch (fPMConversion) {
case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
builder->fsCodeAppendf(
"%s = vec4(ceil(%s.%s * %s.a * 255.0) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
break;
case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
// Add a compensation(0.001) here to avoid the side effect of the floor operation.
// In Intel GPUs, the integer value converted from floor(%s.r * 255.0) / 255.0
// is less than the integer value converted from %s.r by 1 when the %s.r is
// converted from the integer value 2^n, such as 1, 2, 4, 8, etc.
builder->fsCodeAppendf(
"%s = vec4(floor(%s.%s * %s.a * 255.0 + 0.001) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
break;
case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
builder->fsCodeAppendf(
"%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
break;
case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
builder->fsCodeAppendf(
"%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
break;
default:
SkFAIL("Unknown conversion op.");
break;
}
builder->fsCodeAppendf("%s = %s;", outputColor, tmpVar.c_str());
}
SkString modulate;
GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
builder->fsCodeAppend(modulate.c_str());
}
static inline void GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&,
GrEffectKeyBuilder* b) {
const GrConfigConversionEffect& conv = drawEffect.castEffect<GrConfigConversionEffect>();
uint32_t key = (conv.swapsRedAndBlue() ? 0 : 1) | (conv.pmConversion() << 1);
b->add32(key);
}
private:
bool fSwapRedAndBlue;
GrConfigConversionEffect::PMConversion fPMConversion;
typedef GrGLEffect INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion,
const SkMatrix& matrix)
: GrSingleTextureEffect(texture, matrix)
, fSwapRedAndBlue(swapRedAndBlue)
, fPMConversion(pmConversion) {
SkASSERT(kRGBA_8888_GrPixelConfig == texture->config() ||
kBGRA_8888_GrPixelConfig == texture->config());
// Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
SkASSERT(swapRedAndBlue || kNone_PMConversion != pmConversion);
}
const GrBackendEffectFactory& GrConfigConversionEffect::getFactory() const {
return GrTBackendEffectFactory<GrConfigConversionEffect>::getInstance();
}
bool GrConfigConversionEffect::onIsEqual(const GrEffect& s) const {
const GrConfigConversionEffect& other = CastEffect<GrConfigConversionEffect>(s);
return this->texture(0) == s.texture(0) &&
other.fSwapRedAndBlue == fSwapRedAndBlue &&
other.fPMConversion == fPMConversion;
}
void GrConfigConversionEffect::getConstantColorComponents(GrColor* color,
uint32_t* validFlags) const {
this->updateConstantColorComponentsForModulation(color, validFlags);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_EFFECT_TEST(GrConfigConversionEffect);
GrEffect* GrConfigConversionEffect::TestCreate(SkRandom* random,
GrContext*,
const GrDrawTargetCaps&,
GrTexture* textures[]) {
PMConversion pmConv = static_cast<PMConversion>(random->nextULessThan(kPMConversionCnt));
bool swapRB;
if (kNone_PMConversion == pmConv) {
swapRB = true;
} else {
swapRB = random->nextBool();
}
return SkNEW_ARGS(GrConfigConversionEffect,
(textures[GrEffectUnitTest::kSkiaPMTextureIdx],
swapRB,
pmConv,
GrEffectUnitTest::TestMatrix(random)));
}
///////////////////////////////////////////////////////////////////////////////
void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
PMConversion* pmToUPMRule,
PMConversion* upmToPMRule) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
uint32_t* srcData = data.get();
uint32_t* firstRead = data.get() + 256 * 256;
uint32_t* secondRead = data.get() + 2 * 256 * 256;
// Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
// values in row y. We set r,g, and b to the same value since they are handled identically.
for (int y = 0; y < 256; ++y) {
for (int x = 0; x < 256; ++x) {
uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
color[3] = y;
color[2] = SkTMin(x, y);
color[1] = SkTMin(x, y);
color[0] = SkTMin(x, y);
}
}
GrTextureDesc desc;
desc.fFlags = kRenderTarget_GrTextureFlagBit |
kNoStencil_GrTextureFlagBit;
desc.fWidth = 256;
desc.fHeight = 256;
desc.fConfig = kRGBA_8888_GrPixelConfig;
SkAutoTUnref<GrTexture> readTex(context->createUncachedTexture(desc, NULL, 0));
if (!readTex.get()) {
return;
}
SkAutoTUnref<GrTexture> tempTex(context->createUncachedTexture(desc, NULL, 0));
if (!tempTex.get()) {
return;
}
desc.fFlags = kNone_GrTextureFlags;
SkAutoTUnref<GrTexture> dataTex(context->createUncachedTexture(desc, data, 0));
if (!dataTex.get()) {
return;
}
static const PMConversion kConversionRules[][2] = {
{kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
{kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
};
GrContext::AutoWideOpenIdentityDraw awoid(context, NULL);
bool failed = true;
for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
*pmToUPMRule = kConversionRules[i][0];
*upmToPMRule = kConversionRules[i][1];
static const SkRect kDstRect = SkRect::MakeWH(SkIntToScalar(256), SkIntToScalar(256));
static const SkRect kSrcRect = SkRect::MakeWH(SK_Scalar1, SK_Scalar1);
// We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
// from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
// We then verify that two reads produced the same values.
SkAutoTUnref<GrEffect> pmToUPM1(SkNEW_ARGS(GrConfigConversionEffect, (dataTex,
false,
*pmToUPMRule,
SkMatrix::I())));
SkAutoTUnref<GrEffect> upmToPM(SkNEW_ARGS(GrConfigConversionEffect, (readTex,
false,
*upmToPMRule,
SkMatrix::I())));
SkAutoTUnref<GrEffect> pmToUPM2(SkNEW_ARGS(GrConfigConversionEffect, (tempTex,
false,
*pmToUPMRule,
SkMatrix::I())));
context->setRenderTarget(readTex->asRenderTarget());
GrPaint paint1;
paint1.addColorEffect(pmToUPM1);
context->drawRectToRect(paint1, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
context->setRenderTarget(tempTex->asRenderTarget());
GrPaint paint2;
paint2.addColorEffect(upmToPM);
context->drawRectToRect(paint2, kDstRect, kSrcRect);
context->setRenderTarget(readTex->asRenderTarget());
GrPaint paint3;
paint3.addColorEffect(pmToUPM2);
context->drawRectToRect(paint3, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
failed = false;
for (int y = 0; y < 256 && !failed; ++y) {
for (int x = 0; x <= y; ++x) {
if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
failed = true;
break;
}
}
}
}
if (failed) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
}
}
const GrEffect* GrConfigConversionEffect::Create(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion,
const SkMatrix& matrix) {
if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
// If we returned a GrConfigConversionEffect that was equivalent to a GrSimpleTextureEffect
// then we may pollute our texture cache with redundant shaders. So in the case that no
// conversions were requested we instead return a GrSimpleTextureEffect.
return GrSimpleTextureEffect::Create(texture, matrix);
} else {
if (kRGBA_8888_GrPixelConfig != texture->config() &&
kBGRA_8888_GrPixelConfig != texture->config() &&
kNone_PMConversion != pmConversion) {
// The PM conversions assume colors are 0..255
return NULL;
}
return SkNEW_ARGS(GrConfigConversionEffect, (texture,
swapRedAndBlue,
pmConversion,
matrix));
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: hwpf/fapi2/include/target_types.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file target_types.H
* @brief definitions for fapi2 target types
*/
#ifndef __FAPI2_TARGET_TYPES__
#define __FAPI2_TARGET_TYPES__
#include <stdint.h>
/// FAPI namespace
namespace fapi2
{
///
/// @enum fapi::TargetType
/// @brief Types, kinds, of targets
/// @note TYPE_NONE is used to represent empty/NULL targets in lists
/// or tables. TYPE_ALL is used to pass targets to methods which
/// can act generally on any type of target
///
/// Target Kind
enum TargetType
{
TARGET_TYPE_NONE = 0x00000000, ///< No type
TARGET_TYPE_SYSTEM = 0x00000001, ///< System type
TARGET_TYPE_DIMM = 0x00000002, ///< DIMM type
TARGET_TYPE_PROC_CHIP = 0x00000004, ///< Processor type
TARGET_TYPE_MEMBUF_CHIP = 0x00000008, ///< Membuf type
TARGET_TYPE_EX = 0x00000010, ///< EX - 2x Core, L2, L3 - can be deconfigured
TARGET_TYPE_MBA = 0x00000020, ///< MBA type
TARGET_TYPE_MCS = 0x00000040, ///< MCS type
TARGET_TYPE_XBUS = 0x00000080, ///< XBUS type
TARGET_TYPE_ABUS = 0x00000100, ///< ABUS type
TARGET_TYPE_L4 = 0x00000200, ///< L4 type
TARGET_TYPE_CORE = 0x00000400, ///< Core - 4x threads(?) - can be deconfigured
TARGET_TYPE_EQ = 0x00000800, ///< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured
TARGET_TYPE_MCA = 0x00001000, ///< MCA type
TARGET_TYPE_MCBIST = 0x00002000, ///< MCBIST type
TARGET_TYPE_MI = 0x00004000, ///< MI Memory Interface (Cumulus)
TARGET_TYPE_CAPP = 0x00008000, ///< CAPP target
TARGET_TYPE_DMI = 0x00010000, ///< DMI type
TARGET_TYPE_OBUS = 0x00020000, ///< OBUS type
TARGET_TYPE_NV = 0x00040000, ///< NV bus type
TARGET_TYPE_SBE = 0x00080000, ///< SBE type
TARGET_TYPE_PPE = 0x00100000, ///< PPE type
TARGET_TYPE_PERV = 0x00200000, ///< Pervasive type
TARGET_TYPE_PEC = 0x00400000, ///< PEC type
TARGET_TYPE_PHB = 0x00800000, ///< PHB type
TARGET_TYPE_ALL = 0xFFFFFFFF, ///< Any/All types
// Compound target types
TARGET_TYPE_CHIPS = TARGET_TYPE_PROC_CHIP |
TARGET_TYPE_MEMBUF_CHIP,
TARGET_TYPE_CHIPLETS = TARGET_TYPE_EX |
TARGET_TYPE_MBA |
TARGET_TYPE_MCS |
TARGET_TYPE_XBUS |
TARGET_TYPE_ABUS |
TARGET_TYPE_L4 |
TARGET_TYPE_CORE |
TARGET_TYPE_EQ |
TARGET_TYPE_MCA |
TARGET_TYPE_MCBIST |
TARGET_TYPE_MI |
TARGET_TYPE_DMI |
TARGET_TYPE_OBUS |
TARGET_TYPE_NV |
TARGET_TYPE_SBE |
TARGET_TYPE_PPE |
TARGET_TYPE_PERV |
TARGET_TYPE_PEC |
TARGET_TYPE_PHB,
// Mappings to target types found in the error xml files
TARGET_TYPE_EX_CHIPLET = TARGET_TYPE_EX,
TARGET_TYPE_MBA_CHIPLET = TARGET_TYPE_MBA,
TARGET_TYPE_MCS_CHIPLET = TARGET_TYPE_MCS,
TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS,
TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS,
};
///
/// @brief Enumeration of chiplet filters
///
enum TargetFilter
{
TARGET_FILTER_TP = 0x80000000, // Pervasive 1
TARGET_FILTER_NEST_NORTH = 0x40000000, // Pervasive 2
TARGET_FILTER_NEST_SOUTH = 0x20000000, // Pervasive 3
TARGET_FILTER_NEST_EAST = 0x10000000, // Pervasive 4
TARGET_FILTER_NEST_WEST = 0x08000000, // Pervasive 5
TARGET_FILTER_XBUS = 0x04000000, // Pervasive 6
TARGET_FILTER_MC_WEST = 0x02000000, // Pervasive 7
TARGET_FILTER_MC_EAST = 0x01000000, // Pervasive 8
TARGET_FILTER_OBUS0 = 0x00800000, // Pervasive 9
TARGET_FILTER_OBUS1 = 0x00400000, // Pervasive 10
TARGET_FILTER_OBUS2 = 0x00200000, // Pervasive 11
TARGET_FILTER_OBUS3 = 0x00100000, // Pervasive 12
TARGET_FILTER_PCI0 = 0x00080000, // Pervasive 13
TARGET_FILTER_PCI1 = 0x00040000, // Pervasive 14
TARGET_FILTER_PCI2 = 0x00020000, // Pervasive 15
// Composite filters follow
// Pervasive 2-5 (eg N0-N3) < req'd
TARGET_FILTER_ALL_NEST = (TARGET_FILTER_NEST_NORTH |
TARGET_FILTER_NEST_SOUTH | TARGET_FILTER_NEST_EAST |
TARGET_FILTER_NEST_WEST),
// Pervasive 2-4 (eg N0-N2) < req'd
TARGET_FILTER_NEST_SLAVES =
(TARGET_FILTER_NEST_NORTH | TARGET_FILTER_NEST_SOUTH |
TARGET_FILTER_NEST_EAST),
// Pervasive 5 (eg N32) < req'd
TARGET_FILTER_NEST_MASTER = TARGET_FILTER_NEST_WEST,
// Pervasive 7-8 (eg MC0-MC1)
TARGET_FILTER_ALL_MC =
(TARGET_FILTER_MC_WEST | TARGET_FILTER_MC_EAST),
// Pervasive 9-12 (OB0-OB3)
TARGET_FILTER_ALL_OBUS =
(TARGET_FILTER_OBUS0 | TARGET_FILTER_OBUS1 | TARGET_FILTER_OBUS2 |
TARGET_FILTER_OBUS3),
// Pervasive 13-15 (PCI0-PCI2)
TARGET_FILTER_ALL_PCI =
(TARGET_FILTER_PCI0 | TARGET_FILTER_PCI1 | TARGET_FILTER_PCI2),
// Sync mode filter = All NEST + All MCS
TARGET_FILTER_SYNC_MODE_NEST =
(TARGET_FILTER_ALL_NEST | TARGET_FILTER_ALL_MC),
// All IO Targets except NEST
TARGET_FILTER_ALL_IO_EXCEPT_NEST =
(TARGET_FILTER_XBUS | TARGET_FILTER_ALL_PCI | TARGET_FILTER_ALL_OBUS),
};
/// @cond
constexpr TargetType operator|(TargetType x, TargetType y)
{
return static_cast<TargetType>(static_cast<int>(x) |
static_cast<int>(y));
}
template<uint64_t V>
class bitCount
{
public:
// Don't use enums, too hard to compare
static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1);
};
template<>
class bitCount<0>
{
public:
static const uint8_t count = 0;
};
/// @endcond
}
#endif
<commit_msg>Updated target filter definitions<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: hwpf/fapi2/include/target_types.H $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file target_types.H
* @brief definitions for fapi2 target types
*/
#ifndef __FAPI2_TARGET_TYPES__
#define __FAPI2_TARGET_TYPES__
#include <stdint.h>
/// FAPI namespace
namespace fapi2
{
///
/// @enum fapi::TargetType
/// @brief Types, kinds, of targets
/// @note TYPE_NONE is used to represent empty/NULL targets in lists
/// or tables. TYPE_ALL is used to pass targets to methods which
/// can act generally on any type of target
///
/// Target Kind
enum TargetType
{
TARGET_TYPE_NONE = 0x00000000, ///< No type
TARGET_TYPE_SYSTEM = 0x00000001, ///< System type
TARGET_TYPE_DIMM = 0x00000002, ///< DIMM type
TARGET_TYPE_PROC_CHIP = 0x00000004, ///< Processor type
TARGET_TYPE_MEMBUF_CHIP = 0x00000008, ///< Membuf type
TARGET_TYPE_EX = 0x00000010, ///< EX - 2x Core, L2, L3 - can be deconfigured
TARGET_TYPE_MBA = 0x00000020, ///< MBA type
TARGET_TYPE_MCS = 0x00000040, ///< MCS type
TARGET_TYPE_XBUS = 0x00000080, ///< XBUS type
TARGET_TYPE_ABUS = 0x00000100, ///< ABUS type
TARGET_TYPE_L4 = 0x00000200, ///< L4 type
TARGET_TYPE_CORE = 0x00000400, ///< Core - 4x threads(?) - can be deconfigured
TARGET_TYPE_EQ = 0x00000800, ///< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured
TARGET_TYPE_MCA = 0x00001000, ///< MCA type
TARGET_TYPE_MCBIST = 0x00002000, ///< MCBIST type
TARGET_TYPE_MI = 0x00004000, ///< MI Memory Interface (Cumulus)
TARGET_TYPE_CAPP = 0x00008000, ///< CAPP target
TARGET_TYPE_DMI = 0x00010000, ///< DMI type
TARGET_TYPE_OBUS = 0x00020000, ///< OBUS type
TARGET_TYPE_NV = 0x00040000, ///< NV bus type
TARGET_TYPE_SBE = 0x00080000, ///< SBE type
TARGET_TYPE_PPE = 0x00100000, ///< PPE type
TARGET_TYPE_PERV = 0x00200000, ///< Pervasive type
TARGET_TYPE_PEC = 0x00400000, ///< PEC type
TARGET_TYPE_PHB = 0x00800000, ///< PHB type
TARGET_TYPE_ALL = 0xFFFFFFFF, ///< Any/All types
// Compound target types
TARGET_TYPE_CHIPS = TARGET_TYPE_PROC_CHIP |
TARGET_TYPE_MEMBUF_CHIP,
TARGET_TYPE_CHIPLETS = TARGET_TYPE_EX |
TARGET_TYPE_MBA |
TARGET_TYPE_MCS |
TARGET_TYPE_XBUS |
TARGET_TYPE_ABUS |
TARGET_TYPE_L4 |
TARGET_TYPE_CORE |
TARGET_TYPE_EQ |
TARGET_TYPE_MCA |
TARGET_TYPE_MCBIST |
TARGET_TYPE_MI |
TARGET_TYPE_DMI |
TARGET_TYPE_OBUS |
TARGET_TYPE_NV |
TARGET_TYPE_SBE |
TARGET_TYPE_PPE |
TARGET_TYPE_PERV |
TARGET_TYPE_PEC |
TARGET_TYPE_PHB,
// Mappings to target types found in the error xml files
TARGET_TYPE_EX_CHIPLET = TARGET_TYPE_EX,
TARGET_TYPE_MBA_CHIPLET = TARGET_TYPE_MBA,
TARGET_TYPE_MCS_CHIPLET = TARGET_TYPE_MCS,
TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS,
TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS,
};
///
/// @brief Enumeration of chiplet filters
///
enum TargetFilter
{
TARGET_FILTER_TP = 0x8000000000000000, // Pervasive 1
TARGET_FILTER_NEST_NORTH = 0x4000000000000000, // Pervasive 2
TARGET_FILTER_NEST_SOUTH = 0x2000000000000000, // Pervasive 3
TARGET_FILTER_NEST_EAST = 0x1000000000000000, // Pervasive 4
TARGET_FILTER_NEST_WEST = 0x0800000000000000, // Pervasive 5
TARGET_FILTER_XBUS = 0x0400000000000000, // Pervasive 6
TARGET_FILTER_MC_WEST = 0x0200000000000000, // Pervasive 7
TARGET_FILTER_MC_EAST = 0x0100000000000000, // Pervasive 8
TARGET_FILTER_OBUS0 = 0x0080000000000000, // Pervasive 9
TARGET_FILTER_OBUS1 = 0x0040000000000000, // Pervasive 10
TARGET_FILTER_OBUS2 = 0x0020000000000000, // Pervasive 11
TARGET_FILTER_OBUS3 = 0x0010000000000000, // Pervasive 12
TARGET_FILTER_PCI0 = 0x0008000000000000, // Pervasive 13
TARGET_FILTER_PCI1 = 0x0004000000000000, // Pervasive 14
TARGET_FILTER_PCI2 = 0x0002000000000000, // Pervasive 15
TARGET_FILTER_CACHE0 = 0x0001000000000000, // Pervasive 16
TARGET_FILTER_CACHE1 = 0x0000800000000000, // Pervasive 17
TARGET_FILTER_CACHE2 = 0x0000400000000000, // Pervasive 18
TARGET_FILTER_CACHE3 = 0x0000200000000000, // Pervasive 19
TARGET_FILTER_CACHE4 = 0x0000100000000000, // Pervasive 20
TARGET_FILTER_CACHE5 = 0x0000080000000000, // Pervasive 21
TARGET_FILTER_CORE0 = 0x0000040000000000, // Pervasive 32
TARGET_FILTER_CORE1 = 0x0000020000000000, // Pervasive 33
TARGET_FILTER_CORE2 = 0x0000010000000000, // Pervasive 34
TARGET_FILTER_CORE3 = 0x0000008000000000, // Pervasive 35
TARGET_FILTER_CORE4 = 0x0000004000000000, // Pervasive 36
TARGET_FILTER_CORE5 = 0x0000002000000000, // Pervasive 37
TARGET_FILTER_CORE6 = 0x0000001000000000, // Pervasive 38
TARGET_FILTER_CORE7 = 0x0000000800000000, // Pervasive 39
TARGET_FILTER_CORE8 = 0x0000000400000000, // Pervasive 40
TARGET_FILTER_CORE9 = 0x0000000200000000, // Pervasive 41
TARGET_FILTER_CORE10 = 0x0000000100000000, // Pervasive 42
TARGET_FILTER_CORE11 = 0x0000000080000000, // Pervasive 43
TARGET_FILTER_CORE12 = 0x0000000040000000, // Pervasive 44
TARGET_FILTER_CORE13 = 0x0000000020000000, // Pervasive 45
TARGET_FILTER_CORE14 = 0x0000000010000000, // Pervasive 46
TARGET_FILTER_CORE15 = 0x0000000008000000, // Pervasive 47
TARGET_FILTER_CORE16 = 0x0000000004000000, // Pervasive 48
TARGET_FILTER_CORE17 = 0x0000000002000000, // Pervasive 49
TARGET_FILTER_CORE18 = 0x0000000001000000, // Pervasive 50
TARGET_FILTER_CORE19 = 0x0000000000800000, // Pervasive 51
TARGET_FILTER_CORE20 = 0x0000000000400000, // Pervasive 52
TARGET_FILTER_CORE21 = 0x0000000000200000, // Pervasive 53
TARGET_FILTER_CORE22 = 0x0000000000100000, // Pervasive 54
TARGET_FILTER_CORE23 = 0x0000000000080000, // Pervasive 55
// Composite filters follow
// Pervasive 32-55 (all cores)
TARGET_FILTER_ALL_CORES = (TARGET_FILTER_CORE0 |
TARGET_FILTER_CORE1 | TARGET_FILTER_CORE2 |
TARGET_FILTER_CORE3 | TARGET_FILTER_CORE4 |
TARGET_FILTER_CORE5 | TARGET_FILTER_CORE6 |
TARGET_FILTER_CORE7 | TARGET_FILTER_CORE8 |
TARGET_FILTER_CORE9 | TARGET_FILTER_CORE10 |
TARGET_FILTER_CORE11 | TARGET_FILTER_CORE12 |
TARGET_FILTER_CORE13 | TARGET_FILTER_CORE14 |
TARGET_FILTER_CORE15 | TARGET_FILTER_CORE16 |
TARGET_FILTER_CORE17 | TARGET_FILTER_CORE18 |
TARGET_FILTER_CORE19 | TARGET_FILTER_CORE20 |
TARGET_FILTER_CORE21 | TARGET_FILTER_CORE22 |
TARGET_FILTER_CORE23),
// Pervasive 16-21 (all caches)
TARGET_FILTER_ALL_CACHES = (TARGET_FILTER_CACHE0 |
TARGET_FILTER_CACHE1 | TARGET_FILTER_CACHE2 |
TARGET_FILTER_CACHE3 | TARGET_FILTER_CACHE4 |
TARGET_FILTER_CACHE5),
// Pervasive 2-5 (eg N0-N3) < req'd
TARGET_FILTER_ALL_NEST = (TARGET_FILTER_NEST_NORTH |
TARGET_FILTER_NEST_SOUTH | TARGET_FILTER_NEST_EAST |
TARGET_FILTER_NEST_WEST),
// Pervasive 2-4 (eg N0-N2) < req'd
TARGET_FILTER_NEST_SLAVES =
(TARGET_FILTER_NEST_NORTH | TARGET_FILTER_NEST_SOUTH |
TARGET_FILTER_NEST_EAST),
// Pervasive 5 (eg N32) < req'd
TARGET_FILTER_NEST_MASTER = TARGET_FILTER_NEST_WEST,
// Pervasive 7-8 (eg MC0-MC1)
TARGET_FILTER_ALL_MC =
(TARGET_FILTER_MC_WEST | TARGET_FILTER_MC_EAST),
// Pervasive 9-12 (OB0-OB3)
TARGET_FILTER_ALL_OBUS =
(TARGET_FILTER_OBUS0 | TARGET_FILTER_OBUS1 | TARGET_FILTER_OBUS2 |
TARGET_FILTER_OBUS3),
// Pervasive 13-15 (PCI0-PCI2)
TARGET_FILTER_ALL_PCI =
(TARGET_FILTER_PCI0 | TARGET_FILTER_PCI1 | TARGET_FILTER_PCI2),
// Sync mode filter = All NEST + All MCS
TARGET_FILTER_SYNC_MODE_NEST =
(TARGET_FILTER_ALL_NEST | TARGET_FILTER_ALL_MC),
// All IO Targets except NEST
TARGET_FILTER_ALL_IO_EXCEPT_NEST =
(TARGET_FILTER_XBUS | TARGET_FILTER_ALL_PCI | TARGET_FILTER_ALL_OBUS),
// All sync mode IO except NEST
TARGET_FILTER_SYNC_MODE_ALL_IO_EXCEPT_NEST =
(TARGET_FILTER_ALL_MC | TARGET_FILTER_XBUS | TARGET_FILTER_ALL_PCI |
TARGET_FILTER_ALL_OBUS),
// All sync mode NEST slaves
TARGET_FILTER_SYNC_MODE_NEST_SLAVES =
(TARGET_FILTER_ALL_MC | TARGET_FILTER_NEST_SLAVES),
// All sync mode IO
TARGET_FILTER_SYNC_MODE_ALL_IO =
(TARGET_FILTER_ALL_MC | TARGET_FILTER_ALL_NEST |
TARGET_FILTER_ALL_OBUS | TARGET_FILTER_ALL_PCI |
TARGET_FILTER_XBUS),
// All IO
TARGET_FILTER_ALL_IO = (TARGET_FILTER_ALL_NEST |
TARGET_FILTER_ALL_OBUS | TARGET_FILTER_ALL_PCI |
TARGET_FILTER_XBUS),
// All sync mode except TP
TARGET_FILTER_SYNC_MODE_ALL_EXCEPT_TP =
(TARGET_FILTER_ALL_MC | TARGET_FILTER_ALL_NEST |
TARGET_FILTER_ALL_OBUS | TARGET_FILTER_ALL_PCI |
TARGET_FILTER_XBUS | TARGET_FILTER_ALL_CORES |
TARGET_FILTER_ALL_CACHES),
};
/// @cond
constexpr TargetType operator|(TargetType x, TargetType y)
{
return static_cast<TargetType>(static_cast<int>(x) |
static_cast<int>(y));
}
template<uint64_t V>
class bitCount
{
public:
// Don't use enums, too hard to compare
static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1);
};
template<>
class bitCount<0>
{
public:
static const uint8_t count = 0;
};
/// @endcond
}
#endif
<|endoftext|> |
<commit_before>#include "SimpleITKTestHarness.h"
#include "sitkImageFileReader.h"
#include "sitkCastImageFilter.h"
#include "sitkElastixImageFilter.h"
#include "sitkTransformixImageFilter.h"
namespace itk {
namespace simple {
bool stfxIsEmpty( const Image image )
{
return ( image.GetWidth() == 0 && image.GetHeight() == 0 );
}
TEST( TransformixImageFilter, ObjectOrientedInterface )
{
Image fixedImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitkFloat32 );
Image movingImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitkFloat32 );
ElastixImageFilter silx;
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage );
silx.Execute();
TransformixImageFilter stfx;
EXPECT_EQ( stfx.GetName(), "TransformixImageFilter" );
EXPECT_EQ( stfx.GetTransformParameterMap().size(), 0u );
ASSERT_THROW( stfx.Execute(), GenericException );
EXPECT_NO_THROW( stfx.SetMovingImage( movingImage ) );
ASSERT_THROW( stfx.Execute(), GenericException );
EXPECT_NO_THROW( stfx.SetTransformParameterMap( silx.GetTransformParameterMap() ) );
EXPECT_NO_THROW( stfx.Execute() );
EXPECT_FALSE( stfxIsEmpty( stfx.GetResultImage() ) );
EXPECT_NO_THROW( stfx.Execute() );
EXPECT_FALSE( stfxIsEmpty( stfx.GetResultImage() ) );
EXPECT_NO_THROW( stfx.Execute() );
EXPECT_FALSE( stfxIsEmpty( stfx.GetResultImage() ) );
}
TEST( TransformixImageFilter, ProceduralInterface )
{
Image fixedImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitkFloat32 );
Image movingImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitkFloat32 );
Image resultImage;
ElastixImageFilter silx;
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage );
silx.Execute();
std::string outputDirectory = ".";
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0] ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0], true ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0], true, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0], false, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap() ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap(), true ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap(), true, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap(), false, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
ElastixImageFilter::ParameterMapVectorType parameterMapVector = silx.GetTransformParameterMap();
parameterMapVector[ parameterMapVector.size()-1 ][ "WriteResultImage" ] = ElastixImageFilter::ParameterValueVectorType( 1, "false" );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap() ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
}
TEST( TransformixImageFilter, ComputeDeformationField )
{
Image fixedImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitkFloat32 );
Image movingImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitkFloat32 );
Image resultImage;
ElastixImageFilter silx;
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage );
silx.SetParameter( "MaximumNumberOfIterations", "1" );
silx.Execute();
TransformixImageFilter stfx;
stfx.SetTransformParameterMap(silx.GetTransformParameterMap());
stfx.ComputeDeformationFieldOn();
stfx.Execute();
Image deformationField = stfx.GetDeformationField();
deformationField.GetPixelAsVectorFloat32( { 0, 0 } );
EXPECT_NO_THROW( deformationField.GetPixelAsVectorFloat32( { 0, 0 } ) );
}
#ifdef SITK_4D_IMAGES
TEST( TransformixImageFilter, Transformation4D )
{
Image fixedImage = ReadImage( dataFinder.GetFile( "Input/4D.nii.gz" ) );
Image movingImage1 = ReadImage( dataFinder.GetFile( "Input/4D.nii.gz" ) );
Image movingImage2 = ReadImage( dataFinder.GetFile( "Input/4D.nii.gz" ) );
Image resultImage1;
Image resultImage2;
ElastixImageFilter silx;
silx.SetParameterMap( "groupwise" );
silx.SetParameter( "MaximumNumberOfIterations", "8.0" );
silx.SetParameter( "FinalGridSpacingInPhysicalUnits", "32.0" );
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage1 );
resultImage1 = silx.Execute();
silx.PrintParameterMap(silx.GetTransformParameterMap());
TransformixImageFilter stfx;
stfx.SetMovingImage( movingImage2 );
stfx.SetTransformParameterMap( silx.GetTransformParameterMap() );
resultImage2 = stfx.Execute();
}
#endif // SITK_4D_IMAGES
} // namespace simple
} // namespace itk
<commit_msg>BUG: Use double-brackets for initialization of itk::Index<commit_after>#include "SimpleITKTestHarness.h"
#include "sitkImageFileReader.h"
#include "sitkCastImageFilter.h"
#include "sitkElastixImageFilter.h"
#include "sitkTransformixImageFilter.h"
namespace itk {
namespace simple {
bool stfxIsEmpty( const Image image )
{
return ( image.GetWidth() == 0 && image.GetHeight() == 0 );
}
TEST( TransformixImageFilter, ObjectOrientedInterface )
{
Image fixedImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitkFloat32 );
Image movingImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitkFloat32 );
ElastixImageFilter silx;
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage );
silx.Execute();
TransformixImageFilter stfx;
EXPECT_EQ( stfx.GetName(), "TransformixImageFilter" );
EXPECT_EQ( stfx.GetTransformParameterMap().size(), 0u );
ASSERT_THROW( stfx.Execute(), GenericException );
EXPECT_NO_THROW( stfx.SetMovingImage( movingImage ) );
ASSERT_THROW( stfx.Execute(), GenericException );
EXPECT_NO_THROW( stfx.SetTransformParameterMap( silx.GetTransformParameterMap() ) );
EXPECT_NO_THROW( stfx.Execute() );
EXPECT_FALSE( stfxIsEmpty( stfx.GetResultImage() ) );
EXPECT_NO_THROW( stfx.Execute() );
EXPECT_FALSE( stfxIsEmpty( stfx.GetResultImage() ) );
EXPECT_NO_THROW( stfx.Execute() );
EXPECT_FALSE( stfxIsEmpty( stfx.GetResultImage() ) );
}
TEST( TransformixImageFilter, ProceduralInterface )
{
Image fixedImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitkFloat32 );
Image movingImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitkFloat32 );
Image resultImage;
ElastixImageFilter silx;
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage );
silx.Execute();
std::string outputDirectory = ".";
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0] ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0], true ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0], true, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap()[0], false, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap() ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap(), true ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap(), true, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap(), false, outputDirectory ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
ElastixImageFilter::ParameterMapVectorType parameterMapVector = silx.GetTransformParameterMap();
parameterMapVector[ parameterMapVector.size()-1 ][ "WriteResultImage" ] = ElastixImageFilter::ParameterValueVectorType( 1, "false" );
EXPECT_NO_THROW( resultImage = Transformix( movingImage, silx.GetTransformParameterMap() ) );
EXPECT_FALSE( stfxIsEmpty( resultImage ) );
}
TEST( TransformixImageFilter, ComputeDeformationField )
{
Image fixedImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitkFloat32 );
Image movingImage = Cast( ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitkFloat32 );
Image resultImage;
ElastixImageFilter silx;
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage );
silx.SetParameter( "MaximumNumberOfIterations", "1" );
silx.Execute();
TransformixImageFilter stfx;
stfx.SetTransformParameterMap(silx.GetTransformParameterMap());
stfx.ComputeDeformationFieldOn();
stfx.Execute();
Image deformationField = stfx.GetDeformationField();
std::vector<uint32_t> index;
index.push_back(0);
index.push_back(0);
EXPECT_NO_THROW( deformationField.GetPixelAsVectorFloat32( index ) );
}
#ifdef SITK_4D_IMAGES
TEST( TransformixImageFilter, Transformation4D )
{
Image fixedImage = ReadImage( dataFinder.GetFile( "Input/4D.nii.gz" ) );
Image movingImage1 = ReadImage( dataFinder.GetFile( "Input/4D.nii.gz" ) );
Image movingImage2 = ReadImage( dataFinder.GetFile( "Input/4D.nii.gz" ) );
Image resultImage1;
Image resultImage2;
ElastixImageFilter silx;
silx.SetParameterMap( "groupwise" );
silx.SetParameter( "MaximumNumberOfIterations", "8.0" );
silx.SetParameter( "FinalGridSpacingInPhysicalUnits", "32.0" );
silx.SetFixedImage( fixedImage );
silx.SetMovingImage( movingImage1 );
resultImage1 = silx.Execute();
silx.PrintParameterMap(silx.GetTransformParameterMap());
TransformixImageFilter stfx;
stfx.SetMovingImage( movingImage2 );
stfx.SetTransformParameterMap( silx.GetTransformParameterMap() );
resultImage2 = stfx.Execute();
}
#endif // SITK_4D_IMAGES
} // namespace simple
} // namespace itk
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include "config.h"
#endif
#ifdef HAVE_ALUGRID_SERIAL_H
#define ENABLE_ALUGRID 1
#undef HAVE_ALUGRID
#define HAVE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
static_assert(false, "This study requires a serial alugrid!");
#endif // HAVE_ALUGRID_SERIAL_H
#include <memory>
#include <boost/filesystem.hpp>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/misc/gridwidth.hh>
#include <dune/fem/gridpart/levelgridpart.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/gdt/operator/prolongations.hh>
#include "discretizations.hh"
using namespace Dune;
using namespace Dune::GDT;
template< class DiscretizationType >
class ConvergenceStudy
{
public:
template< class GridType, class ReferenceDiscretizationType, class ReferenceSolutionType >
static void run(GridType& grid,
const ReferenceDiscretizationType& reference_discretization,
const size_t num_refinements,
const ReferenceSolutionType& reference_solution,
const std::string header)
{
typedef typename ReferenceDiscretizationType::DomainFieldType DomainFieldType;
typedef typename ReferenceDiscretizationType::RangeFieldType RangeFieldType;
typedef typename ReferenceDiscretizationType::SpaceType::GridPartType GridPartType;
// prepare the data structures
std::vector< size_t > num_grid_elements(num_refinements + 1);
std::vector< DomainFieldType > grid_width(num_refinements + 1);
std::vector< RangeFieldType > l2_errors(num_refinements + 1);
std::vector< RangeFieldType > h1_errors(num_refinements + 1);
// print table header
const std::string bar = "=================================================================";
auto& info = DSC_LOG.info();
info << header << std::endl;
if (header.size() > bar.size())
info << Stuff::Common::whitespaceify(header, '=') << std::endl;
else
info << bar << std::endl;
info << " grid | L2 (relative) | H1 (relative) " << std::endl;
info << "---------------------+---------------------+---------------------" << std::endl;
info << " size | width | error | EOC | error | EOC " << std::endl;
info << "==========+==========+==========+==========+==========+==========" << std::endl;
// compute norm of reference solution
ProductOperator::L2< GridPartType > l2_product_operator(reference_discretization.grid_part());
const RangeFieldType reference_solution_l2_norm = std::sqrt(l2_product_operator.apply2(reference_solution,
reference_solution));
ProductOperator::H1< GridPartType > h1_product_operator(reference_discretization.grid_part());
const RangeFieldType reference_solution_h1_error = std::sqrt(h1_product_operator.apply2(reference_solution,
reference_solution));
// iterate
for (size_t ii = 0; ii <= num_refinements; ++ii) {
if (ii > 0)
info << "----------+----------+----------+----------+----------+----------" << std::endl;
const size_t level = 2*ii + 1;
GridPartType level_grid_part(grid, level);
num_grid_elements[ii] = grid.size(level, 0);
grid_width[ii] = Fem::GridWidth::calcGridWidth(level_grid_part);
info << " " << std::setw(8) << num_grid_elements[ii]
<< " | " << std::setw(8) << std::setprecision(2) << std::scientific << grid_width[ii]
<< " | " << std::flush;
// discretize
const DiscretizationType discretization(level_grid_part,
reference_discretization.boundary_info(),
reference_discretization.diffusion(),
reference_discretization.force(),
reference_discretization.dirichlet());
auto discrete_solution = discretization.solve();
typedef typename ReferenceDiscretizationType::DiscreteFunctionType DiscreteFunctionType;
typedef typename ReferenceDiscretizationType::VectorType VectorType;
auto discrete_solution_on_reference_grid
= std::make_shared< DiscreteFunctionType >(reference_discretization.space(),
std::make_shared< VectorType >(reference_discretization.space().mapper().size()),
"discrete_solution");
ProlongationOperator::Generic::apply(*discrete_solution, *discrete_solution_on_reference_grid);
// compute errors
const auto errors = reference_discretization.compute_errors(reference_solution,
*(discrete_solution_on_reference_grid));
// * L2
l2_errors[ii] = errors[0];
info << std::setw(8) << std::setprecision(2) << std::scientific << l2_errors[ii] / reference_solution_l2_norm
<< " | " << std::flush;
if (ii == 0)
info << std::setw(11) << "---- | " << std::flush;
else
info << std::setw(8) << std::setprecision(2) << std::fixed
<< std::log(l2_errors[ii] / l2_errors[ii - 1])
/ std::log(grid_width[ii] / grid_width[ii - 1])
<< " | " << std::flush;
// * H1
h1_errors[ii] = errors[1];
info << std::setw(8) << std::setprecision(2) << std::scientific << h1_errors[ii] / reference_solution_h1_error
<< " | " << std::flush;
if (ii == 0)
info << std::setw(8) << "----" << std::flush;
else
info << std::setw(8) << std::setprecision(2) << std::fixed
<< std::log(h1_errors[ii] / h1_errors[ii - 1])
/ std::log(grid_width[ii] / grid_width[ii - 1])
<< std::flush;
info << std::endl;
} // iterate
}
}; // class ConvergenceStudy
int main(int argc, char** argv)
{
try {
// defines
static const unsigned int dimDomain = 2;
static const unsigned int dimRange = 1;
typedef double RangeFieldType;
const std::string static_id = "example.elliptic.convergence_study";
// read or write settings file
if (!boost::filesystem::exists(static_id + ".settings")) {
std::cout << "writing default settings to '" << static_id + ".settings'" << std::endl;
std::ofstream file;
file.open(static_id + ".settings");
file << "integration_order = 4" << std::endl;
file << "num_refinements = 3" << std::endl;
file.close();
} else {
std::cout << "reading default settings from'" << static_id + ".settings'" << std::endl;
std::cout << std::endl;
Stuff::Common::ExtendedParameterTree settings(argc, argv, static_id + ".settings");
const size_t integration_order = settings.get("integration_order", 4);
const size_t num_refinements = settings.get("num_refinements", 3);
DSC_LOG.create(Stuff::Common::LOG_INFO, "", "");
auto& info = DSC_LOG.info();
info << "==================================================================================" << std::endl;
info << " convergence study (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007)" << std::endl;
info << " dimDomain = " << dimDomain << ", dimRange = " << dimRange << std::endl;
info << " integration_order = " << integration_order << std::endl;
info << " num_refinements = " << num_refinements << std::endl;
info << "==================================================================================" << std::endl;
// mpi
Dune::Fem::MPIManager::initialize(argc, argv);
// prepare the grid
typedef Dune::ALUConformGrid< dimDomain, dimDomain > GridType;
typedef typename GridType::ctype DomainFieldType;
typedef Stuff::GridProviderCube< GridType > GridProviderType;
GridProviderType grid_provider(-1, 1, 2);
GridType& grid = *(grid_provider.grid());
grid.globalRefine(1);
for (size_t ii = 1; ii <= (num_refinements + 2); ++ii)
grid.globalRefine(GridType::refineStepsForHalf);
// prepare the analytical functions
typedef Stuff::FunctionConstant< DomainFieldType, dimDomain, RangeFieldType, dimRange > ConstantFunctionType;
typedef Stuff::FunctionExpression< DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType;
const ConstantFunctionType diffusion(1.0);
const ExpressionFunctionType force("x",
"0.5 * pi * pi * cos(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])",
integration_order);
const ConstantFunctionType dirichlet(0.0);
const ExpressionFunctionType exact_solution("x",
"cos(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])",
{"-0.5 * pi * sin(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])",
"-0.5 * pi * cos(0.5 * pi * x[0]) * sin(0.5 * pi * x[1])"},
integration_order);
typedef typename Fem::LevelGridPart< GridType > GridPartType;
const Stuff::GridboundaryAllDirichlet< typename GridPartType::GridViewType > boundary_info;
// compute reference
const GridPartType reference_grid_part(grid, 2*num_refinements + 3);
// continuous galerkin discretization
typedef Example::CGDiscretization< GridPartType, 1 > CG_1_DiscretizationType;
const CG_1_DiscretizationType cg_1_reference_discretization(reference_grid_part, boundary_info, diffusion, force, dirichlet);
ConvergenceStudy< CG_1_DiscretizationType >::run(grid,
cg_1_reference_discretization,
num_refinements,
exact_solution,
"continuous galerkin, polOrder = 1, error against exact solution");
info << std::endl;
typedef Example::CGDiscretization< GridPartType, 2 > CG_2_DiscretizationType;
const CG_2_DiscretizationType cg_2_reference_discretization(reference_grid_part, boundary_info, diffusion, force, dirichlet);
ConvergenceStudy< CG_2_DiscretizationType >::run(grid,
cg_2_reference_discretization,
num_refinements,
exact_solution,
"continuous galerkin, polOrder = 2, error against exact solution");
} // read or write settings file
// done
return 0;
} catch (Dune::Exception& e) {
std::cerr << "Dune reported error: " << e.what() << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
} // try
} // main
<commit_msg>[examples.elliptic.convergence_study] update<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include "config.h"
#endif
#ifdef HAVE_ALUGRID_SERIAL_H
#define ENABLE_ALUGRID 1
#undef HAVE_ALUGRID
#define HAVE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
static_assert(false, "This study requires a serial alugrid!");
#endif // HAVE_ALUGRID_SERIAL_H
#include <memory>
#include <boost/filesystem.hpp>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/misc/gridwidth.hh>
#include <dune/fem/gridpart/levelgridpart.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/gdt/operator/prolongations.hh>
#include "discretizations.hh"
using namespace Dune;
using namespace Dune::GDT;
template< class DiscretizationType >
class ConvergenceStudy
{
public:
template< class GridType, class ReferenceDiscretizationType, class ReferenceSolutionType >
static void run(GridType& grid,
const ReferenceDiscretizationType& reference_discretization,
const size_t num_refinements,
const ReferenceSolutionType& reference_solution,
const std::string header)
{
typedef typename ReferenceDiscretizationType::DomainFieldType DomainFieldType;
typedef typename ReferenceDiscretizationType::RangeFieldType RangeFieldType;
typedef typename ReferenceDiscretizationType::SpaceType::GridPartType GridPartType;
// prepare the data structures
std::vector< size_t > num_grid_elements(num_refinements + 1);
std::vector< DomainFieldType > grid_width(num_refinements + 1);
std::vector< RangeFieldType > l2_errors(num_refinements + 1);
std::vector< RangeFieldType > h1_errors(num_refinements + 1);
// print table header
const std::string bar = "=================================================================";
auto& info = DSC_LOG.info();
info << header << std::endl;
if (header.size() > bar.size())
info << Stuff::Common::whitespaceify(header, '=') << std::endl;
else
info << bar << std::endl;
info << " grid | L2 (relative) | H1 (relative) " << std::endl;
info << "---------------------+---------------------+---------------------" << std::endl;
info << " size | width | error | EOC | error | EOC " << std::endl;
info << "==========+==========+==========+==========+==========+==========" << std::endl;
// compute norm of reference solution
ProductOperator::L2< GridPartType > l2_product_operator(reference_discretization.grid_part());
const RangeFieldType reference_solution_l2_norm = std::sqrt(l2_product_operator.apply2(reference_solution,
reference_solution));
ProductOperator::H1< GridPartType > h1_product_operator(reference_discretization.grid_part());
const RangeFieldType reference_solution_h1_error = std::sqrt(h1_product_operator.apply2(reference_solution,
reference_solution));
// iterate
for (size_t ii = 0; ii <= num_refinements; ++ii) {
if (ii > 0)
info << "----------+----------+----------+----------+----------+----------" << std::endl;
const size_t level = 2*ii + 1;
GridPartType level_grid_part(grid, level);
num_grid_elements[ii] = grid.size(level, 0);
grid_width[ii] = Fem::GridWidth::calcGridWidth(level_grid_part);
info << " " << std::setw(8) << num_grid_elements[ii]
<< " | " << std::setw(8) << std::setprecision(2) << std::scientific << grid_width[ii]
<< " | " << std::flush;
// discretize
const DiscretizationType discretization(level_grid_part,
reference_discretization.boundary_info(),
reference_discretization.diffusion(),
reference_discretization.force(),
reference_discretization.dirichlet());
auto discrete_solution = discretization.solve();
typedef typename ReferenceDiscretizationType::DiscreteFunctionType DiscreteFunctionType;
typedef typename ReferenceDiscretizationType::VectorType VectorType;
auto discrete_solution_on_reference_grid
= std::make_shared< DiscreteFunctionType >(reference_discretization.space(),
std::make_shared< VectorType >(reference_discretization.space().mapper().size()),
"discrete_solution");
ProlongationOperator::Generic::apply(*discrete_solution, *discrete_solution_on_reference_grid);
// compute errors
const auto errors = reference_discretization.compute_errors(reference_solution,
*(discrete_solution_on_reference_grid));
// * L2
l2_errors[ii] = errors[0];
info << std::setw(8) << std::setprecision(2) << std::scientific << l2_errors[ii] / reference_solution_l2_norm
<< " | " << std::flush;
if (ii == 0)
info << std::setw(11) << "---- | " << std::flush;
else
info << std::setw(8) << std::setprecision(2) << std::fixed
<< std::log(l2_errors[ii] / l2_errors[ii - 1])
/ std::log(grid_width[ii] / grid_width[ii - 1])
<< " | " << std::flush;
// * H1
h1_errors[ii] = errors[1];
info << std::setw(8) << std::setprecision(2) << std::scientific << h1_errors[ii] / reference_solution_h1_error
<< " | " << std::flush;
if (ii == 0)
info << std::setw(8) << "----" << std::flush;
else
info << std::setw(8) << std::setprecision(2) << std::fixed
<< std::log(h1_errors[ii] / h1_errors[ii - 1])
/ std::log(grid_width[ii] / grid_width[ii - 1])
<< std::flush;
info << std::endl;
} // iterate
}
}; // class ConvergenceStudy
int main(int argc, char** argv)
{
try {
// defines
static const unsigned int dimDomain = 2;
static const unsigned int dimRange = 1;
typedef double RangeFieldType;
const std::string static_id = "example.elliptic.convergence_study";
// read or write settings file
if (!boost::filesystem::exists(static_id + ".settings")) {
std::cout << "writing default settings to '" << static_id + ".settings'" << std::endl;
std::ofstream file;
file.open(static_id + ".settings");
file << "integration_order = 4" << std::endl;
file << "num_refinements = 3" << std::endl;
file.close();
} else {
std::cout << "reading default settings from'" << static_id + ".settings'" << std::endl;
std::cout << std::endl;
Stuff::Common::ExtendedParameterTree settings(argc, argv, static_id + ".settings");
const size_t integration_order = settings.get("integration_order", 4);
const size_t num_refinements = settings.get("num_refinements", 3);
DSC_LOG.create(Stuff::Common::LOG_INFO, "", "");
auto& info = DSC_LOG.info();
info << "==================================================================================" << std::endl;
info << " convergence study (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007)" << std::endl;
info << " dimDomain = " << dimDomain << ", dimRange = " << dimRange << std::endl;
info << " integration_order = " << integration_order << std::endl;
info << " num_refinements = " << num_refinements << std::endl;
info << "==================================================================================" << std::endl;
// mpi
Dune::Fem::MPIManager::initialize(argc, argv);
// prepare the grid
typedef Dune::ALUConformGrid< dimDomain, dimDomain > GridType;
typedef typename GridType::ctype DomainFieldType;
typedef Stuff::GridProviderCube< GridType > GridProviderType;
GridProviderType grid_provider(-1, 1, 2);
GridType& grid = *(grid_provider.grid());
grid.globalRefine(1);
for (size_t ii = 1; ii <= (num_refinements + 2); ++ii)
grid.globalRefine(GridType::refineStepsForHalf);
// prepare the analytical functions
typedef Stuff::FunctionConstant< DomainFieldType, dimDomain, RangeFieldType, dimRange > ConstantFunctionType;
typedef Stuff::FunctionExpression< DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType;
const ConstantFunctionType diffusion(1.0);
const ExpressionFunctionType force("x",
"0.5 * pi * pi * cos(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])",
integration_order);
const ConstantFunctionType dirichlet(0.0);
const ExpressionFunctionType exact_solution("x",
"cos(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])",
{"-0.5 * pi * sin(0.5 * pi * x[0]) * cos(0.5 * pi * x[1])",
"-0.5 * pi * cos(0.5 * pi * x[0]) * sin(0.5 * pi * x[1])"},
integration_order);
typedef typename Fem::LevelGridPart< GridType > GridPartType;
const Stuff::GridboundaryAllDirichlet< typename GridPartType::GridViewType > boundary_info;
// compute reference
const GridPartType reference_grid_part(grid, 2*num_refinements + 3);
// continuous galerkin discretization
typedef Example::CGDiscretization< GridPartType, 1 > CG_1_DiscretizationType;
const CG_1_DiscretizationType cg_1_reference_discretization(reference_grid_part,
boundary_info,
diffusion,
force,
dirichlet);
ConvergenceStudy< CG_1_DiscretizationType >::run(grid,
cg_1_reference_discretization,
num_refinements,
exact_solution,
"continuous galerkin, polOrder = 1, error against exact solution");
info << std::endl;
typedef Example::CGDiscretization< GridPartType, 2 > CG_2_DiscretizationType;
const CG_2_DiscretizationType cg_2_reference_discretization(reference_grid_part,
boundary_info,
diffusion,
force,
dirichlet);
ConvergenceStudy< CG_2_DiscretizationType >::run(grid,
cg_2_reference_discretization,
num_refinements,
exact_solution,
"continuous galerkin, polOrder = 2, error against exact solution");
info << std::endl;
// symmetric interior penalty discontinuous galerkin discretization
typedef Example::SIPDGDiscretization< GridPartType, 1 > SIPDG_1_DiscretizationType;
const SIPDG_1_DiscretizationType sipdg_1_reference_discretization(reference_grid_part,
boundary_info,
diffusion,
force,
dirichlet);
ConvergenceStudy< SIPDG_1_DiscretizationType >::run(grid,
sipdg_1_reference_discretization,
num_refinements,
exact_solution,
"symmetric interior penalty discontinuous galerkin, polOrder = 1, error against exact solution");
info << std::endl;
} // read or write settings file
// done
return 0;
} catch (Dune::Exception& e) {
std::cerr << "Dune reported error: " << e.what() << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
} // try
} // main
<|endoftext|> |
<commit_before>/*
*
* copyright (c) 2010 ZAO Inventos (inventos.ru)
* copyright (c) 2010 jk@inventos.ru
* copyright (c) 2010 kuzalex@inventos.ru
* copyright (c) 2010 artint@inventos.ru
*
* This file is part of mp4frag.
*
* mp4grag 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.
*
* mp4frag is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include "mp4frag.hh"
#include <boost/program_options.hpp>
#include <boost/system/system_error.hpp>
#include <boost/system/error_code.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
using namespace boost::system;
namespace bfs = boost::filesystem;
using boost::lexical_cast;
namespace {
bfs::path manifest_name = "manifest.f4m";
std::string video_id("some_video");
std::vector<bfs::path> srcfiles;
bool produce_template = false;
bool manifest_only = false;
int fragment_duration;
}
void parse_options(int argc, char **argv) {
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("src", po::value< std::vector<bfs::path> >(&srcfiles), "source mp4 file name")
("video_id", po::value<std::string>(&video_id)->default_value("some_video"), "video id for manifest file")
("manifest", po::value<bfs::path>(&manifest_name)->default_value("manifest.f4m"), "manifest file name")
("fragmentduration", po::value<int>(&fragment_duration)->default_value(3000), "single fragment duration, ms")
("template", "make template files instead of full fragments")
("nofragments", "make manifest only")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help") || argc == 1 || srcfiles.size() == 0) {
std::cerr << desc << "\n";
exit(1);
}
produce_template = vm.count("template") != 0;
manifest_only = vm.count("nofragments") != 0;
}
boost::shared_ptr<Mapping> create_mapping(const std::string& filename) {
return boost::shared_ptr<Mapping>(new Mapping(filename.c_str()));
}
#include <sys/time.h>
int main(int argc, char **argv) try {
parse_options(argc, argv);
std::vector<boost::shared_ptr<Media> > fileinfo_list;
struct timeval then, now;
gettimeofday(&then, 0);
BOOST_FOREACH(bfs::path& srcfile, srcfiles) {
boost::shared_ptr<Media> pmedia = make_fragments(srcfile.string(), fragment_duration);
fileinfo_list.push_back(pmedia);
pmedia->medianame = bfs::complete(srcfile).string();
}
gettimeofday(&now, 0);
double diff = now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);
gettimeofday(&then, 0);
gettimeofday(&now, 0);
diff -= now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);
std::cerr << "Parsed in " << diff << " seconds\n";
if ( !manifest_only ) {
if ( produce_template ) {
std::filebuf out;
std::string indexname = (manifest_name.parent_path() / "index").string();
if ( out.open(indexname.c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
serialize(&out, fileinfo_list);
if ( !out.close() ) {
throw std::runtime_error("Error closing " + indexname);
}
}
else {
throw std::runtime_error("Error opening " + indexname);
}
#if TESTING
Mapping index(indexname.c_str());
for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
}
for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
std::filebuf out;
std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
bfs::path fragment_file = mediadir / fragment_basename;
if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
get_fragment(&out, ix, fragment - 1, index.data(), index.size(), create_mapping);
if ( !out.close() ) {
throw std::runtime_error("Error closing " + fragment_file.string());
}
}
else {
throw std::runtime_error("Error opening " + fragment_file.string());
}
}
}
#endif
}
else {
for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
}
for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
std::filebuf out;
std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
bfs::path fragment_file = mediadir / fragment_basename;
if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
serialize_fragment(&out, pmedia, fragment - 1);
if ( !out.close() ) {
throw std::runtime_error("Error closing " + fragment_file.string());
}
}
else {
throw std::runtime_error("Error opening " + fragment_file.string());
}
}
}
}
}
std::filebuf manifest_filebuf;
if ( manifest_filebuf.open(manifest_name.string().c_str(),
std::ios::out | std::ios::binary | std::ios::trunc) ) {
get_manifest(&manifest_filebuf, fileinfo_list, video_id);
if ( !manifest_filebuf.close() ) {
std::stringstream errmsg;
errmsg << "Error closing " << manifest_name;
throw std::runtime_error(errmsg.str());
}
}
else {
throw std::runtime_error("Error opening " + manifest_name.string());
}
}
catch ( std::exception& e ) {
std::cerr << e.what() << "\n";
}
<commit_msg>Option name changed.<commit_after>/*
*
* copyright (c) 2010 ZAO Inventos (inventos.ru)
* copyright (c) 2010 jk@inventos.ru
* copyright (c) 2010 kuzalex@inventos.ru
* copyright (c) 2010 artint@inventos.ru
*
* This file is part of mp4frag.
*
* mp4grag 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.
*
* mp4frag is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include "mp4frag.hh"
#include <boost/program_options.hpp>
#include <boost/system/system_error.hpp>
#include <boost/system/error_code.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
using namespace boost::system;
namespace bfs = boost::filesystem;
using boost::lexical_cast;
namespace {
bfs::path manifest_name = "manifest.f4m";
std::string video_id("some_video");
std::vector<bfs::path> srcfiles;
bool produce_template = false;
bool manifest_only = false;
int fragment_duration;
}
void parse_options(int argc, char **argv) {
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("src", po::value< std::vector<bfs::path> >(&srcfiles), "source mp4 file name")
("video_id", po::value<std::string>(&video_id)->default_value("some_video"), "video id for manifest file")
("manifest", po::value<bfs::path>(&manifest_name)->default_value("manifest.f4m"), "manifest file name")
("fragmentduration", po::value<int>(&fragment_duration)->default_value(3000), "single fragment duration, ms")
("index", "make index files instead of full fragments")
("nofragments", "make manifest only")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help") || argc == 1 || srcfiles.size() == 0) {
std::cerr << desc << "\n";
exit(1);
}
produce_template = vm.count("template") != 0;
manifest_only = vm.count("nofragments") != 0;
}
boost::shared_ptr<Mapping> create_mapping(const std::string& filename) {
return boost::shared_ptr<Mapping>(new Mapping(filename.c_str()));
}
#include <sys/time.h>
int main(int argc, char **argv) try {
parse_options(argc, argv);
std::vector<boost::shared_ptr<Media> > fileinfo_list;
struct timeval then, now;
gettimeofday(&then, 0);
BOOST_FOREACH(bfs::path& srcfile, srcfiles) {
boost::shared_ptr<Media> pmedia = make_fragments(srcfile.string(), fragment_duration);
fileinfo_list.push_back(pmedia);
pmedia->medianame = bfs::complete(srcfile).string();
}
gettimeofday(&now, 0);
double diff = now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);
gettimeofday(&then, 0);
gettimeofday(&now, 0);
diff -= now.tv_sec - then.tv_sec + 1e-6*(now.tv_usec - then.tv_usec);
std::cerr << "Parsed in " << diff << " seconds\n";
if ( !manifest_only ) {
if ( produce_template ) {
std::filebuf out;
std::string indexname = (manifest_name.parent_path() / "index").string();
if ( out.open(indexname.c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
serialize(&out, fileinfo_list);
if ( !out.close() ) {
throw std::runtime_error("Error closing " + indexname);
}
}
else {
throw std::runtime_error("Error opening " + indexname);
}
#if TESTING
Mapping index(indexname.c_str());
for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
}
for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
std::filebuf out;
std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
bfs::path fragment_file = mediadir / fragment_basename;
if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
get_fragment(&out, ix, fragment - 1, index.data(), index.size(), create_mapping);
if ( !out.close() ) {
throw std::runtime_error("Error closing " + fragment_file.string());
}
}
else {
throw std::runtime_error("Error opening " + fragment_file.string());
}
}
}
#endif
}
else {
for ( unsigned ix = 0; ix < fileinfo_list.size(); ++ix ) {
boost::shared_ptr<Media>& pmedia = fileinfo_list[ix];
bfs::path mediadir = manifest_name.parent_path() / lexical_cast<std::string>(ix);
if ( mkdir(mediadir.string().c_str(), 0755) == -1 && errno != EEXIST ) {
throw system_error(errno, get_system_category(), "mkdir " + mediadir.string());
}
for ( unsigned fragment = 1; fragment <= pmedia->fragments.size(); ++fragment ) {
std::filebuf out;
std::string fragment_basename = std::string("Seg1-Frag") + boost::lexical_cast<std::string>(fragment);
bfs::path fragment_file = mediadir / fragment_basename;
if ( out.open(fragment_file.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc) ) {
serialize_fragment(&out, pmedia, fragment - 1);
if ( !out.close() ) {
throw std::runtime_error("Error closing " + fragment_file.string());
}
}
else {
throw std::runtime_error("Error opening " + fragment_file.string());
}
}
}
}
}
std::filebuf manifest_filebuf;
if ( manifest_filebuf.open(manifest_name.string().c_str(),
std::ios::out | std::ios::binary | std::ios::trunc) ) {
get_manifest(&manifest_filebuf, fileinfo_list, video_id);
if ( !manifest_filebuf.close() ) {
std::stringstream errmsg;
errmsg << "Error closing " << manifest_name;
throw std::runtime_error(errmsg.str());
}
}
else {
throw std::runtime_error("Error opening " + manifest_name.string());
}
}
catch ( std::exception& e ) {
std::cerr << e.what() << "\n";
}
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP 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 <lib/core/PeerId.h>
#include <lib/mdns/Discovery_ImplPlatform.h>
#include <lib/support/UnitTestRegistration.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/fake/MdnsImpl.h>
#include <nlunit-test.h>
#if !defined(CHIP_DEVICE_LAYER_TARGET_FAKE) || CHIP_DEVICE_LAYER_TARGET_FAKE != 1
#error "This test is designed for use only with the fake platform"
#endif
namespace {
using namespace chip;
using namespace chip::Mdns;
const uint8_t kMac[kMaxMacSize] = { 1, 2, 3, 4, 5, 6, 7, 8 };
const char host[] = "0102030405060708";
const PeerId kPeerId1 = PeerId().SetCompressedFabricId(0xBEEFBEEFF00DF00D).SetNodeId(0x1111222233334444);
const PeerId kPeerId2 = PeerId().SetCompressedFabricId(0x5555666677778888).SetNodeId(0x1212343456567878);
OperationalAdvertisingParameters operationalParams1 = OperationalAdvertisingParameters()
.SetPeerId(kPeerId1)
.SetMac(ByteSpan(kMac))
.SetPort(CHIP_PORT)
.EnableIpV4(true)
.SetMRPRetryIntervals(32, 33);
test::ExpectedCall operationalCall1 = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolTcp)
.SetServiceName("_matter")
.SetInstanceName("BEEFBEEFF00DF00D-1111222233334444")
.SetHostName(host)
.AddTxt("CRI", "32")
.AddTxt("CRA", "33");
OperationalAdvertisingParameters operationalParams2 = OperationalAdvertisingParameters()
.SetPeerId(kPeerId2)
.SetMac(ByteSpan(kMac))
.SetPort(CHIP_PORT)
.EnableIpV4(true)
.SetMRPRetryIntervals(32, 33);
test::ExpectedCall operationalCall2 = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolTcp)
.SetServiceName("_matter")
.SetInstanceName("5555666677778888-1212343456567878")
.SetHostName(host)
.AddTxt("CRI", "32")
.AddTxt("CRA", "33");
CommissionAdvertisingParameters commissionableNodeParamsSmall =
CommissionAdvertisingParameters()
.SetCommissionAdvertiseMode(CommssionAdvertiseMode::kCommissionableNode)
.SetMac(ByteSpan(kMac))
.SetLongDiscriminator(0xFFE)
.SetShortDiscriminator(0xF)
.SetCommissioningMode(CommissioningMode::kDisabled);
// Instance names need to be obtained from the advertiser, so they are not set here.
test::ExpectedCall commissionableSmall = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolUdp)
.SetServiceName("_matterc")
.SetHostName(host)
.AddTxt("CM", "0")
.AddTxt("D", "4094")
.AddSubtype("_S15")
.AddSubtype("_L4094");
CommissionAdvertisingParameters commissionableNodeParamsLargeBasic =
CommissionAdvertisingParameters()
.SetCommissionAdvertiseMode(CommssionAdvertiseMode::kCommissionableNode)
.SetMac(ByteSpan(kMac, sizeof(kMac)))
.SetLongDiscriminator(22)
.SetShortDiscriminator(2)
.SetVendorId(chip::Optional<uint16_t>(555))
.SetDeviceType(chip::Optional<uint16_t>(25))
.SetCommissioningMode(CommissioningMode::kEnabledBasic)
.SetDeviceName(chip::Optional<const char *>("testy-test"))
.SetPairingHint(chip::Optional<uint16_t>(3))
.SetPairingInstr(chip::Optional<const char *>("Pair me"))
.SetProductId(chip::Optional<uint16_t>(897))
.SetRotatingId(chip::Optional<const char *>("id_that_spins"));
test::ExpectedCall commissionableLargeBasic = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolUdp)
.SetServiceName("_matterc")
.SetHostName(host)
.AddTxt("D", "22")
.AddTxt("VP", "555+897")
.AddTxt("CM", "1")
.AddTxt("DT", "25")
.AddTxt("DN", "testy-test")
.AddTxt("RI", "id_that_spins")
.AddTxt("PI", "Pair me")
.AddTxt("PH", "3")
.AddSubtype("_S2")
.AddSubtype("_L22")
.AddSubtype("_V555")
.AddSubtype("_T25")
.AddSubtype("_CM");
CommissionAdvertisingParameters commissionableNodeParamsLargeEnhanced =
CommissionAdvertisingParameters()
.SetCommissionAdvertiseMode(CommssionAdvertiseMode::kCommissionableNode)
.SetMac(ByteSpan(kMac, sizeof(kMac)))
.SetLongDiscriminator(22)
.SetShortDiscriminator(2)
.SetVendorId(chip::Optional<uint16_t>(555))
.SetDeviceType(chip::Optional<uint16_t>(25))
.SetCommissioningMode(CommissioningMode::kEnabledEnhanced)
.SetDeviceName(chip::Optional<const char *>("testy-test"))
.SetPairingHint(chip::Optional<uint16_t>(3))
.SetPairingInstr(chip::Optional<const char *>("Pair me"))
.SetProductId(chip::Optional<uint16_t>(897))
.SetRotatingId(chip::Optional<const char *>("id_that_spins"));
test::ExpectedCall commissionableLargeEnhanced = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolUdp)
.SetServiceName("_matterc")
.SetHostName(host)
.AddTxt("D", "22")
.AddTxt("VP", "555+897")
.AddTxt("CM", "2")
.AddTxt("DT", "25")
.AddTxt("DN", "testy-test")
.AddTxt("RI", "id_that_spins")
.AddTxt("PI", "Pair me")
.AddTxt("PH", "3")
.AddSubtype("_S2")
.AddSubtype("_L22")
.AddSubtype("_V555")
.AddSubtype("_T25")
.AddSubtype("_CM");
void TestStub(nlTestSuite * inSuite, void * inContext)
{
// This is a test of the fake platform impl. We want
// We want the platform to return unexpected event if it gets a start
// without an expected event.
ChipLogError(Discovery, "Test platform returns error correctly");
DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance();
NL_TEST_ASSERT(inSuite, mdnsPlatform.Init() == CHIP_NO_ERROR);
OperationalAdvertisingParameters params;
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(params) == CHIP_ERROR_UNEXPECTED_EVENT);
}
void TestOperational(nlTestSuite * inSuite, void * inContext)
{
ChipLogError(Discovery, "Test operational");
test::Reset();
DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance();
NL_TEST_ASSERT(inSuite, mdnsPlatform.Init() == CHIP_NO_ERROR);
operationalCall1.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(operationalCall1) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(operationalParams1) == CHIP_NO_ERROR);
// Next call to advertise should call start again with just the new data.
test::Reset();
operationalCall2.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(operationalCall2) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(operationalParams2) == CHIP_NO_ERROR);
}
void TestCommissionableNode(nlTestSuite * inSuite, void * inContext)
{
ChipLogError(Discovery, "Test commissionable");
test::Reset();
DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance();
NL_TEST_ASSERT(inSuite, mdnsPlatform.Init() == CHIP_NO_ERROR);
commissionableSmall.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite,
mdnsPlatform.GetCommissionableInstanceName(commissionableSmall.instanceName,
sizeof(commissionableSmall.instanceName)) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableSmall) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsSmall) == CHIP_NO_ERROR);
// TODO: Right now, platform impl doesn't stop commissionable node before starting a new one. Add stop call here once that is
// fixed.
test::Reset();
commissionableLarge.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite,
mdnsPlatform.GetCommissionableInstanceName(commissionableLargeBasic.instanceName,
sizeof(commissionableLargeBasic.instanceName)) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableLargeBasic) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsLargeBasic) == CHIP_NO_ERROR);
test::Reset();
commissionableLarge.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite,
mdnsPlatform.GetCommissionableInstanceName(commissionableLargeEnhanced.instanceName,
sizeof(commissionableLargeEnhanced.instanceName)) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableLargeEnhanced) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsLargeEnhanced) == CHIP_NO_ERROR);
}
const nlTest sTests[] = {
NL_TEST_DEF("TestStub", TestStub), //
NL_TEST_DEF("TestOperational", TestOperational), //
NL_TEST_DEF("TestCommissionableNode", TestCommissionableNode), //
NL_TEST_SENTINEL() //
};
} // namespace
int TestMdnsPlatform(void)
{
nlTestSuite theSuite = { "MdnsPlatform", &sTests[0], nullptr, nullptr };
nlTestRunner(&theSuite, nullptr);
return nlTestRunnerStats(&theSuite);
}
CHIP_REGISTER_TEST_SUITE(TestMdnsPlatform)
<commit_msg>Fix compile error on TestPlatform. (#9707)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP 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 <lib/core/PeerId.h>
#include <lib/mdns/Discovery_ImplPlatform.h>
#include <lib/support/UnitTestRegistration.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/fake/MdnsImpl.h>
#include <nlunit-test.h>
#if !defined(CHIP_DEVICE_LAYER_TARGET_FAKE) || CHIP_DEVICE_LAYER_TARGET_FAKE != 1
#error "This test is designed for use only with the fake platform"
#endif
namespace {
using namespace chip;
using namespace chip::Mdns;
const uint8_t kMac[kMaxMacSize] = { 1, 2, 3, 4, 5, 6, 7, 8 };
const char host[] = "0102030405060708";
const PeerId kPeerId1 = PeerId().SetCompressedFabricId(0xBEEFBEEFF00DF00D).SetNodeId(0x1111222233334444);
const PeerId kPeerId2 = PeerId().SetCompressedFabricId(0x5555666677778888).SetNodeId(0x1212343456567878);
OperationalAdvertisingParameters operationalParams1 = OperationalAdvertisingParameters()
.SetPeerId(kPeerId1)
.SetMac(ByteSpan(kMac))
.SetPort(CHIP_PORT)
.EnableIpV4(true)
.SetMRPRetryIntervals(32, 33);
test::ExpectedCall operationalCall1 = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolTcp)
.SetServiceName("_matter")
.SetInstanceName("BEEFBEEFF00DF00D-1111222233334444")
.SetHostName(host)
.AddTxt("CRI", "32")
.AddTxt("CRA", "33");
OperationalAdvertisingParameters operationalParams2 = OperationalAdvertisingParameters()
.SetPeerId(kPeerId2)
.SetMac(ByteSpan(kMac))
.SetPort(CHIP_PORT)
.EnableIpV4(true)
.SetMRPRetryIntervals(32, 33);
test::ExpectedCall operationalCall2 = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolTcp)
.SetServiceName("_matter")
.SetInstanceName("5555666677778888-1212343456567878")
.SetHostName(host)
.AddTxt("CRI", "32")
.AddTxt("CRA", "33");
CommissionAdvertisingParameters commissionableNodeParamsSmall =
CommissionAdvertisingParameters()
.SetCommissionAdvertiseMode(CommssionAdvertiseMode::kCommissionableNode)
.SetMac(ByteSpan(kMac))
.SetLongDiscriminator(0xFFE)
.SetShortDiscriminator(0xF)
.SetCommissioningMode(CommissioningMode::kDisabled);
// Instance names need to be obtained from the advertiser, so they are not set here.
test::ExpectedCall commissionableSmall = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolUdp)
.SetServiceName("_matterc")
.SetHostName(host)
.AddTxt("CM", "0")
.AddTxt("D", "4094")
.AddSubtype("_S15")
.AddSubtype("_L4094");
CommissionAdvertisingParameters commissionableNodeParamsLargeBasic =
CommissionAdvertisingParameters()
.SetCommissionAdvertiseMode(CommssionAdvertiseMode::kCommissionableNode)
.SetMac(ByteSpan(kMac, sizeof(kMac)))
.SetLongDiscriminator(22)
.SetShortDiscriminator(2)
.SetVendorId(chip::Optional<uint16_t>(555))
.SetDeviceType(chip::Optional<uint16_t>(25))
.SetCommissioningMode(CommissioningMode::kEnabledBasic)
.SetDeviceName(chip::Optional<const char *>("testy-test"))
.SetPairingHint(chip::Optional<uint16_t>(3))
.SetPairingInstr(chip::Optional<const char *>("Pair me"))
.SetProductId(chip::Optional<uint16_t>(897))
.SetRotatingId(chip::Optional<const char *>("id_that_spins"));
test::ExpectedCall commissionableLargeBasic = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolUdp)
.SetServiceName("_matterc")
.SetHostName(host)
.AddTxt("D", "22")
.AddTxt("VP", "555+897")
.AddTxt("CM", "1")
.AddTxt("DT", "25")
.AddTxt("DN", "testy-test")
.AddTxt("RI", "id_that_spins")
.AddTxt("PI", "Pair me")
.AddTxt("PH", "3")
.AddSubtype("_S2")
.AddSubtype("_L22")
.AddSubtype("_V555")
.AddSubtype("_T25")
.AddSubtype("_CM");
CommissionAdvertisingParameters commissionableNodeParamsLargeEnhanced =
CommissionAdvertisingParameters()
.SetCommissionAdvertiseMode(CommssionAdvertiseMode::kCommissionableNode)
.SetMac(ByteSpan(kMac, sizeof(kMac)))
.SetLongDiscriminator(22)
.SetShortDiscriminator(2)
.SetVendorId(chip::Optional<uint16_t>(555))
.SetDeviceType(chip::Optional<uint16_t>(25))
.SetCommissioningMode(CommissioningMode::kEnabledEnhanced)
.SetDeviceName(chip::Optional<const char *>("testy-test"))
.SetPairingHint(chip::Optional<uint16_t>(3))
.SetPairingInstr(chip::Optional<const char *>("Pair me"))
.SetProductId(chip::Optional<uint16_t>(897))
.SetRotatingId(chip::Optional<const char *>("id_that_spins"));
test::ExpectedCall commissionableLargeEnhanced = test::ExpectedCall()
.SetProtocol(MdnsServiceProtocol::kMdnsProtocolUdp)
.SetServiceName("_matterc")
.SetHostName(host)
.AddTxt("D", "22")
.AddTxt("VP", "555+897")
.AddTxt("CM", "2")
.AddTxt("DT", "25")
.AddTxt("DN", "testy-test")
.AddTxt("RI", "id_that_spins")
.AddTxt("PI", "Pair me")
.AddTxt("PH", "3")
.AddSubtype("_S2")
.AddSubtype("_L22")
.AddSubtype("_V555")
.AddSubtype("_T25")
.AddSubtype("_CM");
void TestStub(nlTestSuite * inSuite, void * inContext)
{
// This is a test of the fake platform impl. We want
// We want the platform to return unexpected event if it gets a start
// without an expected event.
ChipLogError(Discovery, "Test platform returns error correctly");
DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance();
NL_TEST_ASSERT(inSuite, mdnsPlatform.Init() == CHIP_NO_ERROR);
OperationalAdvertisingParameters params;
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(params) == CHIP_ERROR_UNEXPECTED_EVENT);
}
void TestOperational(nlTestSuite * inSuite, void * inContext)
{
ChipLogError(Discovery, "Test operational");
test::Reset();
DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance();
NL_TEST_ASSERT(inSuite, mdnsPlatform.Init() == CHIP_NO_ERROR);
operationalCall1.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(operationalCall1) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(operationalParams1) == CHIP_NO_ERROR);
// Next call to advertise should call start again with just the new data.
test::Reset();
operationalCall2.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(operationalCall2) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(operationalParams2) == CHIP_NO_ERROR);
}
void TestCommissionableNode(nlTestSuite * inSuite, void * inContext)
{
ChipLogError(Discovery, "Test commissionable");
test::Reset();
DiscoveryImplPlatform & mdnsPlatform = DiscoveryImplPlatform::GetInstance();
NL_TEST_ASSERT(inSuite, mdnsPlatform.Init() == CHIP_NO_ERROR);
commissionableSmall.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite,
mdnsPlatform.GetCommissionableInstanceName(commissionableSmall.instanceName,
sizeof(commissionableSmall.instanceName)) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableSmall) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsSmall) == CHIP_NO_ERROR);
// TODO: Right now, platform impl doesn't stop commissionable node before starting a new one. Add stop call here once that is
// fixed.
test::Reset();
commissionableLargeBasic.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite,
mdnsPlatform.GetCommissionableInstanceName(commissionableLargeBasic.instanceName,
sizeof(commissionableLargeBasic.instanceName)) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableLargeBasic) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsLargeBasic) == CHIP_NO_ERROR);
test::Reset();
commissionableLargeEnhanced.callType = test::CallType::kStart;
NL_TEST_ASSERT(inSuite,
mdnsPlatform.GetCommissionableInstanceName(commissionableLargeEnhanced.instanceName,
sizeof(commissionableLargeEnhanced.instanceName)) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, test::AddExpectedCall(commissionableLargeEnhanced) == CHIP_NO_ERROR);
NL_TEST_ASSERT(inSuite, mdnsPlatform.Advertise(commissionableNodeParamsLargeEnhanced) == CHIP_NO_ERROR);
}
const nlTest sTests[] = {
NL_TEST_DEF("TestStub", TestStub), //
NL_TEST_DEF("TestOperational", TestOperational), //
NL_TEST_DEF("TestCommissionableNode", TestCommissionableNode), //
NL_TEST_SENTINEL() //
};
} // namespace
int TestMdnsPlatform(void)
{
nlTestSuite theSuite = { "MdnsPlatform", &sTests[0], nullptr, nullptr };
nlTestRunner(&theSuite, nullptr);
return nlTestRunnerStats(&theSuite);
}
CHIP_REGISTER_TEST_SUITE(TestMdnsPlatform)
<|endoftext|> |
<commit_before>#include "zmq.h"
#include <iostream>
#include "AliHLTDataTypes.h"
#include "AliHLTComponent.h"
#include "AliHLTMessage.h"
#include "TClass.h"
#include "TMap.h"
#include "TPRegexp.h"
#include "TObjString.h"
#include "TList.h"
#include "TMessage.h"
#include "TRint.h"
#include "TApplication.h"
#include <time.h>
#include <string>
#include <map>
#include "AliZMQhelpers.h"
//this is meant to become a class, hence the structure with global vars etc.
//Also the code is rather flat - it is a bit of a playground to test ideas.
//TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling
//zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide
//easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...)
//methods
int ProcessOptionString(TString arguments);
int InitZMQ();
void* work(void* param);
int Run();
//configuration vars
TString fZMQconfigIN = "";
TString fZMQconfigOUT = "";
TString fZMQconfigMON = "";
Bool_t fSendOnMerge = kTRUE;
Bool_t fResetOnSend = kFALSE;
//ZMQ stuff
void* fZMQcontext = NULL; //ze zmq context
void* fZMQmon = NULL; //the request-reply socket, here we request the merged data
void* fZMQout = NULL; //the monitoring socket, here we publish a copy of the data
void* fZMQin = NULL; //the in socket - entry point for the data to be merged.
int inType = -1;
int outType = -1;
int monType = -1;
int fZMQtimeout = -1;
int fZMQmaxQueueSize = 100;
int fSleep = 0;
bool fVerbose = false;
const char* fUSAGE =
"ZMQproxy: a simple monitored ZMQ proxy\n"
"caveat: using a REQ socket causes a custom request to be sent;\n"
" only the reply is forwardedto the backend.\n"
" For request forwarding use DEALER-ROUTER.\n"
"options:\n"
" -in : socket in\n"
" -out : socket out\n"
" -mon : monitor socket\n"
" -sleep : sleep between polls (ms) (if in is a REQ socket)\n"
" -timeout : timeout for a poll (ms)\n"
;
int capture(void* capture, zmq_msg_t* msg, int more = 0)
{
int rc = 0;
if (!capture) return 0;
zmq_msg_t ctrl;
rc = zmq_msg_init(&ctrl);
if (rc<0) return -1;
rc = zmq_msg_copy(&ctrl, msg);
if (rc<0) return -1;
return zmq_msg_send(&ctrl, capture, more?ZMQ_SNDMORE:0);
}
int forward(void* from, void* to, void* mon, zmq_msg_t* msg)
{
int rc = 0;
int more = 0;
size_t moresize = sizeof(more);
while (true)
{
rc = zmq_msg_recv(msg,from,0);
if (rc<0) return -1;
rc = zmq_getsockopt(from, ZMQ_RCVMORE, &more, &moresize);
if (from!=mon) {
rc = capture(mon,msg,more);
}
if (rc<0) return -1;
rc = zmq_msg_send(msg,to,more?ZMQ_SNDMORE:0);
if (rc<0) return -1;
if (more==0) break;
}
if (fVerbose) printf("forwarded...\n");
return 0;
}
//_______________________________________________________________________________________
int Run()
{
int rc = 0;
bool interrunpted = false;
while (!interrunpted)
{
//send the requests first
//it is OK to block if there is no remote end
//the use case is to go from REQ->PUB for the event display
//otherwise the reconnect can take a while
if (inType==ZMQ_REQ) {
if (fVerbose) printf("requesting on %p %s\n",fZMQin, fZMQconfigIN.Data());
rc = alizmq_msg_send("","",fZMQin,0);
}
if (outType==ZMQ_REQ) {
if (fVerbose) printf("requesting on %s\n",fZMQconfigOUT.Data());
alizmq_msg_send("","",fZMQout,0);
}
//poll socket readiness for sending
Int_t noutSockets=2;
zmq_pollitem_t outSockets[] = {
{ fZMQin, 0, ZMQ_POLLOUT, 0 },
{ fZMQout, 0, ZMQ_POLLOUT, 0 },
{ fZMQmon, 0, ZMQ_POLLOUT, 0 },
};
rc = zmq_poll(outSockets, noutSockets, fZMQtimeout); //poll outSockets
if (rc==-1 && errno==ETERM)
{
//this can only happen if the context was terminated, one of the inSockets are
//not valid or operation was interrupted
Printf("zmq_poll (out) was interrupted! rc = %i, %s", rc, zmq_strerror(errno));
break;
}
//in
if (outSockets[0].revents & ZMQ_POLLOUT)
{
if (fVerbose) printf("socket (%p) %s signals ZMQ_POLLOUT\n",fZMQin, fZMQconfigIN.Data());
}
//out
if (outSockets[1].revents & ZMQ_POLLOUT)
{
if (fVerbose) printf("socket %p (%s) signals ZMQ_POLLOUT\n", fZMQout, fZMQconfigOUT.Data());
}
//mon
if (outSockets[2].revents & ZMQ_POLLOUT)
{
if (fVerbose) printf("socket %p (%s) signals ZMQ_POLLOUT\n", fZMQmon, fZMQconfigMON.Data());
}
//poll incoming data
Int_t ninSockets=3;
zmq_pollitem_t inSockets[] = {
{ fZMQin, 0, ZMQ_POLLIN, 0 },
{ fZMQout, 0, ZMQ_POLLIN, 0 },
{ fZMQmon, 0, ZMQ_POLLIN, 0 },
};
if (fVerbose) printf("starting poll in\n");
int pollrc = zmq_poll(inSockets, ninSockets, fZMQtimeout); //poll inSockets
if (pollrc==-1 && errno==ETERM)
{
//this can only happen if the context was terminated, one of the inSockets are
//not valid or operation was interrupted
Printf("zmq_poll (in) was interrupted! rc = %i, %s", rc, zmq_strerror(errno));
break;
}
zmq_msg_t msg;
zmq_msg_init(&msg);
//in
if (inSockets[0].revents & ZMQ_POLLIN)
{
if (fVerbose) printf("data in on %s\n",fZMQconfigIN.Data());
if (outSockets[1].events & ZMQ_POLLOUT)
{
rc = forward(fZMQin,fZMQout,fZMQmon,&msg);
}
}
//out
if (inSockets[1].revents & ZMQ_POLLIN)
{
if (fVerbose) printf("data in on %s\n",fZMQconfigOUT.Data());
if (outSockets[0].events & ZMQ_POLLOUT)
{
rc = forward(fZMQout,fZMQin,fZMQmon,&msg);
}
}
//mon
if (inSockets[2].revents & ZMQ_POLLIN)
{
if (fVerbose) printf("data in on %s\n",fZMQconfigMON.Data());
if (outSockets[2].events & ZMQ_POLLOUT)
{
rc = forward(fZMQmon,fZMQmon,NULL,&msg);
}
}
zmq_msg_close(&msg);
//if we time out (waiting for a response) reinit the REQ socket(s)
if (pollrc==0)
{
if (inType==ZMQ_REQ) {
if (fVerbose) printf("no reply from %s in %i ms, server died?\n",
fZMQconfigIN.Data(), fZMQtimeout);
rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(),
-1, fZMQmaxQueueSize);
if (fVerbose) printf("rc of reinit %i\n",rc);
}
if (outType==ZMQ_REQ) {
if (fVerbose) printf("no reply from %s in %i ms, server died?\n",
fZMQconfigOUT.Data(), fZMQtimeout);
rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(),
-1, fZMQmaxQueueSize);
if (fVerbose) printf("rc of reinit %i\n",rc);
}
if (monType==ZMQ_REQ) {
if (fVerbose) printf("no reply from %s in %i ms, server died?\n",
fZMQconfigMON.Data(), fZMQtimeout);
rc = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(),
-1, fZMQmaxQueueSize);
if (fVerbose) printf("rc of reinit %i\n",rc);
}
}
if (fSleep>0) usleep(fSleep);
}
return rc;
}
//_______________________________________________________________________________________
int InitZMQ()
{
//init or reinit stuff
int rc = 0;
inType = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, fZMQmaxQueueSize);
outType = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), -1, fZMQmaxQueueSize);
monType = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(), -1, fZMQmaxQueueSize);
printf("socket init (in,out,mon): %i, %i, %i, %s, %s, %s\n",inType,outType,monType,alizmq_socket_name(inType),alizmq_socket_name(outType),alizmq_socket_name(monType));
return rc;
}
//______________________________________________________________________________
int ProcessOptionString(TString arguments)
{
//process passed options
aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments);
int nOptions = 0;
for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i)
{
const TString& option = i->first;
const TString& value = i->second;
if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in"))
{
fZMQconfigIN = value;
}
else if (option.EqualTo("ZMQconfigOUT") || option.EqualTo("out"))
{
fZMQconfigOUT = value;
}
else if (option.EqualTo("ZMQconfigMON") || option.EqualTo("mon"))
{
fZMQconfigMON = value;
}
else if (option.EqualTo("Verbose"))
{
fVerbose = true;
}
else if (option.EqualTo("sleep"))
{
fSleep = value.Atoi() * 1000;
}
else if (option.EqualTo("timeout"))
{
fZMQtimeout = value.Atoi();
}
else
{
nOptions=-1;
break;
}
nOptions++;
}
delete options; //tidy up
return nOptions;
}
//_______________________________________________________________________________________
int main(int argc, char** argv)
{
int mainReturnCode=0;
//process args
TString argString = AliOptionParser::GetFullArgString(argc,argv);
if (ProcessOptionString(argString)<=0)
{
printf("%s",fUSAGE);
return 1;
}
//the context
fZMQcontext = alizmq_context();
//init stuff
if (InitZMQ()<0) {
Printf("failed init");
return 1;
}
Run();
//destroy ZMQ sockets
zmq_close(fZMQmon);
zmq_close(fZMQin);
//zmq_close(fZMQout);
zmq_ctx_destroy(fZMQcontext);
return mainReturnCode;
}
<commit_msg>close the message properly after an error<commit_after>#include "zmq.h"
#include <iostream>
#include "AliHLTDataTypes.h"
#include "AliHLTComponent.h"
#include "AliHLTMessage.h"
#include "TClass.h"
#include "TMap.h"
#include "TPRegexp.h"
#include "TObjString.h"
#include "TList.h"
#include "TMessage.h"
#include "TRint.h"
#include "TApplication.h"
#include <time.h>
#include <string>
#include <map>
#include "AliZMQhelpers.h"
//this is meant to become a class, hence the structure with global vars etc.
//Also the code is rather flat - it is a bit of a playground to test ideas.
//TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling
//zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide
//easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...)
//methods
int ProcessOptionString(TString arguments);
int InitZMQ();
void* work(void* param);
int Run();
//configuration vars
TString fZMQconfigIN = "";
TString fZMQconfigOUT = "";
TString fZMQconfigMON = "";
Bool_t fSendOnMerge = kTRUE;
Bool_t fResetOnSend = kFALSE;
//ZMQ stuff
void* fZMQcontext = NULL; //ze zmq context
void* fZMQmon = NULL; //the request-reply socket, here we request the merged data
void* fZMQout = NULL; //the monitoring socket, here we publish a copy of the data
void* fZMQin = NULL; //the in socket - entry point for the data to be merged.
int inType = -1;
int outType = -1;
int monType = -1;
int fZMQtimeout = -1;
int fZMQmaxQueueSize = 100;
int fSleep = 0;
bool fVerbose = false;
const char* fUSAGE =
"ZMQproxy: a simple monitored ZMQ proxy\n"
"caveat: using a REQ socket causes a custom request to be sent;\n"
" only the reply is forwardedto the backend.\n"
" For request forwarding use DEALER-ROUTER.\n"
"options:\n"
" -in : socket in\n"
" -out : socket out\n"
" -mon : monitor socket\n"
" -sleep : sleep between polls (ms) (if in is a REQ socket)\n"
" -timeout : timeout for a poll (ms)\n"
;
int capture(void* capture, zmq_msg_t* msg, int more = 0)
{
int rc = 0;
if (!capture) return 0;
zmq_msg_t ctrl;
rc = zmq_msg_init(&ctrl);
if (rc<0) return -1;
rc = zmq_msg_copy(&ctrl, msg);
if (rc<0) {
zmq_msg_close(&ctrl);
return -1;
}
rc = zmq_msg_send(&ctrl, capture, more?ZMQ_SNDMORE:0);
if (rc<0) {
zmq_msg_close(&ctrl);
}
return rc;
}
int forward(void* from, void* to, void* mon, zmq_msg_t* msg)
{
int rc = 0;
int more = 0;
size_t moresize = sizeof(more);
while (true)
{
rc = zmq_msg_recv(msg,from,0);
if (rc<0) return -1;
rc = zmq_getsockopt(from, ZMQ_RCVMORE, &more, &moresize);
if (from!=mon) {
rc = capture(mon,msg,more);
}
if (rc<0) return -1;
rc = zmq_msg_send(msg,to,more?ZMQ_SNDMORE:0);
if (rc<0) return -1;
if (more==0) break;
}
if (fVerbose) printf("forwarded...\n");
return 0;
}
//_______________________________________________________________________________________
int Run()
{
int rc = 0;
bool interrunpted = false;
while (!interrunpted)
{
//send the requests first
//it is OK to block if there is no remote end
//the use case is to go from REQ->PUB for the event display
//otherwise the reconnect can take a while
if (inType==ZMQ_REQ) {
if (fVerbose) printf("requesting on %p %s\n",fZMQin, fZMQconfigIN.Data());
rc = alizmq_msg_send("","",fZMQin,0);
}
if (outType==ZMQ_REQ) {
if (fVerbose) printf("requesting on %s\n",fZMQconfigOUT.Data());
alizmq_msg_send("","",fZMQout,0);
}
//poll socket readiness for sending
Int_t noutSockets=2;
zmq_pollitem_t outSockets[] = {
{ fZMQin, 0, ZMQ_POLLOUT, 0 },
{ fZMQout, 0, ZMQ_POLLOUT, 0 },
{ fZMQmon, 0, ZMQ_POLLOUT, 0 },
};
rc = zmq_poll(outSockets, noutSockets, fZMQtimeout); //poll outSockets
if (rc==-1 && errno==ETERM)
{
//this can only happen if the context was terminated, one of the inSockets are
//not valid or operation was interrupted
Printf("zmq_poll (out) was interrupted! rc = %i, %s", rc, zmq_strerror(errno));
break;
}
//in
if (outSockets[0].revents & ZMQ_POLLOUT)
{
if (fVerbose) printf("socket (%p) %s signals ZMQ_POLLOUT\n",fZMQin, fZMQconfigIN.Data());
}
//out
if (outSockets[1].revents & ZMQ_POLLOUT)
{
if (fVerbose) printf("socket %p (%s) signals ZMQ_POLLOUT\n", fZMQout, fZMQconfigOUT.Data());
}
//mon
if (outSockets[2].revents & ZMQ_POLLOUT)
{
if (fVerbose) printf("socket %p (%s) signals ZMQ_POLLOUT\n", fZMQmon, fZMQconfigMON.Data());
}
//poll incoming data
Int_t ninSockets=3;
zmq_pollitem_t inSockets[] = {
{ fZMQin, 0, ZMQ_POLLIN, 0 },
{ fZMQout, 0, ZMQ_POLLIN, 0 },
{ fZMQmon, 0, ZMQ_POLLIN, 0 },
};
if (fVerbose) printf("starting poll in\n");
int pollrc = zmq_poll(inSockets, ninSockets, fZMQtimeout); //poll inSockets
if (pollrc==-1 && errno==ETERM)
{
//this can only happen if the context was terminated, one of the inSockets are
//not valid or operation was interrupted
Printf("zmq_poll (in) was interrupted! rc = %i, %s", rc, zmq_strerror(errno));
break;
}
zmq_msg_t msg;
zmq_msg_init(&msg);
//in
if (inSockets[0].revents & ZMQ_POLLIN)
{
if (fVerbose) printf("data in on %s\n",fZMQconfigIN.Data());
if (outSockets[1].events & ZMQ_POLLOUT)
{
rc = forward(fZMQin,fZMQout,fZMQmon,&msg);
}
}
//out
if (inSockets[1].revents & ZMQ_POLLIN)
{
if (fVerbose) printf("data in on %s\n",fZMQconfigOUT.Data());
if (outSockets[0].events & ZMQ_POLLOUT)
{
rc = forward(fZMQout,fZMQin,fZMQmon,&msg);
}
}
//mon
if (inSockets[2].revents & ZMQ_POLLIN)
{
if (fVerbose) printf("data in on %s\n",fZMQconfigMON.Data());
if (outSockets[2].events & ZMQ_POLLOUT)
{
rc = forward(fZMQmon,fZMQmon,NULL,&msg);
}
}
zmq_msg_close(&msg);
//if we time out (waiting for a response) reinit the REQ socket(s)
if (pollrc==0)
{
if (inType==ZMQ_REQ) {
if (fVerbose) printf("no reply from %s in %i ms, server died?\n",
fZMQconfigIN.Data(), fZMQtimeout);
rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(),
-1, fZMQmaxQueueSize);
if (fVerbose) printf("rc of reinit %i\n",rc);
}
if (outType==ZMQ_REQ) {
if (fVerbose) printf("no reply from %s in %i ms, server died?\n",
fZMQconfigOUT.Data(), fZMQtimeout);
rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(),
-1, fZMQmaxQueueSize);
if (fVerbose) printf("rc of reinit %i\n",rc);
}
if (monType==ZMQ_REQ) {
if (fVerbose) printf("no reply from %s in %i ms, server died?\n",
fZMQconfigMON.Data(), fZMQtimeout);
rc = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(),
-1, fZMQmaxQueueSize);
if (fVerbose) printf("rc of reinit %i\n",rc);
}
}
if (fSleep>0) usleep(fSleep);
}
return rc;
}
//_______________________________________________________________________________________
int InitZMQ()
{
//init or reinit stuff
int rc = 0;
inType = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, fZMQmaxQueueSize);
outType = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), -1, fZMQmaxQueueSize);
monType = alizmq_socket_init(fZMQmon, fZMQcontext, fZMQconfigMON.Data(), -1, fZMQmaxQueueSize);
printf("socket init (in,out,mon): %i, %i, %i, %s, %s, %s\n",inType,outType,monType,alizmq_socket_name(inType),alizmq_socket_name(outType),alizmq_socket_name(monType));
return rc;
}
//______________________________________________________________________________
int ProcessOptionString(TString arguments)
{
//process passed options
aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments);
int nOptions = 0;
for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i)
{
const TString& option = i->first;
const TString& value = i->second;
if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in"))
{
fZMQconfigIN = value;
}
else if (option.EqualTo("ZMQconfigOUT") || option.EqualTo("out"))
{
fZMQconfigOUT = value;
}
else if (option.EqualTo("ZMQconfigMON") || option.EqualTo("mon"))
{
fZMQconfigMON = value;
}
else if (option.EqualTo("Verbose"))
{
fVerbose = true;
}
else if (option.EqualTo("sleep"))
{
fSleep = value.Atoi() * 1000;
}
else if (option.EqualTo("timeout"))
{
fZMQtimeout = value.Atoi();
}
else
{
nOptions=-1;
break;
}
nOptions++;
}
delete options; //tidy up
return nOptions;
}
//_______________________________________________________________________________________
int main(int argc, char** argv)
{
int mainReturnCode=0;
//process args
TString argString = AliOptionParser::GetFullArgString(argc,argv);
if (ProcessOptionString(argString)<=0)
{
printf("%s",fUSAGE);
return 1;
}
//the context
fZMQcontext = alizmq_context();
//init stuff
if (InitZMQ()<0) {
Printf("failed init");
return 1;
}
Run();
//destroy ZMQ sockets
zmq_close(fZMQmon);
zmq_close(fZMQin);
//zmq_close(fZMQout);
zmq_ctx_destroy(fZMQcontext);
return mainReturnCode;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: paraprev.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:33:57 $
*
* 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_svx.hxx"
// include ---------------------------------------------------------------
#include "paraprev.hxx"
// STATIC DATA -----------------------------------------------------------
#define FOUR_POINTS 80
// class SvxParaPrevWindow -----------------------------------------------
SvxParaPrevWindow::SvxParaPrevWindow( Window* pParent, const ResId& rId ) :
Window( pParent, rId ),
nLeftMargin ( 0 ),
nRightMargin ( 0 ),
nFirstLineOfst ( 0 ),
nUpper ( 0 ),
nLower ( 0 ),
eAdjust ( SVX_ADJUST_LEFT ),
eLastLine ( SVX_ADJUST_LEFT ),
eLine ( SVX_PREV_LINESPACE_1 ),
nLineVal ( 0 )
{
// defaultmaessing in Twips rechnen
SetMapMode( MapMode( MAP_TWIP ) );
aWinSize = GetOutputSizePixel();
aWinSize = PixelToLogic( aWinSize );
Size aTmp(1, 1);
aTmp = PixelToLogic(aTmp);
aWinSize.Width() -= aTmp.Width() /2;
aWinSize.Height() -= aTmp.Height() /2;
aSize = Size( 11905, 16837 );
SetBorderStyle( WINDOW_BORDER_MONO );
}
// -----------------------------------------------------------------------
void SvxParaPrevWindow::Paint( const Rectangle& )
{
DrawParagraph( TRUE );
}
// -----------------------------------------------------------------------
#define DEF_MARGIN 120
void SvxParaPrevWindow::DrawParagraph( BOOL bAll )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
const Color& rWinColor = rStyleSettings.GetWindowColor();
Color aGrayColor(COL_LIGHTGRAY);
SetFillColor( Color( rWinColor ) );
if( bAll )
DrawRect( Rectangle( Point(), aWinSize ) );
SetLineColor();
long nH = aWinSize.Height() / 19;
Size aLineSiz( aWinSize.Width() - DEF_MARGIN, nH ),
aSiz = aLineSiz;
Point aPnt;
aPnt.X() = DEF_MARGIN / 2;
SetFillColor( aGrayColor );
for ( USHORT i = 0; i < 9; ++i )
{
if ( 3 == i )
{
SetFillColor( Color( COL_GRAY ) );
long nTop = nUpper * aLineSiz.Height() / aSize.Height();
aPnt.Y() += nTop * 2;
}
if ( 6 == i )
SetFillColor( aGrayColor );
if ( 3 <= i && 6 > i )
{
long nLeft = nLeftMargin * aLineSiz.Width() / aSize.Width();
long nFirst = nFirstLineOfst * aLineSiz.Width() / aSize.Width();
long nTmp = nLeft + nFirst;
if ( 3 == i )
{
aPnt.X() += nTmp;
aSiz.Width() -= nTmp;
}
else
{
aPnt.X() += nLeft;
aSiz.Width() -= nLeft;
}
long nRight = nRightMargin * aLineSiz.Width() / aSize.Width();
aSiz.Width() -= nRight;
}
if ( 4 == i || 5 == i || 6 == i )
{
switch ( eLine )
{
case SVX_PREV_LINESPACE_1: break;
case SVX_PREV_LINESPACE_15: aPnt.Y() += nH / 2; break;
case SVX_PREV_LINESPACE_2: aPnt.Y() += nH; break;
case SVX_PREV_LINESPACE_PROP:
case SVX_PREV_LINESPACE_MIN:
case SVX_PREV_LINESPACE_DURCH: break;
}
}
aPnt.Y() += nH;
if ( (3 <= i) && (5 >= i) )
{
long nLW;
switch( i )
{
case 3: nLW = aLineSiz.Width() * 8 / 10; break;
case 4: nLW = aLineSiz.Width() * 9 / 10; break;
case 5: nLW = aLineSiz.Width() / 2; break;
}
if ( nLW > aSiz.Width() )
nLW = aSiz.Width();
switch ( eAdjust )
{
case SVX_ADJUST_LEFT:
break;
case SVX_ADJUST_RIGHT:
aPnt.X() += ( aSiz.Width() - nLW );
break;
case SVX_ADJUST_CENTER:
aPnt.X() += ( aSiz.Width() - nLW ) / 2;
break;
default: ; //prevent warning
}
if( SVX_ADJUST_BLOCK == eAdjust )
{
if( 5 == i )
{
switch( eLastLine )
{
case SVX_ADJUST_LEFT:
break;
case SVX_ADJUST_RIGHT:
aPnt.X() += ( aSiz.Width() - nLW );
break;
case SVX_ADJUST_CENTER:
aPnt.X() += ( aSiz.Width() - nLW ) / 2;
break;
case SVX_ADJUST_BLOCK:
nLW = aSiz.Width();
break;
default: ; //prevent warning
}
}
else
nLW = aSiz.Width();
}
aSiz.Width() = nLW;
}
Rectangle aRect( aPnt, aSiz );
if ( Lines[i] != aRect || bAll )
{
if ( !bAll )
{
Color aFillCol = GetFillColor();
SetFillColor( rWinColor );
DrawRect( Lines[i] );
SetFillColor( aFillCol );
}
DrawRect( aRect );
Lines[i] = aRect;
}
if ( 5 == i )
{
long nBottom = nLower * aLineSiz.Height() / aSize.Height();
aPnt.Y() += nBottom * 2;
}
aPnt.Y() += nH;
// wieder zuruecksetzen, fuer jede Linie neu berechnen
aPnt.X() = DEF_MARGIN / 2;
aSiz = aLineSiz;
}
}
#undef DEF_MARGIN
// -----------------------------------------------------------------------
void SvxParaPrevWindow::OutputSizeChanged()
{
aWinSize = GetOutputSizePixel();
aWinSize = PixelToLogic( aWinSize );
Invalidate();
}
<commit_msg>INTEGRATION: CWS sb59 (1.10.62); FILE MERGED 2006/08/03 13:51:35 cl 1.10.62.1: removed compiler warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: paraprev.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:24:42 $
*
* 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_svx.hxx"
// include ---------------------------------------------------------------
#include "paraprev.hxx"
// STATIC DATA -----------------------------------------------------------
#define FOUR_POINTS 80
// class SvxParaPrevWindow -----------------------------------------------
SvxParaPrevWindow::SvxParaPrevWindow( Window* pParent, const ResId& rId ) :
Window( pParent, rId ),
nLeftMargin ( 0 ),
nRightMargin ( 0 ),
nFirstLineOfst ( 0 ),
nUpper ( 0 ),
nLower ( 0 ),
eAdjust ( SVX_ADJUST_LEFT ),
eLastLine ( SVX_ADJUST_LEFT ),
eLine ( SVX_PREV_LINESPACE_1 ),
nLineVal ( 0 )
{
// defaultmaessing in Twips rechnen
SetMapMode( MapMode( MAP_TWIP ) );
aWinSize = GetOutputSizePixel();
aWinSize = PixelToLogic( aWinSize );
Size aTmp(1, 1);
aTmp = PixelToLogic(aTmp);
aWinSize.Width() -= aTmp.Width() /2;
aWinSize.Height() -= aTmp.Height() /2;
aSize = Size( 11905, 16837 );
SetBorderStyle( WINDOW_BORDER_MONO );
}
// -----------------------------------------------------------------------
void SvxParaPrevWindow::Paint( const Rectangle& )
{
DrawParagraph( TRUE );
}
// -----------------------------------------------------------------------
#define DEF_MARGIN 120
void SvxParaPrevWindow::DrawParagraph( BOOL bAll )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
const Color& rWinColor = rStyleSettings.GetWindowColor();
Color aGrayColor(COL_LIGHTGRAY);
SetFillColor( Color( rWinColor ) );
if( bAll )
DrawRect( Rectangle( Point(), aWinSize ) );
SetLineColor();
long nH = aWinSize.Height() / 19;
Size aLineSiz( aWinSize.Width() - DEF_MARGIN, nH ),
aSiz = aLineSiz;
Point aPnt;
aPnt.X() = DEF_MARGIN / 2;
SetFillColor( aGrayColor );
for ( USHORT i = 0; i < 9; ++i )
{
if ( 3 == i )
{
SetFillColor( Color( COL_GRAY ) );
long nTop = nUpper * aLineSiz.Height() / aSize.Height();
aPnt.Y() += nTop * 2;
}
if ( 6 == i )
SetFillColor( aGrayColor );
if ( 3 <= i && 6 > i )
{
long nLeft = nLeftMargin * aLineSiz.Width() / aSize.Width();
long nFirst = nFirstLineOfst * aLineSiz.Width() / aSize.Width();
long nTmp = nLeft + nFirst;
if ( 3 == i )
{
aPnt.X() += nTmp;
aSiz.Width() -= nTmp;
}
else
{
aPnt.X() += nLeft;
aSiz.Width() -= nLeft;
}
long nRight = nRightMargin * aLineSiz.Width() / aSize.Width();
aSiz.Width() -= nRight;
}
if ( 4 == i || 5 == i || 6 == i )
{
switch ( eLine )
{
case SVX_PREV_LINESPACE_1: break;
case SVX_PREV_LINESPACE_15: aPnt.Y() += nH / 2; break;
case SVX_PREV_LINESPACE_2: aPnt.Y() += nH; break;
case SVX_PREV_LINESPACE_PROP:
case SVX_PREV_LINESPACE_MIN:
case SVX_PREV_LINESPACE_DURCH: break;
}
}
aPnt.Y() += nH;
if ( (3 <= i) && (5 >= i) )
{
long nLW;
switch( i )
{
default:
case 3: nLW = aLineSiz.Width() * 8 / 10; break;
case 4: nLW = aLineSiz.Width() * 9 / 10; break;
case 5: nLW = aLineSiz.Width() / 2; break;
}
if ( nLW > aSiz.Width() )
nLW = aSiz.Width();
switch ( eAdjust )
{
case SVX_ADJUST_LEFT:
break;
case SVX_ADJUST_RIGHT:
aPnt.X() += ( aSiz.Width() - nLW );
break;
case SVX_ADJUST_CENTER:
aPnt.X() += ( aSiz.Width() - nLW ) / 2;
break;
default: ; //prevent warning
}
if( SVX_ADJUST_BLOCK == eAdjust )
{
if( 5 == i )
{
switch( eLastLine )
{
case SVX_ADJUST_LEFT:
break;
case SVX_ADJUST_RIGHT:
aPnt.X() += ( aSiz.Width() - nLW );
break;
case SVX_ADJUST_CENTER:
aPnt.X() += ( aSiz.Width() - nLW ) / 2;
break;
case SVX_ADJUST_BLOCK:
nLW = aSiz.Width();
break;
default: ; //prevent warning
}
}
else
nLW = aSiz.Width();
}
aSiz.Width() = nLW;
}
Rectangle aRect( aPnt, aSiz );
if ( Lines[i] != aRect || bAll )
{
if ( !bAll )
{
Color aFillCol = GetFillColor();
SetFillColor( rWinColor );
DrawRect( Lines[i] );
SetFillColor( aFillCol );
}
DrawRect( aRect );
Lines[i] = aRect;
}
if ( 5 == i )
{
long nBottom = nLower * aLineSiz.Height() / aSize.Height();
aPnt.Y() += nBottom * 2;
}
aPnt.Y() += nH;
// wieder zuruecksetzen, fuer jede Linie neu berechnen
aPnt.X() = DEF_MARGIN / 2;
aSiz = aLineSiz;
}
}
#undef DEF_MARGIN
// -----------------------------------------------------------------------
void SvxParaPrevWindow::OutputSizeChanged()
{
aWinSize = GetOutputSizePixel();
aWinSize = PixelToLogic( aWinSize );
Invalidate();
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "ExpressionUnderCursor.h"
#include "SimpleLexer.h"
#include "BackwardsScanner.h"
#include <Token.h>
#include <QTextCursor>
#include <QTextBlock>
using namespace CPlusPlus;
ExpressionUnderCursor::ExpressionUnderCursor()
: _jumpedComma(false)
{ }
ExpressionUnderCursor::~ExpressionUnderCursor()
{ }
int ExpressionUnderCursor::startOfExpression(BackwardsScanner &tk, int index)
{
if (tk[index - 1].is(T_GREATER)) {
const int matchingBraceIndex = tk.startOfMatchingBrace(index);
if (tk[matchingBraceIndex - 1].is(T_IDENTIFIER))
index = matchingBraceIndex - 1;
}
index = startOfExpression_helper(tk, index);
if (_jumpedComma) {
const SimpleToken &tok = tk[index - 1];
switch (tok.kind()) {
case T_COMMA:
case T_LPAREN:
case T_LBRACKET:
case T_LBRACE:
case T_SEMICOLON:
case T_COLON:
case T_QUESTION:
break;
default:
if (tok.isOperator())
return startOfExpression(tk, index - 1);
break;
}
}
return index;
}
int ExpressionUnderCursor::startOfExpression_helper(BackwardsScanner &tk, int index)
{
if (tk[index - 1].isLiteral()) {
return index - 1;
} else if (tk[index - 1].is(T_THIS)) {
return index - 1;
} else if (tk[index - 1].is(T_TYPEID)) {
return index - 1;
} else if (tk[index - 1].is(T_SIGNAL)) {
if (tk[index - 2].is(T_COMMA) && !_jumpedComma) {
_jumpedComma = true;
return startOfExpression(tk, index - 2);
}
return index - 1;
} else if (tk[index - 1].is(T_SLOT)) {
if (tk[index - 2].is(T_COMMA) && !_jumpedComma) {
_jumpedComma = true;
return startOfExpression(tk, index - 2);
}
return index - 1;
} else if (tk[index - 1].is(T_IDENTIFIER)) {
if (tk[index - 2].is(T_TILDE)) {
if (tk[index - 3].is(T_COLON_COLON)) {
return startOfExpression(tk, index - 3);
} else if (tk[index - 3].is(T_DOT) || tk[index - 3].is(T_ARROW)) {
return startOfExpression(tk, index - 3);
}
return index - 2;
} else if (tk[index - 2].is(T_COLON_COLON)) {
return startOfExpression(tk, index - 1);
} else if (tk[index - 2].is(T_DOT) || tk[index - 2].is(T_ARROW)) {
return startOfExpression(tk, index - 2);
} else if (tk[index - 2].is(T_DOT_STAR) || tk[index - 2].is(T_ARROW_STAR)) {
return startOfExpression(tk, index - 2);
} else if (tk[index - 2].is(T_LBRACKET)) {
// array subscription:
// array[i
return index - 1;
} else if (tk[index - 2].is(T_COLON)) {
// either of:
// cond ? expr1 : id
// or:
// [receiver messageParam:id
// and in both cases, the id (and only the id) is what we want, so:
return index - 1;
} else if (tk[index - 2].is(T_IDENTIFIER) && tk[index - 3].is(T_LBRACKET)) {
// Very common Objective-C case:
// [receiver message
// which we handle immediately:
return index - 3;
} else {
// See if we are handling an Objective-C messaging expression in the form of:
// [receiver messageParam1:expression messageParam2
// or:
// [receiver messageParam1:expression messageParam2:expression messageParam3
// ... etc
int i = index - 1;
while (tk[i].isNot(T_EOF_SYMBOL)) {
if (tk[i].is(T_LBRACKET))
break;
if (tk[i].is(T_LBRACE) || tk[i].is(T_RBRACE))
break;
else if (tk[i].is(T_RBRACKET))
i = tk.startOfMatchingBrace(i + 1) - 1;
else
--i;
}
int j = i;
while (tk[j].is(T_LBRACKET))
++j;
if (tk[j].is(T_IDENTIFIER) && tk[j + 1].is(T_IDENTIFIER))
return i;
}
return index - 1;
} else if (tk[index - 1].is(T_RPAREN)) {
int matchingBraceIndex = tk.startOfMatchingBrace(index);
if (matchingBraceIndex != index) {
if (tk[matchingBraceIndex - 1].is(T_GREATER)) {
int lessIndex = tk.startOfMatchingBrace(matchingBraceIndex);
if (lessIndex != matchingBraceIndex - 1) {
if (tk[lessIndex - 1].is(T_DYNAMIC_CAST) ||
tk[lessIndex - 1].is(T_STATIC_CAST) ||
tk[lessIndex - 1].is(T_CONST_CAST) ||
tk[lessIndex - 1].is(T_REINTERPRET_CAST))
return lessIndex - 1;
else if (tk[lessIndex - 1].is(T_IDENTIFIER))
return startOfExpression(tk, lessIndex);
else if (tk[lessIndex - 1].is(T_SIGNAL))
return startOfExpression(tk, lessIndex);
else if (tk[lessIndex - 1].is(T_SLOT))
return startOfExpression(tk, lessIndex);
}
}
return startOfExpression(tk, matchingBraceIndex);
}
return index;
} else if (tk[index - 1].is(T_RBRACKET)) {
int rbracketIndex = tk.startOfMatchingBrace(index);
if (rbracketIndex != index)
return startOfExpression(tk, rbracketIndex);
return index;
} else if (tk[index - 1].is(T_COLON_COLON)) {
if (tk[index - 2].is(T_GREATER)) { // ### not exactly
int lessIndex = tk.startOfMatchingBrace(index - 1);
if (lessIndex != index - 1)
return startOfExpression(tk, lessIndex);
return index - 1;
} else if (tk[index - 2].is(T_IDENTIFIER)) {
return startOfExpression(tk, index - 1);
}
return index - 1;
} else if (tk[index - 1].is(T_DOT) || tk[index - 1].is(T_ARROW)) {
return startOfExpression(tk, index - 1);
} else if (tk[index - 1].is(T_DOT_STAR) || tk[index - 1].is(T_ARROW_STAR)) {
return startOfExpression(tk, index - 1);
}
return index;
}
bool ExpressionUnderCursor::isAccessToken(const SimpleToken &tk)
{
switch (tk.kind()) {
case T_COLON_COLON:
case T_DOT: case T_ARROW:
case T_DOT_STAR: case T_ARROW_STAR:
return true;
default:
return false;
} // switch
}
QString ExpressionUnderCursor::operator()(const QTextCursor &cursor)
{
BackwardsScanner scanner(cursor);
_jumpedComma = false;
const int initialSize = scanner.startToken();
const int i = startOfExpression(scanner, initialSize);
if (i == initialSize)
return QString();
return scanner.mid(i);
}
int ExpressionUnderCursor::startOfFunctionCall(const QTextCursor &cursor) const
{
BackwardsScanner scanner(cursor);
int index = scanner.startToken();
forever {
const SimpleToken &tk = scanner[index - 1];
if (tk.is(T_EOF_SYMBOL))
break;
else if (tk.is(T_LPAREN))
return scanner.startPosition() + tk.position();
else if (tk.is(T_RPAREN)) {
int matchingBrace = scanner.startOfMatchingBrace(index);
if (matchingBrace == index) // If no matching brace found
return -1;
index = matchingBrace;
} else
--index;
}
return -1;
}
<commit_msg>Added bounds check.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "ExpressionUnderCursor.h"
#include "SimpleLexer.h"
#include "BackwardsScanner.h"
#include <Token.h>
#include <QTextCursor>
#include <QTextBlock>
using namespace CPlusPlus;
ExpressionUnderCursor::ExpressionUnderCursor()
: _jumpedComma(false)
{ }
ExpressionUnderCursor::~ExpressionUnderCursor()
{ }
int ExpressionUnderCursor::startOfExpression(BackwardsScanner &tk, int index)
{
if (tk[index - 1].is(T_GREATER)) {
const int matchingBraceIndex = tk.startOfMatchingBrace(index);
if (tk[matchingBraceIndex - 1].is(T_IDENTIFIER))
index = matchingBraceIndex - 1;
}
index = startOfExpression_helper(tk, index);
if (_jumpedComma) {
const SimpleToken &tok = tk[index - 1];
switch (tok.kind()) {
case T_COMMA:
case T_LPAREN:
case T_LBRACKET:
case T_LBRACE:
case T_SEMICOLON:
case T_COLON:
case T_QUESTION:
break;
default:
if (tok.isOperator())
return startOfExpression(tk, index - 1);
break;
}
}
return index;
}
int ExpressionUnderCursor::startOfExpression_helper(BackwardsScanner &tk, int index)
{
if (tk[index - 1].isLiteral()) {
return index - 1;
} else if (tk[index - 1].is(T_THIS)) {
return index - 1;
} else if (tk[index - 1].is(T_TYPEID)) {
return index - 1;
} else if (tk[index - 1].is(T_SIGNAL)) {
if (tk[index - 2].is(T_COMMA) && !_jumpedComma) {
_jumpedComma = true;
return startOfExpression(tk, index - 2);
}
return index - 1;
} else if (tk[index - 1].is(T_SLOT)) {
if (tk[index - 2].is(T_COMMA) && !_jumpedComma) {
_jumpedComma = true;
return startOfExpression(tk, index - 2);
}
return index - 1;
} else if (tk[index - 1].is(T_IDENTIFIER)) {
if (tk[index - 2].is(T_TILDE)) {
if (tk[index - 3].is(T_COLON_COLON)) {
return startOfExpression(tk, index - 3);
} else if (tk[index - 3].is(T_DOT) || tk[index - 3].is(T_ARROW)) {
return startOfExpression(tk, index - 3);
}
return index - 2;
} else if (tk[index - 2].is(T_COLON_COLON)) {
return startOfExpression(tk, index - 1);
} else if (tk[index - 2].is(T_DOT) || tk[index - 2].is(T_ARROW)) {
return startOfExpression(tk, index - 2);
} else if (tk[index - 2].is(T_DOT_STAR) || tk[index - 2].is(T_ARROW_STAR)) {
return startOfExpression(tk, index - 2);
} else if (tk[index - 2].is(T_LBRACKET)) {
// array subscription:
// array[i
return index - 1;
} else if (tk[index - 2].is(T_COLON)) {
// either of:
// cond ? expr1 : id
// or:
// [receiver messageParam:id
// and in both cases, the id (and only the id) is what we want, so:
return index - 1;
} else if (tk[index - 2].is(T_IDENTIFIER) && tk[index - 3].is(T_LBRACKET)) {
// Very common Objective-C case:
// [receiver message
// which we handle immediately:
return index - 3;
} else {
// See if we are handling an Objective-C messaging expression in the form of:
// [receiver messageParam1:expression messageParam2
// or:
// [receiver messageParam1:expression messageParam2:expression messageParam3
// ... etc
int i = index - 1;
while (i >= 0 && tk[i].isNot(T_EOF_SYMBOL)) {
if (tk[i].is(T_LBRACKET))
break;
if (tk[i].is(T_LBRACE) || tk[i].is(T_RBRACE))
break;
else if (tk[i].is(T_RBRACKET))
i = tk.startOfMatchingBrace(i + 1) - 1;
else
--i;
}
int j = i;
while (tk[j].is(T_LBRACKET))
++j;
if (tk[j].is(T_IDENTIFIER) && tk[j + 1].is(T_IDENTIFIER))
return i;
}
return index - 1;
} else if (tk[index - 1].is(T_RPAREN)) {
int matchingBraceIndex = tk.startOfMatchingBrace(index);
if (matchingBraceIndex != index) {
if (tk[matchingBraceIndex - 1].is(T_GREATER)) {
int lessIndex = tk.startOfMatchingBrace(matchingBraceIndex);
if (lessIndex != matchingBraceIndex - 1) {
if (tk[lessIndex - 1].is(T_DYNAMIC_CAST) ||
tk[lessIndex - 1].is(T_STATIC_CAST) ||
tk[lessIndex - 1].is(T_CONST_CAST) ||
tk[lessIndex - 1].is(T_REINTERPRET_CAST))
return lessIndex - 1;
else if (tk[lessIndex - 1].is(T_IDENTIFIER))
return startOfExpression(tk, lessIndex);
else if (tk[lessIndex - 1].is(T_SIGNAL))
return startOfExpression(tk, lessIndex);
else if (tk[lessIndex - 1].is(T_SLOT))
return startOfExpression(tk, lessIndex);
}
}
return startOfExpression(tk, matchingBraceIndex);
}
return index;
} else if (tk[index - 1].is(T_RBRACKET)) {
int rbracketIndex = tk.startOfMatchingBrace(index);
if (rbracketIndex != index)
return startOfExpression(tk, rbracketIndex);
return index;
} else if (tk[index - 1].is(T_COLON_COLON)) {
if (tk[index - 2].is(T_GREATER)) { // ### not exactly
int lessIndex = tk.startOfMatchingBrace(index - 1);
if (lessIndex != index - 1)
return startOfExpression(tk, lessIndex);
return index - 1;
} else if (tk[index - 2].is(T_IDENTIFIER)) {
return startOfExpression(tk, index - 1);
}
return index - 1;
} else if (tk[index - 1].is(T_DOT) || tk[index - 1].is(T_ARROW)) {
return startOfExpression(tk, index - 1);
} else if (tk[index - 1].is(T_DOT_STAR) || tk[index - 1].is(T_ARROW_STAR)) {
return startOfExpression(tk, index - 1);
}
return index;
}
bool ExpressionUnderCursor::isAccessToken(const SimpleToken &tk)
{
switch (tk.kind()) {
case T_COLON_COLON:
case T_DOT: case T_ARROW:
case T_DOT_STAR: case T_ARROW_STAR:
return true;
default:
return false;
} // switch
}
QString ExpressionUnderCursor::operator()(const QTextCursor &cursor)
{
BackwardsScanner scanner(cursor);
_jumpedComma = false;
const int initialSize = scanner.startToken();
const int i = startOfExpression(scanner, initialSize);
if (i == initialSize)
return QString();
return scanner.mid(i);
}
int ExpressionUnderCursor::startOfFunctionCall(const QTextCursor &cursor) const
{
BackwardsScanner scanner(cursor);
int index = scanner.startToken();
forever {
const SimpleToken &tk = scanner[index - 1];
if (tk.is(T_EOF_SYMBOL))
break;
else if (tk.is(T_LPAREN))
return scanner.startPosition() + tk.position();
else if (tk.is(T_RPAREN)) {
int matchingBrace = scanner.startOfMatchingBrace(index);
if (matchingBrace == index) // If no matching brace found
return -1;
index = matchingBrace;
} else
--index;
}
return -1;
}
<|endoftext|> |
<commit_before>
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDICOMImageReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "DICOMParser.h"
#include "DICOMAppHelper.h"
#include "vtkDICOMImageReader.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkDirectory.h"
#include <vtkstd/vector>
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkDICOMImageReader, "1.13");
vtkStandardNewMacro(vtkDICOMImageReader);
class vtkDICOMImageReaderVector : public vtkstd::vector<vtkstd::string>
{
};
vtkDICOMImageReader::vtkDICOMImageReader()
{
this->Parser = new DICOMParser();
this->AppHelper = new DICOMAppHelper();
this->DirectoryName = NULL;
this->DICOMFileNames = new vtkDICOMImageReaderVector();
}
vtkDICOMImageReader::~vtkDICOMImageReader()
{
delete this->Parser;
delete this->AppHelper;
delete this->DICOMFileNames;
}
void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkImageReader2::PrintSelf(os, indent);
if (this->DirectoryName)
{
os << "DirectoryName : " << this->DirectoryName << "\n";
}
else
{
os << "DirectoryName : (NULL)" << "\n";
}
if (this->FileName)
{
os << "FileName : " << this->FileName << "\n";
}
else
{
os << "FileName : (NULL)" << "\n";
}
}
int vtkDICOMImageReader::CanReadFile(const char* fname)
{
bool canOpen = this->Parser->OpenFile((char*) fname);
if (canOpen == false)
{
vtkErrorMacro("DICOMParser couldn't open : " << fname);
return 0;
}
bool canRead = this->Parser->IsDICOMFile();
if (canRead == true)
{
return 1;
}
else
{
return 0;
}
}
void vtkDICOMImageReader::ExecuteInformation()
{
if (this->FileName == NULL && this->DirectoryName == NULL)
{
return;
}
if (this->FileName)
{
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->Parser->ReadHeader();
this->SetupOutputInformation(1);
}
else if (this->DirectoryName)
{
vtkDirectory* dir = vtkDirectory::New();
int opened = dir->Open(this->DirectoryName);
if (!opened)
{
vtkErrorMacro("Couldn't open " << this->DirectoryName);
dir->Delete();
return;
}
int numFiles = dir->GetNumberOfFiles();
vtkDebugMacro( << "There are " << numFiles << " files in the directory.");
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
for (int i = 0; i < numFiles; i++)
{
if (strcmp(dir->GetFile(i), ".") == 0 ||
strcmp(dir->GetFile(i), "..") == 0)
{
continue;
}
vtkstd::string temp = this->DirectoryName;
vtkstd::string temp2 = dir->GetFile(i);
vtkstd::string delim = "/";
vtkstd::string fileString = temp + delim + temp2;
int val = this->CanReadFile(fileString.c_str());
if (val == 1)
{
vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames.");
this->DICOMFileNames->push_back(fileString);
}
else
{
vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val);
}
}
vtkstd::vector<vtkstd::string>::iterator iter;
for (iter = this->DICOMFileNames->begin();
iter != this->DICOMFileNames->end();
iter++)
{
char* fn = (char*) (*iter).c_str();
vtkDebugMacro( << "Trying : " << fn);
bool couldOpen = this->Parser->OpenFile(fn);
if (!couldOpen)
{
dir->Delete();
return;
}
//HERE
this->Parser->ClearAllDICOMTagCallbacks();
this->AppHelper->RegisterCallbacks(this->Parser);
// this->AppHelper->SetFileName(fn);
this->Parser->ReadHeader();
vtkDebugMacro( << "File name : " << fn );
vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber());
}
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
// this->AppHelper->SortFilenamesBySlice();
// unsigned int num_files = this->AppHelper->GetNumberOfSortedFilenames();
// for (unsigned int k = 0; k < num_files; k++)
// {
// sortedFiles.push_back(std::pair<int,std::string>(k, this->AppHelper->GetFilenameForSlice(k)));
// }
//this->AppHelper->GetSliceNumberFilenamePairs(sortedFiles);
this->SetupOutputInformation(static_cast<int>(sortedFiles.size()));
//this->AppHelper->OutputSeries();
if (sortedFiles.size() > 0)
{
this->DICOMFileNames->clear();
vtkstd::vector<vtkstd::pair<float, vtkstd::string> >::iterator siter;
for (siter = sortedFiles.begin();
siter != sortedFiles.end();
siter++)
{
vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str());
vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first);
this->DICOMFileNames->push_back((*siter).second);
}
}
else
{
vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!");
}
dir->Delete();
}
}
void vtkDICOMImageReader::ExecuteData(vtkDataObject *output)
{
vtkImageData *data = this->AllocateOutputData(output);
data->GetPointData()->GetScalars()->SetName("DICOMImage");
if (this->FileName)
{
vtkDebugMacro( << "Single file : " << this->FileName);
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
//this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLength;
this->AppHelper->GetImageData(imgData, dataType, imageDataLength);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
memcpy(buffer, imgData, imageDataLength);
}
else if (this->DICOMFileNames->size() > 0)
{
vtkDebugMacro( << "Multiple files (" << static_cast<int>(this->DICOMFileNames->size()) << ")");
this->Parser->ClearAllDICOMTagCallbacks();
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
vtkstd::vector<vtkstd::string>::iterator fiter;
int count = 0;
int numFiles = static_cast<int>(this->DICOMFileNames->size());
for (fiter = this->DICOMFileNames->begin();
fiter != this->DICOMFileNames->end();
fiter++)
{
count++;
vtkDebugMacro( << "File : " << (*fiter).c_str());
this->Parser->OpenFile((char*)(*fiter).c_str());
// this->AppHelper->SetFileName((char*)(*fiter).c_str());
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLengthInBytes;
this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes);
memcpy(buffer, imgData, imageDataLengthInBytes);
buffer = ((char*) buffer) + imageDataLengthInBytes;
this->UpdateProgress(float(count)/float(numFiles));
int len = static_cast<int> (strlen((char*) (*fiter).c_str()));
char* filename = new char[len+1];
strcpy(filename, (char*) (*fiter).c_str());
this->SetProgressText(filename);
}
}
else
{
vtkDebugMacro( << "Execute data -- no files!");
}
}
void vtkDICOMImageReader::SetupOutputInformation(int num_slices)
{
int width = this->AppHelper->GetWidth();
int height = this->AppHelper->GetHeight();
int bit_depth = this->AppHelper->GetBitsAllocated();
int num_comp = this->AppHelper->GetNumberOfComponents();
this->DataExtent[0] = 0;
this->DataExtent[1] = width - 1;
this->DataExtent[2] = 0;
this->DataExtent[3] = height - 1;
this->DataExtent[4] = 0;
this->DataExtent[5] = num_slices - 1;
bool isFloat = this->AppHelper->RescaledImageDataIsFloat();
bool sign = this->AppHelper->RescaledImageDataIsSigned();
if (isFloat)
{
this->SetDataScalarTypeToFloat();
}
else if (bit_depth <= 8)
{
this->SetDataScalarTypeToUnsignedChar();
}
else
{
if (sign)
{
this->SetDataScalarTypeToShort();
}
else
{
this->SetDataScalarTypeToUnsignedShort();
}
}
this->SetNumberOfScalarComponents(num_comp);
this->vtkImageReader2::ExecuteInformation();
}
void vtkDICOMImageReader::SetDirectoryName(const char* dn)
{
if (dn == NULL)
{
return;
}
int len = static_cast<int>(strlen(dn));
if (this->DirectoryName != NULL)
{
delete [] this->DirectoryName;
}
this->DirectoryName = new char[len+1];
strcpy(this->DirectoryName, dn);
this->FileName = NULL;
this->Modified();
}
float* vtkDICOMImageReader::GetPixelSpacing()
{
return this->AppHelper->GetPixelSpacing();
}
int vtkDICOMImageReader::GetWidth()
{
return this->AppHelper->GetWidth();
}
int vtkDICOMImageReader::GetHeight()
{
return this->AppHelper->GetHeight();
}
float* vtkDICOMImageReader::GetImagePositionPatient()
{
return this->AppHelper->GetImagePositionPatient();
}
int vtkDICOMImageReader::GetBitsAllocated()
{
return this->AppHelper->GetBitsAllocated();
}
int vtkDICOMImageReader::GetPixelRepresentation()
{
return this->AppHelper->GetPixelRepresentation();
}
int vtkDICOMImageReader::GetNumberOfComponents()
{
return this->AppHelper->GetNumberOfComponents();
}
const char* vtkDICOMImageReader::GetTransferSyntaxUID()
{
return this->AppHelper->GetTransferSyntaxUID().c_str();
}
float vtkDICOMImageReader::GetRescaleSlope()
{
return this->AppHelper->GetRescaleSlope();
}
float vtkDICOMImageReader::GetRescaleOffset()
{
return this->AppHelper->GetRescaleOffset();
}
const char* vtkDICOMImageReader::GetPatientName()
{
return this->AppHelper->GetPatientName().c_str();
}
const char* vtkDICOMImageReader::GetStudyUID()
{
return this->AppHelper->GetStudyUID().c_str();
}
float vtkDICOMImageReader::GetGantryAngle()
{
return this->AppHelper->GetGantryAngle();
}
<commit_msg>BUG: Fixed GetPixelSpacing to return values based on slice position.<commit_after>
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDICOMImageReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "DICOMParser.h"
#include "DICOMAppHelper.h"
#include "vtkDICOMImageReader.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkDirectory.h"
#include <vtkstd/vector>
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkDICOMImageReader, "1.14");
vtkStandardNewMacro(vtkDICOMImageReader);
class vtkDICOMImageReaderVector : public vtkstd::vector<vtkstd::string>
{
};
vtkDICOMImageReader::vtkDICOMImageReader()
{
this->Parser = new DICOMParser();
this->AppHelper = new DICOMAppHelper();
this->DirectoryName = NULL;
this->DICOMFileNames = new vtkDICOMImageReaderVector();
}
vtkDICOMImageReader::~vtkDICOMImageReader()
{
delete this->Parser;
delete this->AppHelper;
delete this->DICOMFileNames;
}
void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkImageReader2::PrintSelf(os, indent);
if (this->DirectoryName)
{
os << "DirectoryName : " << this->DirectoryName << "\n";
}
else
{
os << "DirectoryName : (NULL)" << "\n";
}
if (this->FileName)
{
os << "FileName : " << this->FileName << "\n";
}
else
{
os << "FileName : (NULL)" << "\n";
}
}
int vtkDICOMImageReader::CanReadFile(const char* fname)
{
bool canOpen = this->Parser->OpenFile((char*) fname);
if (canOpen == false)
{
vtkErrorMacro("DICOMParser couldn't open : " << fname);
return 0;
}
bool canRead = this->Parser->IsDICOMFile();
if (canRead == true)
{
return 1;
}
else
{
return 0;
}
}
void vtkDICOMImageReader::ExecuteInformation()
{
if (this->FileName == NULL && this->DirectoryName == NULL)
{
return;
}
if (this->FileName)
{
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->Parser->ReadHeader();
this->SetupOutputInformation(1);
}
else if (this->DirectoryName)
{
vtkDirectory* dir = vtkDirectory::New();
int opened = dir->Open(this->DirectoryName);
if (!opened)
{
vtkErrorMacro("Couldn't open " << this->DirectoryName);
dir->Delete();
return;
}
int numFiles = dir->GetNumberOfFiles();
vtkDebugMacro( << "There are " << numFiles << " files in the directory.");
this->DICOMFileNames->clear();
//this->AppHelper->ClearSeriesUIDMap();
//this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
for (int i = 0; i < numFiles; i++)
{
if (strcmp(dir->GetFile(i), ".") == 0 ||
strcmp(dir->GetFile(i), "..") == 0)
{
continue;
}
vtkstd::string temp = this->DirectoryName;
vtkstd::string temp2 = dir->GetFile(i);
vtkstd::string delim = "/";
vtkstd::string fileString = temp + delim + temp2;
int val = this->CanReadFile(fileString.c_str());
if (val == 1)
{
vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames.");
this->DICOMFileNames->push_back(fileString);
}
else
{
vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val);
}
}
vtkstd::vector<vtkstd::string>::iterator iter;
for (iter = this->DICOMFileNames->begin();
iter != this->DICOMFileNames->end();
iter++)
{
char* fn = (char*) (*iter).c_str();
vtkDebugMacro( << "Trying : " << fn);
bool couldOpen = this->Parser->OpenFile(fn);
if (!couldOpen)
{
dir->Delete();
return;
}
//HERE
this->Parser->ClearAllDICOMTagCallbacks();
this->AppHelper->RegisterCallbacks(this->Parser);
// this->AppHelper->SetFileName(fn);
this->Parser->ReadHeader();
vtkDebugMacro( << "File name : " << fn );
vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber());
}
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
// this->AppHelper->SortFilenamesBySlice();
// unsigned int num_files = this->AppHelper->GetNumberOfSortedFilenames();
// for (unsigned int k = 0; k < num_files; k++)
// {
// sortedFiles.push_back(std::pair<int,std::string>(k, this->AppHelper->GetFilenameForSlice(k)));
// }
//this->AppHelper->GetSliceNumberFilenamePairs(sortedFiles);
this->SetupOutputInformation(static_cast<int>(sortedFiles.size()));
//this->AppHelper->OutputSeries();
if (sortedFiles.size() > 0)
{
this->DICOMFileNames->clear();
vtkstd::vector<vtkstd::pair<float, vtkstd::string> >::iterator siter;
for (siter = sortedFiles.begin();
siter != sortedFiles.end();
siter++)
{
vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str());
vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first);
this->DICOMFileNames->push_back((*siter).second);
}
}
else
{
vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!");
}
dir->Delete();
}
}
void vtkDICOMImageReader::ExecuteData(vtkDataObject *output)
{
vtkImageData *data = this->AllocateOutputData(output);
data->GetPointData()->GetScalars()->SetName("DICOMImage");
if (this->FileName)
{
vtkDebugMacro( << "Single file : " << this->FileName);
this->Parser->ClearAllDICOMTagCallbacks();
this->Parser->OpenFile(this->FileName);
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
//this->AppHelper->SetFileName(this->FileName);
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLength;
this->AppHelper->GetImageData(imgData, dataType, imageDataLength);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
memcpy(buffer, imgData, imageDataLength);
}
else if (this->DICOMFileNames->size() > 0)
{
vtkDebugMacro( << "Multiple files (" << static_cast<int>(this->DICOMFileNames->size()) << ")");
this->Parser->ClearAllDICOMTagCallbacks();
// this->AppHelper->ClearSeriesUIDMap();
// this->AppHelper->ClearSliceNumberMap();
this->AppHelper->Clear();
this->AppHelper->RegisterCallbacks(this->Parser);
this->AppHelper->RegisterPixelDataCallback(this->Parser);
void* buffer = data->GetScalarPointer();
if (buffer == NULL)
{
vtkErrorMacro(<< "No memory allocated for image data!");
return;
}
vtkstd::vector<vtkstd::string>::iterator fiter;
int count = 0;
int numFiles = static_cast<int>(this->DICOMFileNames->size());
for (fiter = this->DICOMFileNames->begin();
fiter != this->DICOMFileNames->end();
fiter++)
{
count++;
vtkDebugMacro( << "File : " << (*fiter).c_str());
this->Parser->OpenFile((char*)(*fiter).c_str());
// this->AppHelper->SetFileName((char*)(*fiter).c_str());
this->Parser->ReadHeader();
void* imgData = NULL;
DICOMParser::VRTypes dataType;
unsigned long imageDataLengthInBytes;
this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes);
memcpy(buffer, imgData, imageDataLengthInBytes);
buffer = ((char*) buffer) + imageDataLengthInBytes;
this->UpdateProgress(float(count)/float(numFiles));
int len = static_cast<int> (strlen((char*) (*fiter).c_str()));
char* filename = new char[len+1];
strcpy(filename, (char*) (*fiter).c_str());
this->SetProgressText(filename);
}
}
else
{
vtkDebugMacro( << "Execute data -- no files!");
}
}
void vtkDICOMImageReader::SetupOutputInformation(int num_slices)
{
int width = this->AppHelper->GetWidth();
int height = this->AppHelper->GetHeight();
int bit_depth = this->AppHelper->GetBitsAllocated();
int num_comp = this->AppHelper->GetNumberOfComponents();
this->DataExtent[0] = 0;
this->DataExtent[1] = width - 1;
this->DataExtent[2] = 0;
this->DataExtent[3] = height - 1;
this->DataExtent[4] = 0;
this->DataExtent[5] = num_slices - 1;
bool isFloat = this->AppHelper->RescaledImageDataIsFloat();
bool sign = this->AppHelper->RescaledImageDataIsSigned();
if (isFloat)
{
this->SetDataScalarTypeToFloat();
}
else if (bit_depth <= 8)
{
this->SetDataScalarTypeToUnsignedChar();
}
else
{
if (sign)
{
this->SetDataScalarTypeToShort();
}
else
{
this->SetDataScalarTypeToUnsignedShort();
}
}
this->SetNumberOfScalarComponents(num_comp);
this->vtkImageReader2::ExecuteInformation();
}
void vtkDICOMImageReader::SetDirectoryName(const char* dn)
{
if (dn == NULL)
{
return;
}
int len = static_cast<int>(strlen(dn));
if (this->DirectoryName != NULL)
{
delete [] this->DirectoryName;
}
this->DirectoryName = new char[len+1];
strcpy(this->DirectoryName, dn);
this->FileName = NULL;
this->Modified();
}
float* vtkDICOMImageReader::GetPixelSpacing()
{
vtkstd::vector<vtkstd::pair<float, vtkstd::string> > sortedFiles;
this->AppHelper->GetImagePositionPatientFilenamePairs(sortedFiles);
float* spacing = this->AppHelper->GetPixelSpacing();
this->DataSpacing[0] = spacing[0];
this->DataSpacing[1] = spacing[1];
if (sortedFiles.size() > 1)
{
vtkstd::pair<float, vtkstd::string> p1 = sortedFiles[0];
vtkstd::pair<float, vtkstd::string> p2 = sortedFiles[1];
this->DataSpacing[2] = fabs(p1.first - p2.first);
}
else
{
this->DataSpacing[2] = spacing[2];
}
return this->DataSpacing;
}
int vtkDICOMImageReader::GetWidth()
{
return this->AppHelper->GetWidth();
}
int vtkDICOMImageReader::GetHeight()
{
return this->AppHelper->GetHeight();
}
float* vtkDICOMImageReader::GetImagePositionPatient()
{
return this->AppHelper->GetImagePositionPatient();
}
int vtkDICOMImageReader::GetBitsAllocated()
{
return this->AppHelper->GetBitsAllocated();
}
int vtkDICOMImageReader::GetPixelRepresentation()
{
return this->AppHelper->GetPixelRepresentation();
}
int vtkDICOMImageReader::GetNumberOfComponents()
{
return this->AppHelper->GetNumberOfComponents();
}
const char* vtkDICOMImageReader::GetTransferSyntaxUID()
{
return this->AppHelper->GetTransferSyntaxUID().c_str();
}
float vtkDICOMImageReader::GetRescaleSlope()
{
return this->AppHelper->GetRescaleSlope();
}
float vtkDICOMImageReader::GetRescaleOffset()
{
return this->AppHelper->GetRescaleOffset();
}
const char* vtkDICOMImageReader::GetPatientName()
{
return this->AppHelper->GetPatientName().c_str();
}
const char* vtkDICOMImageReader::GetStudyUID()
{
return this->AppHelper->GetStudyUID().c_str();
}
float vtkDICOMImageReader::GetGantryAngle()
{
return this->AppHelper->GetGantryAngle();
}
<|endoftext|> |
<commit_before>#ifndef TOML11_COLOR_HPP
#define TOML11_COLOR_HPP
#include <ostream>
#include <cstdint>
#ifdef TOML11_COLORIZE_ERROR_MESSAGE
#define TOML11_COLORED_MESSAGE_ACTIVATED true
#else
#define TOML11_COLORED_MESSAGE_ACTIVATED false
#endif
namespace toml
{
// put ANSI escape sequence to ostream
namespace color_ansi
{
namespace detail
{
inline int colorize_index()
{
static const int index = std::ios_base::xalloc();
return index;
}
} // detail
inline std::ostream& colorize(std::ostream& os)
{
// by default, it is zero.
os.iword(detail::colorize_index()) = 1;
return os;
}
inline std::ostream& nocolorize(std::ostream& os)
{
os.iword(detail::colorize_index()) = 0;
return os;
}
inline std::ostream& reset (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[00m";} return os;}
inline std::ostream& bold (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[01m";} return os;}
inline std::ostream& grey (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[30m";} return os;}
inline std::ostream& red (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[31m";} return os;}
inline std::ostream& green (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[32m";} return os;}
inline std::ostream& yellow (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[33m";} return os;}
inline std::ostream& blue (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[34m";} return os;}
inline std::ostream& magenta(std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[35m";} return os;}
inline std::ostream& cyan (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[36m";} return os;}
inline std::ostream& white (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[37m";} return os;}
} // color_ansi
// do nothing.
namespace nocolor
{
inline std::ostream& colorize (std::ostream& os) noexcept {return os;}
inline std::ostream& nocolorize(std::ostream& os) noexcept {return os;}
inline std::ostream& reset (std::ostream& os) noexcept {return os;}
inline std::ostream& bold (std::ostream& os) noexcept {return os;}
inline std::ostream& grey (std::ostream& os) noexcept {return os;}
inline std::ostream& red (std::ostream& os) noexcept {return os;}
inline std::ostream& green (std::ostream& os) noexcept {return os;}
inline std::ostream& yellow (std::ostream& os) noexcept {return os;}
inline std::ostream& blue (std::ostream& os) noexcept {return os;}
inline std::ostream& magenta (std::ostream& os) noexcept {return os;}
inline std::ostream& cyan (std::ostream& os) noexcept {return os;}
inline std::ostream& white (std::ostream& os) noexcept {return os;}
} // nocolor
#ifdef TOML11_COLORIZE_ERROR_MESSAGE
namespace color = color_ansi;
#else
namespace color = nocolor;
#endif
} // toml
#endif// TOML11_COLOR_HPP
<commit_msg>refactor: remove nocolor:: operations<commit_after>#ifndef TOML11_COLOR_HPP
#define TOML11_COLOR_HPP
#include <ostream>
#include <cstdint>
#ifdef TOML11_COLORIZE_ERROR_MESSAGE
#define TOML11_COLORED_MESSAGE_ACTIVATED true
#else
#define TOML11_COLORED_MESSAGE_ACTIVATED false
#endif
namespace toml
{
// put ANSI escape sequence to ostream
namespace color_ansi
{
namespace detail
{
inline int colorize_index()
{
static const int index = std::ios_base::xalloc();
return index;
}
} // detail
inline std::ostream& colorize(std::ostream& os)
{
// by default, it is zero.
os.iword(detail::colorize_index()) = 1;
return os;
}
inline std::ostream& nocolorize(std::ostream& os)
{
os.iword(detail::colorize_index()) = 0;
return os;
}
inline std::ostream& reset (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[00m";} return os;}
inline std::ostream& bold (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[01m";} return os;}
inline std::ostream& grey (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[30m";} return os;}
inline std::ostream& red (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[31m";} return os;}
inline std::ostream& green (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[32m";} return os;}
inline std::ostream& yellow (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[33m";} return os;}
inline std::ostream& blue (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[34m";} return os;}
inline std::ostream& magenta(std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[35m";} return os;}
inline std::ostream& cyan (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[36m";} return os;}
inline std::ostream& white (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[37m";} return os;}
} // color_ansi
// ANSI escape sequence is the only and default colorization method currently
namespace color = color_ansi;
} // toml
#endif// TOML11_COLOR_HPP
<|endoftext|> |
<commit_before>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "ipcchannel.h"
#include "tempfiles.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/nowide/convert.hpp>
#include <boost/interprocess/sync/named_semaphore.hpp>
using namespace std;
using namespace boost;
using namespace boost::posix_time;
IPCChannel::IPCChannel(std::string name, int channelNumber, bool isSlave)
{
_name = name;
_channelNumber = channelNumber;
_isSlave = isSlave;
_memory = new interprocess::managed_shared_memory(interprocess::open_or_create, name.c_str(), 8*1024*1024);
tempFiles_addShmemFileName(name);
stringstream mutexInName;
stringstream mutexOutName;
stringstream dataInName;
stringstream dataOutName;
stringstream semaphoreInName;
stringstream semaphoreOutName;
if (isSlave)
{
mutexInName << name << "-sm";
mutexOutName << name << "-mm";
dataInName << name << "-sd";
dataOutName << name << "-md";
semaphoreInName << name << "-ss";
semaphoreOutName << name << "-ms";
}
else
{
mutexInName << name << "-mm";
mutexOutName << name << "-sm";
dataInName << name << "-md";
dataOutName << name << "-sd";
semaphoreInName << name << "-ms";
semaphoreOutName << name << "-ss";
}
mutexInName << channelNumber;
mutexOutName << channelNumber;
dataInName << channelNumber;
dataOutName << channelNumber;
semaphoreInName << channelNumber;
semaphoreOutName << channelNumber;
_mutexIn = _memory->find_or_construct<interprocess::interprocess_mutex>(mutexInName.str().c_str())();
_mutexOut = _memory->find_or_construct<interprocess::interprocess_mutex>(mutexOutName.str().c_str())();
_dataIn = _memory->find_or_construct<String>(dataInName.str().c_str())(_memory->get_segment_manager());
_dataOut = _memory->find_or_construct<String>(dataOutName.str().c_str())(_memory->get_segment_manager());
#ifdef __APPLE__
_semaphoreIn = sem_open(mutexInName.str().c_str(), O_CREAT, S_IWUSR | S_IRGRP | S_IROTH, 0);
_semaphoreOut = sem_open(mutexOutName.str().c_str(), O_CREAT, S_IWUSR | S_IRGRP | S_IROTH, 0);
if (isSlave == false)
{
// cleanse the semaphores; they don't seem to reliably initalise to zero.
while (sem_trywait(_semaphoreIn) == 0)
; // do nothing
while (sem_trywait(_semaphoreOut) == 0)
; // do nothing
}
#elif defined __WIN32__
wstring inName = nowide::widen(semaphoreInName.str());
wstring outName = nowide::widen(semaphoreOutName.str());
LPCWSTR inLPCWSTR = inName.c_str();
LPCWSTR outLPCWSTR = outName.c_str();
if (isSlave == false)
{
_semaphoreIn = CreateSemaphore(NULL, 0, 1, inLPCWSTR);
_semaphoreOut = CreateSemaphore(NULL, 0, 1, outLPCWSTR);
}
else
{
_semaphoreIn = OpenSemaphore(SYNCHRONIZE, false, inLPCWSTR);
_semaphoreOut = OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, false, outLPCWSTR);
}
#else
if (_isSlave == false)
{
interprocess::named_semaphore::remove(mutexInName.str().c_str());
interprocess::named_semaphore::remove(mutexOutName.str().c_str());
_semaphoreIn = new interprocess::named_semaphore(interprocess::create_only, mutexInName.str().c_str(), 0);
_semaphoreOut = new interprocess::named_semaphore(interprocess::create_only, mutexOutName.str().c_str(), 0);
}
else
{
_semaphoreIn = new interprocess::named_semaphore(interprocess::open_only, mutexInName.str().c_str());
_semaphoreOut = new interprocess::named_semaphore(interprocess::open_only, mutexOutName.str().c_str());
}
#endif
}
void IPCChannel::send(string &data)
{
_mutexOut->lock();
_dataOut->assign(data.begin(), data.end());
#ifdef __APPLE__
sem_post(_semaphoreOut);
#elif defined __WIN32__
ReleaseSemaphore(_semaphoreOut, 1, NULL);
#else
_semaphoreOut->post();
#endif
_mutexOut->unlock();
}
bool IPCChannel::receive(string &data, int timeout)
{
if (tryWait(timeout))
{
_mutexIn->lock();
while (tryWait())
; // clear it completely
data.assign(_dataIn->c_str(), _dataIn->size());
_mutexIn->unlock();
return true;
}
return false;
}
bool IPCChannel::tryWait(int timeout)
{
bool messageWaiting;
#ifdef __APPLE__
messageWaiting = sem_trywait(_semaphoreIn) == 0;
while (timeout > 0 && messageWaiting == false)
{
usleep(100000);
timeout -= 10;
messageWaiting = sem_trywait(_semaphoreIn) == 0;
}
#elif defined __WIN32__
messageWaiting = (WaitForSingleObject(_semaphoreIn, timeout) == WAIT_OBJECT_0);
#else
if (timeout > 0)
{
ptime now(microsec_clock::universal_time());
ptime then = now + microseconds(1000 * timeout);
messageWaiting = _semaphoreIn->timed_wait(then);
}
else
{
messageWaiting = _semaphoreIn->try_wait();
}
#endif
return messageWaiting;
}
<commit_msg>Postmerge fix<commit_after>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "ipcchannel.h"
#include "tempfiles.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/nowide/convert.hpp>
using namespace std;
using namespace boost;
using namespace boost::posix_time;
IPCChannel::IPCChannel(std::string name, int channelNumber, bool isSlave)
{
_name = name;
_channelNumber = channelNumber;
_isSlave = isSlave;
_memory = new interprocess::managed_shared_memory(interprocess::open_or_create, name.c_str(), 8*1024*1024);
tempFiles_addShmemFileName(name);
stringstream mutexInName;
stringstream mutexOutName;
stringstream dataInName;
stringstream dataOutName;
stringstream semaphoreInName;
stringstream semaphoreOutName;
if (isSlave)
{
mutexInName << name << "-sm";
mutexOutName << name << "-mm";
dataInName << name << "-sd";
dataOutName << name << "-md";
semaphoreInName << name << "-ss";
semaphoreOutName << name << "-ms";
}
else
{
mutexInName << name << "-mm";
mutexOutName << name << "-sm";
dataInName << name << "-md";
dataOutName << name << "-sd";
semaphoreInName << name << "-ms";
semaphoreOutName << name << "-ss";
}
mutexInName << channelNumber;
mutexOutName << channelNumber;
dataInName << channelNumber;
dataOutName << channelNumber;
semaphoreInName << channelNumber;
semaphoreOutName << channelNumber;
_mutexIn = _memory->find_or_construct<interprocess::interprocess_mutex>(mutexInName.str().c_str())();
_mutexOut = _memory->find_or_construct<interprocess::interprocess_mutex>(mutexOutName.str().c_str())();
_dataIn = _memory->find_or_construct<String>(dataInName.str().c_str())(_memory->get_segment_manager());
_dataOut = _memory->find_or_construct<String>(dataOutName.str().c_str())(_memory->get_segment_manager());
#ifdef __APPLE__
_semaphoreIn = sem_open(mutexInName.str().c_str(), O_CREAT, S_IWUSR | S_IRGRP | S_IROTH, 0);
_semaphoreOut = sem_open(mutexOutName.str().c_str(), O_CREAT, S_IWUSR | S_IRGRP | S_IROTH, 0);
if (isSlave == false)
{
// cleanse the semaphores; they don't seem to reliably initalise to zero.
while (sem_trywait(_semaphoreIn) == 0)
; // do nothing
while (sem_trywait(_semaphoreOut) == 0)
; // do nothing
}
#elif defined __WIN32__
wstring inName = nowide::widen(semaphoreInName.str());
wstring outName = nowide::widen(semaphoreOutName.str());
LPCWSTR inLPCWSTR = inName.c_str();
LPCWSTR outLPCWSTR = outName.c_str();
if (isSlave == false)
{
_semaphoreIn = CreateSemaphore(NULL, 0, 1, inLPCWSTR);
_semaphoreOut = CreateSemaphore(NULL, 0, 1, outLPCWSTR);
}
else
{
_semaphoreIn = OpenSemaphore(SYNCHRONIZE, false, inLPCWSTR);
_semaphoreOut = OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, false, outLPCWSTR);
}
#else
if (_isSlave == false)
{
interprocess::named_semaphore::remove(mutexInName.str().c_str());
interprocess::named_semaphore::remove(mutexOutName.str().c_str());
_semaphoreIn = new interprocess::named_semaphore(interprocess::create_only, mutexInName.str().c_str(), 0);
_semaphoreOut = new interprocess::named_semaphore(interprocess::create_only, mutexOutName.str().c_str(), 0);
}
else
{
_semaphoreIn = new interprocess::named_semaphore(interprocess::open_only, mutexInName.str().c_str());
_semaphoreOut = new interprocess::named_semaphore(interprocess::open_only, mutexOutName.str().c_str());
}
#endif
}
void IPCChannel::send(string &data)
{
_mutexOut->lock();
_dataOut->assign(data.begin(), data.end());
#ifdef __APPLE__
sem_post(_semaphoreOut);
#elif defined __WIN32__
ReleaseSemaphore(_semaphoreOut, 1, NULL);
#else
_semaphoreOut->post();
#endif
_mutexOut->unlock();
}
bool IPCChannel::receive(string &data, int timeout)
{
if (tryWait(timeout))
{
_mutexIn->lock();
while (tryWait())
; // clear it completely
data.assign(_dataIn->c_str(), _dataIn->size());
_mutexIn->unlock();
return true;
}
return false;
}
bool IPCChannel::tryWait(int timeout)
{
bool messageWaiting;
#ifdef __APPLE__
messageWaiting = sem_trywait(_semaphoreIn) == 0;
while (timeout > 0 && messageWaiting == false)
{
usleep(100000);
timeout -= 10;
messageWaiting = sem_trywait(_semaphoreIn) == 0;
}
#elif defined __WIN32__
messageWaiting = (WaitForSingleObject(_semaphoreIn, timeout) == WAIT_OBJECT_0);
#else
if (timeout > 0)
{
ptime now(microsec_clock::universal_time());
ptime then = now + microseconds(1000 * timeout);
messageWaiting = _semaphoreIn->timed_wait(then);
}
else
{
messageWaiting = _semaphoreIn->try_wait();
}
#endif
return messageWaiting;
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2017, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file CDIUtils.hxx
*
* Utility library for interpreting CDI XML files.
*
* @author Balazs Racz
* @date 31 Aug 2017
*/
#ifndef _OPENLCB_CDIUTILS_HXX_
#define _OPENLCB_CDIUTILS_HXX_
#include "sxmlc.h"
namespace openlcb
{
class CDIUtils
{
public:
struct XMLDocDeleter
{
void operator()(XMLDoc *doc)
{
if (!doc)
return;
cleanup_doc(doc);
XMLDoc_free(doc);
delete doc;
}
};
typedef std::unique_ptr<XMLDoc, XMLDocDeleter> xmldoc_ptr_t;
/// Searches the list of children for the first child with a specific tag.
/// @param parent is the node whose children to search.
/// @param tag is which child to look for.
/// @return nullptr if not found, else the first occurrence of tag in the
/// children.
static XMLNode *find_child_or_null(XMLNode *parent, const char *tag)
{
auto count = XMLNode_get_children_count(parent);
for (int i = 0; i < count; ++i)
{
auto *c = XMLNode_get_child(parent, i);
if (strcmp(tag, c->tag) == 0)
return c;
}
return nullptr;
}
static string find_node_name(XMLNode *node, const char *def)
{
auto *n = find_child_or_null(node, "name");
if (n == nullptr || n->text == nullptr)
return def;
return n->text;
}
static string find_node_description(XMLNode *node)
{
auto *n = find_child_or_null(node, "description");
if (n == nullptr || n->text == nullptr)
return "";
return n->text;
}
static void prepare_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
node->user = nullptr;
node = XMLNode_next(node);
}
}
static void cleanup_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
free(node->user);
node = XMLNode_next(node);
}
}
template <class T, typename... Args>
static void new_userinfo(T **info, XMLNode *node, Args &&... args)
{
HASSERT(node->user == nullptr);
static_assert(std::is_trivially_destructible<T>::value == true,
"Userdata attached to nodes must be trivially destructible");
*info = malloc(sizeof(T));
new (*info) T(std::forward<Args>(args)...);
node->user = *info;
}
private:
// Static class; never instantiated.
CDIUtils();
};
} // namespace openlcb
#endif // _OPENLCB_CDIUTILS_HXX_
<commit_msg>Adds the offset layout algorithm for the CDI utils.<commit_after>/** \copyright
* Copyright (c) 2017, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file CDIUtils.hxx
*
* Utility library for interpreting CDI XML files.
*
* @author Balazs Racz
* @date 31 Aug 2017
*/
#ifndef _OPENLCB_CDIUTILS_HXX_
#define _OPENLCB_CDIUTILS_HXX_
#include "sxmlc.h"
namespace openlcb
{
class CDIUtils
{
public:
/// Helper class for unique_ptr to delete an XML document correctly.
struct XMLDocDeleter
{
void operator()(XMLDoc *doc)
{
if (!doc)
return;
cleanup_doc(doc);
XMLDoc_free(doc);
delete doc;
}
};
/// Smart pointer class for holding XML documents.
typedef std::unique_ptr<XMLDoc, XMLDocDeleter> xmldoc_ptr_t;
/// Searches the list of children for the first child with a specific tag.
/// @param parent is the node whose children to search.
/// @param tag is which child to look for.
/// @return nullptr if not found, else the first occurrence of tag in the
/// children.
static XMLNode *find_child_or_null(XMLNode *parent, const char *tag)
{
auto count = XMLNode_get_children_count(parent);
for (int i = 0; i < count; ++i)
{
auto *c = XMLNode_get_child(parent, i);
if (strcmp(tag, c->tag) == 0)
return c;
}
return nullptr;
}
/// Finds the name of a CDI element.
///
/// @param node is a CDI element (segment, group, or config element).
/// @return finds a child tag <name> and returns its contents. Returns
/// empty string if no <name> was found.
static string find_node_name(XMLNode *node, const char *def)
{
auto *n = find_child_or_null(node, "name");
if (n == nullptr || n->text == nullptr)
return def;
return n->text;
}
/// Find the description of a CDI element.
///
/// @param node is a CDI element (segment, group, or config element).
/// @return finds a child tag <description> and returns its
/// contents. Returns empty string if no <description> was found.
static string find_node_description(XMLNode *node)
{
auto *n = find_child_or_null(node, "description");
if (n == nullptr || n->text == nullptr)
return "";
return n->text;
}
/// Clears out al luserinfo structure pointers. This is necessary to use
/// the new_userinfo call below. Call this after the XML has been
/// successfully parsed.
/// @param doc document to prepare up.
static void prepare_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
node->user = nullptr;
node = XMLNode_next(node);
}
}
/// Deletes all userinfo structures allocated in a doc.
/// @param doc document to clean up.
static void cleanup_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
free(node->user);
node = XMLNode_next(node);
}
}
/// Allocates a new object of type T for the node as userinfo; calls T's
/// constructor with args..., stores the resulting pointer in the userinfo
/// pointer of node.
/// @param info output argument for the userinfo structure pointer.
/// @param node which XML node the userinfo should point at.
/// @param args... forwarded as the constructor arguments for T (can be
/// empty).
template <class T, typename... Args>
static void new_userinfo(T **info, XMLNode *node, Args &&... args)
{
HASSERT(node->user == nullptr);
static_assert(std::is_trivially_destructible<T>::value == true,
"Userdata attached to nodes must be trivially destructible");
*info = static_cast<T *>(malloc(sizeof(T)));
new (*info) T(std::forward<Args>(args)...);
node->user = *info;
}
/// Retrieve the userinfo structure from an XML node.
/// @param info will be set to the userinfo structure using an unchecked
/// cast to T. This variable must be of the same (or compatible) type as
/// what the userinfo has been allocated to.
/// @param node is the XML element node whose userinfo we are trying to
/// fetch
template <class T> static void get_userinfo(T **info, XMLNode *node)
{
HASSERT(node);
*info = static_cast<T *>(node->user);
}
/// Allocation data we hold about a Data Element in its userinfo structure.
struct NodeInfo
{
/// Offset of the address of this element from the address of the
/// parent group element. This is the sum of size values of the
/// preceding elements within the given group. Inside a repeated group
/// these offsets are counted from the current repetition start offset.
int offset_from_parent = 0;
/// Total number of bytes that this element occupies. This includes all
/// repetitions for a repeated group.
int size = 0;
};
static int get_numeric_attribute(
XMLNode *node, const char *attr_name, int def = 0)
{
const SXML_CHAR *attr_value;
XMLNode_get_attribute_with_default(
node, attr_name, &attr_value, nullptr);
if ((!attr_value) || (attr_value[0] == 0))
{
return def;
}
return atoi(attr_value);
}
/// Allocates all userinfo structures within a segment and performs the
/// offset layout algorithm.
static void layout_segment(XMLNode *segment)
{
HASSERT(strcmp(segment->tag, "segment") == 0);
unsigned current_offset = get_numeric_attribute(segment, "origin");
NodeInfo *info;
new_userinfo(&info, segment);
info->offset_from_parent = current_offset;
if (XMLNode_get_children_count(segment) == 0)
return;
XMLNode *current_parent = segment;
XMLNode *current_child = XMLNode_get_child(segment, 0);
NodeInfo *parent_info = info;
while (true)
{
if (strcmp(current_child->tag, "name") == 0 ||
strcmp(current_child->tag, "description") == 0 ||
strcmp(current_child->tag, "repname") == 0)
{
// Do nothing, not a data element
}
else
{
new_userinfo(&info, current_child);
parent_info->size +=
get_numeric_attribute(current_child, "offset", 0);
info->offset_from_parent = parent_info->size;
if (strcmp(current_child->tag, "eventid") == 0)
{
info->size = 8;
}
else if (strcmp(current_child->tag, "string") == 0 ||
strcmp(current_child->tag, "int") == 0 ||
strcmp(current_child->tag, "float") == 0)
{
info->size =
get_numeric_attribute(current_child, "size", 1);
}
else if (strcmp(current_child->tag, "group") == 0)
{
if (XMLNode_get_children_count(current_child) > 0)
{
current_parent = current_child;
current_child = XMLNode_get_child(current_parent, 0);
get_userinfo(&parent_info, current_parent);
continue;
}
// an empty group has size == 0 and we don't need to do
// anything here.
}
parent_info->size += info->size;
}
// Move to next child.
while ((current_child = XMLNode_next_sibling(current_child)) ==
nullptr)
{
// End of children; must go up.
if (current_parent == segment)
{
// nowhere to go up
break;
}
current_child = current_parent;
current_parent = current_child->father;
// handle groups with repetitions
get_userinfo(&info, current_child);
get_userinfo(&parent_info, current_parent);
int repcount =
get_numeric_attribute(current_child, "replication", 1);
info->size *= repcount;
parent_info->size += info->size;
}
if (current_parent == segment && current_child == nullptr)
{
// end of iteration
break;
}
}
}
private:
// Static class; never instantiated.
CDIUtils();
};
} // namespace openlcb
#endif // _OPENLCB_CDIUTILS_HXX_
<|endoftext|> |
<commit_before>// testIK.cpp
// Author: Ayman Habib based on Peter Loan's version
/* Copyright (c) 2005, Stanford University and Peter Loan.
*
* 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.
*/
// INCLUDES
#include <string>
#include <OpenSim/Common/Storage.h>
#include <OpenSim/Common/ScaleSet.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/MarkerSet.h>
#include <OpenSim/Tools/ScaleTool.h>
#include <OpenSim/Common/MarkerData.h>
#include <OpenSim/Common/SimmMotionData.h>
#include <OpenSim/Tools/IKSolverImpl.h>
#include <OpenSim/Tools/IKTarget.h>
using namespace std;
using namespace OpenSim;
string filesToCompare[] = {
"CrouchGaitSP.jnt",
"CrouchGaitSP.msl",
"CrouchGaitSP.xml",
"CrouchGaitScale.xml"
};
//______________________________________________________________________________
/**
* Test program to read SIMM model elements from an XML file.
*
* @param argc Number of command line arguments (should be 1).
* @param argv Command line arguments: simmReadXML inFile
*/
int main(int argc,char **argv)
{
// Construct model and read parameters file
//Object::RegisterType(VisibleObject());
Object::RegisterType(ScaleTool());
ScaleTool::registerTypes();
ScaleTool* subject = new ScaleTool("CrouchGait.xml");
Model* model = subject->createModel();
if (!subject->isDefaultModelScaler())
{
ModelScaler& scaler = subject->getModelScaler();
scaler.processModel(model, subject->getPathToSubject(), subject->getMass());
}
else
{
cout << "Scaling parameters not set. Model is not scaled." << endl;
}
if (!subject->isDefaultMarkerPlacer())
{
MarkerPlacer& placer = subject->getMarkerPlacer();
placer.processModel(model, subject->getPathToSubject());
}
else
{
cout << "Marker placement parameters not set. No markers have been moved." << endl;
}
delete model;
delete subject;
/* Compare results with standard*/
bool success = true;
for (int i=0; i < 4 && success; i++){
string command = "cmp "+filesToCompare[i]+" "+"std_"+filesToCompare[i];
success = success && (system(command.c_str())==0);
}
cout << "Path used = " << getenv("PATH") << endl;
return (success?0:1);
}
<commit_msg>fixed<commit_after>// testIK.cpp
// Author: Ayman Habib based on Peter Loan's version
/* Copyright (c) 2005, Stanford University and Peter Loan.
*
* 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.
*/
// INCLUDES
#include <string>
#include <OpenSim/Common/Storage.h>
#include <OpenSim/Common/ScaleSet.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/MarkerSet.h>
#include <OpenSim/Tools/ScaleTool.h>
#include <OpenSim/Common/MarkerData.h>
#include <OpenSim/Common/SimmMotionData.h>
#include <OpenSim/Tools/IKSolverImpl.h>
#include <OpenSim/Tools/IKTarget.h>
using namespace std;
using namespace OpenSim;
string filesToCompare[] = {
"CrouchGaitSP.jnt",
"CrouchGaitSP.msl",
"CrouchGaitSP.xml",
"CrouchGaitScale.xml"
};
//______________________________________________________________________________
/**
* Test program to read SIMM model elements from an XML file.
*
* @param argc Number of command line arguments (should be 1).
* @param argv Command line arguments: simmReadXML inFile
*/
int main(int argc,char **argv)
{
// Construct model and read parameters file
//Object::RegisterType(VisibleObject());
Object::RegisterType(ScaleTool());
ScaleTool::registerTypes();
ScaleTool* subject = new ScaleTool("CrouchGait.xml");
Model* model = subject->createModel();
if (!subject->isDefaultModelScaler())
{
ModelScaler& scaler = subject->getModelScaler();
scaler.processModel(model, subject->getPathToSubject(), subject->getSubjectMass());
}
else
{
cout << "Scaling parameters not set. Model is not scaled." << endl;
}
if (!subject->isDefaultMarkerPlacer())
{
MarkerPlacer& placer = subject->getMarkerPlacer();
placer.processModel(model, subject->getPathToSubject());
}
else
{
cout << "Marker placement parameters not set. No markers have been moved." << endl;
}
delete model;
delete subject;
/* Compare results with standard*/
bool success = true;
for (int i=0; i < 4 && success; i++){
string command = "cmp "+filesToCompare[i]+" "+"std_"+filesToCompare[i];
success = success && (system(command.c_str())==0);
}
cout << "Path used = " << getenv("PATH") << endl;
return (success?0:1);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "sal/config.h"
#include <comphelper/processfactory.hxx>
#include <osl/thread.h>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <ucbhelper/content.hxx>
#include <unotools/datetime.hxx>
#include <svx/svdotext.hxx>
#include <svx/svdmodel.hxx>
#include <editeng/editdata.hxx>
#include <sfx2/lnkbase.hxx>
#include <sfx2/linkmgr.hxx>
#include <tools/urlobj.hxx>
#include <svl/urihelper.hxx>
#include <tools/tenccvt.hxx>
#include <boost/scoped_ptr.hpp>
class ImpSdrObjTextLink: public ::sfx2::SvBaseLink
{
SdrTextObj* pSdrObj;
public:
ImpSdrObjTextLink( SdrTextObj* pObj1 )
: ::sfx2::SvBaseLink( ::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE ),
pSdrObj( pObj1 )
{}
virtual ~ImpSdrObjTextLink();
virtual void Closed() SAL_OVERRIDE;
virtual ::sfx2::SvBaseLink::UpdateResult DataChanged(
const OUString& rMimeType, const ::com::sun::star::uno::Any & rValue ) SAL_OVERRIDE;
};
ImpSdrObjTextLink::~ImpSdrObjTextLink()
{
}
void ImpSdrObjTextLink::Closed()
{
if (pSdrObj )
{
// set pLink of the object to NULL, because we are destroying the link instance now
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if (pData!=NULL) pData->pLink=NULL;
pSdrObj->ReleaseTextLink();
}
SvBaseLink::Closed();
}
::sfx2::SvBaseLink::UpdateResult ImpSdrObjTextLink::DataChanged(
const OUString& /*rMimeType*/, const ::com::sun::star::uno::Any & /*rValue */)
{
bool bForceReload = false;
SdrModel* pModel = pSdrObj ? pSdrObj->GetModel() : 0;
sfx2::LinkManager* pLinkManager= pModel ? pModel->GetLinkManager() : 0;
if( pLinkManager )
{
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if( pData )
{
OUString aFile;
OUString aFilter;
pLinkManager->GetDisplayNames( this, 0,&aFile, 0, &aFilter );
if( pData->aFileName != aFile ||
pData->aFilterName != aFilter )
{
pData->aFileName = aFile;
pData->aFilterName = aFilter;
pSdrObj->SetChanged();
bForceReload = true;
}
}
}
if (pSdrObj )
pSdrObj->ReloadLinkedText( bForceReload );
return SUCCESS;
}
TYPEINIT1(ImpSdrObjTextLinkUserData,SdrObjUserData);
ImpSdrObjTextLinkUserData::ImpSdrObjTextLinkUserData(SdrTextObj* pObj1):
SdrObjUserData(SdrInventor,SDRUSERDATA_OBJTEXTLINK,0),
pObj(pObj1),
aFileDate0( DateTime::EMPTY ),
pLink(NULL),
eCharSet(RTL_TEXTENCODING_DONTKNOW)
{
}
ImpSdrObjTextLinkUserData::~ImpSdrObjTextLinkUserData()
{
delete pLink;
}
SdrObjUserData* ImpSdrObjTextLinkUserData::Clone(SdrObject* pObj1) const
{
ImpSdrObjTextLinkUserData* pData=new ImpSdrObjTextLinkUserData((SdrTextObj*)pObj1);
pData->aFileName =aFileName;
pData->aFilterName=aFilterName;
pData->aFileDate0 =aFileDate0;
pData->eCharSet =eCharSet;
pData->pLink=NULL;
return pData;
}
void SdrTextObj::SetTextLink(const OUString& rFileName, const OUString& rFilterName, rtl_TextEncoding eCharSet)
{
if(eCharSet == RTL_TEXTENCODING_DONTKNOW)
eCharSet = osl_getThreadTextEncoding();
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
if (pData!=NULL) {
ReleaseTextLink();
}
pData=new ImpSdrObjTextLinkUserData(this);
pData->aFileName=rFileName;
pData->aFilterName=rFilterName;
pData->eCharSet=eCharSet;
AppendUserData(pData);
ImpLinkAnmeldung();
}
void SdrTextObj::ReleaseTextLink()
{
ImpLinkAbmeldung();
sal_uInt16 nAnz=GetUserDataCount();
for (sal_uInt16 nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData* pData=GetUserData(nNum);
if (pData->GetInventor()==SdrInventor && pData->GetId()==SDRUSERDATA_OBJTEXTLINK) {
DeleteUserData(nNum);
}
}
}
bool SdrTextObj::ReloadLinkedText( bool bForceLoad)
{
ImpSdrObjTextLinkUserData* pData = GetLinkUserData();
bool bRet = true;
if( pData )
{
DateTime aFileDT( DateTime::EMPTY );
bool bExists = true;
try
{
INetURLObject aURL( pData->aFileName );
DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
::ucbhelper::Content aCnt( aURL.GetMainURL( INetURLObject::NO_DECODE ), ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >(), comphelper::getProcessComponentContext() );
::com::sun::star::uno::Any aAny( aCnt.getPropertyValue("DateModified") );
::com::sun::star::util::DateTime aDateTime;
aAny >>= aDateTime;
::utl::typeConvert( aDateTime, aFileDT );
}
catch( ... )
{
bExists = false;
}
if( bExists )
{
bool bLoad = false;
if( bForceLoad )
bLoad = true;
else
bLoad = ( aFileDT > pData->aFileDate0 );
if( bLoad )
{
bRet = LoadText( pData->aFileName, pData->aFilterName, pData->eCharSet );
}
pData->aFileDate0 = aFileDT;
}
}
return bRet;
}
bool SdrTextObj::LoadText(const OUString& rFileName, const OUString& /*rFilterName*/, rtl_TextEncoding eCharSet)
{
INetURLObject aFileURL( rFileName );
bool bRet = false;
if( aFileURL.GetProtocol() == INET_PROT_NOT_VALID )
{
OUString aFileURLStr;
if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( rFileName, aFileURLStr ) )
aFileURL = INetURLObject( aFileURLStr );
else
aFileURL.SetSmartURL( rFileName );
}
DBG_ASSERT( aFileURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
boost::scoped_ptr<SvStream> pIStm(::utl::UcbStreamHelper::CreateStream( aFileURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ ));
if( pIStm )
{
pIStm->SetStreamCharSet(GetSOLoadTextEncoding(eCharSet));
char cRTF[5];
cRTF[4] = 0;
pIStm->Read(cRTF, 5);
bool bRTF = cRTF[0] == '{' && cRTF[1] == '\\' && cRTF[2] == 'r' && cRTF[3] == 't' && cRTF[4] == 'f';
pIStm->Seek(0);
if( !pIStm->GetError() )
{
SetText( *pIStm, aFileURL.GetMainURL( INetURLObject::NO_DECODE ), sal::static_int_cast< sal_uInt16 >( bRTF ? EE_FORMAT_RTF : EE_FORMAT_TEXT ) );
bRet = true;
}
}
return bRet;
}
ImpSdrObjTextLinkUserData* SdrTextObj::GetLinkUserData() const
{
ImpSdrObjTextLinkUserData* pData=NULL;
sal_uInt16 nAnz=GetUserDataCount();
for (sal_uInt16 nNum=nAnz; nNum>0 && pData==NULL;) {
nNum--;
pData=(ImpSdrObjTextLinkUserData*)GetUserData(nNum);
if (pData->GetInventor()!=SdrInventor || pData->GetId()!=SDRUSERDATA_OBJTEXTLINK) {
pData=NULL;
}
}
return pData;
}
void SdrTextObj::ImpLinkAnmeldung()
{
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
sfx2::LinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink==NULL) { // don't register twice
pData->pLink = new ImpSdrObjTextLink(this);
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
!pData->aFilterName.isEmpty() ?
&pData->aFilterName : NULL,
NULL);
}
}
void SdrTextObj::ImpLinkAbmeldung()
{
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
sfx2::LinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink!=NULL) { // don't register twice
// when doing Remove, *pLink is deleted implicitly
pLinkManager->Remove( pData->pLink );
pData->pLink=NULL;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Avoid invalid downcasts<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "sal/config.h"
#include <comphelper/processfactory.hxx>
#include <osl/thread.h>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <ucbhelper/content.hxx>
#include <unotools/datetime.hxx>
#include <svx/svdotext.hxx>
#include <svx/svdmodel.hxx>
#include <editeng/editdata.hxx>
#include <sfx2/lnkbase.hxx>
#include <sfx2/linkmgr.hxx>
#include <tools/urlobj.hxx>
#include <svl/urihelper.hxx>
#include <tools/tenccvt.hxx>
#include <boost/scoped_ptr.hpp>
class ImpSdrObjTextLink: public ::sfx2::SvBaseLink
{
SdrTextObj* pSdrObj;
public:
ImpSdrObjTextLink( SdrTextObj* pObj1 )
: ::sfx2::SvBaseLink( ::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE ),
pSdrObj( pObj1 )
{}
virtual ~ImpSdrObjTextLink();
virtual void Closed() SAL_OVERRIDE;
virtual ::sfx2::SvBaseLink::UpdateResult DataChanged(
const OUString& rMimeType, const ::com::sun::star::uno::Any & rValue ) SAL_OVERRIDE;
};
ImpSdrObjTextLink::~ImpSdrObjTextLink()
{
}
void ImpSdrObjTextLink::Closed()
{
if (pSdrObj )
{
// set pLink of the object to NULL, because we are destroying the link instance now
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if (pData!=NULL) pData->pLink=NULL;
pSdrObj->ReleaseTextLink();
}
SvBaseLink::Closed();
}
::sfx2::SvBaseLink::UpdateResult ImpSdrObjTextLink::DataChanged(
const OUString& /*rMimeType*/, const ::com::sun::star::uno::Any & /*rValue */)
{
bool bForceReload = false;
SdrModel* pModel = pSdrObj ? pSdrObj->GetModel() : 0;
sfx2::LinkManager* pLinkManager= pModel ? pModel->GetLinkManager() : 0;
if( pLinkManager )
{
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if( pData )
{
OUString aFile;
OUString aFilter;
pLinkManager->GetDisplayNames( this, 0,&aFile, 0, &aFilter );
if( pData->aFileName != aFile ||
pData->aFilterName != aFilter )
{
pData->aFileName = aFile;
pData->aFilterName = aFilter;
pSdrObj->SetChanged();
bForceReload = true;
}
}
}
if (pSdrObj )
pSdrObj->ReloadLinkedText( bForceReload );
return SUCCESS;
}
TYPEINIT1(ImpSdrObjTextLinkUserData,SdrObjUserData);
ImpSdrObjTextLinkUserData::ImpSdrObjTextLinkUserData(SdrTextObj* pObj1):
SdrObjUserData(SdrInventor,SDRUSERDATA_OBJTEXTLINK,0),
pObj(pObj1),
aFileDate0( DateTime::EMPTY ),
pLink(NULL),
eCharSet(RTL_TEXTENCODING_DONTKNOW)
{
}
ImpSdrObjTextLinkUserData::~ImpSdrObjTextLinkUserData()
{
delete pLink;
}
SdrObjUserData* ImpSdrObjTextLinkUserData::Clone(SdrObject* pObj1) const
{
ImpSdrObjTextLinkUserData* pData=new ImpSdrObjTextLinkUserData((SdrTextObj*)pObj1);
pData->aFileName =aFileName;
pData->aFilterName=aFilterName;
pData->aFileDate0 =aFileDate0;
pData->eCharSet =eCharSet;
pData->pLink=NULL;
return pData;
}
void SdrTextObj::SetTextLink(const OUString& rFileName, const OUString& rFilterName, rtl_TextEncoding eCharSet)
{
if(eCharSet == RTL_TEXTENCODING_DONTKNOW)
eCharSet = osl_getThreadTextEncoding();
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
if (pData!=NULL) {
ReleaseTextLink();
}
pData=new ImpSdrObjTextLinkUserData(this);
pData->aFileName=rFileName;
pData->aFilterName=rFilterName;
pData->eCharSet=eCharSet;
AppendUserData(pData);
ImpLinkAnmeldung();
}
void SdrTextObj::ReleaseTextLink()
{
ImpLinkAbmeldung();
sal_uInt16 nAnz=GetUserDataCount();
for (sal_uInt16 nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData* pData=GetUserData(nNum);
if (pData->GetInventor()==SdrInventor && pData->GetId()==SDRUSERDATA_OBJTEXTLINK) {
DeleteUserData(nNum);
}
}
}
bool SdrTextObj::ReloadLinkedText( bool bForceLoad)
{
ImpSdrObjTextLinkUserData* pData = GetLinkUserData();
bool bRet = true;
if( pData )
{
DateTime aFileDT( DateTime::EMPTY );
bool bExists = true;
try
{
INetURLObject aURL( pData->aFileName );
DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
::ucbhelper::Content aCnt( aURL.GetMainURL( INetURLObject::NO_DECODE ), ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >(), comphelper::getProcessComponentContext() );
::com::sun::star::uno::Any aAny( aCnt.getPropertyValue("DateModified") );
::com::sun::star::util::DateTime aDateTime;
aAny >>= aDateTime;
::utl::typeConvert( aDateTime, aFileDT );
}
catch( ... )
{
bExists = false;
}
if( bExists )
{
bool bLoad = false;
if( bForceLoad )
bLoad = true;
else
bLoad = ( aFileDT > pData->aFileDate0 );
if( bLoad )
{
bRet = LoadText( pData->aFileName, pData->aFilterName, pData->eCharSet );
}
pData->aFileDate0 = aFileDT;
}
}
return bRet;
}
bool SdrTextObj::LoadText(const OUString& rFileName, const OUString& /*rFilterName*/, rtl_TextEncoding eCharSet)
{
INetURLObject aFileURL( rFileName );
bool bRet = false;
if( aFileURL.GetProtocol() == INET_PROT_NOT_VALID )
{
OUString aFileURLStr;
if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( rFileName, aFileURLStr ) )
aFileURL = INetURLObject( aFileURLStr );
else
aFileURL.SetSmartURL( rFileName );
}
DBG_ASSERT( aFileURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
boost::scoped_ptr<SvStream> pIStm(::utl::UcbStreamHelper::CreateStream( aFileURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ ));
if( pIStm )
{
pIStm->SetStreamCharSet(GetSOLoadTextEncoding(eCharSet));
char cRTF[5];
cRTF[4] = 0;
pIStm->Read(cRTF, 5);
bool bRTF = cRTF[0] == '{' && cRTF[1] == '\\' && cRTF[2] == 'r' && cRTF[3] == 't' && cRTF[4] == 'f';
pIStm->Seek(0);
if( !pIStm->GetError() )
{
SetText( *pIStm, aFileURL.GetMainURL( INetURLObject::NO_DECODE ), sal::static_int_cast< sal_uInt16 >( bRTF ? EE_FORMAT_RTF : EE_FORMAT_TEXT ) );
bRet = true;
}
}
return bRet;
}
ImpSdrObjTextLinkUserData* SdrTextObj::GetLinkUserData() const
{
sal_uInt16 nAnz=GetUserDataCount();
for (sal_uInt16 nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData * pData=GetUserData(nNum);
if (pData->GetInventor() == SdrInventor
&& pData->GetId() == SDRUSERDATA_OBJTEXTLINK)
{
return static_cast<ImpSdrObjTextLinkUserData *>(pData);
}
}
return 0;
}
void SdrTextObj::ImpLinkAnmeldung()
{
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
sfx2::LinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink==NULL) { // don't register twice
pData->pLink = new ImpSdrObjTextLink(this);
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
!pData->aFilterName.isEmpty() ?
&pData->aFilterName : NULL,
NULL);
}
}
void SdrTextObj::ImpLinkAbmeldung()
{
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
sfx2::LinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink!=NULL) { // don't register twice
// when doing Remove, *pLink is deleted implicitly
pLinkManager->Remove( pData->pLink );
pData->pLink=NULL;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_SVX_SOURCE_TABLE_TABLEUNDO_HXX
#define INCLUDED_SVX_SOURCE_TABLE_TABLEUNDO_HXX
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/table/CellContentType.hpp>
#include "svx/svdotable.hxx"
#include "svx/svdobj.hxx"
#include "svx/svdundo.hxx"
#include <svx/sdrobjectuser.hxx>
#include "celltypes.hxx"
namespace sdr { namespace properties {
class TextProperties;
} }
class OutlinerParaObject;
namespace sdr { namespace table {
class CellUndo : public SdrUndoAction, public sdr::ObjectUser
{
public:
CellUndo( const SdrObjectWeakRef& xObjRef, const CellRef& xCell );
virtual ~CellUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
virtual bool Merge( SfxUndoAction *pNextAction ) SAL_OVERRIDE;
void dispose();
virtual void ObjectInDestruction(const SdrObject& rObject) SAL_OVERRIDE;
private:
struct Data
{
sdr::properties::TextProperties* mpProperties;
OutlinerParaObject* mpOutlinerParaObject;
::com::sun::star::table::CellContentType mnCellContentType;
OUString msFormula;
double mfValue;
::sal_Int32 mnError;
bool mbMerged;
::sal_Int32 mnRowSpan;
::sal_Int32 mnColSpan;
Data()
: mpProperties(NULL)
, mpOutlinerParaObject(NULL)
, mnCellContentType(css::table::CellContentType_EMPTY)
, mfValue(0)
, mnError(0)
, mbMerged(false)
, mnRowSpan(0)
, mnColSpan(0)
{
}
};
void setDataToCell( const Data& rData );
void getDataFromCell( Data& rData );
SdrObjectWeakRef mxObjRef;
CellRef mxCell;
Data maUndoData;
Data maRedoData;
bool mbUndo;
};
class InsertRowUndo : public SdrUndoAction
{
public:
InsertRowUndo( const TableModelRef& xTable, sal_Int32 nIndex, RowVector& aNewRows );
virtual ~InsertRowUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
RowVector maRows;
bool mbUndo;
};
class RemoveRowUndo : public SdrUndoAction
{
public:
RemoveRowUndo( const TableModelRef& xTable, sal_Int32 nIndex, RowVector& aRemovedRows );
virtual ~RemoveRowUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
RowVector maRows;
bool mbUndo;
};
class InsertColUndo : public SdrUndoAction
{
public:
InsertColUndo( const TableModelRef& xTable, sal_Int32 nIndex, ColumnVector& aNewCols, CellVector& aCells );
virtual ~InsertColUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
ColumnVector maColumns;
CellVector maCells;
bool mbUndo;
};
class RemoveColUndo : public SdrUndoAction
{
public:
RemoveColUndo( const TableModelRef& xTable, sal_Int32 nIndex, ColumnVector& aNewCols, CellVector& aCells );
virtual ~RemoveColUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
ColumnVector maColumns;
CellVector maCells;
bool mbUndo;
};
class TableColumnUndo : public SdrUndoAction
{
public:
explicit TableColumnUndo( const TableColumnRef& xCol );
virtual ~TableColumnUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
virtual bool Merge( SfxUndoAction *pNextAction ) SAL_OVERRIDE;
private:
struct Data
{
sal_Int32 mnColumn;
sal_Int32 mnWidth;
bool mbOptimalWidth;
bool mbIsVisible;
bool mbIsStartOfNewPage;
OUString maName;
};
void setData( const Data& rData );
void getData( Data& rData );
TableColumnRef mxCol;
Data maUndoData;
Data maRedoData;
bool mbHasRedoData;
};
class TableRowUndo : public SdrUndoAction
{
public:
explicit TableRowUndo( const TableRowRef& xRow );
virtual ~TableRowUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
virtual bool Merge( SfxUndoAction *pNextAction ) SAL_OVERRIDE;
private:
struct Data
{
CellVector maCells;
sal_Int32 mnRow;
sal_Int32 mnHeight;
bool mbOptimalHeight;
bool mbIsVisible;
bool mbIsStartOfNewPage;
OUString maName;
};
void setData( const Data& rData );
void getData( Data& rData );
TableRowRef mxRow;
Data maUndoData;
Data maRedoData;
bool mbHasRedoData;
};
class TableStyleUndo : public SdrUndoAction
{
public:
explicit TableStyleUndo( const SdrTableObj& rTableObj );
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
SdrObjectWeakRef mxObjRef;
struct Data
{
TableStyleSettings maSettings;
::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > mxTableStyle;
};
void setData( const Data& rData );
void getData( Data& rData );
Data maUndoData;
Data maRedoData;
bool mbHasRedoData;
};
} }
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: uninitMemberVar<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_SVX_SOURCE_TABLE_TABLEUNDO_HXX
#define INCLUDED_SVX_SOURCE_TABLE_TABLEUNDO_HXX
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/table/CellContentType.hpp>
#include "svx/svdotable.hxx"
#include "svx/svdobj.hxx"
#include "svx/svdundo.hxx"
#include <svx/sdrobjectuser.hxx>
#include "celltypes.hxx"
namespace sdr { namespace properties {
class TextProperties;
} }
class OutlinerParaObject;
namespace sdr { namespace table {
class CellUndo : public SdrUndoAction, public sdr::ObjectUser
{
public:
CellUndo( const SdrObjectWeakRef& xObjRef, const CellRef& xCell );
virtual ~CellUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
virtual bool Merge( SfxUndoAction *pNextAction ) SAL_OVERRIDE;
void dispose();
virtual void ObjectInDestruction(const SdrObject& rObject) SAL_OVERRIDE;
private:
struct Data
{
sdr::properties::TextProperties* mpProperties;
OutlinerParaObject* mpOutlinerParaObject;
::com::sun::star::table::CellContentType mnCellContentType;
OUString msFormula;
double mfValue;
::sal_Int32 mnError;
bool mbMerged;
::sal_Int32 mnRowSpan;
::sal_Int32 mnColSpan;
Data()
: mpProperties(NULL)
, mpOutlinerParaObject(NULL)
, mnCellContentType(css::table::CellContentType_EMPTY)
, mfValue(0)
, mnError(0)
, mbMerged(false)
, mnRowSpan(0)
, mnColSpan(0)
{
}
};
void setDataToCell( const Data& rData );
void getDataFromCell( Data& rData );
SdrObjectWeakRef mxObjRef;
CellRef mxCell;
Data maUndoData;
Data maRedoData;
bool mbUndo;
};
class InsertRowUndo : public SdrUndoAction
{
public:
InsertRowUndo( const TableModelRef& xTable, sal_Int32 nIndex, RowVector& aNewRows );
virtual ~InsertRowUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
RowVector maRows;
bool mbUndo;
};
class RemoveRowUndo : public SdrUndoAction
{
public:
RemoveRowUndo( const TableModelRef& xTable, sal_Int32 nIndex, RowVector& aRemovedRows );
virtual ~RemoveRowUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
RowVector maRows;
bool mbUndo;
};
class InsertColUndo : public SdrUndoAction
{
public:
InsertColUndo( const TableModelRef& xTable, sal_Int32 nIndex, ColumnVector& aNewCols, CellVector& aCells );
virtual ~InsertColUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
ColumnVector maColumns;
CellVector maCells;
bool mbUndo;
};
class RemoveColUndo : public SdrUndoAction
{
public:
RemoveColUndo( const TableModelRef& xTable, sal_Int32 nIndex, ColumnVector& aNewCols, CellVector& aCells );
virtual ~RemoveColUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
TableModelRef mxTable;
sal_Int32 mnIndex;
ColumnVector maColumns;
CellVector maCells;
bool mbUndo;
};
class TableColumnUndo : public SdrUndoAction
{
public:
explicit TableColumnUndo( const TableColumnRef& xCol );
virtual ~TableColumnUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
virtual bool Merge( SfxUndoAction *pNextAction ) SAL_OVERRIDE;
private:
struct Data
{
sal_Int32 mnColumn;
sal_Int32 mnWidth;
bool mbOptimalWidth;
bool mbIsVisible;
bool mbIsStartOfNewPage;
OUString maName;
Data()
: mnColumn(0)
, mnWidth(0)
, mbOptimalWidth(false)
, mbIsVisible(false)
, mbIsStartOfNewPage(false)
{
}
};
void setData( const Data& rData );
void getData( Data& rData );
TableColumnRef mxCol;
Data maUndoData;
Data maRedoData;
bool mbHasRedoData;
};
class TableRowUndo : public SdrUndoAction
{
public:
explicit TableRowUndo( const TableRowRef& xRow );
virtual ~TableRowUndo();
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
virtual bool Merge( SfxUndoAction *pNextAction ) SAL_OVERRIDE;
private:
struct Data
{
CellVector maCells;
sal_Int32 mnRow;
sal_Int32 mnHeight;
bool mbOptimalHeight;
bool mbIsVisible;
bool mbIsStartOfNewPage;
OUString maName;
};
void setData( const Data& rData );
void getData( Data& rData );
TableRowRef mxRow;
Data maUndoData;
Data maRedoData;
bool mbHasRedoData;
};
class TableStyleUndo : public SdrUndoAction
{
public:
explicit TableStyleUndo( const SdrTableObj& rTableObj );
virtual void Undo() SAL_OVERRIDE;
virtual void Redo() SAL_OVERRIDE;
private:
SdrObjectWeakRef mxObjRef;
struct Data
{
TableStyleSettings maSettings;
::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > mxTableStyle;
};
void setData( const Data& rData );
void getData( Data& rData );
Data maUndoData;
Data maRedoData;
bool mbHasRedoData;
};
} }
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLScalarsToColorsPainter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLScalarsToColorsPainter.h"
#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMapper.h" //for VTK_MATERIALMODE_*
#include "vtkObjectFactory.h"
#include "vtkOpenGLTexture.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
# include "vtkOpenGL.h"
#endif
#include "vtkgl.h" // vtkgl namespace
#ifndef VTK_IMPLEMENT_MESA_CXX
vtkStandardNewMacro(vtkOpenGLScalarsToColorsPainter);
vtkCxxRevisionMacro(vtkOpenGLScalarsToColorsPainter, "1.7");
#endif
//-----------------------------------------------------------------------------
vtkOpenGLScalarsToColorsPainter::vtkOpenGLScalarsToColorsPainter()
{
this->InternalColorTexture = 0;
}
//-----------------------------------------------------------------------------
vtkOpenGLScalarsToColorsPainter::~vtkOpenGLScalarsToColorsPainter()
{
if (this->InternalColorTexture)
{
this->InternalColorTexture->Delete();
this->InternalColorTexture = 0;
}
}
//-----------------------------------------------------------------------------
void vtkOpenGLScalarsToColorsPainter::ReleaseGraphicsResources(vtkWindow* win)
{
if (this->InternalColorTexture)
{
this->InternalColorTexture->ReleaseGraphicsResources(win);
}
this->Superclass::ReleaseGraphicsResources(win);
}
//-----------------------------------------------------------------------------
int vtkOpenGLScalarsToColorsPainter::GetPremultiplyColorsWithAlpha(
vtkActor* actor)
{
GLint alphaBits;
glGetIntegerv(GL_ALPHA_BITS, &alphaBits);
// Dealing with having a correct alpha (none square) in the framebuffer
// is only required if there is an alpha component in the framebuffer
// (doh...) and if we cannot deal directly with BlendFuncSeparate.
return vtkgl::BlendFuncSeparate==0 && alphaBits>0 &&
this->Superclass::GetPremultiplyColorsWithAlpha(actor);
}
//-----------------------------------------------------------------------------
void vtkOpenGLScalarsToColorsPainter::RenderInternal(vtkRenderer *renderer,
vtkActor *actor,
unsigned long typeflags,
bool forceCompileOnly)
{
vtkProperty* prop = actor->GetProperty();
// If we are coloring by texture, then load the texture map.
if (this->ColorTextureMap)
{
if (this->InternalColorTexture == 0)
{
this->InternalColorTexture = vtkOpenGLTexture::New();
this->InternalColorTexture->RepeatOff();
}
this->InternalColorTexture->SetInput(this->ColorTextureMap);
// Keep color from interacting with texture.
float info[4];
info[0] = info[1] = info[2] = info[3] = 1.0;
glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, info );
this->LastWindow = renderer->GetRenderWindow();
}
else if (this->LastWindow)
{
// release the texture.
this->ReleaseGraphicsResources(this->LastWindow);
this->LastWindow = 0;
}
// if we are doing vertex colors then set lmcolor to adjust
// the current materials ambient and diffuse values using
// vertex color commands otherwise tell it not to.
glDisable( GL_COLOR_MATERIAL );
if (this->UsingScalarColoring)
{
GLenum lmcolorMode;
if (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT)
{
if (prop->GetAmbient() > prop->GetDiffuse())
{
lmcolorMode = GL_AMBIENT;
}
else
{
lmcolorMode = GL_DIFFUSE;
}
}
else if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT_AND_DIFFUSE)
{
lmcolorMode = GL_AMBIENT_AND_DIFFUSE;
}
else if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT)
{
lmcolorMode = GL_AMBIENT;
}
else // if (this->ScalarMaterialMode == VTK_MATERIALMODE_DIFFUSE)
{
lmcolorMode = GL_DIFFUSE;
}
glColorMaterial( GL_FRONT_AND_BACK, lmcolorMode);
glEnable( GL_COLOR_MATERIAL );
if (this->ColorTextureMap)
{
this->InternalColorTexture->Load(renderer);
}
}
int pre_multiplied_by_alpha = this->GetPremultiplyColorsWithAlpha(actor);
// We colors were premultiplied by alpha then we change the blending
// function to one that will compute correct blended destination alpha
// value, otherwise we stick with the default.
if (pre_multiplied_by_alpha)
{
// save the blend function.
glPushAttrib(GL_COLOR_BUFFER_BIT);
// the following function is not correct with textures because there are
// not premultiplied by alpha.
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
this->Superclass::RenderInternal(renderer, actor, typeflags,forceCompileOnly);
if (pre_multiplied_by_alpha)
{
// restore the blend function
glPopAttrib();
}
}
//-----------------------------------------------------------------------------
void vtkOpenGLScalarsToColorsPainter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<commit_msg>BUG: 7730. pqColorScaleToolbar wasn't push property value changes hence the effect was delayed. vtkOpenGLScalarsToColorsPainter was erroneously enabling color material when texture was used for scalar coloring. That resulted in interference between the material properties and scalar color. Merged from CVS head.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLScalarsToColorsPainter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLScalarsToColorsPainter.h"
#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMapper.h" //for VTK_MATERIALMODE_*
#include "vtkObjectFactory.h"
#include "vtkOpenGLTexture.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
# include "vtkOpenGL.h"
#endif
#include "vtkgl.h" // vtkgl namespace
#ifndef VTK_IMPLEMENT_MESA_CXX
vtkStandardNewMacro(vtkOpenGLScalarsToColorsPainter);
vtkCxxRevisionMacro(vtkOpenGLScalarsToColorsPainter, "1.7.2.1");
#endif
//-----------------------------------------------------------------------------
vtkOpenGLScalarsToColorsPainter::vtkOpenGLScalarsToColorsPainter()
{
this->InternalColorTexture = 0;
}
//-----------------------------------------------------------------------------
vtkOpenGLScalarsToColorsPainter::~vtkOpenGLScalarsToColorsPainter()
{
if (this->InternalColorTexture)
{
this->InternalColorTexture->Delete();
this->InternalColorTexture = 0;
}
}
//-----------------------------------------------------------------------------
void vtkOpenGLScalarsToColorsPainter::ReleaseGraphicsResources(vtkWindow* win)
{
if (this->InternalColorTexture)
{
this->InternalColorTexture->ReleaseGraphicsResources(win);
}
this->Superclass::ReleaseGraphicsResources(win);
}
//-----------------------------------------------------------------------------
int vtkOpenGLScalarsToColorsPainter::GetPremultiplyColorsWithAlpha(
vtkActor* actor)
{
GLint alphaBits;
glGetIntegerv(GL_ALPHA_BITS, &alphaBits);
// Dealing with having a correct alpha (none square) in the framebuffer
// is only required if there is an alpha component in the framebuffer
// (doh...) and if we cannot deal directly with BlendFuncSeparate.
return vtkgl::BlendFuncSeparate==0 && alphaBits>0 &&
this->Superclass::GetPremultiplyColorsWithAlpha(actor);
}
//-----------------------------------------------------------------------------
void vtkOpenGLScalarsToColorsPainter::RenderInternal(vtkRenderer *renderer,
vtkActor *actor,
unsigned long typeflags,
bool forceCompileOnly)
{
vtkProperty* prop = actor->GetProperty();
// If we are coloring by texture, then load the texture map.
if (this->ColorTextureMap)
{
if (this->InternalColorTexture == 0)
{
this->InternalColorTexture = vtkOpenGLTexture::New();
this->InternalColorTexture->RepeatOff();
}
this->InternalColorTexture->SetInput(this->ColorTextureMap);
// Keep color from interacting with texture.
float info[4];
info[0] = info[1] = info[2] = info[3] = 1.0;
glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, info );
this->LastWindow = renderer->GetRenderWindow();
}
else if (this->LastWindow)
{
// release the texture.
this->ReleaseGraphicsResources(this->LastWindow);
this->LastWindow = 0;
}
// if we are doing vertex colors then set lmcolor to adjust
// the current materials ambient and diffuse values using
// vertex color commands otherwise tell it not to.
glDisable( GL_COLOR_MATERIAL );
if (this->UsingScalarColoring)
{
GLenum lmcolorMode;
if (this->ScalarMaterialMode == VTK_MATERIALMODE_DEFAULT)
{
if (prop->GetAmbient() > prop->GetDiffuse())
{
lmcolorMode = GL_AMBIENT;
}
else
{
lmcolorMode = GL_DIFFUSE;
}
}
else if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT_AND_DIFFUSE)
{
lmcolorMode = GL_AMBIENT_AND_DIFFUSE;
}
else if (this->ScalarMaterialMode == VTK_MATERIALMODE_AMBIENT)
{
lmcolorMode = GL_AMBIENT;
}
else // if (this->ScalarMaterialMode == VTK_MATERIALMODE_DIFFUSE)
{
lmcolorMode = GL_DIFFUSE;
}
if (this->ColorTextureMap)
{
this->InternalColorTexture->Load(renderer);
}
else
{
glColorMaterial( GL_FRONT_AND_BACK, lmcolorMode);
glEnable( GL_COLOR_MATERIAL );
}
}
int pre_multiplied_by_alpha = this->GetPremultiplyColorsWithAlpha(actor);
// We colors were premultiplied by alpha then we change the blending
// function to one that will compute correct blended destination alpha
// value, otherwise we stick with the default.
if (pre_multiplied_by_alpha)
{
// save the blend function.
glPushAttrib(GL_COLOR_BUFFER_BIT);
// the following function is not correct with textures because there are
// not premultiplied by alpha.
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
this->Superclass::RenderInternal(renderer, actor, typeflags,forceCompileOnly);
if (pre_multiplied_by_alpha)
{
// restore the blend function
glPopAttrib();
}
}
//-----------------------------------------------------------------------------
void vtkOpenGLScalarsToColorsPainter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-08-14 16:18:44 $
*
* 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 _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual void TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<commit_msg>INTEGRATION: CWS aw024 (1.6.96); FILE MERGED 2006/09/08 19:38:25 aw 1.6.96.3: RESYNC: (1.7-1.8); FILE MERGED 2005/09/17 18:41:31 aw 1.6.96.2: RESYNC: (1.6-1.7); FILE MERGED 2005/04/26 15:09:11 aw 1.6.96.1: #i39528#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 15:10:15 $
*
* 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 _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual ::basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: labfmt.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 07:29:19 $
*
* 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 _LABFMT_HXX
#define _LABFMT_HXX
#include "swuilabimp.hxx" //CHINA001
#include "labimg.hxx"
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
class SwLabFmtPage;
// class SwLabPreview -------------------------------------------------------
class SwLabPreview : public Window
{
long lOutWPix;
long lOutHPix;
long lOutWPix23;
long lOutHPix23;
Color aGrayColor;
String aHDistStr;
String aVDistStr;
String aWidthStr;
String aHeightStr;
String aLeftStr;
String aUpperStr;
String aColsStr;
String aRowsStr;
long lHDistWidth;
long lVDistWidth;
long lHeightWidth;
long lLeftWidth;
long lUpperWidth;
long lColsWidth;
long lXWidth;
long lXHeight;
SwLabItem aItem;
void Paint(const Rectangle&);
void DrawArrow(const Point& rP1, const Point& rP2, BOOL bArrow);
SwLabFmtPage* GetParent() {return (SwLabFmtPage*) Window::GetParent();}
public:
SwLabPreview(const SwLabFmtPage* pParent, const ResId& rResID);
~SwLabPreview();
void Update(const SwLabItem& rItem);
};
// class SwLabFmtPage -------------------------------------------------------
class SwLabFmtPage : public SfxTabPage
{
FixedInfo aMakeFI;
FixedInfo aTypeFI;
SwLabPreview aPreview;
FixedText aHDistText;
MetricField aHDistField;
FixedText aVDistText;
MetricField aVDistField;
FixedText aWidthText;
MetricField aWidthField;
FixedText aHeightText;
MetricField aHeightField;
FixedText aLeftText;
MetricField aLeftField;
FixedText aUpperText;
MetricField aUpperField;
FixedText aColsText;
NumericField aColsField;
FixedText aRowsText;
NumericField aRowsField;
PushButton aSavePB;
Timer aPreviewTimer;
BOOL bModified;
SwLabItem aItem;
SwLabFmtPage(Window* pParent, const SfxItemSet& rSet);
~SwLabFmtPage();
DECL_LINK( ModifyHdl, Edit * );
DECL_LINK( PreviewHdl, Timer * );
DECL_LINK( LoseFocusHdl, Control * );
DECL_LINK( SaveHdl, PushButton* );
void ChangeMinMax();
public:
static SfxTabPage* Create(Window* pParent, const SfxItemSet& rSet);
virtual void ActivatePage(const SfxItemSet& rSet);
virtual int DeactivatePage(SfxItemSet* pSet = 0);
void FillItem(SwLabItem& rItem);
virtual BOOL FillItemSet(SfxItemSet& rSet);
virtual void Reset(const SfxItemSet& rSet);
SwLabDlg* GetParent() {return (SwLabDlg*) SfxTabPage::GetParent()->GetParent();}
};
/* -----------------------------23.01.01 10:26--------------------------------
---------------------------------------------------------------------------*/
class SwSaveLabelDlg : public ModalDialog
{
FixedLine aOptionsFL;
FixedText aMakeFT;
ComboBox aMakeCB;
FixedText aTypeFT;
Edit aTypeED;
OKButton aOKPB;
CancelButton aCancelPB;
HelpButton aHelpPB;
QueryBox aQueryMB;
sal_Bool bSuccess;
SwLabFmtPage* pLabPage;
SwLabRec& rLabRec;
DECL_LINK(OkHdl, OKButton*);
DECL_LINK(ModifyHdl, Edit*);
public:
SwSaveLabelDlg(SwLabFmtPage* pParent, SwLabRec& rRec);
void SetLabel(const rtl::OUString& rMake, const rtl::OUString& rType)
{
aMakeCB.SetText(String(rMake));
aTypeED.SetText(String(rType));
}
sal_Bool GetLabel(SwLabItem& rItem);
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.6.710); FILE MERGED 2007/04/13 12:17:56 tl 1.6.710.3: #i69287# binfilter related comments removed 2007/03/26 12:09:00 tl 1.6.710.2: #i69287# warning-free code 2007/02/22 15:06:44 tl 1.6.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: labfmt.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:43:49 $
*
* 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 _LABFMT_HXX
#define _LABFMT_HXX
#include "swuilabimp.hxx"
#include "labimg.hxx"
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
class SwLabFmtPage;
// class SwLabPreview -------------------------------------------------------
class SwLabPreview : public Window
{
long lOutWPix;
long lOutHPix;
long lOutWPix23;
long lOutHPix23;
Color aGrayColor;
String aHDistStr;
String aVDistStr;
String aWidthStr;
String aHeightStr;
String aLeftStr;
String aUpperStr;
String aColsStr;
String aRowsStr;
long lHDistWidth;
long lVDistWidth;
long lHeightWidth;
long lLeftWidth;
long lUpperWidth;
long lColsWidth;
long lXWidth;
long lXHeight;
SwLabItem aItem;
void Paint(const Rectangle&);
void DrawArrow(const Point& rP1, const Point& rP2, BOOL bArrow);
using Window::GetParent;
SwLabFmtPage* GetParent() {return (SwLabFmtPage*) Window::GetParent();}
public:
SwLabPreview(const SwLabFmtPage* pParent, const ResId& rResID);
~SwLabPreview();
using Window::Update;
void Update(const SwLabItem& rItem);
};
// class SwLabFmtPage -------------------------------------------------------
class SwLabFmtPage : public SfxTabPage
{
FixedInfo aMakeFI;
FixedInfo aTypeFI;
SwLabPreview aPreview;
FixedText aHDistText;
MetricField aHDistField;
FixedText aVDistText;
MetricField aVDistField;
FixedText aWidthText;
MetricField aWidthField;
FixedText aHeightText;
MetricField aHeightField;
FixedText aLeftText;
MetricField aLeftField;
FixedText aUpperText;
MetricField aUpperField;
FixedText aColsText;
NumericField aColsField;
FixedText aRowsText;
NumericField aRowsField;
PushButton aSavePB;
Timer aPreviewTimer;
BOOL bModified;
SwLabItem aItem;
SwLabFmtPage(Window* pParent, const SfxItemSet& rSet);
~SwLabFmtPage();
DECL_LINK( ModifyHdl, Edit * );
DECL_LINK( PreviewHdl, Timer * );
DECL_LINK( LoseFocusHdl, Control * );
DECL_LINK( SaveHdl, PushButton* );
void ChangeMinMax();
public:
using TabPage::ActivatePage;
using TabPage::DeactivatePage;
static SfxTabPage* Create(Window* pParent, const SfxItemSet& rSet);
virtual void ActivatePage(const SfxItemSet& rSet);
virtual int DeactivatePage(SfxItemSet* pSet = 0);
void FillItem(SwLabItem& rItem);
virtual BOOL FillItemSet(SfxItemSet& rSet);
virtual void Reset(const SfxItemSet& rSet);
using Window::GetParent;
SwLabDlg* GetParent() {return (SwLabDlg*) SfxTabPage::GetParent()->GetParent();}
};
/* -----------------------------23.01.01 10:26--------------------------------
---------------------------------------------------------------------------*/
class SwSaveLabelDlg : public ModalDialog
{
FixedLine aOptionsFL;
FixedText aMakeFT;
ComboBox aMakeCB;
FixedText aTypeFT;
Edit aTypeED;
OKButton aOKPB;
CancelButton aCancelPB;
HelpButton aHelpPB;
QueryBox aQueryMB;
sal_Bool bSuccess;
SwLabFmtPage* pLabPage;
SwLabRec& rLabRec;
DECL_LINK(OkHdl, OKButton*);
DECL_LINK(ModifyHdl, Edit*);
public:
SwSaveLabelDlg(SwLabFmtPage* pParent, SwLabRec& rRec);
void SetLabel(const rtl::OUString& rMake, const rtl::OUString& rType)
{
aMakeCB.SetText(String(rMake));
aTypeED.SetText(String(rType));
}
sal_Bool GetLabel(SwLabItem& rItem);
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmdlg.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2007-05-10 16:18:16 $
*
* 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_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
//CHINA001 #ifndef _SVX_BORDER_HXX
//CHINA001 #include <svx/border.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_BACKGRND_HXX //autogen
//CHINA001 #include <svx/backgrnd.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_GRFPAGE_HXX //autogen
//CHINA001 #include <svx/grfpage.hxx>
//CHINA001 #endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _FRMDLG_HXX
#include <frmdlg.hxx>
#endif
#ifndef _FRMPAGE_HXX
#include <frmpage.hxx>
#endif
#ifndef _WRAP_HXX
#include <wrap.hxx>
#endif
#ifndef _COLUMN_HXX
#include <column.hxx>
#endif
#ifndef _MACASSGN_HXX
#include <macassgn.hxx>
#endif
#ifndef _FRMUI_HRC
#include <frmui.hrc>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc>
/*--------------------------------------------------------------------
Beschreibung: Der Traeger des Dialoges
--------------------------------------------------------------------*/
SwFrmDlg::SwFrmDlg( SfxViewFrame* pFrame,
Window* pParent,
const SfxItemSet& rCoreSet,
BOOL bNewFrm,
USHORT nResType,
BOOL bFmt,
UINT16 nDefPage,
const String* pStr) :
SfxTabDialog(pFrame, pParent, SW_RES(nResType), &rCoreSet, pStr != 0),
bNew(bNewFrm),
bFormat(bFmt),
rSet(rCoreSet),
nDlgType(nResType),
pWrtShell(((SwView*)pFrame->GetViewShell())->GetWrtShellPtr())
{
FreeResource();
USHORT nHtmlMode = ::GetHtmlMode(pWrtShell->GetView().GetDocShell());
bHTMLMode = nHtmlMode & HTMLMODE_ON;
// BspFont fuer beide Bsp-TabPages
//
if(pStr)
{
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_COLL_HEADER);
aTmp += *pStr;
aTmp += ')';
}
AddTabPage(TP_FRM_STD, SwFrmPage::Create, 0);
AddTabPage(TP_FRM_ADD, SwFrmAddPage::Create, 0);
AddTabPage(TP_FRM_WRAP, SwWrapTabPage::Create, 0);
AddTabPage(TP_FRM_URL, SwFrmURLPage::Create, 0);
if(nDlgType == DLG_FRM_GRF)
{
AddTabPage( TP_GRF_EXT, SwGrfExtPage::Create, 0 );
AddTabPage( RID_SVXPAGE_GRFCROP ); //CHINA001 AddTabPage( RID_SVXPAGE_GRFCROP, SvxGrfCropPage::Create, 0 );
}
if (nDlgType == DLG_FRM_STD)
{
AddTabPage(TP_COLUMN, SwColumnPage::Create, 0);
}
SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); //CHINA001
DBG_ASSERT(pFact, "Dialogdiet fail!"); //CHINA001
AddTabPage(TP_BACKGROUND, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 ); //CHINA001 AddTabPage(TP_BACKGROUND,SvxBackgroundTabPage::Create, 0);
AddTabPage( TP_MACRO_ASSIGN, SfxMacroTabPage::Create, 0);
AddTabPage( TP_BORDER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), 0 ); //CHINA001 AddTabPage( TP_BORDER, SvxBorderTabPage::Create, 0);
if(bHTMLMode)
{
switch( nDlgType )
{
case DLG_FRM_STD:
if(0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS))
RemoveTabPage(TP_BORDER);
RemoveTabPage(TP_COLUMN);
// kein break
case DLG_FRM_OLE:
RemoveTabPage(TP_FRM_URL);
RemoveTabPage(TP_MACRO_ASSIGN);
break;
case DLG_FRM_GRF:
RemoveTabPage(RID_SVXPAGE_GRFCROP);
break;
}
if( 0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS) ||
nDlgType != DLG_FRM_STD )
RemoveTabPage(TP_BACKGROUND);
}
if (bNew)
SetCurPageId(TP_FRM_STD);
if (nDefPage)
SetCurPageId(nDefPage);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwFrmDlg::~SwFrmDlg()
{
}
void SwFrmDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//CHINA001
switch ( nId )
{
case TP_FRM_STD:
((SwFrmPage&)rPage).SetNewFrame(bNew);
((SwFrmPage&)rPage).SetFormatUsed(bFormat);
((SwFrmPage&)rPage).SetFrmType(nDlgType);
break;
case TP_FRM_ADD:
((SwFrmAddPage&)rPage).SetFormatUsed(bFormat);
((SwFrmAddPage&)rPage).SetFrmType(nDlgType);
((SwFrmAddPage&)rPage).SetNewFrame(bNew);
((SwFrmAddPage&)rPage).SetShell(pWrtShell);
break;
case TP_FRM_WRAP:
((SwWrapTabPage&)rPage).SetNewFrame(bNew);
((SwWrapTabPage&)rPage).SetFormatUsed(bFormat, FALSE);
((SwWrapTabPage&)rPage).SetShell(pWrtShell);
break;
case TP_COLUMN:
{
((SwColumnPage&)rPage).SetFrmMode(TRUE);
((SwColumnPage&)rPage).SetFormatUsed(bFormat);
const SwFmtFrmSize& rSize = (const SwFmtFrmSize&)
rSet.Get( RES_FRM_SIZE );
((SwColumnPage&)rPage).SetPageWidth( rSize.GetWidth() );
}
break;
case TP_MACRO_ASSIGN:
SwMacroAssignDlg::AddEvents( (SfxMacroTabPage&)rPage,
DLG_FRM_GRF == nDlgType ? MACASSGN_GRAPHIC
: DLG_FRM_OLE == nDlgType ? MACASSGN_OLE
: MACASSGN_FRMURL );
break;
case TP_BACKGROUND:
if( DLG_FRM_STD == nDlgType )
{
sal_Int32 nFlagType = SVX_SHOW_SELECTOR;
if(!bHTMLMode)
nFlagType |= SVX_ENABLE_TRANSPARENCY;
aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, nFlagType));
rPage.PageCreated(aSet);
}
break;
case TP_BORDER:
//CHINA001 ((SvxBorderTabPage&) rPage).SetSWMode(SW_BORDER_MODE_FRAME);
{
aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,SW_BORDER_MODE_FRAME));
rPage.PageCreated(aSet);
}
break;
}
}
<commit_msg>INTEGRATION: CWS swwarnings (1.11.222); FILE MERGED 2007/06/01 11:09:08 tl 1.11.222.5: warning-free code 2007/05/29 13:06:42 os 1.11.222.4: RESYNC: (1.11-1.12); FILE MERGED 2007/04/13 12:18:00 tl 1.11.222.3: #i69287# binfilter related comments removed 2007/04/03 13:01:12 tl 1.11.222.2: #i69287# warning-free code 2007/02/27 09:03:48 os 1.11.222.1: #i69287# warnings removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmdlg.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:51:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include <svx/dialogs.hrc>
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _FRMDLG_HXX
#include <frmdlg.hxx>
#endif
#ifndef _FRMPAGE_HXX
#include <frmpage.hxx>
#endif
#ifndef _WRAP_HXX
#include <wrap.hxx>
#endif
#ifndef _COLUMN_HXX
#include <column.hxx>
#endif
#ifndef _MACASSGN_HXX
#include <macassgn.hxx>
#endif
#ifndef _FRMUI_HRC
#include <frmui.hrc>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#include <svx/svxids.hrc>
#include <svx/flagsdef.hxx>
#include <svx/svxdlg.hxx>
/*--------------------------------------------------------------------
Beschreibung: Der Traeger des Dialoges
--------------------------------------------------------------------*/
SwFrmDlg::SwFrmDlg( SfxViewFrame* pViewFrame,
Window* pParent,
const SfxItemSet& rCoreSet,
BOOL bNewFrm,
USHORT nResType,
BOOL bFormat,
UINT16 nDefPage,
const String* pStr) :
SfxTabDialog(pViewFrame, pParent, SW_RES(nResType), &rCoreSet, pStr != 0),
m_bFormat(bFormat),
m_bNew(bNewFrm),
m_rSet(rCoreSet),
m_nDlgType(nResType),
m_pWrtShell(((SwView*)pViewFrame->GetViewShell())->GetWrtShellPtr())
{
FreeResource();
USHORT nHtmlMode = ::GetHtmlMode(m_pWrtShell->GetView().GetDocShell());
m_bHTMLMode = static_cast< BOOL >(nHtmlMode & HTMLMODE_ON);
// BspFont fuer beide Bsp-TabPages
//
if(pStr)
{
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_COLL_HEADER);
aTmp += *pStr;
aTmp += ')';
}
AddTabPage(TP_FRM_STD, SwFrmPage::Create, 0);
AddTabPage(TP_FRM_ADD, SwFrmAddPage::Create, 0);
AddTabPage(TP_FRM_WRAP, SwWrapTabPage::Create, 0);
AddTabPage(TP_FRM_URL, SwFrmURLPage::Create, 0);
if(m_nDlgType == DLG_FRM_GRF)
{
AddTabPage( TP_GRF_EXT, SwGrfExtPage::Create, 0 );
AddTabPage( RID_SVXPAGE_GRFCROP );
}
if (m_nDlgType == DLG_FRM_STD)
{
AddTabPage(TP_COLUMN, SwColumnPage::Create, 0);
}
SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");
AddTabPage(TP_BACKGROUND, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 );
AddTabPage( TP_MACRO_ASSIGN, SfxMacroTabPage::Create, 0);
AddTabPage( TP_BORDER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), 0 );
if(m_bHTMLMode)
{
switch( m_nDlgType )
{
case DLG_FRM_STD:
if(0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS))
RemoveTabPage(TP_BORDER);
RemoveTabPage(TP_COLUMN);
// kein break
case DLG_FRM_OLE:
RemoveTabPage(TP_FRM_URL);
RemoveTabPage(TP_MACRO_ASSIGN);
break;
case DLG_FRM_GRF:
RemoveTabPage(RID_SVXPAGE_GRFCROP);
break;
}
if( 0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS) ||
m_nDlgType != DLG_FRM_STD )
RemoveTabPage(TP_BACKGROUND);
}
if (m_bNew)
SetCurPageId(TP_FRM_STD);
if (nDefPage)
SetCurPageId(nDefPage);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwFrmDlg::~SwFrmDlg()
{
}
void SwFrmDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
switch ( nId )
{
case TP_FRM_STD:
((SwFrmPage&)rPage).SetNewFrame(m_bNew);
((SwFrmPage&)rPage).SetFormatUsed(m_bFormat);
((SwFrmPage&)rPage).SetFrmType(m_nDlgType);
break;
case TP_FRM_ADD:
((SwFrmAddPage&)rPage).SetFormatUsed(m_bFormat);
((SwFrmAddPage&)rPage).SetFrmType(m_nDlgType);
((SwFrmAddPage&)rPage).SetNewFrame(m_bNew);
((SwFrmAddPage&)rPage).SetShell(m_pWrtShell);
break;
case TP_FRM_WRAP:
((SwWrapTabPage&)rPage).SetNewFrame(m_bNew);
((SwWrapTabPage&)rPage).SetFormatUsed(m_bFormat, FALSE);
((SwWrapTabPage&)rPage).SetShell(m_pWrtShell);
break;
case TP_COLUMN:
{
((SwColumnPage&)rPage).SetFrmMode(TRUE);
((SwColumnPage&)rPage).SetFormatUsed(m_bFormat);
const SwFmtFrmSize& rSize = (const SwFmtFrmSize&)
m_rSet.Get( RES_FRM_SIZE );
((SwColumnPage&)rPage).SetPageWidth( rSize.GetWidth() );
}
break;
case TP_MACRO_ASSIGN:
SwMacroAssignDlg::AddEvents( (SfxMacroTabPage&)rPage,
DLG_FRM_GRF == m_nDlgType ? MACASSGN_GRAPHIC
: DLG_FRM_OLE == m_nDlgType ? MACASSGN_OLE
: MACASSGN_FRMURL );
break;
case TP_BACKGROUND:
if( DLG_FRM_STD == m_nDlgType )
{
sal_Int32 nFlagType = SVX_SHOW_SELECTOR;
if(!m_bHTMLMode)
nFlagType |= SVX_ENABLE_TRANSPARENCY;
aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, nFlagType));
rPage.PageCreated(aSet);
}
break;
case TP_BORDER:
{
aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,SW_BORDER_MODE_FRAME));
rPage.PageCreated(aSet);
}
break;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tbxmgr.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:47:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "swtypes.hxx" // nur wegen aEmptyString??
#include "errhdl.hxx"
#include "wdocsh.hxx"
#include "tbxmgr.hxx"
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
SwPopupWindowTbxMgr::SwPopupWindowTbxMgr( USHORT nId, WindowAlign eAlign,
ResId aRIdWin, ResId aRIdTbx,
SfxBindings& rBindings ) :
SvxPopupWindowTbxMgr( nId, eAlign, aRIdWin, aRIdTbx ),
bWeb(FALSE),
aRIdWinTemp(aRIdWin),
aRIdTbxTemp(aRIdTbx),
eAlignment( eAlign ),
mrBindings( rBindings )
{
SfxObjectShell* pObjShell = SfxObjectShell::Current();
if(PTR_CAST(SwWebDocShell, pObjShell))
{
bWeb = TRUE;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
switch(nId)
{
case FN_INSERT_CTRL:
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FOOTNOTE);
rTbx.HideItem(FN_INSERT_ENDNOTE);
rTbx.HideItem(FN_PAGE_STYLE_SET_COLS);
rTbx.HideItem(FN_INSERT_IDX_ENTRY_DLG);
break;
case FN_INSERT_FIELD_CTRL:
rTbx.HideItem(FN_INSERT_FLD_PGNUMBER);
rTbx.HideItem(FN_INSERT_FLD_PGCOUNT);
rTbx.HideItem(FN_INSERT_FLD_TOPIC);
rTbx.HideItem(FN_INSERT_FLD_TITLE);
break;
}
}
else if( FN_INSERT_CTRL == nId)
{
ToolBox& rTbx = GetTbxMgr().GetToolBox();
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
*/
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
void SwPopupWindowTbxMgr::StateChanged(USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
static USHORT __READONLY_DATA aInsertCtrl[] =
{
FN_INSERT_FRAME_INTERACT,
FN_INSERT_FOOTNOTE,
FN_INSERT_ENDNOTE,
FN_PAGE_STYLE_SET_COLS,
FN_INSERT_IDX_ENTRY_DLG,
0
};
static USHORT __READONLY_DATA aInsertFld[] =
{
FN_INSERT_FLD_PGNUMBER,
FN_INSERT_FLD_PGCOUNT,
FN_INSERT_FLD_TOPIC,
FN_INSERT_FLD_TITLE,
0
};
SfxObjectShell* pObjShell = SfxObjectShell::Current();
BOOL bNewWeb = 0 != PTR_CAST(SwWebDocShell, pObjShell);
if(bWeb != bNewWeb)
{
bWeb = bNewWeb;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
const USHORT* pSid = 0;
switch(nSID)
{
case FN_INSERT_CTRL:
pSid = &aInsertCtrl[0];
if(bWeb)
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
else
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
break;
case FN_INSERT_FIELD_CTRL:
pSid = & aInsertFld[0];
break;
}
if(pSid)
{
if(bWeb)
while(*pSid)
{
rTbx.HideItem(*pSid);
pSid++;
}
else
while(*pSid)
{
rTbx.ShowItem(*pSid);
pSid++;
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
}
SfxPopupWindow::StateChanged(nSID, eState, pState);
}
*/
/*
SfxPopupWindow* SwPopupWindowTbxMgr::Clone() const
{
return new SwPopupWindowTbxMgr(
GetId(),
eAlignment,
// ((SwPopupWindowTbxMgr*)this)->GetTbxMgr().GetToolBox().GetAlign(),
aRIdWinTemp,
aRIdTbxTemp,
mrBindings
// (SfxBindings&)GetBindings()
);
}
*/
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.474); FILE MERGED 2006/09/01 17:53:17 kaib 1.5.474.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tbxmgr.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:12:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "cmdid.h"
#include "swtypes.hxx" // nur wegen aEmptyString??
#include "errhdl.hxx"
#include "wdocsh.hxx"
#include "tbxmgr.hxx"
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
SwPopupWindowTbxMgr::SwPopupWindowTbxMgr( USHORT nId, WindowAlign eAlign,
ResId aRIdWin, ResId aRIdTbx,
SfxBindings& rBindings ) :
SvxPopupWindowTbxMgr( nId, eAlign, aRIdWin, aRIdTbx ),
bWeb(FALSE),
aRIdWinTemp(aRIdWin),
aRIdTbxTemp(aRIdTbx),
eAlignment( eAlign ),
mrBindings( rBindings )
{
SfxObjectShell* pObjShell = SfxObjectShell::Current();
if(PTR_CAST(SwWebDocShell, pObjShell))
{
bWeb = TRUE;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
switch(nId)
{
case FN_INSERT_CTRL:
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FOOTNOTE);
rTbx.HideItem(FN_INSERT_ENDNOTE);
rTbx.HideItem(FN_PAGE_STYLE_SET_COLS);
rTbx.HideItem(FN_INSERT_IDX_ENTRY_DLG);
break;
case FN_INSERT_FIELD_CTRL:
rTbx.HideItem(FN_INSERT_FLD_PGNUMBER);
rTbx.HideItem(FN_INSERT_FLD_PGCOUNT);
rTbx.HideItem(FN_INSERT_FLD_TOPIC);
rTbx.HideItem(FN_INSERT_FLD_TITLE);
break;
}
}
else if( FN_INSERT_CTRL == nId)
{
ToolBox& rTbx = GetTbxMgr().GetToolBox();
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT);
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
*/
/*************************************************************************
|*
|*
|*
\************************************************************************/
/*
void SwPopupWindowTbxMgr::StateChanged(USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
static USHORT __READONLY_DATA aInsertCtrl[] =
{
FN_INSERT_FRAME_INTERACT,
FN_INSERT_FOOTNOTE,
FN_INSERT_ENDNOTE,
FN_PAGE_STYLE_SET_COLS,
FN_INSERT_IDX_ENTRY_DLG,
0
};
static USHORT __READONLY_DATA aInsertFld[] =
{
FN_INSERT_FLD_PGNUMBER,
FN_INSERT_FLD_PGCOUNT,
FN_INSERT_FLD_TOPIC,
FN_INSERT_FLD_TITLE,
0
};
SfxObjectShell* pObjShell = SfxObjectShell::Current();
BOOL bNewWeb = 0 != PTR_CAST(SwWebDocShell, pObjShell);
if(bWeb != bNewWeb)
{
bWeb = bNewWeb;
ToolBox& rTbx = GetTbxMgr().GetToolBox();
// jetzt muessen ein paar Items aus der Toolbox versteckt werden:
const USHORT* pSid = 0;
switch(nSID)
{
case FN_INSERT_CTRL:
pSid = &aInsertCtrl[0];
if(bWeb)
rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);
else
rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);
break;
case FN_INSERT_FIELD_CTRL:
pSid = & aInsertFld[0];
break;
}
if(pSid)
{
if(bWeb)
while(*pSid)
{
rTbx.HideItem(*pSid);
pSid++;
}
else
while(*pSid)
{
rTbx.ShowItem(*pSid);
pSid++;
}
Size aSize = GetTbxMgr().CalcWindowSizePixel();
GetTbxMgr().SetPosSizePixel( Point(), aSize );
SetOutputSizePixel( aSize );
}
}
SfxPopupWindow::StateChanged(nSID, eState, pState);
}
*/
/*
SfxPopupWindow* SwPopupWindowTbxMgr::Clone() const
{
return new SwPopupWindowTbxMgr(
GetId(),
eAlignment,
// ((SwPopupWindowTbxMgr*)this)->GetTbxMgr().GetToolBox().GetAlign(),
aRIdWinTemp,
aRIdTbxTemp,
mrBindings
// (SfxBindings&)GetBindings()
);
}
*/
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include <editeng/itemtype.hxx>
#include <unosett.hxx>
#include "swtypes.hxx"
#include "cmdid.h"
#include "uiitems.hxx"
#include "utlui.hrc"
#include "attrdesc.hrc"
#include <unomid.h>
#include <numrule.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
// Breitenangaben der Fussnotenlinien, mit TabPage abstimmen
static const sal_uInt16 nFtnLines[] = {
0,
10,
50,
80,
100,
150
};
#define FTN_LINE_STYLE_COUNT 5
SwPageFtnInfoItem::SwPageFtnInfoItem( const sal_uInt16 nId, SwPageFtnInfo& rInfo) :
SfxPoolItem( nId ),
aFtnInfo(rInfo)
{
}
SwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :
SfxPoolItem( rItem ),
aFtnInfo(rItem.GetPageFtnInfo())
{
}
SwPageFtnInfoItem::~SwPageFtnInfoItem()
{
}
SfxPoolItem* SwPageFtnInfoItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPageFtnInfoItem( *this );
}
int SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( Which() == rAttr.Which(), "keine gleichen Attribute" );
return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());
}
SfxItemPresentation SwPageFtnInfoItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit eCoreUnit,
SfxMapUnit ePresUnit,
String& rText,
const IntlWrapper* pIntl
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return SFX_ITEM_PRESENTATION_NONE;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
sal_uInt16 nHght = (sal_uInt16) GetPageFtnInfo().GetHeight();
if ( nHght )
{
rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );
rText += ' ';
rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );
rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );
}
return ePres;
}
default:; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
bool SwPageFtnInfoItem::QueryValue( Any& rVal, sal_uInt8 nMemberId ) const
{
bool bRet = true;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;
case MID_LINE_WEIGHT : rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;
case MID_LINE_COLOR : rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;
case MID_LINE_RELWIDTH :
{
Fraction aTmp( 100, 1 );
aTmp *= aFtnInfo.GetWidth();
rVal <<= (sal_Int8)(long)aTmp;
}
break;
case MID_LINE_ADJUST : rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;//text::HorizontalAdjust
case MID_LINE_TEXT_DIST : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;
case MID_LINE_FOOTNOTE_DIST: rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;
case MID_FTN_LINE_STYLE :
{
switch ( aFtnInfo.GetLineStyle( ) )
{
default:
case ::editeng::NO_STYLE: rVal <<= sal_Int8( 0 ); break;
case ::editeng::SOLID: rVal <<= sal_Int8( 1 ); break;
case ::editeng::DOTTED: rVal <<= sal_Int8( 2 ); break;
case ::editeng::DASHED: rVal <<= sal_Int8( 3 ); break;
}
break;
}
default:
bRet = false;
}
return bRet;
}
bool SwPageFtnInfoItem::PutValue(const Any& rVal, sal_uInt8 nMemberId)
{
sal_Int32 nSet32 = 0;
bool bRet = true;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_LINE_COLOR :
rVal >>= nSet32;
aFtnInfo.SetLineColor(nSet32);
break;
case MID_FTN_HEIGHT:
case MID_LINE_TEXT_DIST :
case MID_LINE_FOOTNOTE_DIST:
rVal >>= nSet32;
if(nSet32 < 0)
bRet = false;
else
{
nSet32 = MM100_TO_TWIP(nSet32);
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT: aFtnInfo.SetHeight(nSet32); break;
case MID_LINE_TEXT_DIST: aFtnInfo.SetTopDist(nSet32);break;
case MID_LINE_FOOTNOTE_DIST: aFtnInfo.SetBottomDist(nSet32);break;
}
}
break;
case MID_LINE_WEIGHT :
{
sal_Int16 nSet = 0;
rVal >>= nSet;
if(nSet >= 0)
aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));
else
bRet = false;
}
break;
case MID_LINE_RELWIDTH :
{
sal_Int8 nSet = 0;
rVal >>= nSet;
if(nSet < 0)
bRet = false;
else
aFtnInfo.SetWidth(Fraction(nSet, 100));
}
break;
case MID_LINE_ADJUST :
{
sal_Int16 nSet = 0;
rVal >>= nSet;
if(nSet >= 0 && nSet < 3) //text::HorizontalAdjust
aFtnInfo.SetAdj((SwFtnAdj)nSet);
else
bRet = false;
}
case MID_FTN_LINE_STYLE:
{
::editeng::SvxBorderStyle eStyle = ::editeng::NO_STYLE;
sal_Int8 nSet = 0;
rVal >>= nSet;
switch ( nSet )
{
case 1: eStyle = ::editeng::SOLID; break;
case 2: eStyle = ::editeng::DOTTED; break;
case 3: eStyle = ::editeng::DASHED; break;
default: break;
}
aFtnInfo.SetLineStyle( eStyle );
}
break;
default:
bRet = false;
}
return bRet;
}
SwPtrItem::SwPtrItem( const sal_uInt16 nId, void* pPtr ) :
SfxPoolItem( nId ),
pMisc(pPtr)
{
}
/*--------------------------------------------------------------------
Beschreibung: Copy-Konstruktor
--------------------------------------------------------------------*/
SwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )
{
pMisc = rItem.pMisc;
}
/*--------------------------------------------------------------------
Beschreibung: Clonen
--------------------------------------------------------------------*/
SfxPoolItem* SwPtrItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPtrItem( *this );
}
int SwPtrItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( SfxPoolItem::operator==(rAttr), "unequal types" );
const SwPtrItem& rItem = (SwPtrItem&)rAttr;
return ( pMisc == rItem.pMisc );
}
/*--------------------------------------------------------------
SwUINumRuleItem fuer die NumTabPages der FormatNumRule/Stylisten
---------------------------------------------------------------*/
SwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const sal_uInt16 nId )
: SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )
{
}
SwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )
: SfxPoolItem( rItem ),
pRule( new SwNumRule( *rItem.pRule ))
{
}
SwUINumRuleItem::~SwUINumRuleItem()
{
delete pRule;
}
SfxPoolItem* SwUINumRuleItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwUINumRuleItem( *this );
}
int SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( SfxPoolItem::operator==(rAttr), "unequal types" );
return *pRule == *((SwUINumRuleItem&)rAttr).pRule;
}
bool SwUINumRuleItem::QueryValue( uno::Any& rVal, sal_uInt8 /*nMemberId*/ ) const
{
uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);
rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));
return true;
}
bool SwUINumRuleItem::PutValue( const uno::Any& rVal, sal_uInt8 /*nMemberId*/ )
{
uno::Reference< container::XIndexReplace> xRulesRef;
if(rVal >>= xRulesRef)
{
uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);
SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast<SwXNumberingRules*>(
xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;
if(pSwXRules)
{
*pRule = *pSwXRules->GetNumRule();
}
}
return true;
}
SwBackgroundDestinationItem::SwBackgroundDestinationItem(sal_uInt16 _nWhich, sal_uInt16 nValue) :
SfxUInt16Item(_nWhich, nValue)
{
}
SfxPoolItem* SwBackgroundDestinationItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwBackgroundDestinationItem(Which(), GetValue());
}
SwPaMItem::SwPaMItem( const sal_uInt16 nId, SwPaM* pPaM ) :
SfxPoolItem( nId ),
m_pPaM(pPaM)
{
}
SwPaMItem::SwPaMItem( const SwPaMItem& rItem ) : SfxPoolItem( rItem )
{
m_pPaM = rItem.m_pPaM;
}
SfxPoolItem* SwPaMItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPaMItem( *this );
}
int SwPaMItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( SfxPoolItem::operator==(rAttr), "unequal types" );
const SwPaMItem& rItem = (SwPaMItem&)rAttr;
return ( m_pPaM == rItem.m_pPaM );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused definitions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include <editeng/itemtype.hxx>
#include <unosett.hxx>
#include "swtypes.hxx"
#include "cmdid.h"
#include "uiitems.hxx"
#include "utlui.hrc"
#include "attrdesc.hrc"
#include <unomid.h>
#include <numrule.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
SwPageFtnInfoItem::SwPageFtnInfoItem( const sal_uInt16 nId, SwPageFtnInfo& rInfo) :
SfxPoolItem( nId ),
aFtnInfo(rInfo)
{
}
SwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :
SfxPoolItem( rItem ),
aFtnInfo(rItem.GetPageFtnInfo())
{
}
SwPageFtnInfoItem::~SwPageFtnInfoItem()
{
}
SfxPoolItem* SwPageFtnInfoItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPageFtnInfoItem( *this );
}
int SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( Which() == rAttr.Which(), "keine gleichen Attribute" );
return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());
}
SfxItemPresentation SwPageFtnInfoItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit eCoreUnit,
SfxMapUnit ePresUnit,
String& rText,
const IntlWrapper* pIntl
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return SFX_ITEM_PRESENTATION_NONE;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
sal_uInt16 nHght = (sal_uInt16) GetPageFtnInfo().GetHeight();
if ( nHght )
{
rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );
rText += ' ';
rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );
rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );
}
return ePres;
}
default:; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
bool SwPageFtnInfoItem::QueryValue( Any& rVal, sal_uInt8 nMemberId ) const
{
bool bRet = true;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;
case MID_LINE_WEIGHT : rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;
case MID_LINE_COLOR : rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;
case MID_LINE_RELWIDTH :
{
Fraction aTmp( 100, 1 );
aTmp *= aFtnInfo.GetWidth();
rVal <<= (sal_Int8)(long)aTmp;
}
break;
case MID_LINE_ADJUST : rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;//text::HorizontalAdjust
case MID_LINE_TEXT_DIST : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;
case MID_LINE_FOOTNOTE_DIST: rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;
case MID_FTN_LINE_STYLE :
{
switch ( aFtnInfo.GetLineStyle( ) )
{
default:
case ::editeng::NO_STYLE: rVal <<= sal_Int8( 0 ); break;
case ::editeng::SOLID: rVal <<= sal_Int8( 1 ); break;
case ::editeng::DOTTED: rVal <<= sal_Int8( 2 ); break;
case ::editeng::DASHED: rVal <<= sal_Int8( 3 ); break;
}
break;
}
default:
bRet = false;
}
return bRet;
}
bool SwPageFtnInfoItem::PutValue(const Any& rVal, sal_uInt8 nMemberId)
{
sal_Int32 nSet32 = 0;
bool bRet = true;
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_LINE_COLOR :
rVal >>= nSet32;
aFtnInfo.SetLineColor(nSet32);
break;
case MID_FTN_HEIGHT:
case MID_LINE_TEXT_DIST :
case MID_LINE_FOOTNOTE_DIST:
rVal >>= nSet32;
if(nSet32 < 0)
bRet = false;
else
{
nSet32 = MM100_TO_TWIP(nSet32);
switch(nMemberId & ~CONVERT_TWIPS)
{
case MID_FTN_HEIGHT: aFtnInfo.SetHeight(nSet32); break;
case MID_LINE_TEXT_DIST: aFtnInfo.SetTopDist(nSet32);break;
case MID_LINE_FOOTNOTE_DIST: aFtnInfo.SetBottomDist(nSet32);break;
}
}
break;
case MID_LINE_WEIGHT :
{
sal_Int16 nSet = 0;
rVal >>= nSet;
if(nSet >= 0)
aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));
else
bRet = false;
}
break;
case MID_LINE_RELWIDTH :
{
sal_Int8 nSet = 0;
rVal >>= nSet;
if(nSet < 0)
bRet = false;
else
aFtnInfo.SetWidth(Fraction(nSet, 100));
}
break;
case MID_LINE_ADJUST :
{
sal_Int16 nSet = 0;
rVal >>= nSet;
if(nSet >= 0 && nSet < 3) //text::HorizontalAdjust
aFtnInfo.SetAdj((SwFtnAdj)nSet);
else
bRet = false;
}
case MID_FTN_LINE_STYLE:
{
::editeng::SvxBorderStyle eStyle = ::editeng::NO_STYLE;
sal_Int8 nSet = 0;
rVal >>= nSet;
switch ( nSet )
{
case 1: eStyle = ::editeng::SOLID; break;
case 2: eStyle = ::editeng::DOTTED; break;
case 3: eStyle = ::editeng::DASHED; break;
default: break;
}
aFtnInfo.SetLineStyle( eStyle );
}
break;
default:
bRet = false;
}
return bRet;
}
SwPtrItem::SwPtrItem( const sal_uInt16 nId, void* pPtr ) :
SfxPoolItem( nId ),
pMisc(pPtr)
{
}
/*--------------------------------------------------------------------
Beschreibung: Copy-Konstruktor
--------------------------------------------------------------------*/
SwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )
{
pMisc = rItem.pMisc;
}
/*--------------------------------------------------------------------
Beschreibung: Clonen
--------------------------------------------------------------------*/
SfxPoolItem* SwPtrItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPtrItem( *this );
}
int SwPtrItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( SfxPoolItem::operator==(rAttr), "unequal types" );
const SwPtrItem& rItem = (SwPtrItem&)rAttr;
return ( pMisc == rItem.pMisc );
}
/*--------------------------------------------------------------
SwUINumRuleItem fuer die NumTabPages der FormatNumRule/Stylisten
---------------------------------------------------------------*/
SwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const sal_uInt16 nId )
: SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )
{
}
SwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )
: SfxPoolItem( rItem ),
pRule( new SwNumRule( *rItem.pRule ))
{
}
SwUINumRuleItem::~SwUINumRuleItem()
{
delete pRule;
}
SfxPoolItem* SwUINumRuleItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwUINumRuleItem( *this );
}
int SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( SfxPoolItem::operator==(rAttr), "unequal types" );
return *pRule == *((SwUINumRuleItem&)rAttr).pRule;
}
bool SwUINumRuleItem::QueryValue( uno::Any& rVal, sal_uInt8 /*nMemberId*/ ) const
{
uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);
rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));
return true;
}
bool SwUINumRuleItem::PutValue( const uno::Any& rVal, sal_uInt8 /*nMemberId*/ )
{
uno::Reference< container::XIndexReplace> xRulesRef;
if(rVal >>= xRulesRef)
{
uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);
SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast<SwXNumberingRules*>(
xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;
if(pSwXRules)
{
*pRule = *pSwXRules->GetNumRule();
}
}
return true;
}
SwBackgroundDestinationItem::SwBackgroundDestinationItem(sal_uInt16 _nWhich, sal_uInt16 nValue) :
SfxUInt16Item(_nWhich, nValue)
{
}
SfxPoolItem* SwBackgroundDestinationItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwBackgroundDestinationItem(Which(), GetValue());
}
SwPaMItem::SwPaMItem( const sal_uInt16 nId, SwPaM* pPaM ) :
SfxPoolItem( nId ),
m_pPaM(pPaM)
{
}
SwPaMItem::SwPaMItem( const SwPaMItem& rItem ) : SfxPoolItem( rItem )
{
m_pPaM = rItem.m_pPaM;
}
SfxPoolItem* SwPaMItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SwPaMItem( *this );
}
int SwPaMItem::operator==( const SfxPoolItem& rAttr ) const
{
OSL_ENSURE( SfxPoolItem::operator==(rAttr), "unequal types" );
const SwPaMItem& rItem = (SwPaMItem&)rAttr;
return ( m_pPaM == rItem.m_pPaM );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// NOLINT(namespace-envoy)
#include "proxy_wasm_intrinsics.h"
static std::unordered_map<std::string, RootFactory> *root_factories = nullptr;
static std::unordered_map<std::string, ContextFactory> *context_factories = nullptr;
static std::unordered_map<int32_t, std::unique_ptr<ContextBase>> context_map;
static std::unordered_map<std::string, RootContext*> root_context_map;
RegisterContextFactory::RegisterContextFactory(ContextFactory context_factory, RootFactory root_factory, StringView root_id) {
if (!root_factories) {
root_factories = new std::unordered_map<std::string, RootFactory>;
context_factories = new std::unordered_map<std::string, ContextFactory>;
}
if (context_factory)
(*context_factories)[std::string(root_id)] = context_factory;
if (root_factory)
(*root_factories)[std::string(root_id)] = root_factory;
}
static Context* ensureContext(uint32_t context_id, uint32_t root_context_id) {
auto e = context_map.insert(std::make_pair(context_id, nullptr));
if (e.second) {
RootContext *root = context_map[root_context_id].get()->asRoot();
std::string root_id = std::string(root->root_id());
if (!context_factories) {
e.first->second = std::make_unique<Context>(context_id, root);
return e.first->second->asContext();
}
auto factory = context_factories->find(root_id);
if (factory == context_factories->end()) {
throw ProxyException("no context factory for root_id: " + root_id);
} else {
e.first->second = factory->second(context_id, root);
}
}
return e.first->second->asContext();
}
static RootContext* ensureRootContext(uint32_t context_id, std::unique_ptr<WasmData> root_id) {
auto it = context_map.find(context_id);
if (it != context_map.end()) {
return it->second->asRoot();
}
if (!root_factories) {
auto context = std::make_unique<RootContext>(context_id, root_id->view());
RootContext* root_context = context->asRoot();
context_map[context_id] = std::move(context);
return root_context;
}
auto root_id_string = root_id->toString();
auto factory = root_factories->find(root_id_string);
RootContext *root_context;
if (factory != root_factories->end()) {
auto context = factory->second(context_id, root_id->view());
root_context = context->asRoot();
root_context_map[root_id_string] = root_context;
context_map[context_id] = std::move(context);
} else {
// Default handlers.
auto context = std::make_unique<RootContext>(context_id, root_id->view());
root_context = context->asRoot();
context_map[context_id] = std::move(context);
}
return root_context;
}
static ContextBase* getContextBase(uint32_t context_id) {
auto it = context_map.find(context_id);
if (it == context_map.end() || !it->second->asContext()) {
throw ProxyException("no base context context_id: " + std::to_string(context_id));
}
return it->second.get();
}
static Context* getContext(uint32_t context_id) {
auto it = context_map.find(context_id);
if (it == context_map.end() || !it->second->asContext()) {
throw ProxyException("no context context_id: " + std::to_string(context_id));
}
return it->second->asContext();
}
static RootContext* getRootContext(uint32_t context_id) {
auto it = context_map.find(context_id);
if (it == context_map.end() || !it->second->asRoot()) {
throw ProxyException("no root context_id: " + std::to_string(context_id));
}
return it->second->asRoot();
}
RootContext* getRoot(StringView root_id) {
auto it = root_context_map.find(std::string(root_id));
if (it != root_context_map.end()) {
return it->second;
}
return nullptr;
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onStart(uint32_t root_context_id, uint32_t root_id_ptr, uint32_t root_id_size) {
ensureRootContext(root_context_id, std::make_unique<WasmData>(reinterpret_cast<char*>(root_id_ptr), root_id_size))->onStart();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onConfigure(uint32_t root_context_id, uint32_t ptr, uint32_t size) {
getRootContext(root_context_id)->onConfigure(std::make_unique<WasmData>(reinterpret_cast<char*>(ptr), size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onTick(uint32_t root_context_id) { getRootContext(root_context_id)->onTick(); }
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onCreate(uint32_t context_id, uint32_t root_context_id) {
ensureContext(context_id, root_context_id)->onCreate();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterHeadersStatus proxy_onRequestHeaders(uint32_t context_id) {
return getContext(context_id)->onRequestHeaders();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterMetadataStatus proxy_onRequestMetadata(uint32_t context_id) {
return getContext(context_id)->onRequestMetadata();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterDataStatus proxy_onRequestBody(uint32_t context_id,
uint32_t body_buffer_length,
uint32_t end_of_stream) {
return getContext(context_id)->onRequestBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0);
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterTrailersStatus proxy_onRequestTrailers(uint32_t context_id) {
return getContext(context_id)->onRequestTrailers();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterHeadersStatus proxy_onResponseHeaders(uint32_t context_id) {
return getContext(context_id)->onResponseHeaders();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterMetadataStatus proxy_onResponseMetadata(uint32_t context_id) {
return getContext(context_id)->onResponseMetadata();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterDataStatus proxy_onResponseBody(uint32_t context_id,
uint32_t body_buffer_length,
uint32_t end_of_stream) {
return getContext(context_id)->onResponseBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0);
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterTrailersStatus proxy_onResponseTrailers(uint32_t context_id) {
return getContext(context_id)->onResponseTrailers();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onDone(uint32_t context_id) {
getContext(context_id)->onDone();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onLog(uint32_t context_id) {
getContext(context_id)->onLog();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onDelete(uint32_t context_id) {
getContext(context_id)->onDelete();
context_map.erase(context_id);
}
extern "C" EMSCRIPTEN_KEEPALIVE void
proxy_onHttpCallResponse(uint32_t context_id, uint32_t token, uint32_t header_pairs_ptr,
uint32_t header_pairs_size, uint32_t body_ptr, uint32_t body_size,
uint32_t trailer_pairs_ptr, uint32_t trailer_pairs_size) {
getContextBase(context_id)->onHttpCallResponse(
token,
std::make_unique<WasmData>(reinterpret_cast<char*>(header_pairs_ptr), header_pairs_size),
std::make_unique<WasmData>(reinterpret_cast<char*>(body_ptr), body_size),
std::make_unique<WasmData>(reinterpret_cast<char*>(trailer_pairs_ptr), trailer_pairs_size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcCreateInitialMetadata(uint32_t context_id, uint32_t token) {
getContextBase(context_id)->onGrpcCreateInitialMetadata(token);
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcReceiveInitialMetadata(uint32_t context_id, uint32_t token) {
getContextBase(context_id)->onGrpcReceiveInitialMetadata(token);
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcReceiveTrailingMetadata(uint32_t context_id, uint32_t token) {
getContextBase(context_id)->onGrpcReceiveTrailingMetadata(token);
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcReceive(uint32_t context_id, uint32_t token,
uint32_t response_ptr, uint32_t response_size) {
getContextBase(context_id)->onGrpcReceive(token, std::make_unique<WasmData>(reinterpret_cast<char*>(response_ptr), response_size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcClose(uint32_t context_id, uint32_t token,
uint32_t status_code, uint32_t status_message_ptr, uint32_t status_message_size) {
getContextBase(context_id)->onGrpcClose(token, static_cast<GrpcStatus>(status_code), std::make_unique<WasmData>(reinterpret_cast<char*>(status_message_ptr), status_message_size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onQueueReady(uint32_t context_id, uint32_t token) {
getRootContext(context_id)->onQueueReady(token);
}
<commit_msg>fix get context base (#62)<commit_after>// NOLINT(namespace-envoy)
#include "proxy_wasm_intrinsics.h"
static std::unordered_map<std::string, RootFactory> *root_factories = nullptr;
static std::unordered_map<std::string, ContextFactory> *context_factories = nullptr;
static std::unordered_map<int32_t, std::unique_ptr<ContextBase>> context_map;
static std::unordered_map<std::string, RootContext*> root_context_map;
RegisterContextFactory::RegisterContextFactory(ContextFactory context_factory, RootFactory root_factory, StringView root_id) {
if (!root_factories) {
root_factories = new std::unordered_map<std::string, RootFactory>;
context_factories = new std::unordered_map<std::string, ContextFactory>;
}
if (context_factory)
(*context_factories)[std::string(root_id)] = context_factory;
if (root_factory)
(*root_factories)[std::string(root_id)] = root_factory;
}
static Context* ensureContext(uint32_t context_id, uint32_t root_context_id) {
auto e = context_map.insert(std::make_pair(context_id, nullptr));
if (e.second) {
RootContext *root = context_map[root_context_id].get()->asRoot();
std::string root_id = std::string(root->root_id());
if (!context_factories) {
e.first->second = std::make_unique<Context>(context_id, root);
return e.first->second->asContext();
}
auto factory = context_factories->find(root_id);
if (factory == context_factories->end()) {
throw ProxyException("no context factory for root_id: " + root_id);
} else {
e.first->second = factory->second(context_id, root);
}
}
return e.first->second->asContext();
}
static RootContext* ensureRootContext(uint32_t context_id, std::unique_ptr<WasmData> root_id) {
auto it = context_map.find(context_id);
if (it != context_map.end()) {
return it->second->asRoot();
}
if (!root_factories) {
auto context = std::make_unique<RootContext>(context_id, root_id->view());
RootContext* root_context = context->asRoot();
context_map[context_id] = std::move(context);
return root_context;
}
auto root_id_string = root_id->toString();
auto factory = root_factories->find(root_id_string);
RootContext *root_context;
if (factory != root_factories->end()) {
auto context = factory->second(context_id, root_id->view());
root_context = context->asRoot();
root_context_map[root_id_string] = root_context;
context_map[context_id] = std::move(context);
} else {
// Default handlers.
auto context = std::make_unique<RootContext>(context_id, root_id->view());
root_context = context->asRoot();
context_map[context_id] = std::move(context);
}
return root_context;
}
static ContextBase* getContextBase(uint32_t context_id) {
auto it = context_map.find(context_id);
if (it == context_map.end() || !(it->second->asContext() || it->second->asRoot())) {
throw ProxyException("no base context context_id: " + std::to_string(context_id));
}
return it->second.get();
}
static Context* getContext(uint32_t context_id) {
auto it = context_map.find(context_id);
if (it == context_map.end() || !it->second->asContext()) {
throw ProxyException("no context context_id: " + std::to_string(context_id));
}
return it->second->asContext();
}
static RootContext* getRootContext(uint32_t context_id) {
auto it = context_map.find(context_id);
if (it == context_map.end() || !it->second->asRoot()) {
throw ProxyException("no root context_id: " + std::to_string(context_id));
}
return it->second->asRoot();
}
RootContext* getRoot(StringView root_id) {
auto it = root_context_map.find(std::string(root_id));
if (it != root_context_map.end()) {
return it->second;
}
return nullptr;
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onStart(uint32_t root_context_id, uint32_t root_id_ptr, uint32_t root_id_size) {
ensureRootContext(root_context_id, std::make_unique<WasmData>(reinterpret_cast<char*>(root_id_ptr), root_id_size))->onStart();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onConfigure(uint32_t root_context_id, uint32_t ptr, uint32_t size) {
getRootContext(root_context_id)->onConfigure(std::make_unique<WasmData>(reinterpret_cast<char*>(ptr), size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onTick(uint32_t root_context_id) { getRootContext(root_context_id)->onTick(); }
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onCreate(uint32_t context_id, uint32_t root_context_id) {
ensureContext(context_id, root_context_id)->onCreate();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterHeadersStatus proxy_onRequestHeaders(uint32_t context_id) {
return getContext(context_id)->onRequestHeaders();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterMetadataStatus proxy_onRequestMetadata(uint32_t context_id) {
return getContext(context_id)->onRequestMetadata();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterDataStatus proxy_onRequestBody(uint32_t context_id,
uint32_t body_buffer_length,
uint32_t end_of_stream) {
return getContext(context_id)->onRequestBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0);
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterTrailersStatus proxy_onRequestTrailers(uint32_t context_id) {
return getContext(context_id)->onRequestTrailers();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterHeadersStatus proxy_onResponseHeaders(uint32_t context_id) {
return getContext(context_id)->onResponseHeaders();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterMetadataStatus proxy_onResponseMetadata(uint32_t context_id) {
return getContext(context_id)->onResponseMetadata();
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterDataStatus proxy_onResponseBody(uint32_t context_id,
uint32_t body_buffer_length,
uint32_t end_of_stream) {
return getContext(context_id)->onResponseBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0);
}
extern "C" EMSCRIPTEN_KEEPALIVE FilterTrailersStatus proxy_onResponseTrailers(uint32_t context_id) {
return getContext(context_id)->onResponseTrailers();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onDone(uint32_t context_id) {
getContext(context_id)->onDone();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onLog(uint32_t context_id) {
getContext(context_id)->onLog();
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onDelete(uint32_t context_id) {
getContext(context_id)->onDelete();
context_map.erase(context_id);
}
extern "C" EMSCRIPTEN_KEEPALIVE void
proxy_onHttpCallResponse(uint32_t context_id, uint32_t token, uint32_t header_pairs_ptr,
uint32_t header_pairs_size, uint32_t body_ptr, uint32_t body_size,
uint32_t trailer_pairs_ptr, uint32_t trailer_pairs_size) {
getContextBase(context_id)->onHttpCallResponse(
token,
std::make_unique<WasmData>(reinterpret_cast<char*>(header_pairs_ptr), header_pairs_size),
std::make_unique<WasmData>(reinterpret_cast<char*>(body_ptr), body_size),
std::make_unique<WasmData>(reinterpret_cast<char*>(trailer_pairs_ptr), trailer_pairs_size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcCreateInitialMetadata(uint32_t context_id, uint32_t token) {
getContextBase(context_id)->onGrpcCreateInitialMetadata(token);
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcReceiveInitialMetadata(uint32_t context_id, uint32_t token) {
getContextBase(context_id)->onGrpcReceiveInitialMetadata(token);
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcReceiveTrailingMetadata(uint32_t context_id, uint32_t token) {
getContextBase(context_id)->onGrpcReceiveTrailingMetadata(token);
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcReceive(uint32_t context_id, uint32_t token,
uint32_t response_ptr, uint32_t response_size) {
getContextBase(context_id)->onGrpcReceive(token, std::make_unique<WasmData>(reinterpret_cast<char*>(response_ptr), response_size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onGrpcClose(uint32_t context_id, uint32_t token,
uint32_t status_code, uint32_t status_message_ptr, uint32_t status_message_size) {
getContextBase(context_id)->onGrpcClose(token, static_cast<GrpcStatus>(status_code), std::make_unique<WasmData>(reinterpret_cast<char*>(status_message_ptr), status_message_size));
}
extern "C" EMSCRIPTEN_KEEPALIVE void proxy_onQueueReady(uint32_t context_id, uint32_t token) {
getRootContext(context_id)->onQueueReady(token);
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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.
//
#if URHO3D_PLUGINS
#define CR_HOST
#include <atomic>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/Thread.h>
#include <Urho3D/Engine/PluginApplication.h>
#include <Urho3D/IO/File.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <EditorEvents.h>
#include "Editor.h"
#include "PluginManager.h"
#include "EditorEventsPrivate.h"
namespace Urho3D
{
#if __linux__
static const char* platformDynamicLibrarySuffix = ".so";
#elif _WIN32
static const char* platformDynamicLibrarySuffix = ".dll";
#elif __APPLE__
static const char* platformDynamicLibrarySuffix = ".dylib";
#else
# error Unsupported platform.
#endif
#if URHO3D_CSHARP && URHO3D_PLUGINS
struct DomainManagerInterface
{
void* handle;
bool(*LoadPlugin)(void* handle, const char* path);
void(*SetReloading)(void* handle, bool reloading);
bool(*GetReloading)(void* handle);
};
static std::atomic_bool managedInterfaceSet{false};
static DomainManagerInterface managedInterface_;
///
extern "C" URHO3D_EXPORT_API void ParseArgumentsC(int argc, char** argv) { ParseArguments(argc, argv); }
///
extern "C" URHO3D_EXPORT_API Application* CreateEditorApplication(Context* context) { return new Editor(context); }
/// Update a pointer to a struct that facilitates interop between native code and a .net runtime manager object. Will be called every time .net code is reloaded.
extern "C" URHO3D_EXPORT_API void SetManagedRuntimeInterface(DomainManagerInterface* managedInterface)
{
managedInterface_ = *managedInterface;
managedInterfaceSet = true;
}
#endif
Plugin::Plugin(Context* context)
: Object(context)
{
}
bool Plugin::Unload()
{
if (type_ == PLUGIN_NATIVE)
{
cr_plugin_close(nativeContext_);
nativeContext_.userdata = nullptr;
return true;
}
#if URHO3D_CSHARP
else if (type_ == PLUGIN_MANAGED)
{
// Managed plugin unloading requires to tear down entire AppDomain and recreate it. Instruct main .net thread to
// do that and wait.
managedInterfaceSet = false;
managedInterface_.SetReloading(managedInterface_.handle, true);
managedInterface_.handle = nullptr;
// Wait for AppDomain reload.
while (!managedInterfaceSet)
Time::Sleep(0);
return true;
}
#endif
return false;
}
PluginManager::PluginManager(Context* context)
: Object(context)
{
CleanUp();
SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) { OnEndFrame(); });
SubscribeToEvent(E_SIMULATIONSTART, [this](StringHash, VariantMap&) {
for (auto& plugin : plugins_)
{
if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)
reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Start();
}
});
SubscribeToEvent(E_SIMULATIONSTOP, [this](StringHash, VariantMap&) {
for (auto& plugin : plugins_)
{
if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)
reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Stop();
}
});
}
PluginType PluginManager::GetPluginType(const String& path)
{
File file(context_);
if (!file.Open(path, FILE_READ))
return PLUGIN_INVALID;
// This function implements a naive check for plugin validity. Proper check would parse executable headers and look
// for relevant exported function names.
#if __linux__
// ELF magic
if (path.EndsWith(".so"))
{
if (file.ReadUInt() == 0x464C457F)
{
file.Seek(0);
String buf{ };
buf.Resize(file.GetSize());
file.Read(&buf[0], file.GetSize());
auto pos = buf.Find("cr_main");
// Function names are preceeded with 0 in elf files.
if (pos != String::NPOS && buf[pos - 1] == 0)
return PLUGIN_NATIVE;
}
}
#endif
file.Seek(0);
if (path.EndsWith(".dll"))
{
if (file.ReadShort() == 0x5A4D)
{
#if _WIN32
// But only on windows we check if PE file is a native plugin
file.Seek(0);
String buf{};
buf.Resize(file.GetSize());
file.Read(&buf[0], file.GetSize());
auto pos = buf.Find("cr_main");
// Function names are preceeded with 2 byte hint which is preceeded with 0 in PE files.
if (pos != String::NPOS && buf[pos - 3] == 0)
return PLUGIN_NATIVE;
#endif
// PE files are handled on all platforms because managed executables are PE files.
file.Seek(0x3C);
auto e_lfanew = file.ReadUInt();
#if URHO3D_64BIT
const auto netMetadataRvaOffset = 0xF8;
#else
const auto netMetadataRvaOffset = 0xE8;
#endif
file.Seek(e_lfanew + netMetadataRvaOffset); // Seek to .net metadata directory rva
if (file.ReadUInt() != 0)
return PLUGIN_MANAGED;
}
}
if (path.EndsWith(".dylib"))
{
// TODO: MachO file support.
}
return PLUGIN_INVALID;
}
Plugin* PluginManager::Load(const String& name)
{
#if URHO3D_PLUGINS
if (Plugin* loaded = GetPlugin(name))
return loaded;
CleanUp();
String pluginPath = NameToPath(name);
if (pluginPath.Empty())
return nullptr;
SharedPtr<Plugin> plugin(new Plugin(context_));
plugin->type_ = GetPluginType(pluginPath);
if (plugin->type_ == PLUGIN_NATIVE)
{
if (cr_plugin_load(plugin->nativeContext_, pluginPath.CString()))
{
plugin->nativeContext_.userdata = context_;
plugin->name_ = name;
plugin->path_ = pluginPath;
plugins_.Push(plugin);
return plugin.Get();
}
else
URHO3D_LOGWARNINGF("Failed loading native plugin \"%s\".", name.CString());
}
#if URHO3D_CSHARP
else if (plugin->type_ == PLUGIN_MANAGED)
{
if (managedInterface_.LoadPlugin(managedInterface_.handle, pluginPath.CString()))
{
plugin->name_ = name;
plugin->path_ = pluginPath;
plugins_.Push(plugin);
return plugin.Get();
}
}
#endif
#endif
return nullptr;
}
void PluginManager::Unload(Plugin* plugin)
{
if (plugin == nullptr)
return;
auto it = plugins_.Find(SharedPtr<Plugin>(plugin));
if (it == plugins_.End())
{
URHO3D_LOGERRORF("Plugin %s was never loaded.", plugin->name_.CString());
return;
}
plugin->unloading_ = true;
}
void PluginManager::OnEndFrame()
{
#if URHO3D_PLUGINS
for (auto it = plugins_.Begin(); it != plugins_.End();)
{
Plugin* plugin = it->Get();
if (plugin->unloading_)
{
SendEvent(E_EDITORUSERCODERELOADSTART);
// Actual unload
plugin->Unload();
if (plugin->type_ == PLUGIN_MANAGED)
{
// Now load back all managed plugins except this one.
for (auto& plug : plugins_)
{
if (plug == plugin || plug->type_ == PLUGIN_NATIVE)
continue;
managedInterface_.LoadPlugin(managedInterface_.handle, plug->path_.CString());
}
}
SendEvent(E_EDITORUSERCODERELOADEND);
URHO3D_LOGINFOF("Plugin %s was unloaded.", plugin->name_.CString());
it = plugins_.Erase(it);
}
else if (plugin->type_ == PLUGIN_NATIVE && plugin->nativeContext_.userdata)
{
bool reloading = cr_plugin_changed(plugin->nativeContext_);
if (reloading)
SendEvent(E_EDITORUSERCODERELOADSTART);
if (cr_plugin_update(plugin->nativeContext_) != 0)
{
URHO3D_LOGERRORF("Processing plugin \"%s\" failed and it was unloaded.",
GetFileNameAndExtension(plugin->name_).CString());
cr_plugin_close(plugin->nativeContext_);
plugin->nativeContext_.userdata = nullptr;
continue;
}
if (reloading)
{
SendEvent(E_EDITORUSERCODERELOADEND);
if (plugin->nativeContext_.userdata != nullptr)
{
URHO3D_LOGINFOF("Loaded plugin \"%s\" version %d.",
GetFileNameAndExtension(plugin->name_).CString(), plugin->nativeContext_.version);
}
}
it++;
}
else
it++;
}
#endif
}
void PluginManager::CleanUp(String directory)
{
if (directory.Empty())
directory = GetFileSystem()->GetProgramDir();
if (!GetFileSystem()->DirExists(directory))
return;
StringVector files;
GetFileSystem()->ScanDir(files, directory, "*.*", SCAN_FILES, false);
for (const String& file : files)
{
bool possiblyPlugin = false;
#if __linux__
possiblyPlugin |= file.EndsWith(".so");
#endif
#if __APPLE__
possiblyPlugin |= file.EndsWith(".dylib");
#endif
possiblyPlugin |= file.EndsWith(".dll");
if (possiblyPlugin)
{
String name = GetFileName(file);
if (IsDigit(static_cast<unsigned int>(name.Back())))
GetFileSystem()->Delete(ToString("%s/%s", directory.CString(), file.CString()));
}
}
}
Plugin* PluginManager::GetPlugin(const String& name)
{
for (auto it = plugins_.Begin(); it != plugins_.End(); it++)
{
if (it->Get()->name_ == name)
return it->Get();
}
return nullptr;
}
String PluginManager::NameToPath(const String& name) const
{
FileSystem* fs = GetFileSystem();
String result;
#if __linux__ || __APPLE__
result = ToString("%slib%s%s", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);
if (fs->FileExists(result))
return result;
#endif
#if !_WIN32
result = ToString("%s%s%s", fs->GetProgramDir().CString(), name.CString(), ".dll");
if (fs->FileExists(result))
return result;
#endif
result = ToString("%s%s%s", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);
if (fs->FileExists(result))
return result;
return String::EMPTY;
}
String PluginManager::PathToName(const String& path)
{
if (path.EndsWith(platformDynamicLibrarySuffix))
{
String name = GetFileName(path);
#if __linux__ || __APPLE__
if (name.StartsWith("lib"))
name = name.Substring(3);
return name;
#endif
}
else if (path.EndsWith(".dll"))
return GetFileName(path);
return String::EMPTY;
}
PluginManager::~PluginManager()
{
for (auto& plugin : plugins_)
plugin->Unload();
}
}
#endif
<commit_msg>Editor: Fix plugin (un)loading on windows.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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.
//
#if URHO3D_PLUGINS
#define CR_HOST
#include <atomic>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/Thread.h>
#include <Urho3D/Engine/PluginApplication.h>
#include <Urho3D/IO/File.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <EditorEvents.h>
#include "Editor.h"
#include "PluginManager.h"
#include "EditorEventsPrivate.h"
namespace Urho3D
{
#if __linux__
static const char* platformDynamicLibrarySuffix = ".so";
#elif _WIN32
static const char* platformDynamicLibrarySuffix = ".dll";
#elif __APPLE__
static const char* platformDynamicLibrarySuffix = ".dylib";
#else
# error Unsupported platform.
#endif
#if URHO3D_CSHARP && URHO3D_PLUGINS
struct DomainManagerInterface
{
void* handle;
bool(*LoadPlugin)(void* handle, const char* path);
void(*SetReloading)(void* handle, bool reloading);
bool(*GetReloading)(void* handle);
};
static std::atomic_bool managedInterfaceSet{false};
static DomainManagerInterface managedInterface_;
///
extern "C" URHO3D_EXPORT_API void ParseArgumentsC(int argc, char** argv) { ParseArguments(argc, argv); }
///
extern "C" URHO3D_EXPORT_API Application* CreateEditorApplication(Context* context) { return new Editor(context); }
/// Update a pointer to a struct that facilitates interop between native code and a .net runtime manager object. Will be called every time .net code is reloaded.
extern "C" URHO3D_EXPORT_API void SetManagedRuntimeInterface(DomainManagerInterface* managedInterface)
{
managedInterface_ = *managedInterface;
managedInterfaceSet = true;
}
#endif
Plugin::Plugin(Context* context)
: Object(context)
{
}
bool Plugin::Unload()
{
if (type_ == PLUGIN_NATIVE)
{
cr_plugin_close(nativeContext_);
nativeContext_.userdata = nullptr;
return true;
}
#if URHO3D_CSHARP
else if (type_ == PLUGIN_MANAGED)
{
// Managed plugin unloading requires to tear down entire AppDomain and recreate it. Instruct main .net thread to
// do that and wait.
managedInterfaceSet = false;
managedInterface_.SetReloading(managedInterface_.handle, true);
managedInterface_.handle = nullptr;
// Wait for AppDomain reload.
while (!managedInterfaceSet)
Time::Sleep(0);
return true;
}
#endif
return false;
}
PluginManager::PluginManager(Context* context)
: Object(context)
{
CleanUp();
SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) { OnEndFrame(); });
SubscribeToEvent(E_SIMULATIONSTART, [this](StringHash, VariantMap&) {
for (auto& plugin : plugins_)
{
if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)
reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Start();
}
});
SubscribeToEvent(E_SIMULATIONSTOP, [this](StringHash, VariantMap&) {
for (auto& plugin : plugins_)
{
if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)
reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Stop();
}
});
}
PluginType PluginManager::GetPluginType(const String& path)
{
File file(context_);
if (!file.Open(path, FILE_READ))
return PLUGIN_INVALID;
// This function implements a naive check for plugin validity. Proper check would parse executable headers and look
// for relevant exported function names.
#if __linux__
// ELF magic
if (path.EndsWith(".so"))
{
if (file.ReadUInt() == 0x464C457F)
{
file.Seek(0);
String buf{ };
buf.Resize(file.GetSize());
file.Read(&buf[0], file.GetSize());
auto pos = buf.Find("cr_main");
// Function names are preceeded with 0 in elf files.
if (pos != String::NPOS && buf[pos - 1] == 0)
return PLUGIN_NATIVE;
}
}
#endif
file.Seek(0);
if (path.EndsWith(".dll"))
{
if (file.ReadShort() == 0x5A4D)
{
#if _WIN32
// But only on windows we check if PE file is a native plugin
file.Seek(0);
String buf{};
buf.Resize(file.GetSize());
file.Read(&buf[0], file.GetSize());
auto pos = buf.Find("cr_main");
// Function names are preceeded with 2 byte hint which is preceeded with 0 in PE files.
if (pos != String::NPOS && buf[pos - 3] == 0)
return PLUGIN_NATIVE;
#endif
// PE files are handled on all platforms because managed executables are PE files.
file.Seek(0x3C);
auto e_lfanew = file.ReadUInt();
#if URHO3D_64BIT
const auto netMetadataRvaOffset = 0xF8;
#else
const auto netMetadataRvaOffset = 0xE8;
#endif
file.Seek(e_lfanew + netMetadataRvaOffset); // Seek to .net metadata directory rva
if (file.ReadUInt() != 0)
return PLUGIN_MANAGED;
else
return PLUGIN_NATIVE;
}
}
if (path.EndsWith(".dylib"))
{
// TODO: MachO file support.
}
return PLUGIN_INVALID;
}
Plugin* PluginManager::Load(const String& name)
{
#if URHO3D_PLUGINS
if (Plugin* loaded = GetPlugin(name))
return loaded;
CleanUp();
String pluginPath = NameToPath(name);
if (pluginPath.Empty())
return nullptr;
SharedPtr<Plugin> plugin(new Plugin(context_));
plugin->type_ = GetPluginType(pluginPath);
if (plugin->type_ == PLUGIN_NATIVE)
{
if (cr_plugin_load(plugin->nativeContext_, pluginPath.CString()))
{
plugin->nativeContext_.userdata = context_;
plugin->name_ = name;
plugin->path_ = pluginPath;
plugins_.Push(plugin);
return plugin.Get();
}
else
URHO3D_LOGWARNINGF("Failed loading native plugin \"%s\".", name.CString());
}
#if URHO3D_CSHARP
else if (plugin->type_ == PLUGIN_MANAGED)
{
if (managedInterface_.LoadPlugin(managedInterface_.handle, pluginPath.CString()))
{
plugin->name_ = name;
plugin->path_ = pluginPath;
plugins_.Push(plugin);
return plugin.Get();
}
}
#endif
#endif
return nullptr;
}
void PluginManager::Unload(Plugin* plugin)
{
if (plugin == nullptr)
return;
auto it = plugins_.Find(SharedPtr<Plugin>(plugin));
if (it == plugins_.End())
{
URHO3D_LOGERRORF("Plugin %s was never loaded.", plugin->name_.CString());
return;
}
plugin->unloading_ = true;
}
void PluginManager::OnEndFrame()
{
#if URHO3D_PLUGINS
for (auto it = plugins_.Begin(); it != plugins_.End();)
{
Plugin* plugin = it->Get();
if (plugin->unloading_)
{
SendEvent(E_EDITORUSERCODERELOADSTART);
// Actual unload
plugin->Unload();
if (plugin->type_ == PLUGIN_MANAGED)
{
// Now load back all managed plugins except this one.
for (auto& plug : plugins_)
{
if (plug == plugin || plug->type_ == PLUGIN_NATIVE)
continue;
managedInterface_.LoadPlugin(managedInterface_.handle, plug->path_.CString());
}
}
SendEvent(E_EDITORUSERCODERELOADEND);
URHO3D_LOGINFOF("Plugin %s was unloaded.", plugin->name_.CString());
it = plugins_.Erase(it);
}
else if (plugin->type_ == PLUGIN_NATIVE && plugin->nativeContext_.userdata)
{
bool reloading = cr_plugin_changed(plugin->nativeContext_);
if (reloading)
SendEvent(E_EDITORUSERCODERELOADSTART);
if (cr_plugin_update(plugin->nativeContext_) != 0)
{
URHO3D_LOGERRORF("Processing plugin \"%s\" failed and it was unloaded.",
GetFileNameAndExtension(plugin->name_).CString());
cr_plugin_close(plugin->nativeContext_);
plugin->nativeContext_.userdata = nullptr;
continue;
}
if (reloading)
{
SendEvent(E_EDITORUSERCODERELOADEND);
if (plugin->nativeContext_.userdata != nullptr)
{
URHO3D_LOGINFOF("Loaded plugin \"%s\" version %d.",
GetFileNameAndExtension(plugin->name_).CString(), plugin->nativeContext_.version);
}
}
it++;
}
else
it++;
}
#endif
}
void PluginManager::CleanUp(String directory)
{
if (directory.Empty())
directory = GetFileSystem()->GetProgramDir();
if (!GetFileSystem()->DirExists(directory))
return;
StringVector files;
GetFileSystem()->ScanDir(files, directory, "*.*", SCAN_FILES, false);
for (const String& file : files)
{
bool possiblyPlugin = false;
#if __linux__
possiblyPlugin |= file.EndsWith(".so");
#endif
#if __APPLE__
possiblyPlugin |= file.EndsWith(".dylib");
#endif
possiblyPlugin |= file.EndsWith(".dll");
if (possiblyPlugin)
{
String name = GetFileName(file);
if (IsDigit(static_cast<unsigned int>(name.Back())))
GetFileSystem()->Delete(ToString("%s/%s", directory.CString(), file.CString()));
}
}
}
Plugin* PluginManager::GetPlugin(const String& name)
{
for (auto it = plugins_.Begin(); it != plugins_.End(); it++)
{
if (it->Get()->name_ == name)
return it->Get();
}
return nullptr;
}
String PluginManager::NameToPath(const String& name) const
{
FileSystem* fs = GetFileSystem();
String result;
#if __linux__ || __APPLE__
result = ToString("%slib%s%s", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);
if (fs->FileExists(result))
return result;
#endif
#if !_WIN32
result = ToString("%s%s%s", fs->GetProgramDir().CString(), name.CString(), ".dll");
if (fs->FileExists(result))
return result;
#endif
result = ToString("%s%s%s", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);
if (fs->FileExists(result))
return result;
return String::EMPTY;
}
String PluginManager::PathToName(const String& path)
{
#if !_WIN32
if (path.EndsWith(platformDynamicLibrarySuffix))
{
String name = GetFileName(path);
#if __linux__ || __APPLE__
if (name.StartsWith("lib"))
name = name.Substring(3);
#endif
return name;
}
else
#endif
if (path.EndsWith(".dll"))
return GetFileName(path);
return String::EMPTY;
}
PluginManager::~PluginManager()
{
for (auto& plugin : plugins_)
plugin->Unload();
}
}
#endif
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "common/tag.h"
#include "apiTypesV2/Entity.h"
#include "ngsi10/QueryContextResponse.h"
/* ****************************************************************************
*
* Entity::Entity -
*/
Entity::Entity()
{
}
/* ****************************************************************************
*
* Entity::~Entity -
*/
Entity::~Entity()
{
release();
}
/* ****************************************************************************
*
* Entity::render -
*/
std::string Entity::render(ConnectionInfo* ciP, RequestType requestType, bool comma)
{
if ((errorCode.description == "") && ((errorCode.error == "OK") || (errorCode.error == "")))
{
std::string out = "{";
out += JSON_VALUE("id", id);
if (type != "")
{
out += ",";
out += JSON_VALUE("type", type);
}
if (attributeVector.size() != 0)
{
out += ",";
out += attributeVector.toJson(true);
}
out += "}";
if (comma)
{
out += ",";
}
return out;
}
return errorCode.toJson(true);
}
/* ****************************************************************************
*
* Entity::check -
*/
std::string Entity::check(ConnectionInfo* ciP, RequestType requestType)
{
if (id == "")
{
return "No Entity ID";
}
return "OK";
}
/* ****************************************************************************
*
* Entity::present -
*/
void Entity::present(const std::string& indent)
{
LM_F(("%sid: %s", indent.c_str(), id.c_str()));
LM_F(("%stype: %s", indent.c_str(), type.c_str()));
LM_F(("%sisPattern: %s", indent.c_str(), isPattern.c_str()));
attributeVector.present(indent + " ");
}
/* ****************************************************************************
*
* Entity::fill -
*/
void Entity::fill(const std::string& _id, const std::string& _type, const std::string& _isPattern, ContextAttributeVector* aVec)
{
id = _id;
type = _type;
isPattern = _isPattern;
attributeVector.fill(aVec);
}
void Entity::fill(QueryContextResponse* qcrsP)
{
if (qcrsP->errorCode.code != SccOk)
{
//
// If no entity has been found, we respond with a 404 NOT FOUND
// If any other error - use the error for the response
//
errorCode.fill(qcrsP->errorCode);
}
else if (qcrsP->contextElementResponseVector.size()>1)
{
//
// If there are more than one entity, we return an error
// TODO: determine error for this case
//
errorCode.fill("Many entities with that ID", "/v2/entities?id="+qcrsP->contextElementResponseVector[0]->contextElement.entityId.id);
}
else
{
ContextElement* ceP = &qcrsP->contextElementResponseVector[0]->contextElement;
this->fill(ceP->entityId.id, ceP->entityId.type, ceP->entityId.isPattern, &ceP->contextAttributeVector);
}
}
/* ****************************************************************************
*
* Entity::release -
*/
void Entity::release(void)
{
attributeVector.release();
}
<commit_msg>Remove old TODO comment<commit_after>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "common/tag.h"
#include "apiTypesV2/Entity.h"
#include "ngsi10/QueryContextResponse.h"
/* ****************************************************************************
*
* Entity::Entity -
*/
Entity::Entity()
{
}
/* ****************************************************************************
*
* Entity::~Entity -
*/
Entity::~Entity()
{
release();
}
/* ****************************************************************************
*
* Entity::render -
*/
std::string Entity::render(ConnectionInfo* ciP, RequestType requestType, bool comma)
{
if ((errorCode.description == "") && ((errorCode.error == "OK") || (errorCode.error == "")))
{
std::string out = "{";
out += JSON_VALUE("id", id);
if (type != "")
{
out += ",";
out += JSON_VALUE("type", type);
}
if (attributeVector.size() != 0)
{
out += ",";
out += attributeVector.toJson(true);
}
out += "}";
if (comma)
{
out += ",";
}
return out;
}
return errorCode.toJson(true);
}
/* ****************************************************************************
*
* Entity::check -
*/
std::string Entity::check(ConnectionInfo* ciP, RequestType requestType)
{
if (id == "")
{
return "No Entity ID";
}
return "OK";
}
/* ****************************************************************************
*
* Entity::present -
*/
void Entity::present(const std::string& indent)
{
LM_F(("%sid: %s", indent.c_str(), id.c_str()));
LM_F(("%stype: %s", indent.c_str(), type.c_str()));
LM_F(("%sisPattern: %s", indent.c_str(), isPattern.c_str()));
attributeVector.present(indent + " ");
}
/* ****************************************************************************
*
* Entity::fill -
*/
void Entity::fill(const std::string& _id, const std::string& _type, const std::string& _isPattern, ContextAttributeVector* aVec)
{
id = _id;
type = _type;
isPattern = _isPattern;
attributeVector.fill(aVec);
}
void Entity::fill(QueryContextResponse* qcrsP)
{
if (qcrsP->errorCode.code != SccOk)
{
//
// If no entity has been found, we respond with a 404 NOT FOUND
// If any other error - use the error for the response
//
errorCode.fill(qcrsP->errorCode);
}
else if (qcrsP->contextElementResponseVector.size()>1)
{
//
// If there are more than one entity, we return an error
//
errorCode.fill("Many entities with that ID", "/v2/entities?id="+qcrsP->contextElementResponseVector[0]->contextElement.entityId.id);
}
else
{
ContextElement* ceP = &qcrsP->contextElementResponseVector[0]->contextElement;
this->fill(ceP->entityId.id, ceP->entityId.type, ceP->entityId.isPattern, &ceP->contextAttributeVector);
}
}
/* ****************************************************************************
*
* Entity::release -
*/
void Entity::release(void)
{
attributeVector.release();
}
<|endoftext|> |
<commit_before>
/* Include required header */
#include "CoolProp.h"
#include "HumidAirProp.h"
#include "WolframLibrary.h"
/* Return the version of Library Link */
extern "C" DLLEXPORT mint WolframLibrary_getVersion( ) {
return WolframLibraryVersion;
}
/* Initialize Library */
extern "C" DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {
return LIBRARY_NO_ERROR;
}
/* Uninitialize Library */
extern "C" DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {
return;
}
/* Adds one to the input, returning the result */
extern "C" DLLEXPORT int plus_one( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
mreal I1;
I1 = MArgument_getReal(Args[0]);
MArgument_setReal(Res, I1+1.0);
return LIBRARY_NO_ERROR;
}
extern "C" DLLEXPORT int PropsSI( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
if (Argc != 6){ return LIBRARY_FUNCTION_ERROR; }
char *outstring = MArgument_getUTF8String(Args[0]);
char *In1string = MArgument_getUTF8String(Args[1]);
mreal In1val = MArgument_getReal(Args[2]);
char *In2string = MArgument_getUTF8String(Args[3]);
mreal In2val = MArgument_getReal(Args[4]);
char *Fluidstring = MArgument_getUTF8String(Args[5]);
// PropsS version takes all strings, not single-character inputs
double val = CoolProp::PropsSI(outstring,In1string,(double)In1val,In2string,(double)In2val,Fluidstring);
MArgument_setReal(Res, val);
return LIBRARY_NO_ERROR;
}
extern "C" DLLEXPORT int HAPropsSI( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
if (Argc != 7){ return LIBRARY_FUNCTION_ERROR; }
char *outstring = MArgument_getUTF8String(Args[0]);
char *In1string = MArgument_getUTF8String(Args[1]);
mreal In1val = MArgument_getReal(Args[2]);
char *In2string = MArgument_getUTF8String(Args[3]);
mreal In2val = MArgument_getReal(Args[4]);
char *In3string = MArgument_getUTF8String(Args[5]);
mreal In3val = MArgument_getReal(Args[6]);
double val = HumidAir::HAPropsSI(outstring,In1string,(double)In1val,In2string,(double)In2val,In3string,(double)In3val);
MArgument_setReal(Res, val);
return LIBRARY_NO_ERROR;
}
<commit_msg>Free input strings in Mathematica interface (#1761)<commit_after>
/* Include required header */
#include "CoolProp.h"
#include "HumidAirProp.h"
#include "WolframLibrary.h"
/* Return the version of Library Link */
extern "C" DLLEXPORT mint WolframLibrary_getVersion( ) {
return WolframLibraryVersion;
}
/* Initialize Library */
extern "C" DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {
return LIBRARY_NO_ERROR;
}
/* Uninitialize Library */
extern "C" DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {
return;
}
/* Adds one to the input, returning the result */
extern "C" DLLEXPORT int plus_one( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
if (Argc != 1) return LIBRARY_FUNCTION_ERROR;
double x = MArgument_getReal(Args[0]);
MArgument_setReal(Res, x + 1.0);
return LIBRARY_NO_ERROR;
}
extern "C" DLLEXPORT int PropsSI( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
if (Argc != 6) return LIBRARY_FUNCTION_ERROR;
char *Output = MArgument_getUTF8String(Args[0]);
char *Name1 = MArgument_getUTF8String(Args[1]);
double Prop1 = MArgument_getReal(Args[2]);
char *Name2 = MArgument_getUTF8String(Args[3]);
double Prop2 = MArgument_getReal(Args[4]);
char *FluidName = MArgument_getUTF8String(Args[5]);
double val = CoolProp::PropsSI(Output, Name1, Prop1, Name2, Prop2, FluidName);
libData->UTF8String_disown(Output);
libData->UTF8String_disown(Name1);
libData->UTF8String_disown(Name2);
libData->UTF8String_disown(FluidName);
MArgument_setReal(Res, val);
return LIBRARY_NO_ERROR;
}
extern "C" DLLEXPORT int HAPropsSI( WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {
if (Argc != 7) return LIBRARY_FUNCTION_ERROR;
char *Output = MArgument_getUTF8String(Args[0]);
char *Name1 = MArgument_getUTF8String(Args[1]);
double Prop1 = MArgument_getReal(Args[2]);
char *Name2 = MArgument_getUTF8String(Args[3]);
double Prop2 = MArgument_getReal(Args[4]);
char *Name3 = MArgument_getUTF8String(Args[5]);
double Prop3 = MArgument_getReal(Args[6]);
double val = HumidAir::HAPropsSI(Output, Name1, Prop1, Name2, Prop2, Name3, Prop3);
libData->UTF8String_disown(Output);
libData->UTF8String_disown(Name1);
libData->UTF8String_disown(Name2);
libData->UTF8String_disown(Name3);
MArgument_setReal(Res, val);
return LIBRARY_NO_ERROR;
}
<|endoftext|> |
<commit_before>#include "object/object.h"
#include "math/intersect.h"
//#define ENABLE_LINEAR_HITTEST
namespace aten
{
bool face::hit(
const ray& r,
real t_min, real t_max,
hitrecord& rec) const
{
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
bool isHit = hit(
param,
v0, v1, v2,
r,
t_min, t_max,
rec);
if (isHit) {
//rec.obj = parent;
rec.obj = (hitable*)this;
if (parent) {
rec.mtrl = (material*)parent->param.mtrl.ptr;
}
}
return isHit;
}
bool face::hit(
const PrimitiveParamter& param,
const vertex& v0,
const vertex& v1,
const vertex& v2,
const ray& r,
real t_min, real t_max,
hitrecord& rec)
{
bool isHit = false;
const auto res = intersertTriangle(r, v0.pos, v1.pos, v2.pos);
if (res.isIntersect) {
if (res.t < rec.t) {
rec.t = res.t;
auto p = r.org + rec.t * r.dir;
// NOTE
// http://d.hatena.ne.jp/Zellij/20131207/p1
// dSWn(barycentric coordinates).
// v0.
// p = (1 - a - b)*v0 + a*v1 + b*v2
rec.p = (1 - res.a - res.b) * v0.pos + res.a * v1.pos + res.b * v2.pos;
rec.normal = (1 - res.a - res.b) * v0.nml + res.a * v1.nml + res.b * v2.nml;
auto uv = (1 - res.a - res.b) * v0.uv + res.a * v1.uv + res.b * v2.uv;
rec.u = uv.x;
rec.v = uv.y;
// tangent coordinate.
rec.du = normalize(getOrthoVector(rec.normal));
rec.dv = normalize(cross(rec.normal, rec.du));
rec.area = param.area;
isHit = true;
}
}
return isHit;
}
void face::build()
{
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
vec3 vmax(
std::max(v0.pos.x, std::max(v1.pos.x, v2.pos.x)),
std::max(v0.pos.y, std::max(v1.pos.y, v2.pos.y)),
std::max(v0.pos.z, std::max(v1.pos.z, v2.pos.z)));
vec3 vmin(
std::min(v0.pos.x, std::min(v1.pos.x, v2.pos.x)),
std::min(v0.pos.y, std::min(v1.pos.y, v2.pos.y)),
std::min(v0.pos.z, std::min(v1.pos.z, v2.pos.z)));
m_aabb.init(vmin, vmax);
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1.pos - v0.pos;
auto e1 = v2.pos - v0.pos;
param.area = real(0.5) * cross(e0, e1).length();
}
vec3 face::getRandomPosOn(sampler* sampler) const
{
// 0 <= a + b <= 1
real a = sampler->nextSample();
real b = sampler->nextSample();
real d = a + b;
if (d > 1) {
a /= d;
b /= d;
}
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
// dSWn(barycentric coordinates).
// v0.
// p = (1 - a - b)*v0 + a*v1 + b*v2
vec3 p = (1 - a - b) * v0.pos + a * v1.pos + b * v2.pos;
return std::move(p);
}
hitable::SamplingPosNormalPdf face::getSamplePosNormalPdf(sampler* sampler) const
{
// 0 <= a + b <= 1
real a = sampler->nextSample();
real b = sampler->nextSample();
real d = a + b;
if (d > 1) {
a /= d;
b /= d;
}
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
// dSWn(barycentric coordinates).
// v0.
// p = (1 - a - b)*v0 + a*v1 + b*v2
vec3 p = (1 - a - b) * v0.pos + a * v1.pos + b * v2.pos;
vec3 n = (1 - a - b) * v0.nml + a * v1.nml + b * v2.nml;
n.normalize();
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1.pos - v0.pos;
auto e1 = v2.pos - v0.pos;
auto area = real(0.5) * cross(e0, e1).length();
return std::move(hitable::SamplingPosNormalPdf(p + n * AT_MATH_EPSILON, n, area));
}
void shape::build()
{
m_node.build(
(bvhnode**)&faces[0],
(uint32_t)faces.size());
m_aabb = m_node.getBoundingbox();
param.area = 0;
for (const auto f : faces) {
param.area += f->param.area;
}
}
bool shape::hit(
const ray& r,
real t_min, real t_max,
hitrecord& rec) const
{
#ifdef ENABLE_LINEAR_HITTEST
bool isHit = false;
hitrecord tmp;
for (auto f : faces) {
hitrecord tmptmp;
if (f->hit(r, t_min, t_max, tmptmp)) {
if (tmptmp.t < tmp.t) {
tmp = tmptmp;
isHit = true;
}
}
}
if (isHit) {
rec = tmp;
}
#else
auto isHit = m_node.hit(r, t_min, t_max, rec);
#endif
if (isHit) {
rec.mtrl = (material*)param.mtrl.ptr;
}
return isHit;
}
void object::build()
{
m_node.build((bvhnode**)&shapes[0], (uint32_t)shapes.size());
param.area = 0;
m_triangles = 0;
for (const auto s : shapes) {
param.area += s->param.area;
m_triangles += (uint32_t)s->faces.size();
}
}
bool object::hit(
const ray& r,
const mat4& mtxL2W,
real t_min, real t_max,
hitrecord& rec) const
{
#ifdef ENABLE_LINEAR_HITTEST
bool isHit = false;
hitrecord tmp;
for (auto s : shapes) {
hitrecord tmptmp;
if (s->hit(r, t_min, t_max, tmptmp)) {
if (tmptmp.t < tmp.t) {
tmp = tmptmp;
isHit = true;
}
}
}
#else
hitrecord tmp;
bool isHit = m_node.hit(r, t_min, t_max, tmp);
#endif
if (isHit) {
rec = tmp;
face* f = (face*)rec.obj;
#if 0
real originalArea = 0;
{
const auto& v0 = f->vtx[0]->pos;
const auto& v1 = f->vtx[1]->pos;
const auto& v2 = f->vtx[2]->pos;
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1 - v0;
auto e1 = v2 - v0;
originalArea = 0.5 * cross(e0, e1).length();
}
real scaledArea = 0;
{
auto v0 = mtxL2W.apply(f->vtx[0]->pos);
auto v1 = mtxL2W.apply(f->vtx[1]->pos);
auto v2 = mtxL2W.apply(f->vtx[2]->pos);
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1 - v0;
auto e1 = v2 - v0;
scaledArea = 0.5 * cross(e0, e1).length();
}
real ratio = scaledArea / originalArea;
#else
vertex v0, v1;
VertexManager::getVertex(v0, f->param.idx[0]);
VertexManager::getVertex(v1, f->param.idx[1]);
real orignalLen = 0;
{
const auto& p0 = v0.pos;
const auto& p1 = v1.pos;
orignalLen = (p1 - p0).length();
}
real scaledLen = 0;
{
auto p0 = mtxL2W.apply(v0.pos);
auto p1 = mtxL2W.apply(v1.pos);
scaledLen = (p1 - p0).length();
}
real ratio = scaledLen / orignalLen;
ratio = ratio * ratio;
#endif
rec.area = param.area * ratio;
// ŏIIɂ́Aςshapen.
rec.obj = f->parent;
}
return isHit;
}
hitable::SamplingPosNormalPdf object::getSamplePosNormalPdf(const mat4& mtxL2W, sampler* sampler) const
{
auto r = sampler->nextSample();
int shapeidx = (int)(r * (shapes.size() - 1));
auto shape = shapes[shapeidx];
r = sampler->nextSample();
int faceidx = (int)(r * (shape->faces.size() - 1));
auto f = shape->faces[faceidx];
vertex v0, v1;
VertexManager::getVertex(v0, f->param.idx[0]);
VertexManager::getVertex(v1, f->param.idx[1]);
real orignalLen = 0;
{
const auto& p0 = v0.pos;
const auto& p1 = v1.pos;
orignalLen = (p1 - p0).length();
}
real scaledLen = 0;
{
auto p0 = mtxL2W.apply(v0.pos);
auto p1 = mtxL2W.apply(v1.pos);
scaledLen = (p1 - p0).length();
}
real ratio = scaledLen / orignalLen;
ratio = ratio * ratio;
auto area = param.area * ratio;
auto tmp = f->getSamplePosNormalPdf(sampler);
hitable::SamplingPosNormalPdf res(
std::get<0>(tmp),
std::get<1>(tmp),
real(1) / area);
return std::move(res);
}
void object::getShapes(
std::vector<ShapeParameter>& shapeparams,
std::vector<PrimitiveParamter>& primparams) const
{
for (auto s : shapes) {
auto shapeParam = s->param;
shapeParam.primid = primparams.size();
shapeParam.primnum = s->faces.size();
shapeParam.mtrl.idx = aten::material::findMaterialIdx((aten::material*)shapeParam.mtrl.ptr);
for (auto f : s->faces) {
auto faceParam = f->param;
faceParam.parent.idx = shapeparams.size();
primparams.push_back(faceParam);
}
shapeparams.push_back(shapeParam);
}
}
}
<commit_msg>Modify that object has bvh which is built with triangles directly.<commit_after>#include "object/object.h"
#include "math/intersect.h"
//#define ENABLE_LINEAR_HITTEST
#define ENABLE_DIRECT_FACE_BVH
namespace aten
{
bool face::hit(
const ray& r,
real t_min, real t_max,
hitrecord& rec) const
{
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
bool isHit = hit(
param,
v0, v1, v2,
r,
t_min, t_max,
rec);
if (isHit) {
//rec.obj = parent;
rec.obj = (hitable*)this;
if (parent) {
rec.mtrl = (material*)parent->param.mtrl.ptr;
}
}
return isHit;
}
bool face::hit(
const PrimitiveParamter& param,
const vertex& v0,
const vertex& v1,
const vertex& v2,
const ray& r,
real t_min, real t_max,
hitrecord& rec)
{
bool isHit = false;
const auto res = intersertTriangle(r, v0.pos, v1.pos, v2.pos);
if (res.isIntersect) {
if (res.t < rec.t) {
rec.t = res.t;
auto p = r.org + rec.t * r.dir;
// NOTE
// http://d.hatena.ne.jp/Zellij/20131207/p1
// dSWn(barycentric coordinates).
// v0.
// p = (1 - a - b)*v0 + a*v1 + b*v2
rec.p = (1 - res.a - res.b) * v0.pos + res.a * v1.pos + res.b * v2.pos;
rec.normal = (1 - res.a - res.b) * v0.nml + res.a * v1.nml + res.b * v2.nml;
auto uv = (1 - res.a - res.b) * v0.uv + res.a * v1.uv + res.b * v2.uv;
rec.u = uv.x;
rec.v = uv.y;
// tangent coordinate.
rec.du = normalize(getOrthoVector(rec.normal));
rec.dv = normalize(cross(rec.normal, rec.du));
rec.area = param.area;
isHit = true;
}
}
return isHit;
}
void face::build()
{
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
vec3 vmax(
std::max(v0.pos.x, std::max(v1.pos.x, v2.pos.x)),
std::max(v0.pos.y, std::max(v1.pos.y, v2.pos.y)),
std::max(v0.pos.z, std::max(v1.pos.z, v2.pos.z)));
vec3 vmin(
std::min(v0.pos.x, std::min(v1.pos.x, v2.pos.x)),
std::min(v0.pos.y, std::min(v1.pos.y, v2.pos.y)),
std::min(v0.pos.z, std::min(v1.pos.z, v2.pos.z)));
m_aabb.init(vmin, vmax);
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1.pos - v0.pos;
auto e1 = v2.pos - v0.pos;
param.area = real(0.5) * cross(e0, e1).length();
}
vec3 face::getRandomPosOn(sampler* sampler) const
{
// 0 <= a + b <= 1
real a = sampler->nextSample();
real b = sampler->nextSample();
real d = a + b;
if (d > 1) {
a /= d;
b /= d;
}
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
// dSWn(barycentric coordinates).
// v0.
// p = (1 - a - b)*v0 + a*v1 + b*v2
vec3 p = (1 - a - b) * v0.pos + a * v1.pos + b * v2.pos;
return std::move(p);
}
hitable::SamplingPosNormalPdf face::getSamplePosNormalPdf(sampler* sampler) const
{
// 0 <= a + b <= 1
real a = sampler->nextSample();
real b = sampler->nextSample();
real d = a + b;
if (d > 1) {
a /= d;
b /= d;
}
vertex v0, v1, v2;
VertexManager::getVertex(v0, param.idx[0]);
VertexManager::getVertex(v1, param.idx[1]);
VertexManager::getVertex(v2, param.idx[2]);
// dSWn(barycentric coordinates).
// v0.
// p = (1 - a - b)*v0 + a*v1 + b*v2
vec3 p = (1 - a - b) * v0.pos + a * v1.pos + b * v2.pos;
vec3 n = (1 - a - b) * v0.nml + a * v1.nml + b * v2.nml;
n.normalize();
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1.pos - v0.pos;
auto e1 = v2.pos - v0.pos;
auto area = real(0.5) * cross(e0, e1).length();
return std::move(hitable::SamplingPosNormalPdf(p + n * AT_MATH_EPSILON, n, area));
}
void shape::build()
{
#ifndef ENABLE_DIRECT_FACE_BVH
m_node.build(
(bvhnode**)&faces[0],
(uint32_t)faces.size());
m_aabb = m_node.getBoundingbox();
#endif
param.area = 0;
for (const auto f : faces) {
param.area += f->param.area;
}
}
bool shape::hit(
const ray& r,
real t_min, real t_max,
hitrecord& rec) const
{
#ifdef ENABLE_LINEAR_HITTEST
bool isHit = false;
hitrecord tmp;
for (auto f : faces) {
hitrecord tmptmp;
if (f->hit(r, t_min, t_max, tmptmp)) {
if (tmptmp.t < tmp.t) {
tmp = tmptmp;
isHit = true;
}
}
}
if (isHit) {
rec = tmp;
}
#else
auto isHit = m_node.hit(r, t_min, t_max, rec);
#endif
if (isHit) {
rec.mtrl = (material*)param.mtrl.ptr;
}
return isHit;
}
void object::build()
{
#ifdef ENABLE_DIRECT_FACE_BVH
std::vector<face*> faces;
for (auto s : shapes) {
for (auto f : s->faces) {
faces.push_back(f);
}
}
m_node.build((bvhnode**)&faces[0], (uint32_t)faces.size());
#else
m_node.build((bvhnode**)&shapes[0], (uint32_t)shapes.size());
#endif
param.area = 0;
m_triangles = 0;
for (const auto s : shapes) {
param.area += s->param.area;
m_triangles += (uint32_t)s->faces.size();
}
}
bool object::hit(
const ray& r,
const mat4& mtxL2W,
real t_min, real t_max,
hitrecord& rec) const
{
#ifdef ENABLE_LINEAR_HITTEST
bool isHit = false;
hitrecord tmp;
for (auto s : shapes) {
hitrecord tmptmp;
if (s->hit(r, t_min, t_max, tmptmp)) {
if (tmptmp.t < tmp.t) {
tmp = tmptmp;
isHit = true;
}
}
}
#else
hitrecord tmp;
bool isHit = m_node.hit(r, t_min, t_max, tmp);
#endif
if (isHit) {
rec = tmp;
face* f = (face*)rec.obj;
#if 0
real originalArea = 0;
{
const auto& v0 = f->vtx[0]->pos;
const auto& v1 = f->vtx[1]->pos;
const auto& v2 = f->vtx[2]->pos;
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1 - v0;
auto e1 = v2 - v0;
originalArea = 0.5 * cross(e0, e1).length();
}
real scaledArea = 0;
{
auto v0 = mtxL2W.apply(f->vtx[0]->pos);
auto v1 = mtxL2W.apply(f->vtx[1]->pos);
auto v2 = mtxL2W.apply(f->vtx[2]->pos);
// Op`̖ʐ = Qӂ̊Oς̒ / 2;
auto e0 = v1 - v0;
auto e1 = v2 - v0;
scaledArea = 0.5 * cross(e0, e1).length();
}
real ratio = scaledArea / originalArea;
#else
vertex v0, v1;
VertexManager::getVertex(v0, f->param.idx[0]);
VertexManager::getVertex(v1, f->param.idx[1]);
real orignalLen = 0;
{
const auto& p0 = v0.pos;
const auto& p1 = v1.pos;
orignalLen = (p1 - p0).length();
}
real scaledLen = 0;
{
auto p0 = mtxL2W.apply(v0.pos);
auto p1 = mtxL2W.apply(v1.pos);
scaledLen = (p1 - p0).length();
}
real ratio = scaledLen / orignalLen;
ratio = ratio * ratio;
#endif
rec.area = param.area * ratio;
// ŏIIɂ́Aςshapen.
rec.obj = f->parent;
}
return isHit;
}
hitable::SamplingPosNormalPdf object::getSamplePosNormalPdf(const mat4& mtxL2W, sampler* sampler) const
{
auto r = sampler->nextSample();
int shapeidx = (int)(r * (shapes.size() - 1));
auto shape = shapes[shapeidx];
r = sampler->nextSample();
int faceidx = (int)(r * (shape->faces.size() - 1));
auto f = shape->faces[faceidx];
vertex v0, v1;
VertexManager::getVertex(v0, f->param.idx[0]);
VertexManager::getVertex(v1, f->param.idx[1]);
real orignalLen = 0;
{
const auto& p0 = v0.pos;
const auto& p1 = v1.pos;
orignalLen = (p1 - p0).length();
}
real scaledLen = 0;
{
auto p0 = mtxL2W.apply(v0.pos);
auto p1 = mtxL2W.apply(v1.pos);
scaledLen = (p1 - p0).length();
}
real ratio = scaledLen / orignalLen;
ratio = ratio * ratio;
auto area = param.area * ratio;
auto tmp = f->getSamplePosNormalPdf(sampler);
hitable::SamplingPosNormalPdf res(
std::get<0>(tmp),
std::get<1>(tmp),
real(1) / area);
return std::move(res);
}
void object::getShapes(
std::vector<ShapeParameter>& shapeparams,
std::vector<PrimitiveParamter>& primparams) const
{
for (auto s : shapes) {
auto shapeParam = s->param;
shapeParam.primid = primparams.size();
shapeParam.primnum = s->faces.size();
shapeParam.mtrl.idx = aten::material::findMaterialIdx((aten::material*)shapeParam.mtrl.ptr);
for (auto f : s->faces) {
auto faceParam = f->param;
faceParam.parent.idx = shapeparams.size();
primparams.push_back(faceParam);
}
shapeparams.push_back(shapeParam);
}
}
}
<|endoftext|> |
<commit_before>//
// SASolver.h
// Procon26
//
// Created by Riya.Liel on 2015/06/04.
// Copyright (c) 2015年 Riya.Liel. All rights reserved.
//
#ifndef __GA_SASolver_
#define __GA_SASolver_
#include<cmath>
template<class _T,int _STime=1000,int _ETime=1,int _Schedule=99>
class SA_Solver{
public:
SA_Solver(_T target):_target(target){}
typename _T::stateType solveAnswer();
void setAux(typename _T::auxType& aux){_aux = aux;}
private:
double getProbability(int e1,int e2,double t){
return e1 <= e2 ? 1.0 : exp( (e1-e2)/t );
}
typename _T::auxType _aux;
_T _target;
};
template<class _T,int _STime,int _ETime,int _Schedule>
typename _T::stateType SA_Solver<_T,_STime,_ETime,_Schedule>::solveAnswer(){
std::random_device _rnd;
std::mt19937 _mt(_rnd());
std::uniform_real_distribution<double> _distribution(0,1);
double current_time=_STime;
int best_eval=0, old_eval=0;
typename _T::stateType old = _target.getState();
typename _T::stateType best_state;
int count=0;
while(current_time >= _ETime){
count++;
_target.turnState();
int next_eval = _target.calcEvalution(_aux);
if(_distribution(_mt) <= getProbability(old_eval,next_eval,current_time)){
if(best_eval < next_eval){
best_state = _target.getState();
best_eval = next_eval;
}
old_eval = next_eval;
}
else _target = old;
current_time *= _Schedule/100.;
}
return best_state;
}
#endif
<commit_msg>[Fixed]fixed Type checking module<commit_after>//
// SASolver.h
// Procon26
//
// Created by Riya.Liel on 2015/06/04.
// Copyright (c) 2015年 Riya.Liel. All rights reserved.
//
#ifndef __GA_SASolver_
#define __GA_SASolver_
#include<cmath>
/* Prototype Definition */
/* Setting default template for arguments algorithm function objects */
/* default argments: Individual selector : Roulette Select Algorithm.
Evalution scaler : Power Scaling Algorithm. */
template<class _T,int _STime=100,int _ETime=1,int _Schedule=99>
class _SA_Solver;
/* To check Individual Class whether or not it extend GA_Base Class*/
template<class _T,int _STime=100,int _ETime=1,int _Schedule=99>
using SA_Solver = typename std::enable_if< std::is_base_of<SA_Base<_T,typename _T::auxType,typename _T::stateType>,
_T
>::value,
_SA_Solver<_T,_STime,_ETime,_Schedule>
> ::type;
template<class _T,int _STime,int _ETime,int _Schedule>
class _SA_Solver{
public:
_SA_Solver(_T target):_target(target){}
typename _T::stateType solveAnswer();
void setAux(typename _T::auxType& aux){_aux = aux;}
private:
double getProbability(int e1,int e2,double t){
return e1 <= e2 ? 1.0 : exp( (e1-e2)/t );
}
typename _T::auxType _aux;
_T _target;
};
template<class _T,int _STime,int _ETime,int _Schedule>
typename _T::stateType _SA_Solver<_T,_STime,_ETime,_Schedule>::solveAnswer(){
std::random_device _rnd;
std::mt19937 _mt(_rnd());
std::uniform_real_distribution<double> _distribution(0,1);
double current_time=_STime;
int best_eval=0, old_eval=0;
typename _T::stateType old = _target.getState();
typename _T::stateType best_state;
while(current_time >= _ETime){
_target.turnState();
int next_eval = _target.calcEvalution(_aux);
if(_distribution(_mt) <= getProbability(old_eval,next_eval,current_time)){
if(best_eval < next_eval){
best_state = _target.getState();
best_eval = next_eval;
}
old_eval = next_eval;
}
else _target = old;
current_time *= _Schedule/100.;
}
return best_state;
}
#endif
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include <direct.h>
#include "Foundation.h"
#include "ModuleManager.h"
#include "HttpUtilities.h"
#include "DebugOperatorNew.h"
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
// for reporting memory leaks upon debug exit
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
// For generating minidump
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#pragma warning(push)
#pragma warning(disable : 4996)
#include <strsafe.h>
#pragma warning(pop)
#endif
#include "MemoryLeakCheck.h"
void setup(Foundation::Framework &fw);
int run(int argc, char **argv);
void options(int argc, char **argv, Foundation::Framework &fw);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers);
#endif
int main (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// set up a debug flag for memory leaks. Output the results to file when the app exits.
// Note that this file is written to the same directory where the executable resides,
// so you can only use this in a development version where you have write access to
// that directory.
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
HANDLE hLogFile = CreateFileW(L"fullmemoryleaklog.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
__try
{
#endif
return_value = run(argc, argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
}
__except(generate_dump(GetExceptionInformation()))
{
}
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
if (hLogFile != INVALID_HANDLE_VALUE)
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);
}
#endif
// Note: We cannot close the file handle manually here. Have to let the OS close it
// after it has printed out the list of leaks to the file.
// CloseHandle(hLogFile);
return return_value;
}
//! post init setup for framework
void setup (Foundation::Framework &fw)
{
// Exclude the login screen from loading
fw.GetModuleManager()->ExcludeModule("LoginScreenModule");
// Exclude window & rendering related stuff, if a fully headless server is desired
//fw.GetModuleManager()->ExcludeModule("ConsoleModule");
//fw.GetModuleManager()->ExcludeModule("QtInputModule");
//fw.GetModuleManager()->ExcludeModule("OgreRenderingModule");
//fw.GetModuleManager()->ExcludeModule("OpenALAudioModule");
//fw.GetModuleManager()->ExcludeModule("UiServiceModule");
}
std::string GetWorkingDirectory()
{
char *buffer = _getcwd( NULL, 0 );
if (buffer)
{
std::string s = buffer;
free(buffer);
return s;
}
return "(null)";
}
int run (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
printf("Starting up server. Current working directory: %s.\n", GetWorkingDirectory().c_str());
// Create application object
#if !defined(_DEBUG) || !defined (_MSC_VER)
try
#endif
{
HttpUtilities::InitializeHttp();
Foundation::Framework fw(argc, argv);
if (fw.Initialized())
{
setup (fw);
fw.Go();
}
HttpUtilities::UninitializeHttp();
}
#if !defined(_DEBUG) || !defined (_MSC_VER)
catch (std::exception& e)
{
Foundation::Platform::Message("An exception has occurred!", e.what());
#if defined(_DEBUG)
throw;
#else
return_value = EXIT_FAILURE;
#endif
}
#endif
return return_value;
}
#if defined(_MSC_VER) && defined(WINDOWS_APP)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Parse Windows command line
std::vector<std::string> arguments;
std::string cmdLine(lpCmdLine);
unsigned i;
unsigned cmdStart = 0;
unsigned cmdEnd = 0;
bool cmd = false;
bool quote = false;
arguments.push_back("server");
for (i = 0; i < cmdLine.length(); ++i)
{
if (cmdLine[i] == '\"')
quote = !quote;
if ((cmdLine[i] == ' ') && (!quote))
{
if (cmd)
{
cmd = false;
cmdEnd = i;
arguments.push_back(cmdLine.substr(cmdStart, cmdEnd-cmdStart));
}
}
else
{
if (!cmd)
{
cmd = true;
cmdStart = i;
}
}
}
if (cmd)
arguments.push_back(cmdLine.substr(cmdStart, i-cmdStart));
std::vector<const char*> argv;
for (int i = 0; i < arguments.size(); ++i)
argv.push_back(arguments[i].c_str());
if (argv.size())
return main(argv.size(), (char**)&argv[0]);
else
return main(0, 0);
}
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers)
{
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
// Can't use Foundation::Application for application name and version,
// since it might have not been initialized yet, or it might have caused
// the exception in the first place
WCHAR* szAppName = L"realXtend";
WCHAR* szVersion = L"Tundra_v0.3.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPathW( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectoryW( szFileName, 0 );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileW(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, 0, 0);
std::wstring message(L"Program ");
message += szAppName;
message += L" encountered an unexpected error.\n\nCrashdump was saved to location:\n";
message += szFileName;
if (bMiniDumpSuccessful)
Foundation::Platform::Message(L"Minidump generated!", message);
else
Foundation::Platform::Message(szAppName, L"Unexpected error was encountered while generating minidump!");
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
<commit_msg>fix GetWorkingDirectory for unix<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#if defined(_MSC_VER)
#include <direct.h>
#define getcwd _getcwd
#else
#include <unistd.h>
#endif
#include <stdio.h>
#include "Foundation.h"
#include "ModuleManager.h"
#include "HttpUtilities.h"
#include "DebugOperatorNew.h"
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
// for reporting memory leaks upon debug exit
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
// For generating minidump
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#pragma warning(push)
#pragma warning(disable : 4996)
#include <strsafe.h>
#pragma warning(pop)
#endif
#include "MemoryLeakCheck.h"
void setup(Foundation::Framework &fw);
int run(int argc, char **argv);
void options(int argc, char **argv, Foundation::Framework &fw);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers);
#endif
int main (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// set up a debug flag for memory leaks. Output the results to file when the app exits.
// Note that this file is written to the same directory where the executable resides,
// so you can only use this in a development version where you have write access to
// that directory.
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
HANDLE hLogFile = CreateFileW(L"fullmemoryleaklog.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
__try
{
#endif
return_value = run(argc, argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
}
__except(generate_dump(GetExceptionInformation()))
{
}
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
if (hLogFile != INVALID_HANDLE_VALUE)
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);
}
#endif
// Note: We cannot close the file handle manually here. Have to let the OS close it
// after it has printed out the list of leaks to the file.
// CloseHandle(hLogFile);
return return_value;
}
//! post init setup for framework
void setup (Foundation::Framework &fw)
{
// Exclude the login screen from loading
fw.GetModuleManager()->ExcludeModule("LoginScreenModule");
// Exclude window & rendering related stuff, if a fully headless server is desired
//fw.GetModuleManager()->ExcludeModule("ConsoleModule");
//fw.GetModuleManager()->ExcludeModule("QtInputModule");
//fw.GetModuleManager()->ExcludeModule("OgreRenderingModule");
//fw.GetModuleManager()->ExcludeModule("OpenALAudioModule");
//fw.GetModuleManager()->ExcludeModule("UiServiceModule");
}
std::string GetWorkingDirectory()
{
char *buffer = getcwd(NULL, 0);
if (buffer)
{
std::string s = buffer;
free(buffer);
return s;
}
return "(null)";
}
int run (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
printf("Starting up server. Current working directory: %s.\n", GetWorkingDirectory().c_str());
// Create application object
#if !defined(_DEBUG) || !defined (_MSC_VER)
try
#endif
{
HttpUtilities::InitializeHttp();
Foundation::Framework fw(argc, argv);
if (fw.Initialized())
{
setup (fw);
fw.Go();
}
HttpUtilities::UninitializeHttp();
}
#if !defined(_DEBUG) || !defined (_MSC_VER)
catch (std::exception& e)
{
Foundation::Platform::Message("An exception has occurred!", e.what());
#if defined(_DEBUG)
throw;
#else
return_value = EXIT_FAILURE;
#endif
}
#endif
return return_value;
}
#if defined(_MSC_VER) && defined(WINDOWS_APP)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Parse Windows command line
std::vector<std::string> arguments;
std::string cmdLine(lpCmdLine);
unsigned i;
unsigned cmdStart = 0;
unsigned cmdEnd = 0;
bool cmd = false;
bool quote = false;
arguments.push_back("server");
for (i = 0; i < cmdLine.length(); ++i)
{
if (cmdLine[i] == '\"')
quote = !quote;
if ((cmdLine[i] == ' ') && (!quote))
{
if (cmd)
{
cmd = false;
cmdEnd = i;
arguments.push_back(cmdLine.substr(cmdStart, cmdEnd-cmdStart));
}
}
else
{
if (!cmd)
{
cmd = true;
cmdStart = i;
}
}
}
if (cmd)
arguments.push_back(cmdLine.substr(cmdStart, i-cmdStart));
std::vector<const char*> argv;
for (int i = 0; i < arguments.size(); ++i)
argv.push_back(arguments[i].c_str());
if (argv.size())
return main(argv.size(), (char**)&argv[0]);
else
return main(0, 0);
}
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers)
{
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
// Can't use Foundation::Application for application name and version,
// since it might have not been initialized yet, or it might have caused
// the exception in the first place
WCHAR* szAppName = L"realXtend";
WCHAR* szVersion = L"Tundra_v0.3.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPathW( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectoryW( szFileName, 0 );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileW(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, 0, 0);
std::wstring message(L"Program ");
message += szAppName;
message += L" encountered an unexpected error.\n\nCrashdump was saved to location:\n";
message += szFileName;
if (bMiniDumpSuccessful)
Foundation::Platform::Message(L"Minidump generated!", message);
else
Foundation::Platform::Message(szAppName, L"Unexpected error was encountered while generating minidump!");
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
// Local VOTCA includes
#include "votca/xtp/cubefile_writer.h"
#include "votca/xtp/amplitude_integration.h"
#include "votca/xtp/density_integration.h"
#include "votca/xtp/regular_grid.h"
namespace votca {
namespace xtp {
std::vector<std::vector<double>> CubeFile_Writer::CalculateValues(
const Orbitals& orb, QMState state, bool dostateonly,
const Regular_Grid& grid) const {
bool do_amplitude = (state.Type().isSingleParticleState());
if (do_amplitude) {
Eigen::VectorXd amplitude;
if (state.Type() == QMStateType::DQPstate) {
Index amplitudeindex = state.StateIdx() - orb.getGWAmin();
amplitude = orb.CalculateQParticleAORepresentation().col(amplitudeindex);
} else {
amplitude = orb.MOs().eigenvectors().col(state.StateIdx());
}
AmplitudeIntegration<Regular_Grid> ampl(grid);
return ampl.IntegrateAmplitude(amplitude);
} else {
Eigen::MatrixXd mat;
if (state.Type().isExciton() && dostateonly) {
std::array<Eigen::MatrixXd, 2> DMAT =
orb.DensityMatrixExcitedState(state);
mat = DMAT[1] - DMAT[0];
} else {
mat = orb.DensityMatrixFull(state);
}
DensityIntegration<Regular_Grid> density(grid);
density.IntegrateDensity(mat);
return density.getDensities();
}
}
std::vector<double> FlattenValues(
const std::vector<std::vector<double>>& gridvalues) {
Index size = 0;
for (const auto& box : gridvalues) {
size += Index(box.size());
}
std::vector<double> result;
result.reserve(size);
for (const auto& box : gridvalues) {
result.insert(result.end(), box.begin(), box.end());
}
return result;
}
void CubeFile_Writer::WriteFile(const std::string& filename,
const Orbitals& orb, QMState state,
bool dostateonly) const {
Regular_Grid grid;
Eigen::Array3d padding = Eigen::Array3d::Ones() * _padding;
AOBasis basis = orb.SetupDftBasis();
XTP_LOG(Log::info, _log) << " Loaded DFT Basis Set " << orb.getDFTbasisName()
<< std::flush;
grid.GridSetup(_steps, padding, orb.QMAtoms(), basis);
XTP_LOG(Log::info, _log) << " Calculating Gridvalues " << std::flush;
auto temp = CalculateValues(orb, state, dostateonly, grid);
std::vector<double> grid_values = FlattenValues(temp);
XTP_LOG(Log::info, _log) << " Calculated Gridvalues " << std::flush;
bool do_amplitude = (state.Type().isSingleParticleState());
std::ofstream out(filename);
if (!out.is_open()) {
throw std::runtime_error("Bad file handle: " + filename);
}
// write cube header
if (state.isTransition()) {
out << boost::format("Transition state: %1$s \n") % state.ToString();
} else if (do_amplitude) {
out << boost::format("%1$s with energy %2$f eV \n") % state.ToString() %
(orb.getExcitedStateEnergy(state) * tools::conv::hrt2ev);
} else {
if (dostateonly) {
out << boost::format(
"Difference electron density of excited state %1$s \n") %
state.ToString();
} else {
out << boost::format("Total electron density of %1$s state\n") %
state.ToString();
}
}
Eigen::Vector3d start = grid.getStartingPoint();
out << "Created by VOTCA-XTP \n";
if (do_amplitude) {
out << boost::format("-%1$lu %2$f %3$f %4$f \n") % orb.QMAtoms().size() %
start.x() % start.y() % start.z();
} else {
out << boost::format("%1$lu %2$f %3$f %4$f \n") % orb.QMAtoms().size() %
start.x() % start.y() % start.z();
}
Eigen::Array<Index, 3, 1> steps = grid.getSteps();
Eigen::Array3d stepsizes = grid.getStepSizes();
out << boost::format("%1$d %2$f 0.0 0.0 \n") % steps.x() % stepsizes.x();
out << boost::format("%1$d 0.0 %2$f 0.0 \n") % steps.y() % stepsizes.y();
out << boost::format("%1$d 0.0 0.0 %2$f \n") % steps.z() % stepsizes.z();
tools::Elements elements;
for (const QMAtom& atom : orb.QMAtoms()) {
double x = atom.getPos().x();
double y = atom.getPos().y();
double z = atom.getPos().z();
std::string element = atom.getElement();
Index atnum = elements.getEleNum(element);
Index crg = atom.getNuccharge();
out << boost::format("%1$d %2$d %3$f %4$f %5$f\n") % atnum % crg % x % y %
z;
}
if (do_amplitude) {
out << boost::format(" 1 %1$d \n") % (state.StateIdx() + 1);
}
Eigen::TensorMap<Eigen::Tensor<double, 3>> gridvalues(
grid_values.data(), steps.z(), steps.y(), steps.x());
for (Index ix = 0; ix < steps.x(); ix++) {
for (Index iy = 0; iy < steps.y(); iy++) {
Index Nrecord = 0;
for (Index iz = 0; iz < steps.z(); iz++) {
out << boost::format("%1$E ") % gridvalues(iz, iy, ix);
Nrecord++;
if (Nrecord == 6 || iz == (steps.z() - 1)) {
out << "\n";
Nrecord = 0;
}
}
}
}
out.close();
}
} // namespace xtp
} // namespace votca
<commit_msg>refactored cubefile_writer<commit_after>/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
// Local VOTCA includes
#include "votca/xtp/cubefile_writer.h"
#include "votca/xtp/amplitude_integration.h"
#include "votca/xtp/density_integration.h"
#include "votca/xtp/regular_grid.h"
namespace votca {
namespace xtp {
std::vector<std::vector<double>> CubeFile_Writer::CalculateValues(
const Orbitals& orb, QMState state, bool dostateonly,
const Regular_Grid& grid) const {
bool do_amplitude = (state.Type().isSingleParticleState());
if (do_amplitude) {
Eigen::VectorXd amplitude;
if (state.Type() == QMStateType::DQPstate) {
Index amplitudeindex = state.StateIdx() - orb.getGWAmin();
amplitude = orb.CalculateQParticleAORepresentation().col(amplitudeindex);
} else {
amplitude = orb.MOs().eigenvectors().col(state.StateIdx());
}
AmplitudeIntegration<Regular_Grid> ampl(grid);
return ampl.IntegrateAmplitude(amplitude);
} else {
Eigen::MatrixXd mat;
if (state.Type().isExciton() && dostateonly) {
mat = orb.DensityMatrixWithoutGS(state);
} else {
mat = orb.DensityMatrixFull(state);
}
DensityIntegration<Regular_Grid> density(grid);
density.IntegrateDensity(mat);
return density.getDensities();
}
}
std::vector<double> FlattenValues(
const std::vector<std::vector<double>>& gridvalues) {
Index size = 0;
for (const auto& box : gridvalues) {
size += Index(box.size());
}
std::vector<double> result;
result.reserve(size);
for (const auto& box : gridvalues) {
result.insert(result.end(), box.begin(), box.end());
}
return result;
}
void CubeFile_Writer::WriteFile(const std::string& filename,
const Orbitals& orb, QMState state,
bool dostateonly) const {
Regular_Grid grid;
Eigen::Array3d padding = Eigen::Array3d::Ones() * _padding;
AOBasis basis = orb.SetupDftBasis();
XTP_LOG(Log::info, _log) << " Loaded DFT Basis Set " << orb.getDFTbasisName()
<< std::flush;
grid.GridSetup(_steps, padding, orb.QMAtoms(), basis);
XTP_LOG(Log::info, _log) << " Calculating Gridvalues " << std::flush;
auto temp = CalculateValues(orb, state, dostateonly, grid);
std::vector<double> grid_values = FlattenValues(temp);
XTP_LOG(Log::info, _log) << " Calculated Gridvalues " << std::flush;
bool do_amplitude = (state.Type().isSingleParticleState());
std::ofstream out(filename);
if (!out.is_open()) {
throw std::runtime_error("Bad file handle: " + filename);
}
// write cube header
if (state.isTransition()) {
out << boost::format("Transition state: %1$s \n") % state.ToString();
} else if (do_amplitude) {
out << boost::format("%1$s with energy %2$f eV \n") % state.ToString() %
(orb.getExcitedStateEnergy(state) * tools::conv::hrt2ev);
} else {
if (dostateonly) {
out << boost::format(
"Difference electron density of excited state %1$s \n") %
state.ToString();
} else {
out << boost::format("Total electron density of %1$s state\n") %
state.ToString();
}
}
Eigen::Vector3d start = grid.getStartingPoint();
out << "Created by VOTCA-XTP \n";
if (do_amplitude) {
out << boost::format("-%1$lu %2$f %3$f %4$f \n") % orb.QMAtoms().size() %
start.x() % start.y() % start.z();
} else {
out << boost::format("%1$lu %2$f %3$f %4$f \n") % orb.QMAtoms().size() %
start.x() % start.y() % start.z();
}
Eigen::Array<Index, 3, 1> steps = grid.getSteps();
Eigen::Array3d stepsizes = grid.getStepSizes();
out << boost::format("%1$d %2$f 0.0 0.0 \n") % steps.x() % stepsizes.x();
out << boost::format("%1$d 0.0 %2$f 0.0 \n") % steps.y() % stepsizes.y();
out << boost::format("%1$d 0.0 0.0 %2$f \n") % steps.z() % stepsizes.z();
tools::Elements elements;
for (const QMAtom& atom : orb.QMAtoms()) {
double x = atom.getPos().x();
double y = atom.getPos().y();
double z = atom.getPos().z();
std::string element = atom.getElement();
Index atnum = elements.getEleNum(element);
Index crg = atom.getNuccharge();
out << boost::format("%1$d %2$d %3$f %4$f %5$f\n") % atnum % crg % x % y %
z;
}
if (do_amplitude) {
out << boost::format(" 1 %1$d \n") % (state.StateIdx() + 1);
}
Eigen::TensorMap<Eigen::Tensor<double, 3>> gridvalues(
grid_values.data(), steps.z(), steps.y(), steps.x());
for (Index ix = 0; ix < steps.x(); ix++) {
for (Index iy = 0; iy < steps.y(); iy++) {
Index Nrecord = 0;
for (Index iz = 0; iz < steps.z(); iz++) {
out << boost::format("%1$E ") % gridvalues(iz, iy, ix);
Nrecord++;
if (Nrecord == 6 || iz == (steps.z() - 1)) {
out << "\n";
Nrecord = 0;
}
}
}
}
out.close();
}
} // namespace xtp
} // namespace votca
<|endoftext|> |
<commit_before>// To find the largest and smallest element in a give
// L, R range in an array of elememts
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
#define SIZE 1002
void min_sparse_table(int b[SIZE][SIZE], int n) {
int y, k;
k = log2(n);
for(int i = 1; i <= k; i++) {
y = (int)(pow(2.0, (double)(i)));
for(int j = 0; j <= n-y; j++)
b[i][j] = min(b[i-1][j] , b[i-1][j+(y/2)]);
}
}
inline int min_query(int b[SIZE][SIZE], int l, int r) {
int k, x;
k = log2(r - l + 1);
x = (int)(pow(2.0,(double)(k))) - 1;
return min(b[k][l],b[k][r-x]);
}
void max_sparse_table(int c[SIZE][SIZE], int n) {
int y, k;
k = log2(n);
for(int i = 1; i <= k; i++) {
y = (int) (pow(2.0,(double)(i)));
for(int j = 0; j <= n-y; j++)
c[i][j] = max(c[i-1][j] , c[i-1][j+(y/2)]);
}
}
inline int max_query(int c[SIZE][SIZE], int l, int r) {
int k, x;
k = log2(r - l + 1);
x = (int)(pow(2.0, (double)(k))) - 1;
return max(c[k][l], c[k][r-x]);
}
int main() {
int N, b[SIZE][SIZE],c[SIZE][SIZE];
int Q, L, R;
printf("Enter N (max 1000): ");
scanf("%d", &N);
printf("Enter elements:\n");
for(int i = 0; i < N; i++) {
scanf("%d", &b[0][i]);
c[0][i] = b[0][i];
}
min_sparse_table(b, N);
max_sparse_table(c, N);
printf("Enter number of L,R queries : ");
scanf("%d", &Q);
for(int i = 0; i < Q; i++) {
printf("Enter L, R (1-based) : ");
scanf("%d %d", &L, &R);
printf("Minimum in range (%d, %d) = %d\n\n",
L-1, R-1, min_query(b, L-1, R-1));
printf("Maximum in range (%d, %d) = %d\n\n",
L-1, R-1, max_query(c, L-1, R-1));
}
return 0;
}<commit_msg>updated size of 2D array fixing Segmentation Fault<commit_after>// To find the largest and smallest element in a give
// L, R range in an array of elememts
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
#define SIZE 1002
#define MAX_LOG2_SIZE 11
void min_sparse_table(int b[MAX_LOG2_SIZE][SIZE], int n) {
int y, k;
k = log2(n);
for(int i = 1; i <= k; i++) {
y = (int)(pow(2.0, (double)(i)));
for(int j = 0; j <= n-y; j++)
b[i][j] = min(b[i-1][j] , b[i-1][j+(y/2)]);
}
}
inline int min_query(int b[MAX_LOG2_SIZE][SIZE], int l, int r) {
int k, x;
k = log2(r - l + 1);
x = (int)(pow(2.0,(double)(k))) - 1;
return min(b[k][l],b[k][r-x]);
}
void max_sparse_table(int c[MAX_LOG2_SIZE][SIZE], int n) {
int y, k;
k = log2(n);
for(int i = 1; i <= k; i++) {
y = (int) (pow(2.0,(double)(i)));
for(int j = 0; j <= n-y; j++)
c[i][j] = max(c[i-1][j] , c[i-1][j+(y/2)]);
}
}
inline int max_query(int c[MAX_LOG2_SIZE][SIZE], int l, int r) {
int k, x;
k = log2(r - l + 1);
x = (int)(pow(2.0, (double)(k))) - 1;
return max(c[k][l], c[k][r-x]);
}
int main() {
int N, b[MAX_LOG2_SIZE][SIZE],c[MAX_LOG2_SIZE][SIZE];
int Q, L, R;
printf("Enter N (max 1000): ");
scanf("%d", &N);
printf("Enter elements:\n");
for(int i = 0; i < N; i++) {
scanf("%d", &b[0][i]);
c[0][i] = b[0][i];
}
min_sparse_table(b, N);
max_sparse_table(c, N);
printf("Enter number of L,R queries : ");
scanf("%d", &Q);
for(int i = 0; i < Q; i++) {
printf("Enter L, R (1-based) : ");
scanf("%d %d", &L, &R);
printf("Minimum in range (%d, %d) = %d\n\n",
L-1, R-1, min_query(b, L-1, R-1));
printf("Maximum in range (%d, %d) = %d\n\n",
L-1, R-1, max_query(c, L-1, R-1));
}
return 0;
}<|endoftext|> |
<commit_before>#include "Limiter.h"
#include "Testing.h"
#include <iostream>
static auto CurrentTime() { return std::chrono::high_resolution_clock::now(); }
static constexpr auto oneSecond = std::chrono::seconds(1);
std::ostream& operator<<(std::ostream& os, HttpResult::Code code)
{
const auto str =
code == HttpResult::Code::Ok ? "Ok (200)" :
code == HttpResult::Code::TooManyRequests ? "Too many requests (429)" :
"Unknown code";
os << str;
return os;
}
template <typename Clock, typename Duration>
std::string millisecondsSinceStart(std::chrono::time_point<Clock, Duration> timepoint)
{
const static auto start = timepoint.time_since_epoch().count();
return std::to_string((timepoint.time_since_epoch().count() - start) / 1'000'000);
}
static auto TestAllRequestsBelowMaxAreAccepted(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto startTime = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxAllowedRps; ++i)
if (CurrentTime() < startTime + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
static auto TestAllRequestsAboveMaxAreDeclined(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto startTime = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxAllowedRps; ++i)
if (CurrentTime() < startTime + oneSecond)
limiter.ValidateRequest();
while (CurrentTime() < startTime + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
}
static auto TestWithPeakLoadInTheBeginning(int maxAllowedRps)
{
const auto startTime = CurrentTime();
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
// Accepting the requests until we hit the limit.
const auto firstAcceptedRequest = CurrentTime();
for (int i = 0; i < maxAllowedRps; ++i)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
// Not accepting more requests within current second.
while (CurrentTime() < startTime + oneSecond)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
}
// Still not accepting requests if less than one second has elapsed after the first request.
if (CurrentTime() < firstAcceptedRequest + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
std::this_thread::sleep_until(firstAcceptedRequest + std::chrono::milliseconds(900));
if (CurrentTime() < firstAcceptedRequest + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
std::this_thread::sleep_until(firstAcceptedRequest + oneSecond + std::chrono::milliseconds(42));
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
static auto TestWithEvenLoad(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto intervalBetweenRequests = oneSecond / (2 * maxAllowedRps);
for (int iterations = 0; iterations < 5; ++iterations)
{
int requestsSent = 0;
const auto startTime = CurrentTime();
while (requestsSent < maxAllowedRps &&
CurrentTime() < startTime + oneSecond)
{
++requestsSent;
const auto result = limiter.ValidateRequest();
if (result != HttpResult::Code::Ok)
std::cout << "iterations = " << iterations << "; requestsSent = " << requestsSent << '\n';
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
std::this_thread::sleep_for(intervalBetweenRequests);
}
const auto lastValidRequestTime = CurrentTime();
while (CurrentTime() < startTime + oneSecond)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
std::this_thread::sleep_for(intervalBetweenRequests);
}
std::this_thread::sleep_until(lastValidRequestTime + oneSecond);
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
}
static auto TestWithAdjacentPeaks(int maxAllowedRps)
{
const auto startTime = CurrentTime();
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(900));
int requestsSent = 0;
while (requestsSent < maxAllowedRps * 0.8)
{
requestsSent++;
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500));
while (requestsSent < maxAllowedRps)
{
requestsSent++;
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
std::cout << "requestsSent == " << requestsSent << '\n';
while (CurrentTime() < startTime + std::chrono::milliseconds(1900))
{
requestsSent++;
const auto result = limiter.ValidateRequest();
if (result != HttpResult::Code::TooManyRequests)
std::cout << "requestsSent == " << requestsSent << '\n';
ASSERT_EQUAL(result, HttpResult::Code::TooManyRequests);
}
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(2000));
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
namespace LimiterSpecs
{
static constexpr int minRPS = 1;
static constexpr int maxRPS = 100'000;
};
int main()
{
try
{
//TestAllRequestsBelowMaxAreAccepted(LimiterSpecs::maxRPS);
//TestAllRequestsAboveMaxAreDeclined(LimiterSpecs::maxRPS);
//TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS);
//TestWithAdjacentPeaks(LimiterSpecs::maxRPS);
TestWithEvenLoad(LimiterSpecs::maxRPS);
std::cout << "All Tests passed successfully\n";
}
catch (AssertionException& e)
{
std::cout << "One or more of tests failed: " << e.what() << '\n';
}
system("pause");
return 0;
}
<commit_msg>Tests - refactor test with peak load at start of the second<commit_after>#include "Limiter.h"
#include "Testing.h"
#include <iostream>
static auto CurrentTime() { return std::chrono::high_resolution_clock::now(); }
static constexpr auto oneSecond = std::chrono::seconds(1);
std::ostream& operator<<(std::ostream& os, HttpResult::Code code)
{
const auto str =
code == HttpResult::Code::Ok ? "Ok (200)" :
code == HttpResult::Code::TooManyRequests ? "Too many requests (429)" :
"Unknown code";
os << str;
return os;
}
template <typename Clock, typename Duration>
std::string millisecondsSinceStart(std::chrono::time_point<Clock, Duration> timepoint)
{
const static auto start = timepoint.time_since_epoch().count();
return std::to_string((timepoint.time_since_epoch().count() - start) / 1'000'000);
}
static auto TestAllRequestsBelowMaxAreAccepted(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto startTime = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxAllowedRps; ++i)
if (CurrentTime() < startTime + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
static auto TestAllRequestsAboveMaxAreDeclined(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto startTime = std::chrono::high_resolution_clock::now();
for (int i = 0; i < maxAllowedRps; ++i)
if (CurrentTime() < startTime + oneSecond)
limiter.ValidateRequest();
while (CurrentTime() < startTime + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
}
struct TimeStamps
{
const std::chrono::time_point<std::chrono::high_resolution_clock> firstAcceptedRequest;
const std::chrono::time_point<std::chrono::high_resolution_clock> lastAcceptedRequest;
};
static auto TestWithPeakLoadInTheBeginning(Limiter& limiter)
{
// Accepting the requests until we hit the limit.
const auto firstAcceptedRequestTime = CurrentTime();
for (int i = 0; i < limiter.maxRPS(); ++i)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
const auto lastAcceptedRequestTime = CurrentTime();
// Not accepting more requests within current second.
while (CurrentTime() < firstAcceptedRequestTime + oneSecond)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
}
// Still not accepting requests if less than one second has elapsed after the first request.
if (CurrentTime() < firstAcceptedRequestTime + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
std::this_thread::sleep_until(firstAcceptedRequestTime + std::chrono::milliseconds(900));
if (CurrentTime() < firstAcceptedRequestTime + oneSecond)
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
return TimeStamps{ firstAcceptedRequestTime, lastAcceptedRequestTime };
}
static auto TestWithPeakLoadInTheBeginning_SingleIteration(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter);
// Herewith we ensure that NOT MORE than maxAllowedRps requests are allowed per second.
// It is possible that the limiter will allow a bit LESS, though, hence this "delta" allowance
// in the assertion below.
constexpr auto delayDueToTimerIssueObtainedEmpirically = std::chrono::milliseconds(42);
std::this_thread::sleep_until(timeStamps.firstAcceptedRequest + oneSecond + delayDueToTimerIssueObtainedEmpirically);
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
static auto TestWithEvenLoad(int maxAllowedRps)
{
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
const auto intervalBetweenRequests = oneSecond / (2 * maxAllowedRps);
for (int iterations = 0; iterations < 5; ++iterations)
{
int requestsSent = 0;
const auto startTime = CurrentTime();
while (requestsSent < maxAllowedRps &&
CurrentTime() < startTime + oneSecond)
{
++requestsSent;
const auto result = limiter.ValidateRequest();
if (result != HttpResult::Code::Ok)
std::cout << "iterations = " << iterations << "; requestsSent = " << requestsSent << '\n';
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
std::this_thread::sleep_for(intervalBetweenRequests);
}
const auto lastValidRequestTime = CurrentTime();
while (CurrentTime() < startTime + oneSecond)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
std::this_thread::sleep_for(intervalBetweenRequests);
}
std::this_thread::sleep_until(lastValidRequestTime + oneSecond);
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
}
static auto TestWithAdjacentPeaks(int maxAllowedRps)
{
const auto startTime = CurrentTime();
Limiter limiter(maxAllowedRps, 100, std::chrono::milliseconds(10));
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(900));
int requestsSent = 0;
while (requestsSent < maxAllowedRps * 0.8)
{
requestsSent++;
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500));
while (requestsSent < maxAllowedRps)
{
requestsSent++;
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
std::cout << "requestsSent == " << requestsSent << '\n';
while (CurrentTime() < startTime + std::chrono::milliseconds(1900))
{
requestsSent++;
const auto result = limiter.ValidateRequest();
if (result != HttpResult::Code::TooManyRequests)
std::cout << "requestsSent == " << requestsSent << '\n';
ASSERT_EQUAL(result, HttpResult::Code::TooManyRequests);
}
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(2000));
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
namespace LimiterSpecs
{
static constexpr int minRPS = 1;
static constexpr int maxRPS = 100'000;
};
int main()
{
try
{
//TestAllRequestsBelowMaxAreAccepted(LimiterSpecs::maxRPS);
//TestAllRequestsAboveMaxAreDeclined(LimiterSpecs::maxRPS);
//TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS);
//TestWithAdjacentPeaks(LimiterSpecs::maxRPS);
TestWithEvenLoad(LimiterSpecs::maxRPS);
std::cout << "All Tests passed successfully\n";
}
catch (AssertionException& e)
{
std::cout << "One or more of tests failed: " << e.what() << '\n';
}
system("pause");
return 0;
}
<|endoftext|> |
<commit_before>// mmap64_unix.hpp
//
#pragma once
#ifndef __SDL_MEMORY_MMAP64_UNIX_HPP__
#define __SDL_MEMORY_MMAP64_UNIX_HPP__
#include "dataserver/common/common.h"
#if defined(SDL_OS_UNIX)
#include <sys/mman.h>
namespace sdl { namespace mmap64_detail {
struct substitution_failure {}; // represent a failure to declare something
template<typename T>
struct substitution_succeeded : std::true_type {};
template<>
struct substitution_succeeded<substitution_failure> : std::false_type {};
struct get_mmap64 {
private:
template<typename X>
static auto check(X const& x) -> decltype(::mmap64(x, 0, 0, 0, 0, 0));
static substitution_failure check(...);
public:
using type = decltype(check(nullptr));
};
template<bool>
struct select_mmap64 {
template<typename... Values>
static void * call(Values&&... params) {
return ::mmap(std::forward<Values>(params)...);
}
};
template<>
struct select_mmap64<true> {
template<typename... Values>
static void * call(Values&&... params) {
return ::mmap64(std::forward<Values>(params)...);
}
};
struct has_mmap64: substitution_succeeded<get_mmap64::type> {};
} // mmap64_detail
using mmap64_t = mmap64_detail::select_mmap64<mmap64_detail::has_mmap64::value>;
} // sdl
#endif // #if defined(SDL_OS_UNIX)
#endif // __SDL_MEMORY_MMAP64_UNIX_HPP__<commit_msg>fix linux build : mmap64<commit_after>// mmap64_unix.hpp
//
#pragma once
#ifndef __SDL_MEMORY_MMAP64_UNIX_HPP__
#define __SDL_MEMORY_MMAP64_UNIX_HPP__
#include "dataserver/common/common.h"
#if defined(SDL_OS_UNIX)
#include <sys/mman.h>
namespace sdl { namespace mmap64_detail {
struct substitution_failure {}; // represent a failure to declare something
template<typename T>
struct substitution_succeeded : std::true_type {};
template<>
struct substitution_succeeded<substitution_failure> : std::false_type {};
struct get_mmap64 {
private:
template<typename X>
static auto check(X const& x) -> decltype(mmap64(x, 0, 0, 0, 0, 0));
static substitution_failure check(...);
public:
using type = decltype(check(nullptr));
};
template<bool>
struct select_mmap64 {
template<typename... Values>
static void * call(Values&&... params) {
return mmap(std::forward<Values>(params)...);
}
};
template<>
struct select_mmap64<true> {
template<typename... Values>
static void * call(Values&&... params) {
return mmap64(std::forward<Values>(params)...);
}
};
struct has_mmap64: substitution_succeeded<get_mmap64::type> {};
} // mmap64_detail
using mmap64_t = mmap64_detail::select_mmap64<mmap64_detail::has_mmap64::value>;
} // sdl
#endif // #if defined(SDL_OS_UNIX)
#endif // __SDL_MEMORY_MMAP64_UNIX_HPP__<|endoftext|> |
<commit_before>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <config.h>
#include "version.hpp"
#include <boost/concept_check.hpp>
#include <iostream>
const char *
get_version ()
{
return PROJECT_VERSION;
}
void
print_version ()
{
std::cout << "Version: " << PROJECT_VERSION << std::endl;
std::cout << "TODO: print modules versions" << std::endl;
}
<commit_msg>version: Print name and version for each found module<commit_after>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <config.h>
#include "version.hpp"
#include <iostream>
#include "modules.hpp"
const char *
get_version ()
{
return PROJECT_VERSION;
}
void
print_version ()
{
kurento::ModuleManager &moduleManager = kurento::getModuleManager();
std::cout << "Version: " << PROJECT_VERSION << std::endl;
if (moduleManager.getModules().size () > 0) {
std::cout << "Found modules:" << std::endl;
for (auto module : moduleManager.getModules() ) {
std::cout << "\tModule: '" << module.second->getName() << "' version '" <<
module.second->getVersion() << "'" << std::endl;
}
}
}
<|endoftext|> |
<commit_before>#include "framework/builder/cfem_framework_builder.h"
#include <fstream>
#include <streambuf>
#include <deal.II/base/mpi.h>
#include "calculator/cell/integrated_fission_source.h"
#include "calculator/cell/total_aggregated_fission_source.h"
#include "convergence/moments/single_moment_checker_l1_norm.h"
#include "convergence/reporter/mpi_noisy.h"
#include "domain/definition.h"
#include "domain/finite_element/finite_element_gaussian.h"
#include "domain/mesh/mesh_cartesian.h"
#include "eigenvalue/k_effective/updater_via_fission_source.h"
#include "formulation/cfem_diffusion_stamper.h"
#include "formulation/scalar/cfem_diffusion.h"
#include "framework/framework.h"
#include "iteration/updater/source_updater_gauss_seidel.h"
#include "iteration/updater/fixed_updater.h"
#include "iteration/initializer/set_fixed_terms_once.h"
#include "iteration/group/group_source_iteration.h"
#include "iteration/outer/outer_power_iteration.h"
#include "material/material_protobuf.h"
#include "problem/parameter_types.h"
#include "convergence/moments/single_moment_checker_l1_norm.h"
#include "convergence/parameters/single_parameter_checker.h"
#include "convergence/final_checker_or_n.h"
#include "quadrature/angular/angular_quadrature_scalar.h"
#include "quadrature/calculators/spherical_harmonic_zeroth_moment.h"
#include "results/output_dealii_vtu.h"
#include "solver/group/single_group_solver.h"
#include "solver/gmres.h"
#include "system/system.h"
#include "system/solution/mpi_group_angular_solution.h"
#include "system/terms/term.h"
#include "system/terms/term_types.h"
#include "system/moments/spherical_harmonic.h"
namespace bart {
namespace framework {
namespace builder {
template <int dim>
std::unique_ptr<FrameworkI> CFEM_FrameworkBuilder<dim>::BuildFramework(
problem::ParametersI &prm,
dealii::ParameterHandler &d2_prm) {
std::cout << "Setting up materials" << std::endl;
std::ifstream mapping_file(prm.MaterialMapFilename());
std::string material_mapping(
(std::istreambuf_iterator<char>(mapping_file)),
std::istreambuf_iterator<char>());
const int n_groups = 1;
MaterialProtobuf materials(d2_prm);
auto cross_sections_ptr = std::make_shared<bart::data::CrossSections>(materials);
std::cout << "Building Finite Element"<< std::endl;
std::shared_ptr<FiniteElement>finite_element_ptr(std::move(BuildFiniteElement(
&prm)));
std::cout << "Building Domain" << std::endl;
std::shared_ptr<Domain> domain_ptr(std::move(BuildDomain(
&prm,finite_element_ptr, material_mapping)));
std::cout << "Setting up domain" << std::endl;
domain_ptr->SetUpMesh().SetUpDOF();
std::cout << "Building Stamper" << std::endl;
std::shared_ptr<CFEMStamper> stamper_ptr(std::move(BuildStamper(
&prm, domain_ptr, finite_element_ptr, cross_sections_ptr)));
std::cout << "Building fixed updater" << std::endl;
auto fixed_updater_ptr = BuildFixedUpdater(stamper_ptr);
std::cout << "Building source updater" << std::endl;
std::shared_ptr<SourceUpdater> source_updater_ptr(
std::move(BuildSourceUpdater(&prm, stamper_ptr)));
std::cout << "Building Initializer" << std::endl;
auto initializer_ptr =
std::make_unique<iteration::initializer::SetFixedTermsOnce>(
std::move(fixed_updater_ptr), prm.NEnergyGroups(), n_groups);
std::cout << "Building single group solver" << std::endl;
auto single_group_solver_ptr = BuildSingleGroupSolver();
std::cout << "Building inner iteration objects" << std::endl;
auto in_group_final_checker = BuildMomentConvergenceChecker(1e-10, 100);
// Build reporter
using Reporter = bart::convergence::reporter::MpiNoisy;
int this_process = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);
auto pout_ptr = std::make_unique<dealii::ConditionalOStream>(std::cout, this_process == 0);
auto reporter = std::make_shared<Reporter>(std::move(pout_ptr));
// Scalar Quadrature
using ScalarQuadrature = quadrature::angular::AngularQuadratureScalar<dim>;
auto quadrature_ptr = std::make_shared<ScalarQuadrature>();
// Moment calculator
using MomentCalculator = quadrature::calculators::SphericalHarmonicZerothMoment<dim>;
auto moment_calculator = std::make_unique<MomentCalculator>(quadrature_ptr);
// Solution group
auto solution_ptr =
std::make_shared<system::solution::MPIGroupAngularSolution>(n_groups);
data::MatrixParameters matrix_param;
domain_ptr->FillMatrixParameters(matrix_param, prm.Discretization());
std::cout << "==Filling solution object" << std::endl;
for (int group = 0; group < n_groups; ++group) {
auto &solution = solution_ptr->operator[](group);
solution.reinit(matrix_param.rows, MPI_COMM_WORLD);
auto local_elements = solution.locally_owned_elements();
for (auto index : local_elements) {
solution[index] = 1.0;
}
solution.compress(dealii::VectorOperation::insert);
}
std::cout << "Building in-group iteration" << std::endl;
auto in_group_iteration =
std::make_unique<iteration::group::GroupSourceIteration<dim>>(
std::move(single_group_solver_ptr),
std::move(in_group_final_checker),
std::move(moment_calculator),
solution_ptr,
source_updater_ptr,
reporter);
std::cout << "Building K_Effective updater" << std::endl;
// KEffectiveUpdater
using FissionSourceCalulator = calculator::cell::TotalAggregatedFissionSource<dim>;
using IntegratedFissionSourceCalc = calculator::cell::IntegratedFissionSource<dim>;
auto int_fission_ptr = std::make_unique<IntegratedFissionSourceCalc>(
finite_element_ptr, cross_sections_ptr);
auto fission_source_calc_ptr = std::make_unique<FissionSourceCalulator>(
std::move(int_fission_ptr), domain_ptr);
using KEffectiveUpdater = eigenvalue::k_effective::UpdaterViaFissionSource;
// KEffective convergence checker
using KEffConvChecker = bart::convergence::parameters::SingleParameterChecker;
auto k_eff_conv_checker = std::make_unique<KEffConvChecker>();
using KEffectiveFinalCovergence = bart::convergence::FinalCheckerOrN<double,
bart::convergence::parameters::SingleParameterChecker>;
auto k_eff_final_checker = std::make_unique<KEffectiveFinalCovergence>(
std::move(k_eff_conv_checker)
);
// KEffective updater
auto k_effective_updater = std::make_unique<KEffectiveUpdater>(
std::move(fission_source_calc_ptr), 2.0, 10);
std::cout << "Building outer-iteration" << std::endl;
using PowerIteration = iteration::outer::OuterPowerIteration;
auto power_iteration_ptr = std::make_unique<PowerIteration>(
std::move(in_group_iteration),
std::move(k_eff_final_checker),
std::move(k_effective_updater),
source_updater_ptr,
reporter
);
std::cout << "Building System" << std::endl;
auto system = std::make_unique<system::System>();
system->total_groups = prm.NEnergyGroups();
std::unordered_set<bart::system::terms::VariableLinearTerms>
source_terms{bart::system::terms::VariableLinearTerms::kScatteringSource,
bart::system::terms::VariableLinearTerms::kFissionSource};
system->right_hand_side_ptr_ =
std::make_unique<system::terms::MPILinearTerm>(source_terms);
system->left_hand_side_ptr_ =
std::make_unique<system::terms::MPIBilinearTerm>();
std::cout << "Filling system" << std::endl;
// Fill system with objects
for (int group = 0; group <= prm.NEnergyGroups(); ++group) {
// LHS
auto fixed_matrix_ptr = bart::data::BuildMatrix(matrix_param);
system->left_hand_side_ptr_->SetFixedTermPtr(group, fixed_matrix_ptr);
// RHS
auto fixed_vector_ptr =
std::make_shared<bart::system::MPIVector>(matrix_param.rows, MPI_COMM_WORLD);
system->right_hand_side_ptr_->SetFixedTermPtr(group, fixed_vector_ptr);
for (auto term : source_terms) {
auto variable_vector_ptr =
std::make_shared<bart::system::MPIVector>(matrix_param.rows, MPI_COMM_WORLD);
system->right_hand_side_ptr_->SetVariableTermPtr(
group, term, variable_vector_ptr);
}
// Moments
system->current_moments =
std::make_unique<system::moments::SphericalHarmonic>(prm.NEnergyGroups(), 0);
system->previous_moments =
std::make_unique<system::moments::SphericalHarmonic>(prm.NEnergyGroups(), 0);
}
std::cout << "Fill system moments" << std::endl;
for (auto& moment_pair : system->current_moments->moments()) {
auto index = moment_pair.first;
auto& current_moment = system->current_moments->operator[](index);
current_moment.reinit(solution_ptr->operator[](0).size());
auto& previous_moment = system->previous_moments->operator[](index);
previous_moment.reinit(solution_ptr->operator[](0).size());
current_moment = 1;
previous_moment = 1;
}
// Initialize System
system->k_effective = 1.16;
system->total_groups = prm.NEnergyGroups();
system->total_angles = 1;
std::cout << "Build Results Output" << std::endl;
auto results_output_ptr =
std::make_unique<results::OutputDealiiVtu<dim>>(domain_ptr);
return std::make_unique<framework::Framework>(
std::move(system),
std::move(initializer_ptr),
std::move(power_iteration_ptr),
std::move(results_output_ptr));
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildFiniteElement(
problem::ParametersI *problem_parameters)-> std::unique_ptr<FiniteElement> {
return std::make_unique<domain::finite_element::FiniteElementGaussian<dim>>(
problem::DiscretizationType::kContinuousFEM,
problem_parameters->FEPolynomialDegree());
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildDomain(
problem::ParametersI *problem_parameters,
const std::shared_ptr<FiniteElement> &finite_element_ptr,
std::string material_mapping)-> std::unique_ptr<Domain> {
// Build mesh
auto mesh_ptr = std::make_unique<domain::mesh::MeshCartesian<dim>>(
problem_parameters->SpatialMax(),
problem_parameters->NCells(),
material_mapping);
return std::make_unique<domain::Definition<dim>>(
std::move(mesh_ptr), finite_element_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildStamper(
problem::ParametersI *problem_parameters,
const std::shared_ptr<Domain> &domain_ptr,
const std::shared_ptr<FiniteElement> &finite_element_ptr,
const std::shared_ptr<CrossSections> &cross_sections_ptr)
-> std::unique_ptr<CFEMStamper> {
std::unique_ptr<CFEMStamper> return_ptr = nullptr;
// Diffusion Stamper
if (problem_parameters->TransportModel() == problem::EquationType::kDiffusion) {
auto diffusion_ptr = std::make_unique<formulation::scalar::CFEM_Diffusion<dim>>(
finite_element_ptr, cross_sections_ptr);
return_ptr = std::move(
std::make_unique<formulation::CFEM_DiffusionStamper<dim>>(
std::move(diffusion_ptr),
domain_ptr,
problem_parameters->ReflectiveBoundary()));
} else {
AssertThrow(false, dealii::ExcMessage("Unsuppored equation type passed"
"to BuildScalarFormulation"));
}
return return_ptr;
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildSourceUpdater(
problem::ParametersI *,
const std::shared_ptr<CFEMStamper> stamper_ptr)
-> std::unique_ptr<SourceUpdater> {
// TODO(Josh): Add option for non-gauss-seidel updating
using SourceUpdater = iteration::updater::SourceUpdaterGaussSeidel<CFEMStamper>;
return std::make_unique<SourceUpdater>(stamper_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildParameterConvergenceChecker(
double max_delta, int max_iterations)
-> std::unique_ptr<ParameterConvergenceChecker>{
using CheckerType = convergence::parameters::SingleParameterChecker;
using FinalCheckerType = convergence::FinalCheckerOrN<double, CheckerType>;
auto single_checker_ptr = std::make_unique<CheckerType>(max_delta);
auto return_ptr = std::make_unique<FinalCheckerType>(
std::move(single_checker_ptr));
return_ptr->SetMaxIterations(max_iterations);
return std::move(return_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildMomentConvergenceChecker(
double max_delta, int max_iterations)
-> std::unique_ptr<MomentConvergenceChecker>{
//TODO(Josh): Add option for using other than L1Norm
using CheckerType = convergence::moments::SingleMomentCheckerL1Norm;
using FinalCheckerType = convergence::FinalCheckerOrN<
system::moments::MomentVector,
convergence::moments::SingleMomentCheckerI>;
auto single_checker_ptr = std::make_unique<CheckerType>(max_delta);
auto return_ptr = std::make_unique<FinalCheckerType>(
std::move(single_checker_ptr));
return_ptr->SetMaxIterations(max_iterations);
return std::move(return_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildFixedUpdater(
const std::shared_ptr<CFEMStamper> &stamper_ptr)
-> std::unique_ptr<CFEM_FrameworkBuilder::FixedUpdater> {
using FixedUpdaterType = iteration::updater::FixedUpdater<CFEMStamper>;
return std::make_unique<FixedUpdaterType>(stamper_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildSingleGroupSolver(
const int max_iterations,
const double convergence_tolerance) -> std::unique_ptr<SingleGroupSolver> {
std::unique_ptr<SingleGroupSolver> return_ptr = nullptr;
auto linear_solver_ptr = std::make_unique<solver::GMRES>(max_iterations,
convergence_tolerance);
return_ptr = std::move(
std::make_unique<solver::group::SingleGroupSolver>(
std::move(linear_solver_ptr)));
return return_ptr;
}
template class CFEM_FrameworkBuilder<1>;
template class CFEM_FrameworkBuilder<2>;
template class CFEM_FrameworkBuilder<3>;
} // namespace builder
} // namespace framework
} // namespace bart<commit_msg>various updates to CFEM_FrameworkBuilder fixing issues with n_groups and n_angles<commit_after>#include "framework/builder/cfem_framework_builder.h"
#include <fstream>
#include <streambuf>
#include <deal.II/base/mpi.h>
#include "calculator/cell/integrated_fission_source.h"
#include "calculator/cell/total_aggregated_fission_source.h"
#include "convergence/moments/single_moment_checker_l1_norm.h"
#include "convergence/reporter/mpi_noisy.h"
#include "domain/definition.h"
#include "domain/finite_element/finite_element_gaussian.h"
#include "domain/mesh/mesh_cartesian.h"
#include "eigenvalue/k_effective/updater_via_fission_source.h"
#include "formulation/cfem_diffusion_stamper.h"
#include "formulation/scalar/cfem_diffusion.h"
#include "framework/framework.h"
#include "iteration/updater/source_updater_gauss_seidel.h"
#include "iteration/updater/fixed_updater.h"
#include "iteration/initializer/set_fixed_terms_once.h"
#include "iteration/group/group_source_iteration.h"
#include "iteration/outer/outer_power_iteration.h"
#include "material/material_protobuf.h"
#include "problem/parameter_types.h"
#include "convergence/moments/single_moment_checker_l1_norm.h"
#include "convergence/parameters/single_parameter_checker.h"
#include "convergence/final_checker_or_n.h"
#include "quadrature/angular/angular_quadrature_scalar.h"
#include "quadrature/calculators/spherical_harmonic_zeroth_moment.h"
#include "results/output_dealii_vtu.h"
#include "solver/group/single_group_solver.h"
#include "solver/gmres.h"
#include "system/system.h"
#include "system/solution/mpi_group_angular_solution.h"
#include "system/terms/term.h"
#include "system/terms/term_types.h"
#include "system/moments/spherical_harmonic.h"
namespace bart {
namespace framework {
namespace builder {
template <int dim>
std::unique_ptr<FrameworkI> CFEM_FrameworkBuilder<dim>::BuildFramework(
problem::ParametersI &prm,
dealii::ParameterHandler &d2_prm) {
std::cout << "Setting up materials" << std::endl;
std::ifstream mapping_file(prm.MaterialMapFilename());
std::string material_mapping(
(std::istreambuf_iterator<char>(mapping_file)),
std::istreambuf_iterator<char>());
const int n_groups = prm.NEnergyGroups();
const int n_angles = 1;
MaterialProtobuf materials(d2_prm);
auto cross_sections_ptr = std::make_shared<bart::data::CrossSections>(materials);
std::cout << "Building Finite Element"<< std::endl;
std::shared_ptr<FiniteElement>finite_element_ptr(std::move(BuildFiniteElement(
&prm)));
std::cout << "Building Domain" << std::endl;
std::shared_ptr<Domain> domain_ptr(std::move(BuildDomain(
&prm,finite_element_ptr, material_mapping)));
std::cout << "Setting up domain" << std::endl;
domain_ptr->SetUpMesh().SetUpDOF();
std::cout << "Building Stamper" << std::endl;
std::shared_ptr<CFEMStamper> stamper_ptr(std::move(BuildStamper(
&prm, domain_ptr, finite_element_ptr, cross_sections_ptr)));
std::cout << "Building fixed updater" << std::endl;
auto fixed_updater_ptr = BuildFixedUpdater(stamper_ptr);
std::cout << "Building source updater" << std::endl;
std::shared_ptr<SourceUpdater> source_updater_ptr(
std::move(BuildSourceUpdater(&prm, stamper_ptr)));
std::cout << "Building Initializer" << std::endl;
auto initializer_ptr =
std::make_unique<iteration::initializer::SetFixedTermsOnce>(
std::move(fixed_updater_ptr), n_groups, n_angles);
std::cout << "Building single group solver" << std::endl;
auto single_group_solver_ptr = BuildSingleGroupSolver();
std::cout << "Building inner iteration objects" << std::endl;
auto in_group_final_checker = BuildMomentConvergenceChecker(1e-10, 100);
// Build reporter
using Reporter = bart::convergence::reporter::MpiNoisy;
int this_process = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);
auto pout_ptr = std::make_unique<dealii::ConditionalOStream>(std::cout, this_process == 0);
auto reporter = std::make_shared<Reporter>(std::move(pout_ptr));
// Scalar Quadrature
using ScalarQuadrature = quadrature::angular::AngularQuadratureScalar<dim>;
auto quadrature_ptr = std::make_shared<ScalarQuadrature>();
// Moment calculator
using MomentCalculator = quadrature::calculators::SphericalHarmonicZerothMoment<dim>;
auto moment_calculator = std::make_unique<MomentCalculator>(quadrature_ptr);
// Solution group
auto solution_ptr =
std::make_shared<system::solution::MPIGroupAngularSolution>(n_angles);
data::MatrixParameters matrix_param;
domain_ptr->FillMatrixParameters(matrix_param, prm.Discretization());
std::cout << "==Filling solution object" << std::endl;
for (int angle = 0; angle < n_angles; ++angle) {
auto &solution = solution_ptr->operator[](angle);
solution.reinit(matrix_param.rows, MPI_COMM_WORLD);
auto local_elements = solution.locally_owned_elements();
for (auto index : local_elements) {
solution[index] = 1.0;
}
solution.compress(dealii::VectorOperation::insert);
}
std::cout << "Building in-group iteration" << std::endl;
auto in_group_iteration =
std::make_unique<iteration::group::GroupSourceIteration<dim>>(
std::move(single_group_solver_ptr),
std::move(in_group_final_checker),
std::move(moment_calculator),
solution_ptr,
source_updater_ptr,
reporter);
std::cout << "Building K_Effective updater" << std::endl;
// KEffectiveUpdater
using FissionSourceCalulator = calculator::cell::TotalAggregatedFissionSource<dim>;
using IntegratedFissionSourceCalc = calculator::cell::IntegratedFissionSource<dim>;
auto int_fission_ptr = std::make_unique<IntegratedFissionSourceCalc>(
finite_element_ptr, cross_sections_ptr);
auto fission_source_calc_ptr = std::make_unique<FissionSourceCalulator>(
std::move(int_fission_ptr), domain_ptr);
using KEffectiveUpdater = eigenvalue::k_effective::UpdaterViaFissionSource;
// KEffective convergence checker
using KEffConvChecker = bart::convergence::parameters::SingleParameterChecker;
auto k_eff_conv_checker = std::make_unique<KEffConvChecker>();
using KEffectiveFinalCovergence = bart::convergence::FinalCheckerOrN<double,
bart::convergence::parameters::SingleParameterChecker>;
auto k_eff_final_checker = std::make_unique<KEffectiveFinalCovergence>(
std::move(k_eff_conv_checker)
);
// KEffective updater
auto k_effective_updater = std::make_unique<KEffectiveUpdater>(
std::move(fission_source_calc_ptr), 2.0, 10);
std::cout << "Building outer-iteration" << std::endl;
using PowerIteration = iteration::outer::OuterPowerIteration;
auto power_iteration_ptr = std::make_unique<PowerIteration>(
std::move(in_group_iteration),
std::move(k_eff_final_checker),
std::move(k_effective_updater),
source_updater_ptr,
reporter
);
std::cout << "Building System" << std::endl;
auto system = std::make_unique<system::System>();
system->total_groups = n_groups;
std::unordered_set<bart::system::terms::VariableLinearTerms>
source_terms{bart::system::terms::VariableLinearTerms::kScatteringSource,
bart::system::terms::VariableLinearTerms::kFissionSource};
system->right_hand_side_ptr_ =
std::make_unique<system::terms::MPILinearTerm>(source_terms);
system->left_hand_side_ptr_ =
std::make_unique<system::terms::MPIBilinearTerm>();
std::cout << "Filling system" << std::endl;
// Fill system with objects
for (int group = 0; group < n_groups; ++group) {
// LHS
auto fixed_matrix_ptr = bart::data::BuildMatrix(matrix_param);
system->left_hand_side_ptr_->SetFixedTermPtr(group, fixed_matrix_ptr);
// RHS
auto fixed_vector_ptr =
std::make_shared<bart::system::MPIVector>(matrix_param.rows, MPI_COMM_WORLD);
system->right_hand_side_ptr_->SetFixedTermPtr(group, fixed_vector_ptr);
for (auto term : source_terms) {
auto variable_vector_ptr =
std::make_shared<bart::system::MPIVector>(matrix_param.rows, MPI_COMM_WORLD);
system->right_hand_side_ptr_->SetVariableTermPtr(
group, term, variable_vector_ptr);
}
// Moments
system->current_moments =
std::make_unique<system::moments::SphericalHarmonic>(n_groups, 0);
system->previous_moments =
std::make_unique<system::moments::SphericalHarmonic>(n_groups, 0);
}
std::cout << "Fill system moments" << std::endl;
for (auto& moment_pair : system->current_moments->moments()) {
auto index = moment_pair.first;
auto& current_moment = system->current_moments->operator[](index);
current_moment.reinit(solution_ptr->operator[](0).size());
auto& previous_moment = system->previous_moments->operator[](index);
previous_moment.reinit(solution_ptr->operator[](0).size());
current_moment = 1;
previous_moment = 1;
}
// Initialize System
system->k_effective = 1.16;
system->total_groups = n_groups;
system->total_angles = n_angles;
std::cout << "Build Results Output" << std::endl;
auto results_output_ptr =
std::make_unique<results::OutputDealiiVtu<dim>>(domain_ptr);
return std::make_unique<framework::Framework>(
std::move(system),
std::move(initializer_ptr),
std::move(power_iteration_ptr),
std::move(results_output_ptr));
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildFiniteElement(
problem::ParametersI *problem_parameters)-> std::unique_ptr<FiniteElement> {
return std::make_unique<domain::finite_element::FiniteElementGaussian<dim>>(
problem::DiscretizationType::kContinuousFEM,
problem_parameters->FEPolynomialDegree());
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildDomain(
problem::ParametersI *problem_parameters,
const std::shared_ptr<FiniteElement> &finite_element_ptr,
std::string material_mapping)-> std::unique_ptr<Domain> {
// Build mesh
auto mesh_ptr = std::make_unique<domain::mesh::MeshCartesian<dim>>(
problem_parameters->SpatialMax(),
problem_parameters->NCells(),
material_mapping);
return std::make_unique<domain::Definition<dim>>(
std::move(mesh_ptr), finite_element_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildStamper(
problem::ParametersI *problem_parameters,
const std::shared_ptr<Domain> &domain_ptr,
const std::shared_ptr<FiniteElement> &finite_element_ptr,
const std::shared_ptr<CrossSections> &cross_sections_ptr)
-> std::unique_ptr<CFEMStamper> {
std::unique_ptr<CFEMStamper> return_ptr = nullptr;
// Diffusion Stamper
if (problem_parameters->TransportModel() == problem::EquationType::kDiffusion) {
auto diffusion_ptr = std::make_unique<formulation::scalar::CFEM_Diffusion<dim>>(
finite_element_ptr, cross_sections_ptr);
return_ptr = std::move(
std::make_unique<formulation::CFEM_DiffusionStamper<dim>>(
std::move(diffusion_ptr),
domain_ptr,
problem_parameters->ReflectiveBoundary()));
} else {
AssertThrow(false, dealii::ExcMessage("Unsuppored equation type passed"
"to BuildScalarFormulation"));
}
return return_ptr;
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildSourceUpdater(
problem::ParametersI *,
const std::shared_ptr<CFEMStamper> stamper_ptr)
-> std::unique_ptr<SourceUpdater> {
// TODO(Josh): Add option for non-gauss-seidel updating
using SourceUpdater = iteration::updater::SourceUpdaterGaussSeidel<CFEMStamper>;
return std::make_unique<SourceUpdater>(stamper_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildParameterConvergenceChecker(
double max_delta, int max_iterations)
-> std::unique_ptr<ParameterConvergenceChecker>{
using CheckerType = convergence::parameters::SingleParameterChecker;
using FinalCheckerType = convergence::FinalCheckerOrN<double, CheckerType>;
auto single_checker_ptr = std::make_unique<CheckerType>(max_delta);
auto return_ptr = std::make_unique<FinalCheckerType>(
std::move(single_checker_ptr));
return_ptr->SetMaxIterations(max_iterations);
return std::move(return_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildMomentConvergenceChecker(
double max_delta, int max_iterations)
-> std::unique_ptr<MomentConvergenceChecker>{
//TODO(Josh): Add option for using other than L1Norm
using CheckerType = convergence::moments::SingleMomentCheckerL1Norm;
using FinalCheckerType = convergence::FinalCheckerOrN<
system::moments::MomentVector,
convergence::moments::SingleMomentCheckerI>;
auto single_checker_ptr = std::make_unique<CheckerType>(max_delta);
auto return_ptr = std::make_unique<FinalCheckerType>(
std::move(single_checker_ptr));
return_ptr->SetMaxIterations(max_iterations);
return std::move(return_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildFixedUpdater(
const std::shared_ptr<CFEMStamper> &stamper_ptr)
-> std::unique_ptr<CFEM_FrameworkBuilder::FixedUpdater> {
using FixedUpdaterType = iteration::updater::FixedUpdater<CFEMStamper>;
return std::make_unique<FixedUpdaterType>(stamper_ptr);
}
template<int dim>
auto CFEM_FrameworkBuilder<dim>::BuildSingleGroupSolver(
const int max_iterations,
const double convergence_tolerance) -> std::unique_ptr<SingleGroupSolver> {
std::unique_ptr<SingleGroupSolver> return_ptr = nullptr;
auto linear_solver_ptr = std::make_unique<solver::GMRES>(max_iterations,
convergence_tolerance);
return_ptr = std::move(
std::make_unique<solver::group::SingleGroupSolver>(
std::move(linear_solver_ptr)));
return return_ptr;
}
template class CFEM_FrameworkBuilder<1>;
template class CFEM_FrameworkBuilder<2>;
template class CFEM_FrameworkBuilder<3>;
} // namespace builder
} // namespace framework
} // namespace bart<|endoftext|> |
<commit_before>#pragma once
#include <YouBot_monitors/typekit/Types.h>
#include <rtt/Service.hpp>
#include <rtt/Port.hpp>
#include <sensor_msgs/typekit/Types.h>
#include <nav_msgs/typekit/Types.h>
#include <geometry_msgs/typekit/Types.h>
#include <boost/function.hpp>
#include <vector>
namespace YouBot
{
using namespace RTT;
using namespace std;
const size_t max_event_length = 255;
enum control_space {JOINT = 1, CARTESIAN = 2};
enum physical_part {ARM = 1, BASE = 2, BOTH = 3};
enum physical_quantity {POSITION = 1, VELOCITY = 2, TORQUE = 3, FORCE = 4};
enum event_type {LIMIT_EXCEEDED, REACHED};
typedef boost::function<bool(double current_state) > single_value_fp;
typedef boost::function<bool(vector<double> current_state) > state_vector_fp;
// typedef boost::function<bool(double current_state)> check_fp;
typedef struct _monitor
{
physical_part p;
control_space ct;
physical_quantity pt;
event_type et;
bool is_single_value;
single_value_fp single_value;
state_vector_fp state_vector;
} monitor;
class YouBotMonitorService : public Service {
public:
YouBotMonitorService(const string& name, TaskContext* parent);
virtual ~YouBotMonitorService();
virtual void setup_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check, double single_value);
virtual void setup_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check, std::vector<double> state_vector);
virtual void remove_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check);
virtual void clear_monitors();
virtual void setupComponentInterface();
void emitEvent(std::string id, std::string message);
void emitEvent(std::string id, std::string message, bool condition);
protected:
InputPort<sensor_msgs::JointState> base_joint_state;
InputPort<nav_msgs::Odometry> base_cart_state;
InputPort<sensor_msgs::JointState> arm_joint_state;
// InputPort<> arm_cart_state;
OutputPort<YouBot_monitors::monitor_event> events;
YouBot_monitors::monitor_event m_events;
vector<monitor> m_monitors;
};
// single value monitor vs state vector monitor
// Sensor msgs
// Channel name, <pos, velo, force>, limit_exceeded
// Channel name, <pos> pos_reached
// Odometry = Position + Twist
// pos, velo
// Howto: cartforce?
}
<commit_msg>Interface update.<commit_after>#pragma once
#include <YouBot_monitors/typekit/Types.h>
#include <rtt/Service.hpp>
#include <rtt/Port.hpp>
#include <sensor_msgs/typekit/Types.h>
#include <nav_msgs/typekit/Types.h>
#include <geometry_msgs/typekit/Types.h>
#include <boost/function.hpp>
#include <vector>
namespace YouBot
{
using namespace RTT;
using namespace std;
const size_t max_event_length = 255;
enum control_space {JOINT = 1, CARTESIAN = 2};
enum physical_part {ARM = 1, BASE = 2, BOTH = 3};
enum physical_quantity {POSITION = 1, VELOCITY = 2, TORQUE = 3, FORCE = 4};
enum event_type {LIMIT_EXCEEDED, REACHED};
typedef boost::function<bool(double current_state) > single_value_fp;
typedef boost::function<bool(vector<double> current_state) > state_vector_fp;
// typedef boost::function<bool(double current_state)> check_fp;
typedef struct _monitor
{
physical_part p;
control_space ct;
physical_quantity pt;
event_type et;
bool is_single_value;
single_value_fp single_value;
state_vector_fp state_vector;
} monitor;
class YouBotMonitorService : public Service {
public:
YouBotMonitorService(const string& name, TaskContext* parent);
virtual ~YouBotMonitorService();
virtual void setup_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check, unsigned int index, double single_value);
virtual void setup_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check, std::vector<unsigned int> indices, std::vector<double> vector_value);
virtual void remove_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check, unsigned int index, double single_value);
virtual void remove_monitor(physical_part& p, control_space& st, physical_quantity& pt, event_type& to_check, std::vector<unsigned int> indices, std::vector<double> vector_value);
virtual void clear_monitors();
virtual void setupComponentInterface();
void emitEvent(std::string id, std::string message);
void emitEvent(std::string id, std::string message, bool condition);
protected:
InputPort<sensor_msgs::JointState> base_joint_state;
InputPort<nav_msgs::Odometry> base_cart_state;
InputPort<sensor_msgs::JointState> arm_joint_state;
// InputPort<> arm_cart_state;
OutputPort<YouBot_monitors::monitor_event> events;
YouBot_monitors::monitor_event m_events;
vector<monitor> m_monitors;
};
// single value monitor vs state vector monitor
// Sensor msgs
// Channel name, <pos, velo, force>, limit_exceeded
// Channel name, <pos> pos_reached
// Odometry = Position + Twist
// pos, velo
// Howto: cartforce?
}
<|endoftext|> |
<commit_before>#include "commandProcessor.h"
//CommandProcessor
CommandProcessor::CommandProcessor ( QString const & ex )
{
regex.setPattern(ex);
}
CommandProcessor::~CommandProcessor() { }
bool const CommandProcessor::CanProcess ( QString const & command )
{
QStringList rr = command.split(" ");
if((rr.at(0) == "MOVJ_SPLINE_LSPB")||(rr.at(0) == "MOVJ_LSPB")||(rr.at(0) == "MOVL_RPY_LSPB"))
{
if((rr.length() - 5) % 6)
{
ROS_ERROR("Wrong point number!");
return 0;
}
}
bool result = regex.exactMatch(command);
return result;
}
//MOVJ_LSPB_Processor
MOVJ_LSPB_Processor::MOVJ_LSPB_Processor()
: CommandProcessor ( MOTION_CMD(MOVJ_LSPB) )
{ }
Command const MOVJ_LSPB_Processor::Load (QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
QStringList result = command.split(" ");
cc.type = MOTION;
cc.pointsNum = 1;
cc.method = "MOVJ_LSPB";
cc.target = regex.cap(1);
for(int i = 0; i < 6; i++)
cc.motion_params.push_back(result.at(i+2).toDouble());
cc.duration = regex.cap(3).toDouble();
cc.units = "mm,deg,s";
cc.frame = regex.cap(7);
return cc;
}
QString const MOVJ_LSPB_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return 0;
}
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" {" + cc.target + "} ");
for(int j = 0; j < 6; j++)
pub_cmd.append(QString::number(cc.motion_params[j]) + " ");
pub_cmd.append("[" + QString::number(cc.duration) + "] ");
pub_cmd.append("(" + cc.units + ") ");
pub_cmd.append("{" + cc.frame + "}");
// 3.publish command.
return pub_cmd;
}
int const MOVJ_LSPB_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
if((controller_states->_robot_state == "stable")&&(controller_states->action_result == "succeed"))
{
return 1;
}
else if(controller_states->action_result == "speed")
{
return 2;
}
}
return 0;
}
//MOVL_RPY_LSPB_Processor
MOVL_RPY_LSPB_Processor::MOVL_RPY_LSPB_Processor()
: CommandProcessor ( MOTION_CMD(MOVL_RPY_LSPB) )
{ }
Command const MOVL_RPY_LSPB_Processor::Load ( QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
QStringList result = command.split(" ");
cc.type = MOTION;
cc.pointsNum = 1;
cc.method = "MOVL_RPY_LSPB";
cc.target = regex.cap(1);
for(int i = 0; i < 6; i++)
cc.motion_params.push_back(result.at(i+2).toDouble());
cc.duration = regex.cap(3).toDouble();
cc.units = "mm,deg,s";
cc.frame = regex.cap(7);
return cc;
}
QString const MOVL_RPY_LSPB_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return 0;
}
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" {" + cc.target + "} ");
for(int j = 0; j < 6; j++)
pub_cmd.append(QString::number(cc.motion_params[j]) + " ");
pub_cmd.append("[" + QString::number(cc.duration) + "] ");
pub_cmd.append("(" + cc.units + ") ");
pub_cmd.append("{" + cc.frame + "}");
// 3.publish command.
return pub_cmd;
}
int const MOVL_RPY_LSPB_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
if((controller_states->_robot_state == "stable")&&(controller_states->action_result == "succeed"))
{
return 1;
}
else if(controller_states->action_result == "speed")
{
return 2;
}
}
return 0;
}
//MOVJ_SPLINE_LSPB_Processor
MOVJ_SPLINE_LSPB_Processor::MOVJ_SPLINE_LSPB_Processor()
: CommandProcessor ( MOTION_CMD(MOVJ_SPLINE_LSPB) )
{ }
Command const MOVJ_SPLINE_LSPB_Processor::Load ( QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
QStringList result = command.split(" ");
cc.type = MOTION;
if((result.length() -5) % 6)
{
ROS_ERROR("Wrong point number!");
return cc;
}
cc.pointsNum = (result.length() - 5) / 6;
cc.method = "MOVJ_SPLINE_LSPB";
cc.target = regex.cap(1);
for(int i = 0; i < cc.pointsNum * 6; i++)
cc.motion_params.push_back(result.at(i+2).toDouble());
cc.duration = regex.cap(3).toDouble();
cc.units = "mm,deg,s";
cc.frame = regex.cap(7);
return cc;
}
QString const MOVJ_SPLINE_LSPB_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" {" + cc.target + "} ");
for(int j = 0; j < cc.pointsNum * 6; j++)
pub_cmd.append(QString::number(cc.motion_params[j]) + " ");
pub_cmd.append("[" + QString::number(cc.duration) + "] ");
pub_cmd.append("(" + cc.units + ") ");
pub_cmd.append("{" + cc.frame + "}");
// 3.publish command.
return pub_cmd;
}
int const MOVJ_SPLINE_LSPB_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
if((controller_states->_robot_state == "stable")&&(controller_states->action_result == "succeed"))
{
return 1;
}
else if(controller_states->action_result == "speed")
{
return 2;
}
}
return 0;
}
//SET_Processor
SET_Processor::SET_Processor()
: CommandProcessor(IO_CMD(SET))
{ }
Command const SET_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = IO;
cc.method = "SET";
cc.target = regex.cap(1);
cc.io_result = regex.cap(2);
return cc;
}
QString const SET_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" " + cc.target + " ");
pub_cmd.append(cc.io_result);
// 3.publish command.
return pub_cmd;
}
int const SET_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
QStringList commandline = command.split(" ");
if(commandline.at(0) == "SET")
{
// if(states->iostate[commandline.at(1).toInt()] == 1)
// {
return 1;
// }
}
}
return 0;
}
//RESET_Processor
RESET_Processor::RESET_Processor()
: CommandProcessor(IO_CMD(RESET))
{ }
Command const RESET_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = IO;
cc.method = "RESET";
cc.target = regex.cap(1);
return cc;
}
QString const RESET_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" " + cc.target);
// 3.publish command.
return pub_cmd;
}
int const RESET_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
QStringList commandline = command.split(" ");
if(commandline.at(0) == "RESET")
{
// if(states->iostate[commandline.at(1).toInt()] == 1)
// {
return 1;
// }
}
}
return 0;
}
//WAIT_Processor
WAIT_Processor::WAIT_Processor()
: CommandProcessor(WAIT_CMD)
{ }
Command const WAIT_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = WAIT;
cc.method = "WAIT";
cc.target = regex.cap(1);
cc.io_result = regex.cap(2);// new add
return cc;
}
QString const WAIT_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" " + cc.target);
pub_cmd.append(" " + cc.io_result);// new add
// 3.publish command.
return pub_cmd;
}
int const WAIT_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(1) // (m_id == atoi(controller_states->current_id.c_str()))
{
QStringList commandline = command.split(" ");
if(commandline.at(0) == "WAIT")
{
if(states->iostate[commandline.at(1).toInt()] == commandline.at(2).toInt())
{
return 1;
}
}
}
return 0;
}
//PROG_Processor
PROG_Processor::PROG_Processor()
: CommandProcessor(PROG_CMD)
{ }
Command const PROG_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = PROG;
cc.method = "PROG";
cc.target = regex.cap(1);
return cc;
}
QString const PROG_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
if(!cc.target.endsWith(".txt"))
cc.target = cc.target + ".txt";
return cc.target;
}
int const PROG_Processor::CanContinue ( int const m_id, QString const & command, Controller_State const *controller_states, State const *states )
{
ROS_ERROR("This function is no use!");
return -1;
}
<commit_msg>fix bugs in Command's"CanContinue" Functions<commit_after>#include "commandProcessor.h"
//CommandProcessor
CommandProcessor::CommandProcessor ( QString const & ex )
{
regex.setPattern(ex);
}
CommandProcessor::~CommandProcessor() { }
bool const CommandProcessor::CanProcess ( QString const & command )
{
QStringList rr = command.split(" ");
if((rr.at(0) == "MOVJ_SPLINE_LSPB")||(rr.at(0) == "MOVJ_LSPB")||(rr.at(0) == "MOVL_RPY_LSPB"))
{
if((rr.length() - 5) % 6)
{
ROS_ERROR("Wrong point number!");
return 0;
}
}
bool result = regex.exactMatch(command);
return result;
}
//MOVJ_LSPB_Processor
MOVJ_LSPB_Processor::MOVJ_LSPB_Processor()
: CommandProcessor ( MOTION_CMD(MOVJ_LSPB) )
{ }
Command const MOVJ_LSPB_Processor::Load (QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
QStringList result = command.split(" ");
cc.type = MOTION;
cc.pointsNum = 1;
cc.method = "MOVJ_LSPB";
cc.target = regex.cap(1);
for(int i = 0; i < 6; i++)
cc.motion_params.push_back(result.at(i+2).toDouble());
cc.duration = regex.cap(3).toDouble();
cc.units = "mm,deg,s";
cc.frame = regex.cap(7);
return cc;
}
QString const MOVJ_LSPB_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return 0;
}
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" {" + cc.target + "} ");
for(int j = 0; j < 6; j++)
pub_cmd.append(QString::number(cc.motion_params[j]) + " ");
pub_cmd.append("[" + QString::number(cc.duration) + "] ");
pub_cmd.append("(" + cc.units + ") ");
pub_cmd.append("{" + cc.frame + "}");
// 3.publish command.
return pub_cmd;
}
int const MOVJ_LSPB_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
Command cc;
cc = Load(command);
if(cc.method != "MOVJ_LSPB")
return 0;
if(m_id == atoi(controller_states->current_id.c_str()))
{
if((controller_states->_robot_state == "stable")&&(controller_states->action_result == "succeed"))
{
return 1;
}
else if(controller_states->action_result == "speed")
{
return 2;
}
}
return 0;
}
//MOVL_RPY_LSPB_Processor
MOVL_RPY_LSPB_Processor::MOVL_RPY_LSPB_Processor()
: CommandProcessor ( MOTION_CMD(MOVL_RPY_LSPB) )
{ }
Command const MOVL_RPY_LSPB_Processor::Load ( QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
QStringList result = command.split(" ");
cc.type = MOTION;
cc.pointsNum = 1;
cc.method = "MOVL_RPY_LSPB";
cc.target = regex.cap(1);
for(int i = 0; i < 6; i++)
cc.motion_params.push_back(result.at(i+2).toDouble());
cc.duration = regex.cap(3).toDouble();
cc.units = "mm,deg,s";
cc.frame = regex.cap(7);
return cc;
}
QString const MOVL_RPY_LSPB_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return 0;
}
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" {" + cc.target + "} ");
for(int j = 0; j < 6; j++)
pub_cmd.append(QString::number(cc.motion_params[j]) + " ");
pub_cmd.append("[" + QString::number(cc.duration) + "] ");
pub_cmd.append("(" + cc.units + ") ");
pub_cmd.append("{" + cc.frame + "}");
// 3.publish command.
return pub_cmd;
}
int const MOVL_RPY_LSPB_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
Command cc;
cc = Load(command);
if(cc.method != "MOVL_RPY_LSPB")
return 0;
if(m_id == atoi(controller_states->current_id.c_str()))
{
if((controller_states->_robot_state == "stable")&&(controller_states->action_result == "succeed"))
{
return 1;
}
else if(controller_states->action_result == "speed")
{
return 2;
}
}
return 0;
}
//MOVJ_SPLINE_LSPB_Processor
MOVJ_SPLINE_LSPB_Processor::MOVJ_SPLINE_LSPB_Processor()
: CommandProcessor ( MOTION_CMD(MOVJ_SPLINE_LSPB) )
{ }
Command const MOVJ_SPLINE_LSPB_Processor::Load ( QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
QStringList result = command.split(" ");
cc.type = MOTION;
if((result.length() -5) % 6)
{
ROS_ERROR("Wrong point number!");
return cc;
}
cc.pointsNum = (result.length() - 5) / 6;
cc.method = "MOVJ_SPLINE_LSPB";
cc.target = regex.cap(1);
for(int i = 0; i < cc.pointsNum * 6; i++)
cc.motion_params.push_back(result.at(i+2).toDouble());
cc.duration = regex.cap(3).toDouble();
cc.units = "mm,deg,s";
cc.frame = regex.cap(7);
return cc;
}
QString const MOVJ_SPLINE_LSPB_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" {" + cc.target + "} ");
for(int j = 0; j < cc.pointsNum * 6; j++)
pub_cmd.append(QString::number(cc.motion_params[j]) + " ");
pub_cmd.append("[" + QString::number(cc.duration) + "] ");
pub_cmd.append("(" + cc.units + ") ");
pub_cmd.append("{" + cc.frame + "}");
// 3.publish command.
return pub_cmd;
}
int const MOVJ_SPLINE_LSPB_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
Command cc;
cc = Load(command);
if(cc.method != "MOVJ_SPLINE_LSPB")
return 0;
if(m_id == atoi(controller_states->current_id.c_str()))
{
if((controller_states->_robot_state == "stable")&&(controller_states->action_result == "succeed"))
{
return 1;
}
else if(controller_states->action_result == "speed")
{
return 2;
}
}
return 0;
}
//SET_Processor
SET_Processor::SET_Processor()
: CommandProcessor(IO_CMD(SET))
{ }
Command const SET_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = IO;
cc.method = "SET";
cc.target = regex.cap(1);
cc.io_result = regex.cap(2);
return cc;
}
QString const SET_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" " + cc.target + " ");
pub_cmd.append(cc.io_result);
// 3.publish command.
return pub_cmd;
}
int const SET_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
QStringList commandline = command.split(" ");
if(commandline.at(0) == "SET")
{
// if(states->iostate[commandline.at(1).toInt()] == 1)
// {
return 1;
// }
}
}
return 0;
}
//RESET_Processor
RESET_Processor::RESET_Processor()
: CommandProcessor(IO_CMD(RESET))
{ }
Command const RESET_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = IO;
cc.method = "RESET";
cc.target = regex.cap(1);
return cc;
}
QString const RESET_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" " + cc.target);
// 3.publish command.
return pub_cmd;
}
int const RESET_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(m_id == atoi(controller_states->current_id.c_str()))
{
QStringList commandline = command.split(" ");
if(commandline.at(0) == "RESET")
{
// if(states->iostate[commandline.at(1).toInt()] == 1)
// {
return 1;
// }
}
}
return 0;
}
//WAIT_Processor
WAIT_Processor::WAIT_Processor()
: CommandProcessor(WAIT_CMD)
{ }
Command const WAIT_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = WAIT;
cc.method = "WAIT";
cc.target = regex.cap(1);
cc.io_result = regex.cap(2);// new add
return cc;
}
QString const WAIT_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
QString pub_cmd;
pub_cmd.append(cc.method);
pub_cmd.append(" " + cc.target);
pub_cmd.append(" " + cc.io_result);// new add
// 3.publish command.
return pub_cmd;
}
int const WAIT_Processor::CanContinue(int const m_id, QString const & command, Controller_State const *controller_states, State const *states)
{
if(1) // (m_id == atoi(controller_states->current_id.c_str()))
{
QStringList commandline = command.split(" ");
if(commandline.at(0) == "WAIT")
{
if(states->iostate[commandline.at(1).toInt()] == commandline.at(2).toInt())
{
return 1;
}
}
}
return 0;
}
//PROG_Processor
PROG_Processor::PROG_Processor()
: CommandProcessor(PROG_CMD)
{ }
Command const PROG_Processor::Load(QString const & command)
{
Command cc;
if(regex.indexIn(command) == -1)
{
ROS_ERROR("Cannot process this command!");
return cc;
}
cc.type = PROG;
cc.method = "PROG";
cc.target = regex.cap(1);
return cc;
}
QString const PROG_Processor::Process ( QString const & command, Parameter const *params, Actor & actors )
{
// 1.explain command.
Command cc;
cc = Load(command);
// 2.generate command.
if(!cc.target.endsWith(".txt"))
cc.target = cc.target + ".txt";
return cc.target;
}
int const PROG_Processor::CanContinue ( int const m_id, QString const & command, Controller_State const *controller_states, State const *states )
{
ROS_ERROR("This function is no use!");
return -1;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file
* Simple PCI IDE controller with bus mastering capability and UDMA
* modeled after controller in the Intel PIIX4 chip
*/
#ifndef __IDE_CTRL_HH__
#define __IDE_CTRL_HH__
#include "dev/pcidev.hh"
#include "dev/pcireg.h"
#include "dev/io_device.hh"
#define BMIC0 0x0 // Bus master IDE command register
#define BMIS0 0x2 // Bus master IDE status register
#define BMIDTP0 0x4 // Bus master IDE descriptor table pointer register
#define BMIC1 0x8 // Bus master IDE command register
#define BMIS1 0xa // Bus master IDE status register
#define BMIDTP1 0xc // Bus master IDE descriptor table pointer register
// Bus master IDE command register bit fields
#define RWCON 0x08 // Bus master read/write control
#define SSBM 0x01 // Start/stop bus master
// Bus master IDE status register bit fields
#define DMA1CAP 0x40 // Drive 1 DMA capable
#define DMA0CAP 0x20 // Drive 0 DMA capable
#define IDEINTS 0x04 // IDE Interrupt Status
#define IDEDMAE 0x02 // IDE DMA error
#define BMIDEA 0x01 // Bus master IDE active
// IDE Command byte fields
#define IDE_SELECT_OFFSET (6)
#define IDE_SELECT_DEV_BIT 0x10
#define IDE_FEATURE_OFFSET IDE_ERROR_OFFSET
#define IDE_COMMAND_OFFSET IDE_STATUS_OFFSET
// PCI device specific register byte offsets
#define PCI_IDE_TIMING 0x40
#define PCI_SLAVE_TIMING 0x44
#define PCI_UDMA33_CTRL 0x48
#define PCI_UDMA33_TIMING 0x4a
#define IDETIM (0)
#define SIDETIM (4)
#define UDMACTL (5)
#define UDMATIM (6)
typedef enum RegType {
COMMAND_BLOCK = 0,
CONTROL_BLOCK,
BMI_BLOCK
} RegType_t;
class BaseInterface;
class Bus;
class HierParams;
class IdeDisk;
class IntrControl;
class PciConfigAll;
class PhysicalMemory;
class Platform;
/**
* Device model for an Intel PIIX4 IDE controller
*/
class IdeController : public PciDev
{
friend class IdeDisk;
private:
/** Primary command block registers */
Addr pri_cmd_addr;
Addr pri_cmd_size;
/** Primary control block registers */
Addr pri_ctrl_addr;
Addr pri_ctrl_size;
/** Secondary command block registers */
Addr sec_cmd_addr;
Addr sec_cmd_size;
/** Secondary control block registers */
Addr sec_ctrl_addr;
Addr sec_ctrl_size;
/** Bus master interface (BMI) registers */
Addr bmi_addr;
Addr bmi_size;
private:
/** Registers used for bus master interface */
uint8_t bmi_regs[16];
/** Shadows of the device select bit */
uint8_t dev[2];
/** Registers used in PCI configuration */
uint8_t pci_regs[8];
// Internal management variables
bool io_enabled;
bool bm_enabled;
bool cmd_in_progress[4];
private:
/** IDE disks connected to controller */
IdeDisk *disks[4];
private:
/** Parse the access address to pass on to device */
void parseAddr(const Addr &addr, Addr &offset, bool &primary,
RegType_t &type);
/** Select the disk based on the channel and device bit */
int getDisk(bool primary);
/** Select the disk based on a pointer */
int getDisk(IdeDisk *diskPtr);
public:
/** See if a disk is selected based on its pointer */
bool isDiskSelected(IdeDisk *diskPtr);
public:
struct Params : public PciDev::Params
{
/** Array of disk objects */
std::vector<IdeDisk *> disks;
Bus *host_bus;
Tick pio_latency;
HierParams *hier;
};
const Params *params() const { return (const Params *)_params; }
public:
IdeController(Params *p);
~IdeController();
virtual void WriteConfig(int offset, int size, uint32_t data);
virtual void ReadConfig(int offset, int size, uint8_t *data);
void intrPost();
void intrClear();
void setDmaComplete(IdeDisk *disk);
/**
* Read a done field for a given target.
* @param req Contains the address of the field to read.
* @param data Return the field read.
* @return The fault condition of the access.
*/
virtual Fault read(MemReqPtr &req, uint8_t *data);
/**
* Write to the mmapped I/O control registers.
* @param req Contains the address to write to.
* @param data The data to write.
* @return The fault condition of the access.
*/
virtual Fault write(MemReqPtr &req, const uint8_t *data);
/**
* Serialize this object to the given output stream.
* @param os The stream to serialize to.
*/
virtual void serialize(std::ostream &os);
/**
* Reconstruct the state of this object from a checkpoint.
* @param cp The checkpoint use.
* @param section The section name of this object
*/
virtual void unserialize(Checkpoint *cp, const std::string §ion);
/**
* Return how long this access will take.
* @param req the memory request to calcuate
* @return Tick when the request is done
*/
Tick cacheAccess(MemReqPtr &req);
};
#endif // __IDE_CTRL_HH_
<commit_msg>forgot a change in the previous commit. the ide controller doesn't have its own interrupt functions<commit_after>/*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file
* Simple PCI IDE controller with bus mastering capability and UDMA
* modeled after controller in the Intel PIIX4 chip
*/
#ifndef __IDE_CTRL_HH__
#define __IDE_CTRL_HH__
#include "dev/pcidev.hh"
#include "dev/pcireg.h"
#include "dev/io_device.hh"
#define BMIC0 0x0 // Bus master IDE command register
#define BMIS0 0x2 // Bus master IDE status register
#define BMIDTP0 0x4 // Bus master IDE descriptor table pointer register
#define BMIC1 0x8 // Bus master IDE command register
#define BMIS1 0xa // Bus master IDE status register
#define BMIDTP1 0xc // Bus master IDE descriptor table pointer register
// Bus master IDE command register bit fields
#define RWCON 0x08 // Bus master read/write control
#define SSBM 0x01 // Start/stop bus master
// Bus master IDE status register bit fields
#define DMA1CAP 0x40 // Drive 1 DMA capable
#define DMA0CAP 0x20 // Drive 0 DMA capable
#define IDEINTS 0x04 // IDE Interrupt Status
#define IDEDMAE 0x02 // IDE DMA error
#define BMIDEA 0x01 // Bus master IDE active
// IDE Command byte fields
#define IDE_SELECT_OFFSET (6)
#define IDE_SELECT_DEV_BIT 0x10
#define IDE_FEATURE_OFFSET IDE_ERROR_OFFSET
#define IDE_COMMAND_OFFSET IDE_STATUS_OFFSET
// PCI device specific register byte offsets
#define PCI_IDE_TIMING 0x40
#define PCI_SLAVE_TIMING 0x44
#define PCI_UDMA33_CTRL 0x48
#define PCI_UDMA33_TIMING 0x4a
#define IDETIM (0)
#define SIDETIM (4)
#define UDMACTL (5)
#define UDMATIM (6)
typedef enum RegType {
COMMAND_BLOCK = 0,
CONTROL_BLOCK,
BMI_BLOCK
} RegType_t;
class BaseInterface;
class Bus;
class HierParams;
class IdeDisk;
class IntrControl;
class PciConfigAll;
class PhysicalMemory;
class Platform;
/**
* Device model for an Intel PIIX4 IDE controller
*/
class IdeController : public PciDev
{
friend class IdeDisk;
private:
/** Primary command block registers */
Addr pri_cmd_addr;
Addr pri_cmd_size;
/** Primary control block registers */
Addr pri_ctrl_addr;
Addr pri_ctrl_size;
/** Secondary command block registers */
Addr sec_cmd_addr;
Addr sec_cmd_size;
/** Secondary control block registers */
Addr sec_ctrl_addr;
Addr sec_ctrl_size;
/** Bus master interface (BMI) registers */
Addr bmi_addr;
Addr bmi_size;
private:
/** Registers used for bus master interface */
uint8_t bmi_regs[16];
/** Shadows of the device select bit */
uint8_t dev[2];
/** Registers used in PCI configuration */
uint8_t pci_regs[8];
// Internal management variables
bool io_enabled;
bool bm_enabled;
bool cmd_in_progress[4];
private:
/** IDE disks connected to controller */
IdeDisk *disks[4];
private:
/** Parse the access address to pass on to device */
void parseAddr(const Addr &addr, Addr &offset, bool &primary,
RegType_t &type);
/** Select the disk based on the channel and device bit */
int getDisk(bool primary);
/** Select the disk based on a pointer */
int getDisk(IdeDisk *diskPtr);
public:
/** See if a disk is selected based on its pointer */
bool isDiskSelected(IdeDisk *diskPtr);
public:
struct Params : public PciDev::Params
{
/** Array of disk objects */
std::vector<IdeDisk *> disks;
Bus *host_bus;
Tick pio_latency;
HierParams *hier;
};
const Params *params() const { return (const Params *)_params; }
public:
IdeController(Params *p);
~IdeController();
virtual void WriteConfig(int offset, int size, uint32_t data);
virtual void ReadConfig(int offset, int size, uint8_t *data);
void setDmaComplete(IdeDisk *disk);
/**
* Read a done field for a given target.
* @param req Contains the address of the field to read.
* @param data Return the field read.
* @return The fault condition of the access.
*/
virtual Fault read(MemReqPtr &req, uint8_t *data);
/**
* Write to the mmapped I/O control registers.
* @param req Contains the address to write to.
* @param data The data to write.
* @return The fault condition of the access.
*/
virtual Fault write(MemReqPtr &req, const uint8_t *data);
/**
* Serialize this object to the given output stream.
* @param os The stream to serialize to.
*/
virtual void serialize(std::ostream &os);
/**
* Reconstruct the state of this object from a checkpoint.
* @param cp The checkpoint use.
* @param section The section name of this object
*/
virtual void unserialize(Checkpoint *cp, const std::string §ion);
/**
* Return how long this access will take.
* @param req the memory request to calcuate
* @return Tick when the request is done
*/
Tick cacheAccess(MemReqPtr &req);
};
#endif // __IDE_CTRL_HH_
<|endoftext|> |
<commit_before>#include "transforms/data.hpp"
#include "transforms/indexd.hpp"
#include "transforms/statistics.hpp"
#include "transforms/indexd_leveldb.hpp"
<commit_msg>transforms: not leveldb by default<commit_after>#include "transforms/data.hpp"
#include "transforms/indexd.hpp"
#include "transforms/statistics.hpp"
<|endoftext|> |
<commit_before><commit_msg>kth largest 12.11<commit_after><|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include "QGCUASFileView.h"
#include "uas/QGCUASFileManager.h"
#include <QFileDialog>
#include <QDir>
#include <QMessageBox>
QGCUASFileView::QGCUASFileView(QWidget *parent, QGCUASFileManager *manager) :
QWidget(parent),
_manager(manager)
{
_ui.setupUi(this);
bool success = connect(_ui.listFilesButton, SIGNAL(clicked()), this, SLOT(_refreshTree()));
Q_ASSERT(success);
success = connect(_ui.downloadButton, SIGNAL(clicked()), this, SLOT(_downloadFiles()));
Q_ASSERT(success);
success = connect(_ui.treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(_currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));
Q_ASSERT(success);
Q_UNUSED(success);
}
void QGCUASFileView::_downloadFiles(void)
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Download Directory"),
QDir::homePath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
// And now download to this location
QString path;
QTreeWidgetItem* item = _ui.treeWidget->currentItem();
if (item && item->type() == _typeFile) {
do {
path.prepend("/" + item->text(0));
item = item->parent();
} while (item);
qDebug() << "Download: " << path;
bool success = connect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
Q_ASSERT(success);
success = connect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
Q_ASSERT(success);
Q_UNUSED(success);
_manager->downloadPath(path, QDir(dir));
}
}
void QGCUASFileView::_refreshTree(void)
{
QTreeWidgetItem* item;
for (int i=_ui.treeWidget->invisibleRootItem()->childCount(); i>=0; i--) {
item = _ui.treeWidget->takeTopLevelItem(i);
delete item;
}
_walkIndexStack.clear();
_walkItemStack.clear();
_walkIndexStack.append(0);
_walkItemStack.append(_ui.treeWidget->invisibleRootItem());
bool success = connect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_treeStatusMessage(QString)));
Q_ASSERT(success);
success = connect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_treeErrorMessage(QString)));
Q_ASSERT(success);
success = connect(_manager, SIGNAL(listComplete(void)), this, SLOT(_listComplete(void)));
Q_ASSERT(success);
Q_UNUSED(success);
qDebug() << "List: /";
_manager->listDirectory("/");
}
void QGCUASFileView::_treeStatusMessage(const QString& msg)
{
int type;
if (msg.startsWith("F")) {
type = _typeFile;
} else if (msg.startsWith("D")) {
type = _typeDir;
if (msg == "D." || msg == "D..") {
return;
}
} else {
Q_ASSERT(false);
return; // Silence maybe-unitialized on type below
}
QTreeWidgetItem* item;
if (_walkItemStack.count() == 0) {
item = new QTreeWidgetItem(_ui.treeWidget, type);
} else {
item = new QTreeWidgetItem(_walkItemStack.last(), type);
}
Q_CHECK_PTR(item);
item->setText(0, msg.right(msg.size() - 1));
}
void QGCUASFileView::_treeErrorMessage(const QString& msg)
{
QTreeWidgetItem* item;
if (_walkItemStack.count() == 0) {
item = new QTreeWidgetItem(_ui.treeWidget, _typeError);
} else {
item = new QTreeWidgetItem(_walkItemStack.last(), _typeError);
}
Q_CHECK_PTR(item);
item->setText(0, tr("Error: ") + msg);
}
void QGCUASFileView::_listComplete(void)
{
// Walk the current items, traversing down into directories
Again:
int walkIndex = _walkIndexStack.last();
QTreeWidgetItem* parentItem = _walkItemStack.last();
QTreeWidgetItem* childItem = parentItem->child(walkIndex);
// Loop until we hit a directory
while (childItem && childItem->type() != _typeDir) {
// Move to next index at current level
_walkIndexStack.last() = ++walkIndex;
childItem = parentItem->child(walkIndex);
}
if (childItem) {
// Process this item
QString text = childItem->text(0);
// Move to the next item for processing at this level
_walkIndexStack.last() = ++walkIndex;
// Push this new directory on the stack
_walkItemStack.append(childItem);
_walkIndexStack.append(0);
// Ask for the directory list
QString dir;
for (int i=1; i<_walkItemStack.count(); i++) {
QTreeWidgetItem* item = _walkItemStack[i];
dir.append("/" + item->text(0));
}
qDebug() << "List:" << dir;
_manager->listDirectory(dir);
} else {
// We have run out of items at the this level, pop the stack and keep going at that level
_walkIndexStack.removeLast();
_walkItemStack.removeLast();
if (_walkIndexStack.count() != 0) {
goto Again;
} else {
disconnect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_treeStatusMessage(QString)));
disconnect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_treeErrorMessage(QString)));
disconnect(_manager, SIGNAL(listComplete(void)), this, SLOT(_listComplete(void)));
}
}
}
void QGCUASFileView::_downloadStatusMessage(const QString& msg)
{
disconnect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
disconnect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
QMessageBox msgBox;
msgBox.setWindowModality(Qt::ApplicationModal);
msgBox.setText(msg);
msgBox.exec();
}
void QGCUASFileView::_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
Q_UNUSED(previous);
_ui.downloadButton->setEnabled(current ? (current->type() == _typeFile) : false);
}
<commit_msg>Fix multiple clicks on List Files bugs<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include "QGCUASFileView.h"
#include "uas/QGCUASFileManager.h"
#include <QFileDialog>
#include <QDir>
#include <QMessageBox>
QGCUASFileView::QGCUASFileView(QWidget *parent, QGCUASFileManager *manager) :
QWidget(parent),
_manager(manager)
{
_ui.setupUi(this);
bool success = connect(_ui.listFilesButton, SIGNAL(clicked()), this, SLOT(_refreshTree()));
Q_ASSERT(success);
success = connect(_ui.downloadButton, SIGNAL(clicked()), this, SLOT(_downloadFiles()));
Q_ASSERT(success);
success = connect(_ui.treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(_currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));
Q_ASSERT(success);
Q_UNUSED(success);
}
void QGCUASFileView::_downloadFiles(void)
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Download Directory"),
QDir::homePath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
// And now download to this location
QString path;
QTreeWidgetItem* item = _ui.treeWidget->currentItem();
if (item && item->type() == _typeFile) {
do {
path.prepend("/" + item->text(0));
item = item->parent();
} while (item);
qDebug() << "Download: " << path;
bool success = connect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
Q_ASSERT(success);
success = connect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
Q_ASSERT(success);
Q_UNUSED(success);
_manager->downloadPath(path, QDir(dir));
}
}
void QGCUASFileView::_refreshTree(void)
{
_ui.treeWidget->clear();
_walkIndexStack.clear();
_walkItemStack.clear();
_walkIndexStack.append(0);
_walkItemStack.append(_ui.treeWidget->invisibleRootItem());
bool success = connect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_treeStatusMessage(QString)));
Q_ASSERT(success);
success = connect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_treeErrorMessage(QString)));
Q_ASSERT(success);
success = connect(_manager, SIGNAL(listComplete(void)), this, SLOT(_listComplete(void)));
Q_ASSERT(success);
Q_UNUSED(success);
// Don't queue up more than once
_ui.listFilesButton->setEnabled(false);
qDebug() << "List: /";
_manager->listDirectory("/");
}
void QGCUASFileView::_treeStatusMessage(const QString& msg)
{
int type;
if (msg.startsWith("F")) {
type = _typeFile;
} else if (msg.startsWith("D")) {
type = _typeDir;
if (msg == "D." || msg == "D..") {
return;
}
} else {
Q_ASSERT(false);
return; // Silence maybe-unitialized on type below
}
QTreeWidgetItem* item;
item = new QTreeWidgetItem(_walkItemStack.last(), type);
Q_CHECK_PTR(item);
item->setText(0, msg.right(msg.size() - 1));
}
void QGCUASFileView::_treeErrorMessage(const QString& msg)
{
QTreeWidgetItem* item;
item = new QTreeWidgetItem(_walkItemStack.last(), _typeError);
Q_CHECK_PTR(item);
item->setText(0, tr("Error: ") + msg);
// Fake listComplete signal after an error
_listComplete();
}
void QGCUASFileView::_listComplete(void)
{
// Walk the current items, traversing down into directories
Again:
int walkIndex = _walkIndexStack.last();
QTreeWidgetItem* parentItem = _walkItemStack.last();
QTreeWidgetItem* childItem = parentItem->child(walkIndex);
// Loop until we hit a directory
while (childItem && childItem->type() != _typeDir) {
// Move to next index at current level
_walkIndexStack.last() = ++walkIndex;
childItem = parentItem->child(walkIndex);
}
if (childItem) {
// Process this item
QString text = childItem->text(0);
// Move to the next item for processing at this level
_walkIndexStack.last() = ++walkIndex;
// Push this new directory on the stack
_walkItemStack.append(childItem);
_walkIndexStack.append(0);
// Ask for the directory list
QString dir;
for (int i=1; i<_walkItemStack.count(); i++) {
QTreeWidgetItem* item = _walkItemStack[i];
dir.append("/" + item->text(0));
}
qDebug() << "List:" << dir;
_manager->listDirectory(dir);
} else {
// We have run out of items at the this level, pop the stack and keep going at that level
_walkIndexStack.removeLast();
_walkItemStack.removeLast();
if (_walkIndexStack.count() != 0) {
goto Again;
} else {
disconnect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_treeStatusMessage(QString)));
disconnect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_treeErrorMessage(QString)));
disconnect(_manager, SIGNAL(listComplete(void)), this, SLOT(_listComplete(void)));
_ui.listFilesButton->setEnabled(true);
}
}
}
void QGCUASFileView::_downloadStatusMessage(const QString& msg)
{
disconnect(_manager, SIGNAL(statusMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
disconnect(_manager, SIGNAL(errorMessage(QString)), this, SLOT(_downloadStatusMessage(QString)));
QMessageBox msgBox;
msgBox.setWindowModality(Qt::ApplicationModal);
msgBox.setText(msg);
msgBox.exec();
}
void QGCUASFileView::_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
Q_UNUSED(previous);
_ui.downloadButton->setEnabled(current ? (current->type() == _typeFile) : false);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2021 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QElapsedTimer>
#include <QTimer>
#include <deconz/dbg_trace.h>
#include "event.h"
#include "resource.h"
#include "device_tick.h"
#define DEV_TICK_BOOT_TIME 8000
#define TICK_INTERVAL_JOIN 500
#define TICK_INTERVAL_IDLE 1000
struct JoinDevice
{
DeviceKey deviceKey;
quint8 macCapabilities;
};
static const char *RLocal = nullptr;
typedef void (*DT_StateHandler)(DeviceTickPrivate *d, const Event &event);
static void DT_StateInit(DeviceTickPrivate *d, const Event &event);
static void DT_StateJoin(DeviceTickPrivate *d, const Event &event);
static void DT_StateIdle(DeviceTickPrivate *d, const Event &event);
class DeviceTickPrivate
{
public:
DT_StateHandler stateHandler = DT_StateInit;
std::vector<JoinDevice> joinDevices;
DeviceTick *q = nullptr;
QTimer *timer = nullptr;
size_t devIter = 0;
const DeviceContainer *devices = nullptr;
};
/*! Constructor.
*/
DeviceTick::DeviceTick(const DeviceContainer &devices, QObject *parent) :
QObject(parent),
d(new DeviceTickPrivate)
{
d->devices = &devices;
d->q = this;
d->timer = new QTimer(this);
d->timer->setSingleShot(true);
connect(d->timer, &QTimer::timeout, this, &DeviceTick::timoutFired);
d->timer->start(DEV_TICK_BOOT_TIME);
}
/*! Destructor.
*/
DeviceTick::~DeviceTick()
{
Q_ASSERT(d);
delete d;
d = nullptr;
}
/*! Public event entry.
*/
void DeviceTick::handleEvent(const Event &event)
{
d->stateHandler(d, event);
}
/*! State timer callback.
*/
void DeviceTick::timoutFired()
{
d->stateHandler(d, Event(RLocal, REventStateTimeout, 0));
}
/*! Sets a new DeviceTick state.
The events REventStateLeave and REventStateEnter will be triggered accordingly.
*/
static void DT_SetState(DeviceTickPrivate *d, DT_StateHandler state)
{
if (d->stateHandler != state)
{
d->stateHandler(d, Event(RLocal, REventStateLeave, 0));
d->stateHandler = state;
d->stateHandler(d, Event(RLocal, REventStateEnter, 0));
}
}
/*! Starts the state timer. Free function to be mocked by test code.
*/
static void DT_StartTimer(DeviceTickPrivate *d, int timeoutMs)
{
d->timer->start(timeoutMs);
}
/*! Stops the state timer. Free function to be mocked by test code.
*/
static void DT_StopTimer(DeviceTickPrivate *d)
{
d->timer->stop();
}
/*! Initial state to wait DEV_TICK_BOOT_TIME seconds before starting normal operation.
*/
static void DT_StateInit(DeviceTickPrivate *d, const Event &event)
{
if (event.resource() == RLocal && event.what() == REventStateTimeout)
{
DBG_Printf(DBG_INFO, "DEV Tick.Init: booted after %lld seconds\n", DEV_TICK_BOOT_TIME);
DT_SetState(d, DT_StateIdle);
}
}
/*! Emits REventPoll to the next device in DT_StateIdle.
*/
static void DT_PollNextIdleDevice(DeviceTickPrivate *d)
{
const auto devCount = d->devices->size();
if (devCount == 0)
{
return;
}
d->devIter %= devCount;
const auto &device = d->devices->at(d->devIter);
Q_ASSERT(device);
if (device->reachable())
{
emit d->q->eventNotify(Event(device->prefix(), REventPoll, 0, device->key()));
}
d->devIter++;
}
/*! This state is active while Permit Join is disabled for normal idle operation.
It walks over all Devices in TICK_INTERVAL_IDLE spacing.
The state transitions to DT_StateJoin when REventPermitjoinEnabled is received.
*/
static void DT_StateIdle(DeviceTickPrivate *d, const Event &event)
{
if (event.what() == REventPermitjoinEnabled)
{
DT_SetState(d, DT_StateJoin);
}
else if (event.resource() == RLocal)
{
if (event.what() == REventStateTimeout)
{
DT_PollNextIdleDevice(d);
DT_StartTimer(d, TICK_INTERVAL_IDLE);
}
else if (event.what() == REventStateEnter)
{
DT_StartTimer(d, TICK_INTERVAL_IDLE);
}
else if (event.what() == REventStateLeave)
{
DT_StopTimer(d);
}
}
}
/*! Adds a joining device entry to the queue if not already present.
*/
static void DT_RegisterJoiningDevice(DeviceTickPrivate *d, DeviceKey deviceKey, quint8 macCapabilities)
{
Q_ASSERT(deviceKey != 0); // if this triggers we have problems elsewhere
auto i = std::find_if(d->joinDevices.cbegin(), d->joinDevices.cend(), [&deviceKey](const JoinDevice &dev)
{
return deviceKey == dev.deviceKey;
});
if (i == d->joinDevices.cend())
{
JoinDevice dev;
dev.deviceKey = deviceKey;
dev.macCapabilities = macCapabilities;
d->joinDevices.push_back(dev);
DBG_Printf(DBG_INFO, "DEV Tick: fast poll 0x%016llX, mac capabilities: 0x%02X\n", deviceKey, macCapabilities);
}
}
/*! Emits REventPoll to the next device in DT_StateJoin.
*/
static void DT_PollNextJoiningDevice(DeviceTickPrivate *d)
{
if (d->joinDevices.empty())
{
return;
}
d->devIter %= d->joinDevices.size();
Q_ASSERT(d->devIter < d->joinDevices.size());
const JoinDevice &device = d->joinDevices.at(d->devIter);
emit d->q->eventNotify(Event(RDevices, REventPoll, 0, device.deviceKey));
d->devIter++;
}
/*! This state is active while Permit Join is enabled.
When a REventDeviceAnnounce event is received, the device is added to a joining
queue and processed exclusivly and quickly.
The state transitions to DT_StateIdle when Permit Join is disabled.
*/
static void DT_StateJoin(DeviceTickPrivate *d, const Event &event)
{
if (event.what() == REventPermitjoinDisabled)
{
DT_SetState(d, DT_StateIdle);
}
else if (event.what() == REventDeviceAnnounce)
{
DBG_Printf(DBG_INFO, "DEV Tick.Join: %s\n", event.what());
DT_RegisterJoiningDevice(d, event.deviceKey(), static_cast<quint8>(event.num()));
}
else if (event.resource() == RLocal)
{
if (event.what() == REventStateTimeout)
{
DT_PollNextJoiningDevice(d);
DT_StartTimer(d, TICK_INTERVAL_JOIN);
}
else if (event.what() == REventStateEnter)
{
DT_StartTimer(d, TICK_INTERVAL_JOIN);
}
else if (event.what() == REventStateLeave)
{
DT_StopTimer(d);
d->joinDevices.clear();
}
}
}
<commit_msg>Device Tick: While Permit join is enabled send REventAwake<commit_after>/*
* Copyright (c) 2021 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QElapsedTimer>
#include <QTimer>
#include <deconz/dbg_trace.h>
#include "event.h"
#include "resource.h"
#include "device_tick.h"
#define DEV_TICK_BOOT_TIME 8000
#define TICK_INTERVAL_JOIN 500
#define TICK_INTERVAL_IDLE 1000
struct JoinDevice
{
DeviceKey deviceKey;
quint8 macCapabilities;
};
static const char *RLocal = nullptr;
typedef void (*DT_StateHandler)(DeviceTickPrivate *d, const Event &event);
static void DT_StateInit(DeviceTickPrivate *d, const Event &event);
static void DT_StateJoin(DeviceTickPrivate *d, const Event &event);
static void DT_StateIdle(DeviceTickPrivate *d, const Event &event);
class DeviceTickPrivate
{
public:
DT_StateHandler stateHandler = DT_StateInit;
std::vector<JoinDevice> joinDevices;
DeviceTick *q = nullptr;
QTimer *timer = nullptr;
size_t devIter = 0;
const DeviceContainer *devices = nullptr;
};
/*! Constructor.
*/
DeviceTick::DeviceTick(const DeviceContainer &devices, QObject *parent) :
QObject(parent),
d(new DeviceTickPrivate)
{
d->devices = &devices;
d->q = this;
d->timer = new QTimer(this);
d->timer->setSingleShot(true);
connect(d->timer, &QTimer::timeout, this, &DeviceTick::timoutFired);
d->timer->start(DEV_TICK_BOOT_TIME);
}
/*! Destructor.
*/
DeviceTick::~DeviceTick()
{
Q_ASSERT(d);
delete d;
d = nullptr;
}
/*! Public event entry.
*/
void DeviceTick::handleEvent(const Event &event)
{
d->stateHandler(d, event);
}
/*! State timer callback.
*/
void DeviceTick::timoutFired()
{
d->stateHandler(d, Event(RLocal, REventStateTimeout, 0));
}
/*! Sets a new DeviceTick state.
The events REventStateLeave and REventStateEnter will be triggered accordingly.
*/
static void DT_SetState(DeviceTickPrivate *d, DT_StateHandler state)
{
if (d->stateHandler != state)
{
d->stateHandler(d, Event(RLocal, REventStateLeave, 0));
d->stateHandler = state;
d->stateHandler(d, Event(RLocal, REventStateEnter, 0));
}
}
/*! Starts the state timer. Free function to be mocked by test code.
*/
static void DT_StartTimer(DeviceTickPrivate *d, int timeoutMs)
{
d->timer->start(timeoutMs);
}
/*! Stops the state timer. Free function to be mocked by test code.
*/
static void DT_StopTimer(DeviceTickPrivate *d)
{
d->timer->stop();
}
/*! Initial state to wait DEV_TICK_BOOT_TIME seconds before starting normal operation.
*/
static void DT_StateInit(DeviceTickPrivate *d, const Event &event)
{
if (event.resource() == RLocal && event.what() == REventStateTimeout)
{
DBG_Printf(DBG_INFO, "DEV Tick.Init: booted after %lld seconds\n", DEV_TICK_BOOT_TIME);
DT_SetState(d, DT_StateIdle);
}
}
/*! Emits REventPoll to the next device in DT_StateIdle.
*/
static void DT_PollNextIdleDevice(DeviceTickPrivate *d)
{
const auto devCount = d->devices->size();
if (devCount == 0)
{
return;
}
d->devIter %= devCount;
const auto &device = d->devices->at(d->devIter);
Q_ASSERT(device);
if (device->reachable())
{
emit d->q->eventNotify(Event(device->prefix(), REventPoll, 0, device->key()));
}
d->devIter++;
}
/*! This state is active while Permit Join is disabled for normal idle operation.
It walks over all Devices in TICK_INTERVAL_IDLE spacing.
The state transitions to DT_StateJoin when REventPermitjoinEnabled is received.
*/
static void DT_StateIdle(DeviceTickPrivate *d, const Event &event)
{
if (event.what() == REventPermitjoinEnabled)
{
DT_SetState(d, DT_StateJoin);
}
else if (event.resource() == RLocal)
{
if (event.what() == REventStateTimeout)
{
DT_PollNextIdleDevice(d);
DT_StartTimer(d, TICK_INTERVAL_IDLE);
}
else if (event.what() == REventStateEnter)
{
DT_StartTimer(d, TICK_INTERVAL_IDLE);
}
else if (event.what() == REventStateLeave)
{
DT_StopTimer(d);
}
}
}
/*! Adds a joining device entry to the queue if not already present.
*/
static void DT_RegisterJoiningDevice(DeviceTickPrivate *d, DeviceKey deviceKey, quint8 macCapabilities)
{
Q_ASSERT(deviceKey != 0); // if this triggers we have problems elsewhere
auto i = std::find_if(d->joinDevices.cbegin(), d->joinDevices.cend(), [&deviceKey](const JoinDevice &dev)
{
return deviceKey == dev.deviceKey;
});
if (i == d->joinDevices.cend())
{
JoinDevice dev;
dev.deviceKey = deviceKey;
dev.macCapabilities = macCapabilities;
d->joinDevices.push_back(dev);
DBG_Printf(DBG_INFO, "DEV Tick: fast poll 0x%016llX, mac capabilities: 0x%02X\n", deviceKey, macCapabilities);
}
}
/*! Emits REventPoll to the next device in DT_StateJoin.
*/
static void DT_PollNextJoiningDevice(DeviceTickPrivate *d)
{
if (d->joinDevices.empty())
{
return;
}
d->devIter %= d->joinDevices.size();
Q_ASSERT(d->devIter < d->joinDevices.size());
const JoinDevice &device = d->joinDevices.at(d->devIter);
emit d->q->eventNotify(Event(RDevices, REventAwake, 0, device.deviceKey));
d->devIter++;
}
/*! This state is active while Permit Join is enabled.
When a REventDeviceAnnounce event is received, the device is added to a joining
queue and processed exclusivly and quickly.
The state transitions to DT_StateIdle when Permit Join is disabled.
*/
static void DT_StateJoin(DeviceTickPrivate *d, const Event &event)
{
if (event.what() == REventPermitjoinDisabled)
{
DT_SetState(d, DT_StateIdle);
}
else if (event.what() == REventDeviceAnnounce)
{
DBG_Printf(DBG_INFO, "DEV Tick.Join: %s\n", event.what());
DT_RegisterJoiningDevice(d, event.deviceKey(), static_cast<quint8>(event.num()));
}
else if (event.resource() == RLocal)
{
if (event.what() == REventStateTimeout)
{
DT_PollNextJoiningDevice(d);
DT_StartTimer(d, TICK_INTERVAL_JOIN);
}
else if (event.what() == REventStateEnter)
{
DT_StartTimer(d, TICK_INTERVAL_JOIN);
}
else if (event.what() == REventStateLeave)
{
DT_StopTimer(d);
d->joinDevices.clear();
}
}
}
<|endoftext|> |
<commit_before>#include "ClientAuthOperation_p.hpp"
#include "AccountStorage.hpp"
#include "CAppInformation.hpp"
#include "ConnectionApi_p.hpp"
#include "ClientBackend.hpp"
#include "ClientConnection.hpp"
#include "ClientRpcLayer.hpp"
#include "ClientRpcAuthLayer.hpp"
#include "ClientRpcAccountLayer.hpp"
#include "ConnectionError.hpp"
#include "DataStorage_p.hpp"
#include "Debug_p.hpp"
#include "PendingRpcOperation.hpp"
#include "Utils.hpp"
#include "RpcError.hpp"
#ifdef DEVELOPER_BUILD
#include "TLTypesDebug.hpp"
#endif
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_loggingClientAuthOperation, "telegram.client.auth.operation", QtWarningMsg)
namespace Telegram {
namespace Client {
// Explicit templates instantiation to suppress compilation warnings
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAccountPassword *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthAuthorization *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthSentCode *output);
AuthOperationPrivate::AuthOperationPrivate(AuthOperation *parent) :
QObject(parent),
PendingOperationPrivate(),
q_ptr(parent)
{
}
AuthOperationPrivate *AuthOperationPrivate::get(AuthOperation *parent)
{
return static_cast<AuthOperationPrivate*>(parent->d->toQObject());
}
const AuthOperationPrivate *AuthOperationPrivate::get(const AuthOperation *parent)
{
return static_cast<const AuthOperationPrivate*>(parent->d->toQObject());
}
void AuthOperationPrivate::setBackend(Backend *backend)
{
m_backend = backend;
}
void AuthOperationPrivate::setRunMethod(RunMethod method)
{
m_runMethod = method;
}
AuthOperation::AuthOperation(QObject *parent) :
PendingOperation(parent)
{
d = new AuthOperationPrivate(this);
}
QString AuthOperation::phoneNumber() const
{
Q_D(const AuthOperation);
return d->m_phoneNumber;
}
QString AuthOperation::passwordHint() const
{
Q_D(const AuthOperation);
return d->m_passwordHint;
}
bool AuthOperation::hasRecovery() const
{
Q_D(const AuthOperation);
return d->m_hasRecovery;
}
bool AuthOperation::isRegistered() const
{
Q_D(const AuthOperation);
return d->m_registered;
}
void AuthOperation::setPhoneNumber(const QString &phoneNumber)
{
Q_D(AuthOperation);
d->m_phoneNumber = phoneNumber;
}
void AuthOperation::startImplementation()
{
Q_D(AuthOperation);
if (d->m_runMethod) {
callMember<>(d, d->m_runMethod);
}
}
void AuthOperation::abort()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
PendingOperation *AuthOperationPrivate::checkAuthorization()
{
Q_Q(AuthOperation);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO;
AccountStorage *storage = m_backend->accountStorage();
if (!storage->hasMinimalDataSet()) {
q->setFinishedWithError({{PendingOperation::c_text(), QStringLiteral("No minimal account data set")}});
return nullptr;
}
// Backend::connectToServer() automatically takes the data from the account storage,
// So just make some RPC call to check if connection works.
PendingRpcOperation *updateStatusOperation = accountLayer()->updateStatus(false);
connect(updateStatusOperation, &PendingRpcOperation::finished,
this, &AuthOperationPrivate::onAccountStatusUpdateFinished);
return updateStatusOperation;
}
PendingOperation *AuthOperationPrivate::requestAuthCode()
{
Q_Q(AuthOperation);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO;
const CAppInformation *appInfo = m_backend->m_appInformation;
if (!appInfo) {
const QString text = QStringLiteral("Unable to request auth code, "
"because the application information is not set");
return PendingOperation::failOperation(text, this);
}
if (m_phoneNumber.isEmpty()) {
emit q->phoneNumberRequired();
return nullptr;
}
AuthRpcLayer::PendingAuthSentCode *requestCodeOperation
= authLayer()->sendCode(m_phoneNumber, appInfo->appId(), appInfo->appHash());
Connection *connection = Connection::fromOperation(requestCodeOperation);
connect(connection, &BaseConnection::errorOccured, this, &AuthOperationPrivate::onConnectionError);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO
<< "requestPhoneCode"
<< Telegram::Utils::maskPhoneNumber(m_phoneNumber)
<< "on dc" << connection->dcOption().id;
connect(requestCodeOperation, &PendingOperation::finished, this, [this, requestCodeOperation] {
this->onRequestAuthCodeFinished(requestCodeOperation);
});
return requestCodeOperation;
}
PendingOperation *AuthOperation::submitAuthCode(const QString &code)
{
Q_D(AuthOperation);
return d->submitAuthCode(code);
}
PendingOperation *AuthOperationPrivate::submitAuthCode(const QString &code)
{
if (m_authCodeHash.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth code without a code hash");
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << text;
return PendingOperation::failOperation(text);
}
if (code.isEmpty()) {
const QString text = QStringLiteral("Deny to submit empty auth code");
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << text;
return PendingOperation::failOperation(text);
}
PendingOperation *submitOperation = new PendingOperation("AuthOperationPrivate::submitAuthCode", this);
PendingRpcOperation *sendCodeOperation = nullptr;
if (m_registered) {
sendCodeOperation = authLayer()->signIn(m_phoneNumber, m_authCodeHash, code);
connect(sendCodeOperation, &PendingRpcOperation::finished, this,
[this, sendCodeOperation, submitOperation]() {
this->onSignInRpcFinished(sendCodeOperation, submitOperation);
});
} else {
sendCodeOperation = authLayer()->signUp(m_phoneNumber, m_authCodeHash, code, m_firstName, m_lastName);
connect(sendCodeOperation, &PendingRpcOperation::finished, this,
[this, sendCodeOperation, submitOperation]() {
this->onSignUpRpcFinished(sendCodeOperation, submitOperation);
});
}
return sendCodeOperation;
}
PendingOperation *AuthOperationPrivate::getPassword()
{
PendingRpcOperation *passwordRequest = accountLayer()->getPassword();
connect(passwordRequest, &PendingRpcOperation::finished, this, &AuthOperationPrivate::onPasswordRequestFinished);
return passwordRequest;
}
PendingOperation *AuthOperation::submitPassword(const QString &password)
{
Q_D(AuthOperation);
return d->submitPassword(password);
}
PendingOperation *AuthOperationPrivate::submitPassword(const QString &password)
{
if (m_passwordCurrentSalt.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth password (password salt is missing)");
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
const QByteArray pwdData = m_passwordCurrentSalt + password.toUtf8() + m_passwordCurrentSalt;
const QByteArray pwdHash = Utils::sha256(pwdData);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "slt:" << Utils::maskByteArray(m_passwordCurrentSalt);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "pwd:" << Utils::maskByteArray(pwdHash);
PendingRpcOperation *sendPasswordOperation = authLayer()->checkPassword(pwdHash);
connect(sendPasswordOperation, &PendingRpcOperation::finished, this, &AuthOperationPrivate::onCheckPasswordFinished);
return sendPasswordOperation;
}
void AuthOperation::submitPhoneNumber(const QString &phoneNumber)
{
setPhoneNumber(phoneNumber);
if (!isFinished()) {
start();
}
}
bool AuthOperation::submitName(const QString &firstName, const QString &lastName)
{
Q_D(AuthOperation);
d->m_firstName = firstName;
d->m_lastName = lastName;
return !firstName.isEmpty() && !lastName.isEmpty();
}
void AuthOperation::requestCall()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
void AuthOperation::requestSms()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
void AuthOperation::recovery()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
void AuthOperationPrivate::setPasswordCurrentSalt(const QByteArray &salt)
{
m_passwordCurrentSalt = salt;
}
void AuthOperationPrivate::setPasswordHint(const QString &hint)
{
Q_Q(AuthOperation);
if (m_passwordHint == hint) {
return;
}
m_passwordHint = hint;
emit q->passwordHintChanged(hint);
}
void AuthOperationPrivate::setRegistered(bool registered)
{
Q_Q(AuthOperation);
m_registered = registered;
emit q->registeredChanged(registered);
}
AccountRpcLayer *AuthOperationPrivate::accountLayer() const
{
return m_backend->accountLayer();
}
AuthRpcLayer *AuthOperationPrivate::authLayer() const
{
return m_backend->authLayer();
}
AuthOperationPrivate *AuthOperation::d_func()
{
return AuthOperationPrivate::get(this);
}
const AuthOperationPrivate *AuthOperation::d_func() const
{
return AuthOperationPrivate::get(this);
}
void AuthOperationPrivate::onRequestAuthCodeFinished(PendingRpcOperation *rpcOperation)
{
Q_Q(AuthOperation);
if (rpcOperation->rpcError() && rpcOperation->rpcError()->type == RpcError::SeeOther) {
if (m_backend->connectionApi()->status() != ConnectionApi::StatusWaitForAuthentication) {
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "Unexpected SeeOther";
}
const quint32 dcId = rpcOperation->rpcError()->argument;
ConnectionApiPrivate *privateApi = ConnectionApiPrivate::get(m_backend->connectionApi());
connect(privateApi->connectToDc(dcId), &PendingOperation::finished,
this, &AuthOperationPrivate::onRedirectedConnectFinished);
return;
}
if (!rpcOperation->isSucceeded()) {
q->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
}
TLAuthSentCode result;
authLayer()->processReply(rpcOperation, &result);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << result.tlType << result.phoneCodeHash;
if (result.isValid()) {
m_authCodeHash = result.phoneCodeHash;
setRegistered(result.phoneRegistered());
emit q->authCodeRequired();
}
}
void AuthOperationPrivate::onSignInRpcFinished(PendingRpcOperation *rpcOperation, PendingOperation *submitAuthCodeOperation)
{
Q_Q(AuthOperation);
if (rpcOperation->rpcError()) {
const RpcError *error = rpcOperation->rpcError();
switch (error->reason) {
case RpcError::SessionPasswordNeeded:
submitAuthCodeOperation->setFinished();
getPassword();
return;
case RpcError::PhoneCodeHashEmpty:
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "internal error?" << error->message;
break;
case RpcError::PhoneCodeEmpty:
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "internal error?" << error->message;
break;
case RpcError::PhoneCodeInvalid:
emit q->authCodeCheckFailed(AuthOperation::AuthCodeStatusInvalid);
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
case RpcError::PhoneCodeExpired:
emit q->authCodeCheckFailed(AuthOperation::AuthCodeStatusExpired);
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
default:
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "Unexpected error" << error->message;
break;
}
}
if (!rpcOperation->isSucceeded()) {
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
q->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
}
submitAuthCodeOperation->setFinished();
TLAuthAuthorization result;
authLayer()->processReply(rpcOperation, &result);
onGotAuthorization(rpcOperation, result);
}
void AuthOperationPrivate::onSignUpRpcFinished(PendingRpcOperation *rpcOperation, PendingOperation *submitAuthCodeOperation)
{
Q_Q(AuthOperation);
if (!rpcOperation->isSucceeded()) {
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
q->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
}
submitAuthCodeOperation->setFinished();
TLAuthAuthorization result;
authLayer()->processReply(rpcOperation, &result);
onGotAuthorization(rpcOperation, result);
}
void AuthOperationPrivate::onPasswordRequestFinished(PendingRpcOperation *operation)
{
Q_Q(AuthOperation);
if (!operation->isSucceeded()) {
q->setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAccountPassword result;
authLayer()->processReply(operation, &result);
#ifdef DEVELOPER_BUILD
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << result;
#endif
setPasswordCurrentSalt(result.currentSalt);
setPasswordHint(result.hint);
emit q->passwordRequired();
}
void AuthOperationPrivate::onCheckPasswordFinished(PendingRpcOperation *operation)
{
Q_Q(AuthOperation);
if (operation->rpcError()) {
const RpcError *error = operation->rpcError();
if (error->reason == RpcError::PasswordHashInvalid) {
emit q->passwordCheckFailed();
return;
}
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << error->message;
}
if (!operation->isSucceeded()) {
q->setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthAuthorization result;
authLayer()->processReply(operation, &result);
onGotAuthorization(operation, result);
}
void AuthOperationPrivate::onGotAuthorization(PendingRpcOperation *operation, const TLAuthAuthorization &authorization)
{
Q_Q(AuthOperation);
qCDebug(c_loggingClientAuthOperation) << authorization.user.phone
<< authorization.user.firstName
<< authorization.user.lastName;
AccountStorage *storage = m_backend->accountStorage();
storage->setPhoneNumber(authorization.user.phone);
if (storage->accountIdentifier().isEmpty()) {
storage->setAccountIdentifier(authorization.user.phone);
}
DataInternalApi::get(m_backend->dataStorage())->processData(authorization.user);
m_authenticatedConnection = Connection::fromOperation(operation);
m_authenticatedConnection->setStatus(BaseConnection::Status::Signed, BaseConnection::StatusReason::Remote);
q->setFinished();
}
void AuthOperationPrivate::onAccountStatusUpdateFinished(PendingRpcOperation *operation)
{
Q_Q(AuthOperation);
if (!operation->isSucceeded()) {
q->setFinishedWithError(operation->errorDetails());
return;
}
m_authenticatedConnection = Connection::fromOperation(operation);
m_authenticatedConnection->setStatus(BaseConnection::Status::Signed, BaseConnection::StatusReason::Local);
q->setFinished();
}
void AuthOperationPrivate::onConnectionError(const QByteArray &errorBytes)
{
const ConnectionError error(errorBytes);
Q_Q(AuthOperation);
if (q->isFinished()) {
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "Connection error on finished auth operation:" << error.description();
return;
}
q->setFinishedWithError({{PendingOperation::c_text(), error.description()}});
}
void AuthOperationPrivate::onRedirectedConnectFinished(PendingOperation *operation)
{
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << operation->errorDetails();
if (operation->isFailed()) {
return;
}
requestAuthCode();
}
} // Client
} // Telegram namespace
<commit_msg>Client::AuthOperation: Check connection for existence<commit_after>#include "ClientAuthOperation_p.hpp"
#include "AccountStorage.hpp"
#include "CAppInformation.hpp"
#include "ConnectionApi_p.hpp"
#include "ClientBackend.hpp"
#include "ClientConnection.hpp"
#include "ClientRpcLayer.hpp"
#include "ClientRpcAuthLayer.hpp"
#include "ClientRpcAccountLayer.hpp"
#include "ConnectionError.hpp"
#include "DataStorage_p.hpp"
#include "Debug_p.hpp"
#include "PendingRpcOperation.hpp"
#include "Utils.hpp"
#include "RpcError.hpp"
#ifdef DEVELOPER_BUILD
#include "TLTypesDebug.hpp"
#endif
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_loggingClientAuthOperation, "telegram.client.auth.operation", QtWarningMsg)
namespace Telegram {
namespace Client {
// Explicit templates instantiation to suppress compilation warnings
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAccountPassword *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthAuthorization *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthSentCode *output);
AuthOperationPrivate::AuthOperationPrivate(AuthOperation *parent) :
QObject(parent),
PendingOperationPrivate(),
q_ptr(parent)
{
}
AuthOperationPrivate *AuthOperationPrivate::get(AuthOperation *parent)
{
return static_cast<AuthOperationPrivate*>(parent->d->toQObject());
}
const AuthOperationPrivate *AuthOperationPrivate::get(const AuthOperation *parent)
{
return static_cast<const AuthOperationPrivate*>(parent->d->toQObject());
}
void AuthOperationPrivate::setBackend(Backend *backend)
{
m_backend = backend;
}
void AuthOperationPrivate::setRunMethod(RunMethod method)
{
m_runMethod = method;
}
AuthOperation::AuthOperation(QObject *parent) :
PendingOperation(parent)
{
d = new AuthOperationPrivate(this);
}
QString AuthOperation::phoneNumber() const
{
Q_D(const AuthOperation);
return d->m_phoneNumber;
}
QString AuthOperation::passwordHint() const
{
Q_D(const AuthOperation);
return d->m_passwordHint;
}
bool AuthOperation::hasRecovery() const
{
Q_D(const AuthOperation);
return d->m_hasRecovery;
}
bool AuthOperation::isRegistered() const
{
Q_D(const AuthOperation);
return d->m_registered;
}
void AuthOperation::setPhoneNumber(const QString &phoneNumber)
{
Q_D(AuthOperation);
d->m_phoneNumber = phoneNumber;
}
void AuthOperation::startImplementation()
{
Q_D(AuthOperation);
if (d->m_runMethod) {
callMember<>(d, d->m_runMethod);
}
}
void AuthOperation::abort()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
PendingOperation *AuthOperationPrivate::checkAuthorization()
{
Q_Q(AuthOperation);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO;
AccountStorage *storage = m_backend->accountStorage();
if (!storage->hasMinimalDataSet()) {
q->setFinishedWithError({{PendingOperation::c_text(), QStringLiteral("No minimal account data set")}});
return nullptr;
}
// Backend::connectToServer() automatically takes the data from the account storage,
// So just make some RPC call to check if connection works.
PendingRpcOperation *updateStatusOperation = accountLayer()->updateStatus(false);
connect(updateStatusOperation, &PendingRpcOperation::finished,
this, &AuthOperationPrivate::onAccountStatusUpdateFinished);
return updateStatusOperation;
}
PendingOperation *AuthOperationPrivate::requestAuthCode()
{
Q_Q(AuthOperation);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO;
const CAppInformation *appInfo = m_backend->m_appInformation;
if (!appInfo) {
const QString text = QStringLiteral("Unable to request auth code, "
"because the application information is not set");
return PendingOperation::failOperation(text, this);
}
if (m_backend->connectionApi()->status() != ConnectionApi::StatusWaitForAuthentication) {
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "Connection doesn't wait for authentication";
return nullptr;
}
if (m_phoneNumber.isEmpty()) {
emit q->phoneNumberRequired();
return nullptr;
}
Connection *connection = ConnectionApiPrivate::get(m_backend->connectionApi())->getDefaultConnection();
if (!connection) {
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "Unable to get default connection!";
return nullptr;
}
AuthRpcLayer::PendingAuthSentCode *requestCodeOperation
= authLayer()->sendCode(m_phoneNumber, appInfo->appId(), appInfo->appHash());
connect(connection, &BaseConnection::errorOccured, this, &AuthOperationPrivate::onConnectionError);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO
<< "requestPhoneCode"
<< Telegram::Utils::maskPhoneNumber(m_phoneNumber)
<< "on dc" << connection->dcOption().id;
connect(requestCodeOperation, &PendingOperation::finished, this, [this, requestCodeOperation] {
this->onRequestAuthCodeFinished(requestCodeOperation);
});
return requestCodeOperation;
}
PendingOperation *AuthOperation::submitAuthCode(const QString &code)
{
Q_D(AuthOperation);
return d->submitAuthCode(code);
}
PendingOperation *AuthOperationPrivate::submitAuthCode(const QString &code)
{
if (m_authCodeHash.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth code without a code hash");
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << text;
return PendingOperation::failOperation(text);
}
if (code.isEmpty()) {
const QString text = QStringLiteral("Deny to submit empty auth code");
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << text;
return PendingOperation::failOperation(text);
}
PendingOperation *submitOperation = new PendingOperation("AuthOperationPrivate::submitAuthCode", this);
PendingRpcOperation *sendCodeOperation = nullptr;
if (m_registered) {
sendCodeOperation = authLayer()->signIn(m_phoneNumber, m_authCodeHash, code);
connect(sendCodeOperation, &PendingRpcOperation::finished, this,
[this, sendCodeOperation, submitOperation]() {
this->onSignInRpcFinished(sendCodeOperation, submitOperation);
});
} else {
sendCodeOperation = authLayer()->signUp(m_phoneNumber, m_authCodeHash, code, m_firstName, m_lastName);
connect(sendCodeOperation, &PendingRpcOperation::finished, this,
[this, sendCodeOperation, submitOperation]() {
this->onSignUpRpcFinished(sendCodeOperation, submitOperation);
});
}
return sendCodeOperation;
}
PendingOperation *AuthOperationPrivate::getPassword()
{
PendingRpcOperation *passwordRequest = accountLayer()->getPassword();
connect(passwordRequest, &PendingRpcOperation::finished, this, &AuthOperationPrivate::onPasswordRequestFinished);
return passwordRequest;
}
PendingOperation *AuthOperation::submitPassword(const QString &password)
{
Q_D(AuthOperation);
return d->submitPassword(password);
}
PendingOperation *AuthOperationPrivate::submitPassword(const QString &password)
{
if (m_passwordCurrentSalt.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth password (password salt is missing)");
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
const QByteArray pwdData = m_passwordCurrentSalt + password.toUtf8() + m_passwordCurrentSalt;
const QByteArray pwdHash = Utils::sha256(pwdData);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "slt:" << Utils::maskByteArray(m_passwordCurrentSalt);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "pwd:" << Utils::maskByteArray(pwdHash);
PendingRpcOperation *sendPasswordOperation = authLayer()->checkPassword(pwdHash);
connect(sendPasswordOperation, &PendingRpcOperation::finished, this, &AuthOperationPrivate::onCheckPasswordFinished);
return sendPasswordOperation;
}
void AuthOperation::submitPhoneNumber(const QString &phoneNumber)
{
setPhoneNumber(phoneNumber);
if (!isFinished()) {
start();
}
}
bool AuthOperation::submitName(const QString &firstName, const QString &lastName)
{
Q_D(AuthOperation);
d->m_firstName = firstName;
d->m_lastName = lastName;
return !firstName.isEmpty() && !lastName.isEmpty();
}
void AuthOperation::requestCall()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
void AuthOperation::requestSms()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
void AuthOperation::recovery()
{
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "STUB";
}
void AuthOperationPrivate::setPasswordCurrentSalt(const QByteArray &salt)
{
m_passwordCurrentSalt = salt;
}
void AuthOperationPrivate::setPasswordHint(const QString &hint)
{
Q_Q(AuthOperation);
if (m_passwordHint == hint) {
return;
}
m_passwordHint = hint;
emit q->passwordHintChanged(hint);
}
void AuthOperationPrivate::setRegistered(bool registered)
{
Q_Q(AuthOperation);
m_registered = registered;
emit q->registeredChanged(registered);
}
AccountRpcLayer *AuthOperationPrivate::accountLayer() const
{
return m_backend->accountLayer();
}
AuthRpcLayer *AuthOperationPrivate::authLayer() const
{
return m_backend->authLayer();
}
AuthOperationPrivate *AuthOperation::d_func()
{
return AuthOperationPrivate::get(this);
}
const AuthOperationPrivate *AuthOperation::d_func() const
{
return AuthOperationPrivate::get(this);
}
void AuthOperationPrivate::onRequestAuthCodeFinished(PendingRpcOperation *rpcOperation)
{
Q_Q(AuthOperation);
if (rpcOperation->rpcError() && rpcOperation->rpcError()->type == RpcError::SeeOther) {
if (m_backend->connectionApi()->status() != ConnectionApi::StatusWaitForAuthentication) {
qCWarning(c_loggingClientAuthOperation) << CALL_INFO << "Unexpected SeeOther";
}
const quint32 dcId = rpcOperation->rpcError()->argument;
ConnectionApiPrivate *privateApi = ConnectionApiPrivate::get(m_backend->connectionApi());
connect(privateApi->connectToDc(dcId), &PendingOperation::finished,
this, &AuthOperationPrivate::onRedirectedConnectFinished);
return;
}
if (!rpcOperation->isSucceeded()) {
q->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
}
TLAuthSentCode result;
authLayer()->processReply(rpcOperation, &result);
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << result.tlType << result.phoneCodeHash;
if (result.isValid()) {
m_authCodeHash = result.phoneCodeHash;
setRegistered(result.phoneRegistered());
emit q->authCodeRequired();
}
}
void AuthOperationPrivate::onSignInRpcFinished(PendingRpcOperation *rpcOperation, PendingOperation *submitAuthCodeOperation)
{
Q_Q(AuthOperation);
if (rpcOperation->rpcError()) {
const RpcError *error = rpcOperation->rpcError();
switch (error->reason) {
case RpcError::SessionPasswordNeeded:
submitAuthCodeOperation->setFinished();
getPassword();
return;
case RpcError::PhoneCodeHashEmpty:
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "internal error?" << error->message;
break;
case RpcError::PhoneCodeEmpty:
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "internal error?" << error->message;
break;
case RpcError::PhoneCodeInvalid:
emit q->authCodeCheckFailed(AuthOperation::AuthCodeStatusInvalid);
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
case RpcError::PhoneCodeExpired:
emit q->authCodeCheckFailed(AuthOperation::AuthCodeStatusExpired);
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
default:
qCCritical(c_loggingClientAuthOperation) << CALL_INFO << "Unexpected error" << error->message;
break;
}
}
if (!rpcOperation->isSucceeded()) {
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
q->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
}
submitAuthCodeOperation->setFinished();
TLAuthAuthorization result;
authLayer()->processReply(rpcOperation, &result);
onGotAuthorization(rpcOperation, result);
}
void AuthOperationPrivate::onSignUpRpcFinished(PendingRpcOperation *rpcOperation, PendingOperation *submitAuthCodeOperation)
{
Q_Q(AuthOperation);
if (!rpcOperation->isSucceeded()) {
submitAuthCodeOperation->setDelayedFinishedWithError(rpcOperation->errorDetails());
q->setDelayedFinishedWithError(rpcOperation->errorDetails());
return;
}
submitAuthCodeOperation->setFinished();
TLAuthAuthorization result;
authLayer()->processReply(rpcOperation, &result);
onGotAuthorization(rpcOperation, result);
}
void AuthOperationPrivate::onPasswordRequestFinished(PendingRpcOperation *operation)
{
Q_Q(AuthOperation);
if (!operation->isSucceeded()) {
q->setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAccountPassword result;
authLayer()->processReply(operation, &result);
#ifdef DEVELOPER_BUILD
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << result;
#endif
setPasswordCurrentSalt(result.currentSalt);
setPasswordHint(result.hint);
emit q->passwordRequired();
}
void AuthOperationPrivate::onCheckPasswordFinished(PendingRpcOperation *operation)
{
Q_Q(AuthOperation);
if (operation->rpcError()) {
const RpcError *error = operation->rpcError();
if (error->reason == RpcError::PasswordHashInvalid) {
emit q->passwordCheckFailed();
return;
}
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << error->message;
}
if (!operation->isSucceeded()) {
q->setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthAuthorization result;
authLayer()->processReply(operation, &result);
onGotAuthorization(operation, result);
}
void AuthOperationPrivate::onGotAuthorization(PendingRpcOperation *operation, const TLAuthAuthorization &authorization)
{
Q_Q(AuthOperation);
qCDebug(c_loggingClientAuthOperation) << authorization.user.phone
<< authorization.user.firstName
<< authorization.user.lastName;
AccountStorage *storage = m_backend->accountStorage();
storage->setPhoneNumber(authorization.user.phone);
if (storage->accountIdentifier().isEmpty()) {
storage->setAccountIdentifier(authorization.user.phone);
}
DataInternalApi::get(m_backend->dataStorage())->processData(authorization.user);
m_authenticatedConnection = Connection::fromOperation(operation);
m_authenticatedConnection->setStatus(BaseConnection::Status::Signed, BaseConnection::StatusReason::Remote);
q->setFinished();
}
void AuthOperationPrivate::onAccountStatusUpdateFinished(PendingRpcOperation *operation)
{
Q_Q(AuthOperation);
if (!operation->isSucceeded()) {
q->setFinishedWithError(operation->errorDetails());
return;
}
m_authenticatedConnection = Connection::fromOperation(operation);
m_authenticatedConnection->setStatus(BaseConnection::Status::Signed, BaseConnection::StatusReason::Local);
q->setFinished();
}
void AuthOperationPrivate::onConnectionError(const QByteArray &errorBytes)
{
const ConnectionError error(errorBytes);
Q_Q(AuthOperation);
if (q->isFinished()) {
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << "Connection error on finished auth operation:" << error.description();
return;
}
q->setFinishedWithError({{PendingOperation::c_text(), error.description()}});
}
void AuthOperationPrivate::onRedirectedConnectFinished(PendingOperation *operation)
{
qCDebug(c_loggingClientAuthOperation) << CALL_INFO << operation->errorDetails();
if (operation->isFailed()) {
return;
}
requestAuthCode();
}
} // Client
} // Telegram namespace
<|endoftext|> |
<commit_before>// Bell inequalities (CHSH) violation
// Source: ./examples/bell_inequalities.cpp
#include <qpp.h>
using namespace qpp;
using std::cout;
using std::endl;
//TODO: finish the example, incomplete now
int main()
{
ket psi = st.b11; // Measure the singlet Bell state (|01>-|10>)/sqrt(2)
idx N = 1; // number of measurements each party does
// gates
cmat Q = gt.Z;
cmat R = gt.X;
cmat S = (-gt.Z - gt.X) / std::sqrt(2);
cmat T = (gt.Z - gt.X) / std::sqrt(2);
//Q = S = gt.Z;
//R = T = gt.X;
idx statistics[4][4] = {0}; // total statistics
int E[4] = {0}; // experimental estimate
idx gate_idx = 0; // gate index (0, 1, 2 or 3)
for (auto&& gateA: {Q, R}) // measure Alice's side
{
auto evalsA = hevals(gateA); // eigenvalues, so we know the order
auto basisA = hevects(gateA); // eigenvectors, ordered by eigenvalues
for (auto&& gateB: {S, T}) // measure Bob's side
{
// eigenvalues, so we know the order
auto evalsB = hevals(gateB);
auto basisB = hevects(gateB);
for (idx i = 0; i < N; ++i)
{
auto measurementA = measure(psi, basisA, {0});
auto mA = std::get<0>(measurementA); // result on A
// the eigenvalues corresponding to the measurement results
short evalA = static_cast<short>(std::round(evalsA[mA]));
// resulting state on B
auto rhoB = std::get<2>(measurementA)[mA];
auto measurementB = measure(rhoB, basisB);
auto mB = std::get<0>(measurementB); // measurement result B
short evalB = static_cast<short>(std::round(evalsB[mB]));
// count the coincidences
if (evalA == 1 && evalB == 1) // +1 +1
{
statistics[gate_idx][0]++;
E[gate_idx]++;
}
else if (evalA == 1 && evalB == -1) // +1 -1
{
statistics[gate_idx][1]++;
E[gate_idx]--;
}
else if (evalA == -1 && evalB == 1) // -1 +1
{
statistics[gate_idx][2]++;
E[gate_idx]--;
}
else if (evalA == -1 && evalB == -1) // -1 -1
{
statistics[gate_idx][3]++;
E[gate_idx]++;
}
}
++gate_idx;
}
}
std::cout << "Coincidences N = " << N << std::endl;
std::cout << "(N++ N+- N-+ N-- E)" << std::endl;
std::cout << "QS: " << disp(statistics[0], 4, " ");
std::cout << " " << E[0] << std::endl;
std::cout << "QT: " << disp(statistics[1], 4, " ");
std::cout << " " << E[1] << std::endl;
std::cout << "RS: " << disp(statistics[2], 4, " ");
std::cout << " " << E[2] << std::endl;
std::cout << "RT: " << disp(statistics[3], 4, " ");
std::cout << " " << E[3] << std::endl;
double val = (E[0] - E[1] + E[2] + E[3]) / static_cast<double>(N);
std::cout << "<QS> + <RS> + <RT> - <QT> = " << val << std::endl;
std::cout << "Theoretical value 2 * sqrt(2) = " << 2 * std::sqrt(2);
}<commit_msg>commit<commit_after>// Bell inequalities (CHSH) violation
// Source: ./examples/bell_inequalities.cpp
#include <qpp.h>
using namespace qpp;
using std::cout;
using std::endl;
//TODO: finish the example, incomplete now
int main()
{
ket psi = st.b11; // Measure the singlet Bell state (|01>-|10>)/sqrt(2)
idx N = 1; // number of measurements each party does
// gates
cmat Q = gt.Z;
cmat R = gt.X;
cmat S = (-gt.Z - gt.X) / std::sqrt(2);
cmat T = (gt.Z - gt.X) / std::sqrt(2);
//Q = S = gt.Z;
//R = T = gt.X;
idx statistics[4][4] = {0}; // total statistics
int E[4] = {0}; // experimental estimate
idx gate_idx = 0; // gate index (0, 1, 2 or 3)
for (auto&& gateA: {Q, R}) // measure Alice's side
{
auto evalsA = hevals(gateA); // eigenvalues, so we know the order
auto basisA = hevects(gateA); // eigenvectors, ordered by eigenvalues
for (auto&& gateB: {S, T}) // measure Bob's side
{
// eigenvalues, so we know the order
auto evalsB = hevals(gateB);
auto basisB = hevects(gateB);
for (idx i = 0; i < N; ++i)
{
auto measurementA = measure(psi, basisA, {0});
auto mA = std::get<0>(measurementA); // result on A
// the eigenvalues corresponding to the measurement results
short evalA = static_cast<short>(std::round(evalsA[mA]));
// resulting state on B
auto rhoB = std::get<2>(measurementA)[mA];
auto measurementB = measure(rhoB, basisB);
auto mB = std::get<0>(measurementB); // measurement result B
short evalB = static_cast<short>(std::round(evalsB[mB]));
// count the correlations
if (evalA == 1 && evalB == 1) // +1 +1 correlation
{
statistics[gate_idx][0]++;
E[gate_idx]++;
}
else if (evalA == 1 && evalB == -1) // +1 -1 anti-correlation
{
statistics[gate_idx][1]++;
E[gate_idx]--;
}
else if (evalA == -1 && evalB == 1) // -1 +1 anti-correlation
{
statistics[gate_idx][2]++;
E[gate_idx]--;
}
else if (evalA == -1 && evalB == -1) // -1 -1 correlation
{
statistics[gate_idx][3]++;
E[gate_idx]++;
}
}
++gate_idx;
}
}
std::cout << "Coincidences N = " << N << std::endl;
std::cout << "(N++ N+- N-+ N-- E)" << std::endl;
std::cout << "QS: " << disp(statistics[0], 4, " ");
std::cout << " " << E[0] << std::endl;
std::cout << "QT: " << disp(statistics[1], 4, " ");
std::cout << " " << E[1] << std::endl;
std::cout << "RS: " << disp(statistics[2], 4, " ");
std::cout << " " << E[2] << std::endl;
std::cout << "RT: " << disp(statistics[3], 4, " ");
std::cout << " " << E[3] << std::endl;
double val = (E[0] - E[1] + E[2] + E[3]) / static_cast<double>(N);
std::cout << "<QS> + <RS> + <RT> - <QT> = " << val << std::endl;
std::cout << "Theoretical value 2 * sqrt(2) = " << 2 * std::sqrt(2);
}<|endoftext|> |
<commit_before>/*
* SimplePoggio.cpp
*
* Created on: Nov 20, 2008
* Author: bjt
*/
#include "SimplePoggio.hpp"
namespace PV {
SimplePoggio::SimplePoggio(const char * name, HyPerCol * hc) : HyPerLayer(name, hc)
{
init(TypeGeneric);
}
int SimplePoggio::recvSynapticInput(HyPerConn * conn, PVLayerCube * activity, int neighbor)
{
pv_debug_info("[%d]: SimplePoggio::recvSynapticInput: layer %d from %d)",
clayer->columnId,
conn->preSynapticLayer()->clayer->layerId, clayer->layerId);
// use implementation in base class
HyPerLayer::recvSynapticInput(conn, activity, neighbor);
return 0;
}
int SimplePoggio::updateState(float time, float dt)
{
pv_debug_info("[%d]: SimplePoggio::updateState:", clayer->columnId);
// just copy accumulation buffer to membrane potential
// and activity buffer (nonspiking)
pvdata_t * phi = clayer->phi[0];
for (int k = 0; k < clayer->numNeurons; k++) {
#ifdef EXTEND_BORDER_INDEX
int kPhi = kIndexExtended(k, clayer->loc.nx, clayer->loc.ny, clayer->numFeatures,
clayer->loc.nPad);
#else
int kPhi = k;
#endif
clayer->V[k] = phi[kPhi];
clayer->activity->data[k] = phi[kPhi];
phi[kPhi] = 0.0; // reset accumulation buffer
}
return 0;
}
int SimplePoggio::initFinish(int colId, int colRow, int colCol)
{
pv_debug_info("[%d]: SimplePoggio::initFinish: colId=%d colRow=%d, colCol=%d",
clayer->columnId, colId, colRow, colCol);
return 0;
}
int SimplePoggio::setParams(int numParams, float* params)
{
pv_debug_info("[%d]: SimplePoggio::setParams: numParams=%d", clayer->columnId, numParams);
return 0;
}
int SimplePoggio::outputState(float time)
{
pv_debug_info("[%d]: SimplePoggio::outputState:", clayer->columnId);
// use implementation in base class
HyPerLayer::outputState(time);
return 0;
}
}
<commit_msg>Renamed init to initialize to match HyPerConn.<commit_after>/*
* SimplePoggio.cpp
*
* Created on: Nov 20, 2008
* Author: bjt
*/
#include "SimplePoggio.hpp"
namespace PV {
SimplePoggio::SimplePoggio(const char * name, HyPerCol * hc) : HyPerLayer(name, hc)
{
initialize(TypeGeneric);
}
int SimplePoggio::recvSynapticInput(HyPerConn * conn, PVLayerCube * activity, int neighbor)
{
pv_debug_info("[%d]: SimplePoggio::recvSynapticInput: layer %d from %d)",
clayer->columnId,
conn->preSynapticLayer()->clayer->layerId, clayer->layerId);
// use implementation in base class
HyPerLayer::recvSynapticInput(conn, activity, neighbor);
return 0;
}
int SimplePoggio::updateState(float time, float dt)
{
pv_debug_info("[%d]: SimplePoggio::updateState:", clayer->columnId);
// just copy accumulation buffer to membrane potential
// and activity buffer (nonspiking)
pvdata_t * phi = clayer->phi[0];
for (int k = 0; k < clayer->numNeurons; k++) {
#ifdef EXTEND_BORDER_INDEX
int kPhi = kIndexExtended(k, clayer->loc.nx, clayer->loc.ny, clayer->numFeatures,
clayer->loc.nPad);
#else
int kPhi = k;
#endif
clayer->V[k] = phi[kPhi];
clayer->activity->data[k] = phi[kPhi];
phi[kPhi] = 0.0; // reset accumulation buffer
}
return 0;
}
int SimplePoggio::initFinish(int colId, int colRow, int colCol)
{
pv_debug_info("[%d]: SimplePoggio::initFinish: colId=%d colRow=%d, colCol=%d",
clayer->columnId, colId, colRow, colCol);
return 0;
}
int SimplePoggio::setParams(int numParams, float* params)
{
pv_debug_info("[%d]: SimplePoggio::setParams: numParams=%d", clayer->columnId, numParams);
return 0;
}
int SimplePoggio::outputState(float time)
{
pv_debug_info("[%d]: SimplePoggio::outputState:", clayer->columnId);
// use implementation in base class
HyPerLayer::outputState(time);
return 0;
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// socket_base.cpp
//
// Identification: src/wire/socket_base.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "wire/socket_base.h"
#include "wire/wire.h"
#include "common/exception.h"
#include <sys/un.h>
#include <string>
namespace peloton {
namespace wire {
template <typename B>
bool SocketManager<B>::RefillReadBuffer() {
ssize_t bytes_read = 0;
fd_set rset;
bool done = false;
// our buffer is to be emptied
rbuf.Reset();
// return explicitly
while (!done) {
while(bytes_read <= 0) {
// try to fill the available space in the buffer
bytes_read = read(sock_fd, &rbuf.buf[rbuf.buf_ptr],
SOCKET_BUFFER_SIZE - rbuf.buf_size);
// Read failed
if (bytes_read < 0) {
// Some other error occurred, close the socket, remove
// the event and free the client structure.
switch(errno) {
case EINTR:
LOG_DEBUG("Error Reading: EINTR");
break;
case EAGAIN:
LOG_DEBUG("Error Reading: EAGAIN");
break;
case EBADF:
LOG_DEBUG("Error Reading: EBADF");
break;
case EDESTADDRREQ:
LOG_DEBUG("Error Reading: EDESTADDRREQ");
break;
case EDQUOT:
LOG_DEBUG("Error Reading: EDQUOT");
break;
case EFAULT:
LOG_DEBUG("Error Reading: EFAULT");
break;
case EFBIG:
LOG_DEBUG("Error Reading: EFBIG");
break;
case EINVAL:
LOG_DEBUG("Error Reading: EINVAL");
break;
case EIO:
LOG_DEBUG("Error Reading: EIO");
break;
case ENOSPC:
LOG_DEBUG("Error Reading: ENOSPC");
break;
case EPIPE:
LOG_DEBUG("Error Reading: EPIPE");
break;
default:
LOG_DEBUG("Error Reading: UNKNOWN");
}
if (errno == EINTR) {
// interrupts are ok, try again
bytes_read = 0;
continue;
// Read would have blocked if the scoket
// was in blocking mode. Wait till it's readable
} else if (errno == EAGAIN) {
FD_ZERO (&rset);
FD_SET (sock_fd, &rset);
bytes_read = select(sock_fd + 1, &rset, NULL, NULL, NULL);
if (bytes_read < 0) {
LOG_INFO("bytes_read < 0 after select. Fatal");
exit(EXIT_FAILURE);
} else if (bytes_read == 0) {
// timed out without writing any data
LOG_INFO("Timeout without reading");
exit(EXIT_FAILURE);
}
// else, socket is now readable, so loop back up and do the read() again
bytes_read = 0;
continue;
}
else {
// fatal errors
return false;
}
}
else if (bytes_read == 0) {
// If the length of bytes returned by read is 0, this means
// that the client disconnected
disconnected = true;
return false;
}
else {
done = true;
}
}
// read success, update buffer size
rbuf.buf_size += bytes_read;
// reset buffer ptr, to cover special case
rbuf.buf_ptr = 0;
return true;
}
return true;
}
template <typename B>
bool SocketManager<B>::FlushWriteBuffer() {
fd_set rset;
ssize_t written_bytes = 0;
wbuf.buf_ptr = 0;
// still outstanding bytes
while ((int)wbuf.buf_size - written_bytes > 0) {
while(written_bytes <= 0){
written_bytes = write(sock_fd, &wbuf.buf[wbuf.buf_ptr], wbuf.buf_size);
// Write failed
if (written_bytes < 0) {
switch(errno) {
case EINTR:
LOG_DEBUG("Error Writing: EINTR");
break;
case EAGAIN:
LOG_DEBUG("Error Writing: EAGAIN");
break;
case EBADF:
LOG_DEBUG("Error Writing: EBADF");
break;
case EDESTADDRREQ:
LOG_DEBUG("Error Writing: EDESTADDRREQ");
break;
case EDQUOT:
LOG_DEBUG("Error Writing: EDQUOT");
break;
case EFAULT:
LOG_DEBUG("Error Writing: EFAULT");
break;
case EFBIG:
LOG_DEBUG("Error Writing: EFBIG");
break;
case EINVAL:
LOG_DEBUG("Error Writing: EINVAL");
break;
case EIO:
LOG_DEBUG("Error Writing: EIO");
break;
case ENOSPC:
LOG_DEBUG("Error Writing: ENOSPC");
break;
case EPIPE:
LOG_DEBUG("Error Writing: EPIPE");
break;
default:
LOG_DEBUG("Error Writing: UNKNOWN");
}
if (errno == EINTR) {
// interrupts are ok, try again
written_bytes = 0;
continue;
// Write would have blocked if the socket was
// in blocking mode. Wait till it's readable
} else if (errno == EAGAIN) {
FD_ZERO (&rset);
FD_SET (sock_fd, &rset);
written_bytes = select(sock_fd + 1, &rset, NULL, NULL, NULL);
if (written_bytes < 0) {
LOG_INFO("written_bytes < 0 after select. Fatal");
exit(EXIT_FAILURE);
} else if (written_bytes == 0) {
// timed out without writing any data
LOG_INFO("Timeout without writing");
exit(EXIT_FAILURE);
}
// else, socket is now readable, so loop back up and do the read() again
written_bytes = 0;
continue;
}
else {
// fatal errors
return false;
}
}
// weird edge case?
if (written_bytes == 0 && wbuf.buf_size != 0) {
LOG_INFO("Not all data is written");
// fatal
return false;
}
}
// update bookkeping
wbuf.buf_ptr += written_bytes;
wbuf.buf_size -= written_bytes;
}
// buffer is empty
wbuf.Reset();
// we are ok
return true;
}
/*
* read - Tries to read "bytes" bytes into packet's buffer. Returns true on
* success.
* false on failure. B can be any STL container.
*/
template <typename B>
bool SocketManager<B>::ReadBytes(B &pkt_buf, size_t bytes) {
size_t window, pkt_buf_idx = 0;
// while data still needs to be read
while (bytes) {
// how much data is available
window = rbuf.buf_size - rbuf.buf_ptr;
if (bytes <= window) {
pkt_buf.insert(std::end(pkt_buf), std::begin(rbuf.buf) + rbuf.buf_ptr,
std::begin(rbuf.buf) + rbuf.buf_ptr + bytes);
// move the pointer
rbuf.buf_ptr += bytes;
// move pkt_buf_idx as well
pkt_buf_idx += bytes;
return true;
} else {
// read what is available for non-trivial window
if (window > 0) {
pkt_buf.insert(std::end(pkt_buf), std::begin(rbuf.buf) + rbuf.buf_ptr,
std::begin(rbuf.buf) + rbuf.buf_size);
// update bytes leftover
bytes -= window;
// update pkt_buf_idx
pkt_buf_idx += window;
}
// refill buffer, reset buf ptr here
if (!RefillReadBuffer()) {
// nothing more to read, end
return false;
}
}
}
return true;
}
template <typename B>
void SocketManager<B>::PrintWriteBuffer() {
LOG_TRACE("Write Buffer:");
for (size_t i = 0; i < wbuf.buf_size; ++i) {
LOG_TRACE("%u", wbuf.buf[i]);
}
}
template <typename B>
bool SocketManager<B>::BufferWriteBytes(B &pkt_buf, size_t len, uchar type) {
size_t window, pkt_buf_ptr = 0;
int len_nb; // length in network byte order
// check if we don't have enough space in the buffer
if (wbuf.GetMaxSize() - wbuf.buf_ptr < 1 + sizeof(int32_t)) {
// buffer needs to be flushed before adding header
FlushWriteBuffer();
}
// assuming wbuf is now large enough to
// fit type and size fields in one go
if (type != 0) {
// type shouldn't be ignored
wbuf.buf[wbuf.buf_ptr++] = type;
}
// make len include its field size as well
len_nb = htonl(len + sizeof(int32_t));
// append the bytes of this integer in network-byte order
std::copy(reinterpret_cast<uchar *>(&len_nb),
reinterpret_cast<uchar *>(&len_nb) + 4,
std::begin(wbuf.buf) + wbuf.buf_ptr);
// move the write buffer pointer and update size of the socket buffer
wbuf.buf_ptr += sizeof(int32_t);
wbuf.buf_size = wbuf.buf_ptr;
// fill the contents
while (len) {
window = wbuf.GetMaxSize() - wbuf.buf_ptr;
if (len <= window) {
// contents fit in the window, range copy "len" bytes
std::copy(std::begin(pkt_buf) + pkt_buf_ptr,
std::begin(pkt_buf) + pkt_buf_ptr + len,
std::begin(wbuf.buf) + wbuf.buf_ptr);
// Move the cursor and update size of socket buffer
wbuf.buf_ptr += len;
wbuf.buf_size = wbuf.buf_ptr;
// std::cout << "Filled the write buffer but not flushed yet" <<
// std::endl;
// PrintWriteBuffer();
return true;
} else {
/* contents longer than socket buffer size, fill up the socket buffer
* with "window" bytes
*/
std::copy(std::begin(pkt_buf) + pkt_buf_ptr,
std::begin(pkt_buf) + pkt_buf_ptr + window,
std::begin(wbuf.buf) + wbuf.buf_ptr);
// move the packet's cursor
pkt_buf_ptr += window;
len -= window;
wbuf.buf_size = wbuf.GetMaxSize();
// write failure
if (!FlushWriteBuffer()) {
return false;
}
}
}
return true;
}
template <typename B>
void SocketManager<B>::CloseSocket() {
for (;;) {
int status = close(sock_fd);
if (status < 0) {
// failed close
if (errno == EINTR) {
// interrupted, try closing again
continue;
}
}
return;
}
}
// explicit template instantiation for read_bytes
template class SocketManager<PktBuf>;
} // End wire namespace
} // End peloton namespace
<commit_msg>Minor change<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// socket_base.cpp
//
// Identification: src/wire/socket_base.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "wire/socket_base.h"
#include "wire/wire.h"
#include "common/exception.h"
#include <sys/un.h>
#include <string>
namespace peloton {
namespace wire {
template <typename B>
bool SocketManager<B>::RefillReadBuffer() {
ssize_t bytes_read = 0;
fd_set rset;
bool done = false;
// our buffer is to be emptied
rbuf.Reset();
// return explicitly
while (!done) {
while(bytes_read <= 0) {
// try to fill the available space in the buffer
bytes_read = read(sock_fd, &rbuf.buf[rbuf.buf_ptr],
SOCKET_BUFFER_SIZE - rbuf.buf_size);
// Read failed
if (bytes_read < 0) {
// Some other error occurred, close the socket, remove
// the event and free the client structure.
switch(errno) {
case EINTR:
LOG_DEBUG("Error Reading: EINTR");
break;
case EAGAIN:
LOG_DEBUG("Error Reading: EAGAIN");
break;
case EBADF:
LOG_DEBUG("Error Reading: EBADF");
break;
case EDESTADDRREQ:
LOG_DEBUG("Error Reading: EDESTADDRREQ");
break;
case EDQUOT:
LOG_DEBUG("Error Reading: EDQUOT");
break;
case EFAULT:
LOG_DEBUG("Error Reading: EFAULT");
break;
case EFBIG:
LOG_DEBUG("Error Reading: EFBIG");
break;
case EINVAL:
LOG_DEBUG("Error Reading: EINVAL");
break;
case EIO:
LOG_DEBUG("Error Reading: EIO");
break;
case ENOSPC:
LOG_DEBUG("Error Reading: ENOSPC");
break;
case EPIPE:
LOG_DEBUG("Error Reading: EPIPE");
break;
default:
LOG_DEBUG("Error Reading: UNKNOWN");
}
if (errno == EINTR) {
// interrupts are ok, try again
bytes_read = 0;
continue;
// Read would have blocked if the scoket
// was in blocking mode. Wait till it's readable
} else if (errno == EAGAIN) {
FD_ZERO (&rset);
FD_SET (sock_fd, &rset);
bytes_read = select(sock_fd + 1, &rset, NULL, NULL, NULL);
if (bytes_read < 0) {
LOG_INFO("bytes_read < 0 after select. Fatal");
exit(EXIT_FAILURE);
} else if (bytes_read == 0) {
// timed out without writing any data
LOG_INFO("Timeout without reading");
exit(EXIT_FAILURE);
}
// else, socket is now readable, so loop back up and do the read() again
bytes_read = 0;
continue;
}
else {
// fatal errors
return false;
}
}
else if (bytes_read == 0) {
// If the length of bytes returned by read is 0, this means
// that the client disconnected
disconnected = true;
return false;
}
else {
done = true;
}
}
// read success, update buffer size
rbuf.buf_size += bytes_read;
// reset buffer ptr, to cover special case
rbuf.buf_ptr = 0;
return true;
}
return true;
}
template <typename B>
bool SocketManager<B>::FlushWriteBuffer() {
fd_set rset;
ssize_t written_bytes = 0;
wbuf.buf_ptr = 0;
// still outstanding bytes
while ((int)wbuf.buf_size - written_bytes > 0) {
while(written_bytes <= 0){
written_bytes = write(sock_fd, &wbuf.buf[wbuf.buf_ptr], wbuf.buf_size);
// Write failed
if (written_bytes < 0) {
switch(errno) {
case EINTR:
LOG_DEBUG("Error Writing: EINTR");
break;
case EAGAIN:
LOG_DEBUG("Error Writing: EAGAIN");
break;
case EBADF:
LOG_DEBUG("Error Writing: EBADF");
break;
case EDESTADDRREQ:
LOG_DEBUG("Error Writing: EDESTADDRREQ");
break;
case EDQUOT:
LOG_DEBUG("Error Writing: EDQUOT");
break;
case EFAULT:
LOG_DEBUG("Error Writing: EFAULT");
break;
case EFBIG:
LOG_DEBUG("Error Writing: EFBIG");
break;
case EINVAL:
LOG_DEBUG("Error Writing: EINVAL");
break;
case EIO:
LOG_DEBUG("Error Writing: EIO");
break;
case ENOSPC:
LOG_DEBUG("Error Writing: ENOSPC");
break;
case EPIPE:
LOG_DEBUG("Error Writing: EPIPE");
break;
default:
LOG_DEBUG("Error Writing: UNKNOWN");
}
if (errno == EINTR) {
// interrupts are ok, try again
written_bytes = 0;
continue;
// Write would have blocked if the socket was
// in blocking mode. Wait till it's readable
} else if (errno == EAGAIN) {
FD_ZERO (&rset);
FD_SET (sock_fd, &rset);
written_bytes = select(sock_fd + 1, &rset, NULL, NULL, NULL);
if (written_bytes < 0) {
LOG_INFO("written_bytes < 0 after select. Fatal");
exit(EXIT_FAILURE);
} else if (written_bytes == 0) {
// timed out without writing any data
LOG_INFO("Timeout without writing");
exit(EXIT_FAILURE);
}
// else, socket is now readable, so loop back up and do the read() again
written_bytes = 0;
continue;
}
else {
// fatal errors
return false;
}
}
// weird edge case?
if (written_bytes == 0 && wbuf.buf_size != 0) {
LOG_INFO("Not all data is written");
// fatal
return false;
}
}
// update bookkeping
wbuf.buf_ptr += written_bytes;
wbuf.buf_size -= written_bytes;
}
// buffer is empty
wbuf.Reset();
// we are ok
return true;
}
/*
* read - Tries to read "bytes" bytes into packet's buffer. Returns true on
* success.
* false on failure. B can be any STL container.
*/
template <typename B>
bool SocketManager<B>::ReadBytes(B &pkt_buf, size_t bytes) {
size_t window, pkt_buf_idx = 0;
// while data still needs to be read
while (bytes) {
// how much data is available
window = rbuf.buf_size - rbuf.buf_ptr;
if (bytes <= window) {
pkt_buf.insert(std::end(pkt_buf), std::begin(rbuf.buf) + rbuf.buf_ptr,
std::begin(rbuf.buf) + rbuf.buf_ptr + bytes);
// move the pointer
rbuf.buf_ptr += bytes;
// move pkt_buf_idx as well
pkt_buf_idx += bytes;
return true;
} else {
// read what is available for non-trivial window
if (window > 0) {
pkt_buf.insert(std::end(pkt_buf), std::begin(rbuf.buf) + rbuf.buf_ptr,
std::begin(rbuf.buf) + rbuf.buf_size);
// update bytes leftover
bytes -= window;
// update pkt_buf_idx
pkt_buf_idx += window;
}
// refill buffer, reset buf ptr here
if (!RefillReadBuffer()) {
// nothing more to read, end
return false;
}
}
}
return true;
}
template <typename B>
void SocketManager<B>::PrintWriteBuffer() {
LOG_TRACE("Write Buffer:");
for (size_t i = 0; i < wbuf.buf_size; ++i) {
LOG_TRACE("%u", wbuf.buf[i]);
}
}
template <typename B>
bool SocketManager<B>::BufferWriteBytes(B &pkt_buf, size_t len, uchar type) {
size_t window, pkt_buf_ptr = 0;
int len_nb; // length in network byte order
// check if we don't have enough space in the buffer
if (wbuf.GetMaxSize() - wbuf.buf_ptr < 1 + sizeof(int32_t)) {
// buffer needs to be flushed before adding header
FlushWriteBuffer();
}
// assuming wbuf is now large enough to
// fit type and size fields in one go
if (type != 0) {
// type shouldn't be ignored
wbuf.buf[wbuf.buf_ptr++] = type;
}
// make len include its field size as well
len_nb = htonl(len + sizeof(int32_t));
// append the bytes of this integer in network-byte order
std::copy(reinterpret_cast<uchar *>(&len_nb),
reinterpret_cast<uchar *>(&len_nb) + 4,
std::begin(wbuf.buf) + wbuf.buf_ptr);
// move the write buffer pointer and update size of the socket buffer
wbuf.buf_ptr += sizeof(int32_t);
wbuf.buf_size = wbuf.buf_ptr;
// fill the contents
while (len) {
window = wbuf.GetMaxSize() - wbuf.buf_ptr;
if (len <= window) {
// contents fit in the window, range copy "len" bytes
std::copy(std::begin(pkt_buf) + pkt_buf_ptr,
std::begin(pkt_buf) + pkt_buf_ptr + len,
std::begin(wbuf.buf) + wbuf.buf_ptr);
// Move the cursor and update size of socket buffer
wbuf.buf_ptr += len;
wbuf.buf_size = wbuf.buf_ptr;
// std::cout << "Filled the write buffer but not flushed yet" <<
// std::endl;
// PrintWriteBuffer();
return true;
} else {
/* contents longer than socket buffer size, fill up the socket buffer
* with "window" bytes
*/
std::copy(std::begin(pkt_buf) + pkt_buf_ptr,
std::begin(pkt_buf) + pkt_buf_ptr + window,
std::begin(wbuf.buf) + wbuf.buf_ptr);
// move the packet's cursor
pkt_buf_ptr += window;
len -= window;
wbuf.buf_size = wbuf.GetMaxSize();
// write failure
if (!FlushWriteBuffer()) {
return false;
}
}
}
return true;
}
template <typename B>
void SocketManager<B>::CloseSocket() {
for (;;) {
int status = close(sock_fd);
if (status < 0) {
// failed close
if (errno == EINTR) {
// interrupted, try closing again
continue;
}
}
return;
}
}
// explicit template instantiation for read_bytes
template class SocketManager<PktBuf>;
} // End wire namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 "LifeCycleManager.h"
#include "NebulaLog.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * lcm_action_loop(void *arg)
{
LifeCycleManager * lcm;
if ( arg == 0 )
{
return 0;
}
lcm = static_cast<LifeCycleManager *>(arg);
NebulaLog::log("LCM",Log::INFO,"Life-cycle Manager started.");
lcm->am.loop(0,0);
NebulaLog::log("LCM",Log::INFO,"Life-cycle Manager stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int LifeCycleManager::start()
{
int rc;
pthread_attr_t pattr;
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
NebulaLog::log("LCM",Log::INFO,"Starting Life-cycle Manager...");
rc = pthread_create(&lcm_thread,&pattr,lcm_action_loop,(void *) this);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LifeCycleManager::trigger(Actions action, int _vid)
{
int * vid;
string aname;
vid = new int(_vid);
switch (action)
{
case SAVE_SUCCESS:
aname = "SAVE_SUCCESS";
break;
case SAVE_FAILURE:
aname = "SAVE_FAILURE";
break;
case DEPLOY_SUCCESS:
aname = "DEPLOY_SUCCESS";
break;
case DEPLOY_FAILURE:
aname = "DEPLOY_FAILURE";
break;
case SHUTDOWN_SUCCESS:
aname = "SHUTDOWN_SUCCESS";
break;
case SHUTDOWN_FAILURE:
aname = "SHUTDOWN_FAILURE";
break;
case CANCEL_SUCCESS:
aname = "CANCEL_SUCCESS";
break;
case CANCEL_FAILURE:
aname = "CANCEL_FAILURE";
break;
case MONITOR_FAILURE:
aname = "MONITOR_FAILURE";
break;
case MONITOR_SUSPEND:
aname = "MONITOR_SUSPEND";
break;
case MONITOR_DONE:
aname = "MONITOR_DONE";
break;
case PROLOG_SUCCESS:
aname = "PROLOG_SUCCESS";
break;
case PROLOG_FAILURE:
aname = "PROLOG_FAILURE";
break;
case EPILOG_SUCCESS:
aname = "EPILOG_SUCCESS";
break;
case EPILOG_FAILURE:
aname = "EPILOG_FAILURE";
break;
case ATTACH_SUCCESS:
aname = "ATTACH_SUCCESS";
break;
case ATTACH_FAILURE:
aname = "ATTACH_FAILURE";
break;
case DETACH_SUCCESS:
aname = "DETACH_SUCCESS";
break;
case DETACH_FAILURE:
aname = "DETACH_FAILURE";
break;
case SAVEAS_HOT_SUCCESS:
aname = "SAVEAS_HOT_SUCCESS";
break;
case SAVEAS_HOT_FAILURE:
aname = "SAVEAS_HOT_FAILURE";
break;
case ATTACH_NIC_SUCCESS:
aname = "ATTACH_NIC_SUCCESS";
break;
case ATTACH_NIC_FAILURE:
aname = "ATTACH_NIC_FAILURE";
break;
case DETACH_NIC_SUCCESS:
aname = "DETACH_NIC_SUCCESS";
break;
case DETACH_NIC_FAILURE:
aname = "DETACH_NIC_FAILURE";
case CLEANUP_SUCCESS:
aname = "CLEANUP_SUCCESS";
break;
case CLEANUP_FAILURE:
aname = "CLEANUP_FAILURE";
break;
case SNAPSHOT_CREATE_SUCCESS:
aname = "SNAPSHOT_CREATE_SUCCESS";
break;
case SNAPSHOT_CREATE_FAILURE:
aname = "SNAPSHOT_CREATE_FAILURE";
break;
case SNAPSHOT_REVERT_SUCCESS:
aname = "SNAPSHOT_REVERT_SUCCESS";
break;
case SNAPSHOT_REVERT_FAILURE:
aname = "SNAPSHOT_REVERT_FAILURE";
break;
case SNAPSHOT_DELETE_SUCCESS:
aname = "SNAPSHOT_DELETE_SUCCESS";
break;
case SNAPSHOT_DELETE_FAILURE:
aname = "SNAPSHOT_DELETE_FAILURE";
break;
case DEPLOY:
aname = "DEPLOY";
break;
case SUSPEND:
aname = "SUSPEND";
break;
case RESTORE:
aname = "RESTORE";
break;
case STOP:
aname = "STOP";
break;
case CANCEL:
aname = "CANCEL";
break;
case MIGRATE:
aname = "MIGRATE";
break;
case LIVE_MIGRATE:
aname = "LIVE_MIGRATE";
break;
case SHUTDOWN:
aname = "SHUTDOWN";
break;
case UNDEPLOY:
aname = "UNDEPLOY";
break;
case UNDEPLOY_HARD:
aname = "UNDEPLOY_HARD";
break;
case RESTART:
aname = "RESTART";
break;
case DELETE:
aname = "DELETE";
break;
case CLEAN:
aname = "CLEAN";
break;
case FINALIZE:
aname = ACTION_FINALIZE;
break;
case POWEROFF:
aname = "POWEROFF";
break;
case POWEROFF_HARD:
aname = "POWEROFF_HARD";
break;
default:
delete vid;
return;
}
am.trigger(aname,vid);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LifeCycleManager::do_action(const string &action, void * arg)
{
int vid;
ostringstream oss;
if (arg == 0)
{
return;
}
vid = *(static_cast<int *>(arg));
delete static_cast<int *>(arg);
if (action == "SAVE_SUCCESS")
{
save_success_action(vid);
}
else if (action == "SAVE_FAILURE")
{
save_failure_action(vid);
}
else if (action == "DEPLOY_SUCCESS")
{
deploy_success_action(vid);
}
else if (action == "DEPLOY_FAILURE")
{
deploy_failure_action(vid);
}
else if (action == "SHUTDOWN_SUCCESS")
{
shutdown_success_action(vid);
}
else if (action == "SHUTDOWN_FAILURE")
{
shutdown_failure_action(vid);
}
else if (action == "CANCEL_SUCCESS")
{
cancel_success_action(vid);
}
else if (action == "CANCEL_FAILURE")
{
cancel_failure_action(vid);
}
else if (action == "MONITOR_FAILURE")
{
monitor_failure_action(vid);
}
else if (action == "MONITOR_SUSPEND")
{
monitor_suspend_action(vid);
}
else if (action == "MONITOR_DONE")
{
monitor_done_action(vid);
}
else if (action == "PROLOG_SUCCESS")
{
prolog_success_action(vid);
}
else if (action == "PROLOG_FAILURE")
{
prolog_failure_action(vid);
}
else if (action == "EPILOG_SUCCESS")
{
epilog_success_action(vid);
}
else if (action == "EPILOG_FAILURE")
{
epilog_failure_action(vid);
}
else if (action == "ATTACH_SUCCESS")
{
attach_success_action(vid);
}
else if (action == "ATTACH_FAILURE")
{
attach_failure_action(vid);
}
else if (action == "DETACH_SUCCESS")
{
detach_success_action(vid);
}
else if (action == "DETACH_FAILURE")
{
detach_failure_action(vid);
}
else if (action == "SAVEAS_HOT_SUCCESS")
{
saveas_hot_success_action(vid);
}
else if (action == "SAVEAS_HOT_FAILURE")
{
saveas_hot_failure_action(vid);
}
else if (action == "ATTACH_NIC_SUCCESS")
{
attach_nic_success_action(vid);
}
else if (action == "ATTACH_NIC_FAILURE")
{
attach_nic_failure_action(vid);
}
else if (action == "DETACH_NIC_SUCCESS")
{
detach_nic_success_action(vid);
}
else if (action == "DETACH_NIC_FAILURE")
{
detach_nic_failure_action(vid);
}
else if (action == "CLEANUP_SUCCESS")
{
cleanup_callback_action(vid);
}
else if (action == "CLEANUP_FAILURE")
{
cleanup_callback_action(vid);
}
else if (action == "SNAPSHOT_CREATE_SUCCESS")
{
snapshot_create_success(vid);
}
else if (action == "SNAPSHOT_CREATE_FAILURE")
{
snapshot_create_failure(vid);
}
else if (action == "SNAPSHOT_REVERT_SUCCESS")
{
snapshot_revert_success(vid);
}
else if (action == "SNAPSHOT_REVERT_FAILURE")
{
snapshot_revert_failure(vid);
}
else if (action == "SNAPSHOT_DELETE_SUCCESS")
{
snapshot_delete_success(vid);
}
else if (action == "SNAPSHOT_DELETE_FAILURE")
{
snapshot_delete_failure(vid);
}
else if (action == "DEPLOY")
{
deploy_action(vid);
}
else if (action == "SUSPEND")
{
suspend_action(vid);
}
else if (action == "RESTORE")
{
restore_action(vid);
}
else if (action == "STOP")
{
stop_action(vid);
}
else if (action == "CANCEL")
{
cancel_action(vid);
}
else if (action == "MIGRATE")
{
migrate_action(vid);
}
else if (action == "LIVE_MIGRATE")
{
live_migrate_action(vid);
}
else if (action == "SHUTDOWN")
{
shutdown_action(vid);
}
else if (action == "UNDEPLOY")
{
undeploy_action(vid, false);
}
else if (action == "UNDEPLOY_HARD")
{
undeploy_action(vid, true);
}
else if (action == "RESTART")
{
restart_action(vid);
}
else if (action == "DELETE")
{
delete_action(vid);
}
else if (action == "CLEAN")
{
clean_action(vid);
}
else if (action == "POWEROFF")
{
poweroff_action(vid);
}
else if (action == "POWEROFF_HARD")
{
poweroff_hard_action(vid);
}
else if (action == ACTION_FINALIZE)
{
NebulaLog::log("LCM",Log::INFO,"Stopping Life-cycle Manager...");
}
else
{
ostringstream oss;
oss << "Unknown action name: " << action;
NebulaLog::log("LCM", Log::ERROR, oss);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<commit_msg>Bug #2424: Fix nic-detach failure action<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 "LifeCycleManager.h"
#include "NebulaLog.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * lcm_action_loop(void *arg)
{
LifeCycleManager * lcm;
if ( arg == 0 )
{
return 0;
}
lcm = static_cast<LifeCycleManager *>(arg);
NebulaLog::log("LCM",Log::INFO,"Life-cycle Manager started.");
lcm->am.loop(0,0);
NebulaLog::log("LCM",Log::INFO,"Life-cycle Manager stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
int LifeCycleManager::start()
{
int rc;
pthread_attr_t pattr;
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
NebulaLog::log("LCM",Log::INFO,"Starting Life-cycle Manager...");
rc = pthread_create(&lcm_thread,&pattr,lcm_action_loop,(void *) this);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LifeCycleManager::trigger(Actions action, int _vid)
{
int * vid;
string aname;
vid = new int(_vid);
switch (action)
{
case SAVE_SUCCESS:
aname = "SAVE_SUCCESS";
break;
case SAVE_FAILURE:
aname = "SAVE_FAILURE";
break;
case DEPLOY_SUCCESS:
aname = "DEPLOY_SUCCESS";
break;
case DEPLOY_FAILURE:
aname = "DEPLOY_FAILURE";
break;
case SHUTDOWN_SUCCESS:
aname = "SHUTDOWN_SUCCESS";
break;
case SHUTDOWN_FAILURE:
aname = "SHUTDOWN_FAILURE";
break;
case CANCEL_SUCCESS:
aname = "CANCEL_SUCCESS";
break;
case CANCEL_FAILURE:
aname = "CANCEL_FAILURE";
break;
case MONITOR_FAILURE:
aname = "MONITOR_FAILURE";
break;
case MONITOR_SUSPEND:
aname = "MONITOR_SUSPEND";
break;
case MONITOR_DONE:
aname = "MONITOR_DONE";
break;
case PROLOG_SUCCESS:
aname = "PROLOG_SUCCESS";
break;
case PROLOG_FAILURE:
aname = "PROLOG_FAILURE";
break;
case EPILOG_SUCCESS:
aname = "EPILOG_SUCCESS";
break;
case EPILOG_FAILURE:
aname = "EPILOG_FAILURE";
break;
case ATTACH_SUCCESS:
aname = "ATTACH_SUCCESS";
break;
case ATTACH_FAILURE:
aname = "ATTACH_FAILURE";
break;
case DETACH_SUCCESS:
aname = "DETACH_SUCCESS";
break;
case DETACH_FAILURE:
aname = "DETACH_FAILURE";
break;
case SAVEAS_HOT_SUCCESS:
aname = "SAVEAS_HOT_SUCCESS";
break;
case SAVEAS_HOT_FAILURE:
aname = "SAVEAS_HOT_FAILURE";
break;
case ATTACH_NIC_SUCCESS:
aname = "ATTACH_NIC_SUCCESS";
break;
case ATTACH_NIC_FAILURE:
aname = "ATTACH_NIC_FAILURE";
break;
case DETACH_NIC_SUCCESS:
aname = "DETACH_NIC_SUCCESS";
break;
case DETACH_NIC_FAILURE:
aname = "DETACH_NIC_FAILURE";
break;
case CLEANUP_SUCCESS:
aname = "CLEANUP_SUCCESS";
break;
case CLEANUP_FAILURE:
aname = "CLEANUP_FAILURE";
break;
case SNAPSHOT_CREATE_SUCCESS:
aname = "SNAPSHOT_CREATE_SUCCESS";
break;
case SNAPSHOT_CREATE_FAILURE:
aname = "SNAPSHOT_CREATE_FAILURE";
break;
case SNAPSHOT_REVERT_SUCCESS:
aname = "SNAPSHOT_REVERT_SUCCESS";
break;
case SNAPSHOT_REVERT_FAILURE:
aname = "SNAPSHOT_REVERT_FAILURE";
break;
case SNAPSHOT_DELETE_SUCCESS:
aname = "SNAPSHOT_DELETE_SUCCESS";
break;
case SNAPSHOT_DELETE_FAILURE:
aname = "SNAPSHOT_DELETE_FAILURE";
break;
case DEPLOY:
aname = "DEPLOY";
break;
case SUSPEND:
aname = "SUSPEND";
break;
case RESTORE:
aname = "RESTORE";
break;
case STOP:
aname = "STOP";
break;
case CANCEL:
aname = "CANCEL";
break;
case MIGRATE:
aname = "MIGRATE";
break;
case LIVE_MIGRATE:
aname = "LIVE_MIGRATE";
break;
case SHUTDOWN:
aname = "SHUTDOWN";
break;
case UNDEPLOY:
aname = "UNDEPLOY";
break;
case UNDEPLOY_HARD:
aname = "UNDEPLOY_HARD";
break;
case RESTART:
aname = "RESTART";
break;
case DELETE:
aname = "DELETE";
break;
case CLEAN:
aname = "CLEAN";
break;
case FINALIZE:
aname = ACTION_FINALIZE;
break;
case POWEROFF:
aname = "POWEROFF";
break;
case POWEROFF_HARD:
aname = "POWEROFF_HARD";
break;
default:
delete vid;
return;
}
am.trigger(aname,vid);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LifeCycleManager::do_action(const string &action, void * arg)
{
int vid;
ostringstream oss;
if (arg == 0)
{
return;
}
vid = *(static_cast<int *>(arg));
delete static_cast<int *>(arg);
if (action == "SAVE_SUCCESS")
{
save_success_action(vid);
}
else if (action == "SAVE_FAILURE")
{
save_failure_action(vid);
}
else if (action == "DEPLOY_SUCCESS")
{
deploy_success_action(vid);
}
else if (action == "DEPLOY_FAILURE")
{
deploy_failure_action(vid);
}
else if (action == "SHUTDOWN_SUCCESS")
{
shutdown_success_action(vid);
}
else if (action == "SHUTDOWN_FAILURE")
{
shutdown_failure_action(vid);
}
else if (action == "CANCEL_SUCCESS")
{
cancel_success_action(vid);
}
else if (action == "CANCEL_FAILURE")
{
cancel_failure_action(vid);
}
else if (action == "MONITOR_FAILURE")
{
monitor_failure_action(vid);
}
else if (action == "MONITOR_SUSPEND")
{
monitor_suspend_action(vid);
}
else if (action == "MONITOR_DONE")
{
monitor_done_action(vid);
}
else if (action == "PROLOG_SUCCESS")
{
prolog_success_action(vid);
}
else if (action == "PROLOG_FAILURE")
{
prolog_failure_action(vid);
}
else if (action == "EPILOG_SUCCESS")
{
epilog_success_action(vid);
}
else if (action == "EPILOG_FAILURE")
{
epilog_failure_action(vid);
}
else if (action == "ATTACH_SUCCESS")
{
attach_success_action(vid);
}
else if (action == "ATTACH_FAILURE")
{
attach_failure_action(vid);
}
else if (action == "DETACH_SUCCESS")
{
detach_success_action(vid);
}
else if (action == "DETACH_FAILURE")
{
detach_failure_action(vid);
}
else if (action == "SAVEAS_HOT_SUCCESS")
{
saveas_hot_success_action(vid);
}
else if (action == "SAVEAS_HOT_FAILURE")
{
saveas_hot_failure_action(vid);
}
else if (action == "ATTACH_NIC_SUCCESS")
{
attach_nic_success_action(vid);
}
else if (action == "ATTACH_NIC_FAILURE")
{
attach_nic_failure_action(vid);
}
else if (action == "DETACH_NIC_SUCCESS")
{
detach_nic_success_action(vid);
}
else if (action == "DETACH_NIC_FAILURE")
{
detach_nic_failure_action(vid);
}
else if (action == "CLEANUP_SUCCESS")
{
cleanup_callback_action(vid);
}
else if (action == "CLEANUP_FAILURE")
{
cleanup_callback_action(vid);
}
else if (action == "SNAPSHOT_CREATE_SUCCESS")
{
snapshot_create_success(vid);
}
else if (action == "SNAPSHOT_CREATE_FAILURE")
{
snapshot_create_failure(vid);
}
else if (action == "SNAPSHOT_REVERT_SUCCESS")
{
snapshot_revert_success(vid);
}
else if (action == "SNAPSHOT_REVERT_FAILURE")
{
snapshot_revert_failure(vid);
}
else if (action == "SNAPSHOT_DELETE_SUCCESS")
{
snapshot_delete_success(vid);
}
else if (action == "SNAPSHOT_DELETE_FAILURE")
{
snapshot_delete_failure(vid);
}
else if (action == "DEPLOY")
{
deploy_action(vid);
}
else if (action == "SUSPEND")
{
suspend_action(vid);
}
else if (action == "RESTORE")
{
restore_action(vid);
}
else if (action == "STOP")
{
stop_action(vid);
}
else if (action == "CANCEL")
{
cancel_action(vid);
}
else if (action == "MIGRATE")
{
migrate_action(vid);
}
else if (action == "LIVE_MIGRATE")
{
live_migrate_action(vid);
}
else if (action == "SHUTDOWN")
{
shutdown_action(vid);
}
else if (action == "UNDEPLOY")
{
undeploy_action(vid, false);
}
else if (action == "UNDEPLOY_HARD")
{
undeploy_action(vid, true);
}
else if (action == "RESTART")
{
restart_action(vid);
}
else if (action == "DELETE")
{
delete_action(vid);
}
else if (action == "CLEAN")
{
clean_action(vid);
}
else if (action == "POWEROFF")
{
poweroff_action(vid);
}
else if (action == "POWEROFF_HARD")
{
poweroff_hard_action(vid);
}
else if (action == ACTION_FINALIZE)
{
NebulaLog::log("LCM",Log::INFO,"Stopping Life-cycle Manager...");
}
else
{
ostringstream oss;
oss << "Unknown action name: " << action;
NebulaLog::log("LCM", Log::ERROR, oss);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<|endoftext|> |
<commit_before>// This file is part of the "x0" project
// (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
//
// x0 is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <xzero/UnixSignals.h>
#include <xzero/executor/Executor.h>
#include <xzero/io/FileDescriptor.h>
#include <xzero/RuntimeError.h>
#include <xzero/Duration.h>
#include <memory>
#include <mutex>
#include <atomic>
#include <vector>
#include <list>
#if defined(XZERO_OS_LINUX)
#include <linux/epoll.h>
#endif
#if defined(XZERO_OS_DARWIN)
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#endif
namespace xzero {
class SignalWatcher : public Executor::Handle {
public:
typedef Executor::Task Task;
explicit SignalWatcher(Task action) : action_(action) {};
void fire() { Executor::Handle::fire(action_); }
private:
Task action_;
};
#if defined(XZERO_OS_LINUX) // {{{
class LinuxSignals : public UnixSignals {
public:
explicit LinuxSignals(Executor* executor);
~LinuxSignals();
HandleRef executeOnSignal(int signo, Task task) override;
private:
Executor* executor_;
FileDescriptor fd_;
std::vector<std::list<RefPtr<SignalWatcher>>> watchers_;
};
#endif
// }}}
#if defined(XZERO_OS_DARWIN) // {{{
class KQueueSignals : public UnixSignals {
public:
explicit KQueueSignals(Executor* executor);
~KQueueSignals();
HandleRef executeOnSignal(int signo, Task task) override;
void onSignal();
private:
Executor* executor_;
Executor::HandleRef handle_;
FileDescriptor fd_;
std::vector<std::list<RefPtr<SignalWatcher>>> watchers_;
std::atomic<size_t> interests_;
std::mutex mutex_;
};
KQueueSignals::KQueueSignals(Executor* executor)
: executor_(executor),
handle_(),
fd_(kqueue()),
watchers_(128),
interests_(0),
mutex_() {
}
KQueueSignals::~KQueueSignals() {
if (handle_) {
handle_->cancel();
}
}
KQueueSignals::HandleRef KQueueSignals::executeOnSignal(int signo, Task task) {
std::lock_guard<std::mutex> _l(mutex_);
// add event to kqueue
if (watchers_[signo].empty()) {
struct kevent ke;
EV_SET(&ke, signo, EVFILT_SIGNAL, EV_ADD | EV_ONESHOT,
0 /* fflags */,
0 /* data */,
nullptr /* udata */);
int rv = kevent(fd_, &ke, 1, nullptr, 0, nullptr);
if (rv < 0) {
RAISE_ERRNO(errno);
}
}
RefPtr<SignalWatcher> hr(new SignalWatcher(task));
watchers_[signo].emplace_back(hr);
if (interests_.load() == 0) {
handle_ = executor_->executeOnReadable(
fd_,
std::bind(&KQueueSignals::onSignal, this));
}
interests_++;
return hr.as<Executor::Handle>();
}
void KQueueSignals::onSignal() {
// collect pending signals
timespec timeout;
timeout.tv_sec = 0;
timeout.tv_nsec = 0;
struct kevent events[16];
int rv = kevent(fd_, nullptr, 0, events, 128, &timeout);
if (rv < 0)
RAISE_ERRNO(errno);
std::vector<RefPtr<SignalWatcher>> pending(rv);
{
// move pending signals out of the watchers
std::lock_guard<std::mutex> _l(mutex_);
for (int i = 0; i < rv; ++i) {
int signo = events[i].ident;
std::list<RefPtr<SignalWatcher>>& watchers = watchers_[signo];
pending.insert(pending.end(), watchers.begin(), watchers.end());
interests_ -= watchers_[signo].size();
watchers.clear();
}
// reregister for further signals, if anyone interested
if (interests_.load() > 0) {
handle_ = executor_->executeOnReadable(
fd_,
std::bind(&KQueueSignals::onSignal, this));
}
}
// notify interests
for (RefPtr<SignalWatcher>& hr: pending)
executor_->execute(std::bind(&SignalWatcher::fire, hr));
}
#endif
// }}}
std::unique_ptr<UnixSignals> UnixSignals::create(Executor* executor) {
#if defined(XZERO_OS_LINUX)
return std::unique_ptr<UnixSignals>(new LinuxSignals(executor));
#elif defined(XZERO_OS_DARWIN)
return std::unique_ptr<UnixSignals>(new KQueueSignals(executor));
#else
#error "Unsupported platform."
#endif
}
} // namespace xzero
<commit_msg>UnixSignals: working version for OS/X (can't believe I didn't do it for Linux first.)<commit_after>// This file is part of the "x0" project
// (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
//
// x0 is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <xzero/UnixSignals.h>
#include <xzero/executor/Executor.h>
#include <xzero/io/FileDescriptor.h>
#include <xzero/RuntimeError.h>
#include <xzero/Duration.h>
#include <xzero/logging.h>
#include <memory>
#include <mutex>
#include <atomic>
#include <vector>
#include <list>
#include <signal.h>
#if defined(XZERO_OS_LINUX)
#include <linux/epoll.h>
#endif
#if defined(XZERO_OS_DARWIN)
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#endif
namespace xzero {
#if !defined(NDEBUG)
#define TRACE(msg...) logTrace("UnixSignals", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif
class SignalWatcher : public Executor::Handle {
public:
typedef Executor::Task Task;
explicit SignalWatcher(Task action) : action_(action) {};
void fire() { Executor::Handle::fire(action_); }
private:
Task action_;
};
static std::string sig2str(int signo) {
switch (signo) {
case SIGINT: return "SIGINT";
case SIGHUP: return "SIGHUP";
case SIGTERM: return "SIGTERM";
case SIGCONT: return "SIGCONT";
case SIGUSR1: return "SIGUSR1";
case SIGUSR2: return "SIGUSR2";
default: break;
}
char buf[16];
snprintf(buf, sizeof(buf), "<%d>", signo);
return buf;
}
#if defined(XZERO_OS_LINUX) // {{{
class LinuxSignals : public UnixSignals {
public:
explicit LinuxSignals(Executor* executor);
~LinuxSignals();
HandleRef executeOnSignal(int signo, Task task) override;
private:
Executor* executor_;
FileDescriptor fd_;
std::vector<std::list<RefPtr<SignalWatcher>>> watchers_;
};
#endif
// }}}
#if defined(XZERO_OS_DARWIN) // {{{
class KQueueSignals : public UnixSignals {
public:
explicit KQueueSignals(Executor* executor);
~KQueueSignals();
HandleRef executeOnSignal(int signo, Task task) override;
void onSignal();
private:
Executor* executor_;
Executor::HandleRef handle_;
FileDescriptor fd_;
std::vector<std::list<RefPtr<SignalWatcher>>> watchers_;
std::atomic<size_t> interests_;
std::mutex mutex_;
};
KQueueSignals::KQueueSignals(Executor* executor)
: executor_(executor),
handle_(),
fd_(kqueue()),
watchers_(128),
interests_(0),
mutex_() {
}
KQueueSignals::~KQueueSignals() {
if (handle_) {
handle_->cancel();
}
}
KQueueSignals::HandleRef KQueueSignals::executeOnSignal(int signo, Task task) {
std::lock_guard<std::mutex> _l(mutex_);
// add event to kqueue
if (watchers_[signo].empty()) {
struct kevent ke;
EV_SET(&ke, signo, EVFILT_SIGNAL, EV_ADD | EV_ONESHOT,
0 /* fflags */,
0 /* data */,
nullptr /* udata */);
int rv = kevent(fd_, &ke, 1, nullptr, 0, nullptr);
if (rv < 0) {
RAISE_ERRNO(errno);
}
}
RefPtr<SignalWatcher> hr(new SignalWatcher(task));
watchers_[signo].emplace_back(hr);
if (interests_.load() == 0) {
handle_ = executor_->executeOnReadable(
fd_,
std::bind(&KQueueSignals::onSignal, this));
}
interests_++;
return hr.as<Executor::Handle>();
}
void KQueueSignals::onSignal() {
// collect pending signals
timespec timeout;
timeout.tv_sec = 0;
timeout.tv_nsec = 0;
struct kevent events[16];
int rv = kevent(fd_, nullptr, 0, events, 128, &timeout);
if (rv < 0)
RAISE_ERRNO(errno);
std::vector<RefPtr<SignalWatcher>> pending;
pending.reserve(rv);
{
// move pending signals out of the watchers
std::lock_guard<std::mutex> _l(mutex_);
for (int i = 0; i < rv; ++i) {
int signo = events[i].ident;
std::list<RefPtr<SignalWatcher>>& watchers = watchers_[signo];
TRACE("Caught signal $0 with $1 watchers.",
sig2str(signo),
watchers.size());
pending.insert(pending.end(), watchers.begin(), watchers.end());
interests_ -= watchers_[signo].size();
watchers.clear();
}
// reregister for further signals, if anyone interested
if (interests_.load() > 0) {
handle_ = executor_->executeOnReadable(
fd_,
std::bind(&KQueueSignals::onSignal, this));
}
}
// notify interests
for (RefPtr<SignalWatcher>& hr: pending)
executor_->execute(std::bind(&SignalWatcher::fire, hr));
}
#endif
// }}}
std::unique_ptr<UnixSignals> UnixSignals::create(Executor* executor) {
#if defined(XZERO_OS_LINUX)
return std::unique_ptr<UnixSignals>(new LinuxSignals(executor));
#elif defined(XZERO_OS_DARWIN)
return std::unique_ptr<UnixSignals>(new KQueueSignals(executor));
#else
#error "Unsupported platform."
#endif
}
} // namespace xzero
<|endoftext|> |
<commit_before>/*
main.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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.
*/
#include <config-kleopatra.h>
#include "aboutdata.h"
#include "kleopatraapplication.h"
#include "mainwindow.h"
#include <commands/reloadkeyscommand.h>
#include <commands/selftestcommand.h>
#include <utils/gnupg-helper.h>
#ifdef HAVE_USABLE_ASSUAN
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
# include <uiserver/echocommand.h>
# include <uiserver/decryptcommand.h>
# include <uiserver/verifycommand.h>
# include <uiserver/decryptverifyfilescommand.h>
# include <uiserver/decryptfilescommand.h>
# include <uiserver/verifyfilescommand.h>
# include <uiserver/prepencryptcommand.h>
# include <uiserver/encryptcommand.h>
# include <uiserver/signcommand.h>
# include <uiserver/signencryptfilescommand.h>
# include <uiserver/selectcertificatecommand.h>
#else
namespace Kleo {
class UiServer;
}
#endif
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kiconloader.h>
#include <ksplashscreen.h>
#include <KDebug>
#include <QTextDocument> // for Qt::escape
#include <QStringList>
#include <QMessageBox>
#include <QTimer>
#include <QEventLoop>
#include <QThreadPool>
#include <boost/shared_ptr.hpp>
#include <cassert>
using namespace boost;
namespace {
template <typename T>
boost::shared_ptr<T> make_shared_ptr( T * t ) {
return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
}
}
static bool selfCheck( KSplashScreen & splash ) {
splash.showMessage( i18n("Performing Self-Check...") );
Kleo::Commands::SelfTestCommand cmd( 0 );
cmd.setAutoDelete( false );
cmd.setAutomaticMode( true );
cmd.setSplashScreen( &splash );
QEventLoop loop;
QObject::connect( &cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
QObject::connect( &cmd, SIGNAL(info(QString)), &splash, SLOT(showMessage(QString)) );
QTimer::singleShot( 0, &cmd, SLOT(start()) ); // start() may emit finished()...
loop.exec();
if ( cmd.isCanceled() ) {
splash.showMessage( i18nc("didn't pass", "Self-Check Failed") );
return false;
} else {
splash.showMessage( i18n("Self-Check Passed") );
return true;
}
}
static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) {
QEventLoop loop;
Kleo::ReloadKeysCommand * cmd = new Kleo::ReloadKeysCommand( 0 );
QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
#ifdef HAVE_USABLE_ASSUAN
QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) );
#else
Q_UNUSED( server );
#endif
splash->showMessage( i18n("Loading certificate cache...") );
cmd->start();
loop.exec();
splash->showMessage( i18n("Certificate cache loaded.") );
}
int main( int argc, char** argv )
{
{
const unsigned int threads = QThreadPool::globalInstance()->maxThreadCount();
QThreadPool::globalInstance()->setMaxThreadCount( qMax( 2U, threads ) );
}
AboutData aboutData;
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineArgs::addCmdLineOptions( KleopatraApplication::commandLineOptions() );
KleopatraApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint );
int rc;
#ifdef HAVE_USABLE_ASSUAN
try {
Kleo::UiServer server( args->getOption("uiserver-socket") );
QObject::connect( &server, SIGNAL(startKeyManagerRequested()),
&app, SLOT(openOrRaiseMainWindow()) );
#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )
REGISTER( DecryptCommand );
REGISTER( DecryptFilesCommand );
REGISTER( DecryptVerifyFilesCommand );
REGISTER( EchoCommand );
REGISTER( EncryptCommand );
REGISTER( EncryptFilesCommand );
REGISTER( EncryptSignFilesCommand );
REGISTER( PrepEncryptCommand );
REGISTER( SelectCertificateCommand );
REGISTER( SignCommand );
REGISTER( SignEncryptFilesCommand );
REGISTER( SignFilesCommand );
REGISTER( VerifyCommand );
REGISTER( VerifyFilesCommand );
#undef REGISTER
server.start();
#endif
const bool daemon = args->isSet("daemon");
if ( !daemon )
splash.show();
if ( !selfCheck( splash ) )
return 1;
#ifdef HAVE_USABLE_ASSUAN
fillKeyCache( &splash, &server );
#else
fillKeyCache( &splash, 0 );
#endif
app.setIgnoreNewInstance( false );
if ( !daemon ) {
app.newInstance();
splash.finish( app.mainWindow() );
}
rc = app.exec();
#ifdef HAVE_USABLE_ASSUAN
app.setIgnoreNewInstance( true );
QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()),
&app, SLOT(openOrRaiseMainWindow()) );
server.stop();
server.waitForStopped();
} catch ( const std::exception & e ) {
QMessageBox::information( 0, i18n("GPG UI Server Error"),
i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br/>"
"The error given was: <b>%1</b><br/>"
"You can use Kleopatra as a certificate manager, but cryptographic plugins that "
"rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
Qt::escape( QString::fromUtf8( e.what() ) ) ));
app.setIgnoreNewInstance( false );
rc = app.exec();
app.setIgnoreNewInstance( true );
}
#endif
return rc;
}
<commit_msg>argh^2<commit_after>/*
main.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB
Kleopatra 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.
Kleopatra 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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.
*/
#include <config-kleopatra.h>
#include "aboutdata.h"
#include "kleopatraapplication.h"
#include "mainwindow.h"
#include <commands/reloadkeyscommand.h>
#include <commands/selftestcommand.h>
#include <utils/gnupg-helper.h>
#ifdef HAVE_USABLE_ASSUAN
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
# include <uiserver/echocommand.h>
# include <uiserver/decryptcommand.h>
# include <uiserver/verifycommand.h>
# include <uiserver/decryptverifyfilescommand.h>
# include <uiserver/decryptfilescommand.h>
# include <uiserver/verifyfilescommand.h>
# include <uiserver/prepencryptcommand.h>
# include <uiserver/encryptcommand.h>
# include <uiserver/signcommand.h>
# include <uiserver/signencryptfilescommand.h>
# include <uiserver/selectcertificatecommand.h>
#else
namespace Kleo {
class UiServer;
}
#endif
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kiconloader.h>
#include <ksplashscreen.h>
#include <KDebug>
#include <QTextDocument> // for Qt::escape
#include <QStringList>
#include <QMessageBox>
#include <QTimer>
#include <QEventLoop>
#include <QThreadPool>
#include <boost/shared_ptr.hpp>
#include <cassert>
using namespace boost;
namespace {
template <typename T>
boost::shared_ptr<T> make_shared_ptr( T * t ) {
return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
}
}
static bool selfCheck( KSplashScreen & splash ) {
splash.showMessage( i18n("Performing Self-Check...") );
Kleo::Commands::SelfTestCommand cmd( 0 );
cmd.setAutoDelete( false );
cmd.setAutomaticMode( true );
cmd.setSplashScreen( &splash );
QEventLoop loop;
QObject::connect( &cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
QObject::connect( &cmd, SIGNAL(info(QString)), &splash, SLOT(showMessage(QString)) );
QTimer::singleShot( 0, &cmd, SLOT(start()) ); // start() may emit finished()...
loop.exec();
if ( cmd.isCanceled() ) {
splash.showMessage( i18nc("didn't pass", "Self-Check Failed") );
return false;
} else {
splash.showMessage( i18n("Self-Check Passed") );
return true;
}
}
static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) {
QEventLoop loop;
Kleo::ReloadKeysCommand * cmd = new Kleo::ReloadKeysCommand( 0 );
QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
#ifdef HAVE_USABLE_ASSUAN
QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) );
#else
Q_UNUSED( server );
#endif
splash->showMessage( i18n("Loading certificate cache...") );
cmd->start();
loop.exec();
splash->showMessage( i18n("Certificate cache loaded.") );
}
int main( int argc, char** argv )
{
{
const unsigned int threads = QThreadPool::globalInstance()->maxThreadCount();
QThreadPool::globalInstance()->setMaxThreadCount( qMin( 2U, threads ) );
}
AboutData aboutData;
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineArgs::addCmdLineOptions( KleopatraApplication::commandLineOptions() );
KleopatraApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint );
int rc;
#ifdef HAVE_USABLE_ASSUAN
try {
Kleo::UiServer server( args->getOption("uiserver-socket") );
QObject::connect( &server, SIGNAL(startKeyManagerRequested()),
&app, SLOT(openOrRaiseMainWindow()) );
#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )
REGISTER( DecryptCommand );
REGISTER( DecryptFilesCommand );
REGISTER( DecryptVerifyFilesCommand );
REGISTER( EchoCommand );
REGISTER( EncryptCommand );
REGISTER( EncryptFilesCommand );
REGISTER( EncryptSignFilesCommand );
REGISTER( PrepEncryptCommand );
REGISTER( SelectCertificateCommand );
REGISTER( SignCommand );
REGISTER( SignEncryptFilesCommand );
REGISTER( SignFilesCommand );
REGISTER( VerifyCommand );
REGISTER( VerifyFilesCommand );
#undef REGISTER
server.start();
#endif
const bool daemon = args->isSet("daemon");
if ( !daemon )
splash.show();
if ( !selfCheck( splash ) )
return 1;
#ifdef HAVE_USABLE_ASSUAN
fillKeyCache( &splash, &server );
#else
fillKeyCache( &splash, 0 );
#endif
app.setIgnoreNewInstance( false );
if ( !daemon ) {
app.newInstance();
splash.finish( app.mainWindow() );
}
rc = app.exec();
#ifdef HAVE_USABLE_ASSUAN
app.setIgnoreNewInstance( true );
QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()),
&app, SLOT(openOrRaiseMainWindow()) );
server.stop();
server.waitForStopped();
} catch ( const std::exception & e ) {
QMessageBox::information( 0, i18n("GPG UI Server Error"),
i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br/>"
"The error given was: <b>%1</b><br/>"
"You can use Kleopatra as a certificate manager, but cryptographic plugins that "
"rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
Qt::escape( QString::fromUtf8( e.what() ) ) ));
app.setIgnoreNewInstance( false );
rc = app.exec();
app.setIgnoreNewInstance( true );
}
#endif
return rc;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, 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 "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
int read_message(stream_socket& s, char* buffer)
{
using namespace libtorrent::detail;
error_code ec;
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 4)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return -1;
}
char* ptr = buffer;
int length = read_int32(ptr);
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, length)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return -1;
}
return length;
}
void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer)
{
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa"; // peer-id
error_code ec;
std::memcpy(handshake + 28, ih.begin(), 20);
std::generate(handshake + 48, handshake + 68, &rand);
libtorrent::asio::write(s, libtorrent::asio::buffer(handshake, sizeof(handshake) - 1)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 68)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE HANDSHAKE: %s\n", ec.message().c_str());
return;
}
}
void send_interested(stream_socket& s)
{
char msg[] = "\0\0\0\x01\x02";
error_code ec;
libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 5)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND INTERESTED: %s\n", ec.message().c_str());
return;
}
}
void send_request(stream_socket& s, int piece, int block)
{
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* ptr = msg + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
libtorrent::asio::write(s, libtorrent::asio::buffer(msg, sizeof(msg)-1)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
}
// makes sure that pieces that are allowed and then
// rejected aren't requested again
void requester_thread(torrent_info const* ti, tcp::endpoint const* ep, io_service* ios)
{
sha1_hash const& ih = ti->info_hash();
stream_socket s(*ios);
error_code ec;
s.connect(*ep, ec);
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char recv_buffer[16 * 1024 + 1000];
do_handshake(s, ih, recv_buffer);
send_interested(s);
// build a list of all pieces and request them all!
std::vector<int> pieces(ti->num_pieces());
for (int i = 0; i < pieces.size(); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
int block = 0;
int blocks_per_piece = ti->piece_length() / 16 / 1024;
int outstanding_reqs = 0;
while (true)
{
while (outstanding_reqs < 16)
{
send_request(s, pieces.back(), block++);
++outstanding_reqs;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
if (pieces.empty())
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
}
int length = read_message(s, recv_buffer);
if (length == -1) return;
int msg = recv_buffer[0];
if (msg == 7) --outstanding_reqs;
}
}
int main(int argc, char const* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
address_v4 addr = address_v4::from_string(argv[2]);
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
error_code ec;
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<thread*> threads;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
threads.push_back(new thread(boost::bind(&requester_thread, &ti, &ep, &ios)));
libtorrent::sleep(10);
}
for (int i = 0; i < num_connections; ++i)
{
threads.back()->join();
delete threads.back();
threads.pop_back();
}
return 0;
}
<commit_msg>make connection_tester run in a single thread<commit_after>/*
Copyright (c) 2008, 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 "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
struct peer_conn
{
peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
, char const* ih)
: s(ios)
, read_pos(0)
, state(handshaking)
, pieces(num_pieces)
, block(0)
, blocks_per_piece(blocks_pp)
, info_hash(ih)
, outstanding_requests(0)
{
// build a list of all pieces and request them all!
for (int i = 0; i < pieces.size(); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
}
stream_socket s;
char buffer[17*1024];
int read_pos;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<int> pieces;
int block;
int blocks_per_piece;
char const* info_hash;
int outstanding_requests;
void on_connect(error_code const& ec)
{
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa" // peer-id
"\0\0\0\x01\x02"; // interested
char* h = (char*)malloc(sizeof(handshake));
memcpy(h, handshake, sizeof(handshake));
std::memcpy(h + 28, info_hash, 20);
std::generate(h + 48, h + 68, &rand);
boost::asio::async_write(s, libtorrent::asio::buffer(h, sizeof(handshake) - 1)
, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
}
void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
{
free(h);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
boost::asio::async_read(s, libtorrent::asio::buffer(buffer, 68)
, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
}
void on_handshake2(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
return;
}
work();
}
void write_request()
{
if (pieces.empty()) return;
int piece = pieces.back();
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* m = (char*)malloc(sizeof(msg));
memcpy(m, msg, sizeof(msg));
char* ptr = m + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));
++block;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
}
void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
{
free(m);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
++outstanding_requests;
work();
}
void work()
{
if (pieces.empty() && outstanding_requests == 0)
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
// send requests
if (outstanding_requests < 20 && !pieces.empty())
{
write_request();
return;
}
// read message
boost::asio::async_read(s, asio::buffer(buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void on_msg_length(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
unsigned int length = read_uint32(ptr);
if (length > sizeof(buffer))
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
return;
}
boost::asio::async_read(s, asio::buffer(buffer, length)
, boost::bind(&peer_conn::on_message, this, _1, _2));
}
void on_message(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
int msg = read_uint8(ptr);
if (msg == 7) --outstanding_requests;
work();
}
};
int main(int argc, char const* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
address_v4 addr = address_v4::from_string(argv[2]);
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
error_code ec;
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<peer_conn*> conns;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
, ep, (char const*)&ti.info_hash()[0]));
libtorrent::sleep(1);
}
ios.run();
return 0;
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Patrick Spendrin <ps_ml@gmx.de>
//
#include "PlacemarkLoader.h"
#include <QtCore/QBuffer>
#include <QtCore/QDataStream>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QThread>
#include "GeoDataParser.h"
#include "GeoSceneDocument.h"
#include "GeoDataDocument.h"
#include "GeoDataPlacemark.h"
#include "MarbleDirs.h"
#include "MarblePlacemarkModel.h"
#include "PlacemarkContainer.h"
namespace Marble {
PlacemarkLoader::PlacemarkLoader( QObject* parent, const QString& file )
: QThread( parent ),
m_filepath( file ),
m_contents( QString() )
{
}
PlacemarkLoader::PlacemarkLoader( QObject* parent, const QString& contents, const QString& file )
: QThread( parent ),
m_filepath( file ),
m_contents( contents )
{
}
void PlacemarkLoader::run()
{
if( m_contents.isEmpty() ) {
QString defaultcachename;
QString defaultsrcname;
QString defaulthomecache;
PlacemarkContainer *container = new PlacemarkContainer( m_filepath );
if( m_filepath.endsWith(".kml") ) {
m_filepath.remove(QRegExp("\\.kml$"));
}
qDebug() << "starting parser for" << m_filepath;
QFileInfo fileinfo(m_filepath);
if ( fileinfo.isAbsolute() ) {
// We got an _absolute_ path now: e.g. "/patrick.kml"
defaultcachename = m_filepath + ".cache";
defaultsrcname = m_filepath + ".kml";
}
else {
if ( m_filepath.contains( '/' ) ) {
// _relative_ path: "maps/mars/viking/patrick.kml"
defaultcachename = MarbleDirs::path( m_filepath + ".cache" );
defaultsrcname = MarbleDirs::path( m_filepath + ".kml");
defaulthomecache = MarbleDirs::localPath() + m_filepath + ".cache";
}
else {
// _standard_ shared placemarks: "placemarks/patrick.kml"
defaultcachename = MarbleDirs::path( "placemarks/" + m_filepath + ".cache" );
defaultsrcname = MarbleDirs::path( "placemarks/" + m_filepath + ".kml");
defaulthomecache = MarbleDirs::localPath() + "/placemarks/" + m_filepath + ".cache";
}
}
if ( QFile::exists( defaultcachename ) ) {
qDebug() << "Loading Default Placemark Cache File:" + defaultcachename;
bool cacheoutdated = false;
QDateTime sourceLastModified;
QDateTime cacheLastModified;
if ( QFile::exists( defaultsrcname ) ) {
sourceLastModified = QFileInfo( defaultsrcname ).lastModified();
cacheLastModified = QFileInfo( defaultcachename ).lastModified();
if ( cacheLastModified < sourceLastModified )
cacheoutdated = true;
}
bool loadok = false;
if ( cacheoutdated == false ) {
loadok = loadFile( defaultcachename, container );
if ( loadok )
emit placemarksLoaded( this, container );
}
qDebug() << "Loading ended" << loadok;
if ( loadok == true )
return;
}
qDebug() << "No recent Default Placemark Cache File available for " << m_filepath;
if ( QFile::exists( defaultsrcname ) ) {
// Read the KML file.
importKml( defaultsrcname, container );
qDebug() << "ContainerSize for" << m_filepath << ":" << container->size();
// Save the contents in the efficient cache format.
saveFile( defaulthomecache, container );
// ...and finally add it to the PlacemarkContainer
emit placemarksLoaded( this, container );
}
else {
qDebug() << "No Default Placemark Source File for " << m_filepath;
emit placemarkLoaderFailed( this );
}
} else {
PlacemarkContainer *container = new PlacemarkContainer( m_filepath );
// Read the KML Data
importKmlFromData( container );
emit placemarksLoaded( this, container );
}
}
const quint32 MarbleMagicNumber = 0x31415926;
void PlacemarkLoader::importKml( const QString& filename,
PlacemarkContainer* placemarkContainer )
{
GeoDataParser parser( GeoData_KML );
QFile file( filename );
if ( !file.exists() ) {
qWarning( "File does not exist!" );
return;
}
// Open file in right mode
file.open( QIODevice::ReadOnly );
if ( !parser.read( &file ) ) {
qWarning( "Could not parse file!" );
return;
}
GeoDocument* document = parser.releaseDocument();
Q_ASSERT( document );
GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
dataDocument->setFileName( m_filepath );
*placemarkContainer = PlacemarkContainer( dataDocument->placemarks(),
m_filepath );
file.close();
emit newGeoDataDocumentAdded( dataDocument );
}
void PlacemarkLoader::importKmlFromData( PlacemarkContainer* placemarkContainer )
{
GeoDataParser parser( GeoData_KML );
QByteArray ba( m_contents.toUtf8() );
QBuffer buffer( &ba );
buffer.open( QIODevice::ReadOnly );
if ( !parser.read( &buffer ) ) {
qWarning( "Could not parse buffer!" );
return;
}
GeoDocument* document = parser.releaseDocument();
Q_ASSERT( document );
GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
dataDocument->setFileName( m_filepath );
*placemarkContainer = PlacemarkContainer( dataDocument->placemarks(),
m_filepath );
buffer.close();
emit newGeoDataDocumentAdded( dataDocument );
}
void PlacemarkLoader::saveFile( const QString& filename,
PlacemarkContainer* placemarkContainer )
{
if ( QDir( MarbleDirs::localPath() + "/placemarks/" ).exists() == false )
( QDir::root() ).mkpath( MarbleDirs::localPath() + "/placemarks/" );
QFile file( filename );
file.open( QIODevice::WriteOnly );
QDataStream out( &file );
// Write a header with a "magic number" and a version
// out << (quint32)0xA0B0C0D0;
out << (quint32)MarbleMagicNumber;
out << (qint32)014;
out.setVersion( QDataStream::Qt_4_2 );
qreal lon;
qreal lat;
qreal alt;
PlacemarkContainer::const_iterator it = placemarkContainer->constBegin();
PlacemarkContainer::const_iterator const end = placemarkContainer->constEnd();
for (; it != end; ++it )
{
out << (*it)->name();
(*it)->coordinate( lon, lat, alt );
out << lon << lat << alt;
out << QString( (*it)->role() );
out << QString( (*it)->description() );
out << QString( (*it)->countryCode() );
out << (qreal)(*it)->area();
out << (qint64)(*it)->population();
}
}
bool PlacemarkLoader::loadFile( const QString& filename,
PlacemarkContainer* placemarkContainer )
{
QFile file( filename );
file.open( QIODevice::ReadOnly );
QDataStream in( &file );
// Read and check the header
quint32 magic;
in >> magic;
if ( magic != MarbleMagicNumber ) {
qDebug( "Bad file format!" );
return false;
}
// Read the version
qint32 version;
in >> version;
if ( version < 014 ) {
qDebug( "Bad file - too old!" );
return false;
}
/*
if (version > 002) {
qDebug( "Bad file - too new!" );
return;
}
*/
in.setVersion( QDataStream::Qt_4_2 );
// Read the data itself
qreal lon;
qreal lat;
qreal alt;
qreal area;
QString tmpstr;
qint64 tmpint64;
QString testo;
GeoDataPlacemark *mark;
while ( !in.atEnd() ) {
mark = new GeoDataPlacemark;
in >> tmpstr;
mark->setName( tmpstr );
testo = tmpstr;
in >> lon >> lat >> alt;
mark->setCoordinate( lon, lat, alt );
in >> tmpstr;
mark->setRole( tmpstr.at(0) );
in >> tmpstr;
mark->setDescription( tmpstr );
in >> tmpstr;
mark->setCountryCode( tmpstr );
in >> area;
mark->setArea( area );
in >> tmpint64;
mark->setPopulation( tmpint64 );
placemarkContainer->append( mark );
}
return true;
}
#include "PlacemarkLoader.moc"
} // namespace Marble
<commit_msg>Simplify bool expressions, do not compare bool values with "true", just use the value.<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Patrick Spendrin <ps_ml@gmx.de>
//
#include "PlacemarkLoader.h"
#include <QtCore/QBuffer>
#include <QtCore/QDataStream>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QThread>
#include "GeoDataParser.h"
#include "GeoSceneDocument.h"
#include "GeoDataDocument.h"
#include "GeoDataPlacemark.h"
#include "MarbleDirs.h"
#include "MarblePlacemarkModel.h"
#include "PlacemarkContainer.h"
namespace Marble {
PlacemarkLoader::PlacemarkLoader( QObject* parent, const QString& file )
: QThread( parent ),
m_filepath( file ),
m_contents( QString() )
{
}
PlacemarkLoader::PlacemarkLoader( QObject* parent, const QString& contents, const QString& file )
: QThread( parent ),
m_filepath( file ),
m_contents( contents )
{
}
void PlacemarkLoader::run()
{
if( m_contents.isEmpty() ) {
QString defaultcachename;
QString defaultsrcname;
QString defaulthomecache;
PlacemarkContainer *container = new PlacemarkContainer( m_filepath );
if( m_filepath.endsWith(".kml") ) {
m_filepath.remove(QRegExp("\\.kml$"));
}
qDebug() << "starting parser for" << m_filepath;
QFileInfo fileinfo(m_filepath);
if ( fileinfo.isAbsolute() ) {
// We got an _absolute_ path now: e.g. "/patrick.kml"
defaultcachename = m_filepath + ".cache";
defaultsrcname = m_filepath + ".kml";
}
else {
if ( m_filepath.contains( '/' ) ) {
// _relative_ path: "maps/mars/viking/patrick.kml"
defaultcachename = MarbleDirs::path( m_filepath + ".cache" );
defaultsrcname = MarbleDirs::path( m_filepath + ".kml");
defaulthomecache = MarbleDirs::localPath() + m_filepath + ".cache";
}
else {
// _standard_ shared placemarks: "placemarks/patrick.kml"
defaultcachename = MarbleDirs::path( "placemarks/" + m_filepath + ".cache" );
defaultsrcname = MarbleDirs::path( "placemarks/" + m_filepath + ".kml");
defaulthomecache = MarbleDirs::localPath() + "/placemarks/" + m_filepath + ".cache";
}
}
if ( QFile::exists( defaultcachename ) ) {
qDebug() << "Loading Default Placemark Cache File:" + defaultcachename;
bool cacheoutdated = false;
QDateTime sourceLastModified;
QDateTime cacheLastModified;
if ( QFile::exists( defaultsrcname ) ) {
sourceLastModified = QFileInfo( defaultsrcname ).lastModified();
cacheLastModified = QFileInfo( defaultcachename ).lastModified();
if ( cacheLastModified < sourceLastModified )
cacheoutdated = true;
}
bool loadok = false;
if ( cacheoutdated == false ) {
loadok = loadFile( defaultcachename, container );
if ( loadok )
emit placemarksLoaded( this, container );
}
qDebug() << "Loading ended" << loadok;
if ( loadok )
return;
}
qDebug() << "No recent Default Placemark Cache File available for " << m_filepath;
if ( QFile::exists( defaultsrcname ) ) {
// Read the KML file.
importKml( defaultsrcname, container );
qDebug() << "ContainerSize for" << m_filepath << ":" << container->size();
// Save the contents in the efficient cache format.
saveFile( defaulthomecache, container );
// ...and finally add it to the PlacemarkContainer
emit placemarksLoaded( this, container );
}
else {
qDebug() << "No Default Placemark Source File for " << m_filepath;
emit placemarkLoaderFailed( this );
}
} else {
PlacemarkContainer *container = new PlacemarkContainer( m_filepath );
// Read the KML Data
importKmlFromData( container );
emit placemarksLoaded( this, container );
}
}
const quint32 MarbleMagicNumber = 0x31415926;
void PlacemarkLoader::importKml( const QString& filename,
PlacemarkContainer* placemarkContainer )
{
GeoDataParser parser( GeoData_KML );
QFile file( filename );
if ( !file.exists() ) {
qWarning( "File does not exist!" );
return;
}
// Open file in right mode
file.open( QIODevice::ReadOnly );
if ( !parser.read( &file ) ) {
qWarning( "Could not parse file!" );
return;
}
GeoDocument* document = parser.releaseDocument();
Q_ASSERT( document );
GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
dataDocument->setFileName( m_filepath );
*placemarkContainer = PlacemarkContainer( dataDocument->placemarks(),
m_filepath );
file.close();
emit newGeoDataDocumentAdded( dataDocument );
}
void PlacemarkLoader::importKmlFromData( PlacemarkContainer* placemarkContainer )
{
GeoDataParser parser( GeoData_KML );
QByteArray ba( m_contents.toUtf8() );
QBuffer buffer( &ba );
buffer.open( QIODevice::ReadOnly );
if ( !parser.read( &buffer ) ) {
qWarning( "Could not parse buffer!" );
return;
}
GeoDocument* document = parser.releaseDocument();
Q_ASSERT( document );
GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>( document );
dataDocument->setFileName( m_filepath );
*placemarkContainer = PlacemarkContainer( dataDocument->placemarks(),
m_filepath );
buffer.close();
emit newGeoDataDocumentAdded( dataDocument );
}
void PlacemarkLoader::saveFile( const QString& filename,
PlacemarkContainer* placemarkContainer )
{
if ( QDir( MarbleDirs::localPath() + "/placemarks/" ).exists() == false )
( QDir::root() ).mkpath( MarbleDirs::localPath() + "/placemarks/" );
QFile file( filename );
file.open( QIODevice::WriteOnly );
QDataStream out( &file );
// Write a header with a "magic number" and a version
// out << (quint32)0xA0B0C0D0;
out << (quint32)MarbleMagicNumber;
out << (qint32)014;
out.setVersion( QDataStream::Qt_4_2 );
qreal lon;
qreal lat;
qreal alt;
PlacemarkContainer::const_iterator it = placemarkContainer->constBegin();
PlacemarkContainer::const_iterator const end = placemarkContainer->constEnd();
for (; it != end; ++it )
{
out << (*it)->name();
(*it)->coordinate( lon, lat, alt );
out << lon << lat << alt;
out << QString( (*it)->role() );
out << QString( (*it)->description() );
out << QString( (*it)->countryCode() );
out << (qreal)(*it)->area();
out << (qint64)(*it)->population();
}
}
bool PlacemarkLoader::loadFile( const QString& filename,
PlacemarkContainer* placemarkContainer )
{
QFile file( filename );
file.open( QIODevice::ReadOnly );
QDataStream in( &file );
// Read and check the header
quint32 magic;
in >> magic;
if ( magic != MarbleMagicNumber ) {
qDebug( "Bad file format!" );
return false;
}
// Read the version
qint32 version;
in >> version;
if ( version < 014 ) {
qDebug( "Bad file - too old!" );
return false;
}
/*
if (version > 002) {
qDebug( "Bad file - too new!" );
return;
}
*/
in.setVersion( QDataStream::Qt_4_2 );
// Read the data itself
qreal lon;
qreal lat;
qreal alt;
qreal area;
QString tmpstr;
qint64 tmpint64;
QString testo;
GeoDataPlacemark *mark;
while ( !in.atEnd() ) {
mark = new GeoDataPlacemark;
in >> tmpstr;
mark->setName( tmpstr );
testo = tmpstr;
in >> lon >> lat >> alt;
mark->setCoordinate( lon, lat, alt );
in >> tmpstr;
mark->setRole( tmpstr.at(0) );
in >> tmpstr;
mark->setDescription( tmpstr );
in >> tmpstr;
mark->setCountryCode( tmpstr );
in >> area;
mark->setArea( area );
in >> tmpint64;
mark->setPopulation( tmpint64 );
placemarkContainer->append( mark );
}
return true;
}
#include "PlacemarkLoader.moc"
} // namespace Marble
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.